diff --git a/web/app/devbox/devbox-creator.tsx b/web/app/devbox/devbox-creator.tsx new file mode 100644 index 000000000000..19192dfd2c96 --- /dev/null +++ b/web/app/devbox/devbox-creator.tsx @@ -0,0 +1,163 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import type { FormEvent } from "react"; +import { vaultSignInHref } from "../lib/vault-auth"; + +type CreatedDevbox = { + id: string; + provider?: string; + image?: string; + imageVersion?: string; + createdAt?: string; +}; + +type VmErrorBody = { + error?: string; + message?: string; + action?: string; + reason?: string; +}; + +function createIdempotencyKey() { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) { + return crypto.randomUUID(); + } + return `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +function userMessage(status: number, body: VmErrorBody | null) { + if (status === 401) { + return "Sign in first, then create the devbox again."; + } + + const pieces = [body?.message, body?.action ?? body?.reason].filter( + Boolean, + ); + return pieces.join(" ") || `Devbox create failed with status ${status}.`; +} + +export function DevboxCreator() { + const [prompt, setPrompt] = useState(""); + const [isCreating, setIsCreating] = useState(false); + const [created, setCreated] = useState(null); + const [error, setError] = useState(null); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (isCreating) return; + + setIsCreating(true); + setError(null); + setCreated(null); + + try { + const response = await fetch("/api/vm", { + method: "POST", + headers: { + "content-type": "application/json", + "idempotency-key": createIdempotencyKey(), + }, + body: JSON.stringify({ + initialPrompt: prompt.trim() || undefined, + source: "devbox.new", + }), + }); + + const body = (await response.json().catch(() => null)) as + | CreatedDevbox + | VmErrorBody + | null; + + if (!response.ok) { + setError(userMessage(response.status, body as VmErrorBody | null)); + return; + } + + setCreated(body as CreatedDevbox); + } catch (err) { + setError(err instanceof Error ? err.message : "Devbox create failed."); + } finally { + setIsCreating(false); + } + } + + return ( +
+
+

+ Create a devbox +

+

+ Start a fresh cmux Cloud VM. Add the first prompt now, attach from + cmux when it is ready. +

+
+ +
+ +