The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
feat(deploy): one-click publishing to Vercel (#24)
Joey-nexub699e8a54cec
diff --git a/src/app/api/deploy/config/route.ts b/src/app/api/deploy/config/route.tsnew file mode 100644index 00000000..de21d93d--- /dev/null+++ b/src/app/api/deploy/config/route.ts@@ -0,0 +1,74 @@+import { NextRequest, NextResponse } from "next/server";+import {+ DeployError,+ isDeployProviderId,+ publicDeployConfigForProvider,+ readDeployConfig,+ writeDeployConfig,+ type DeployConfig,+ type DeployProviderId,+} from "@/lib/deploy/config";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++/**+ * GET /api/deploy/config?provider=vercel+ * → public-shape config (token masked)+ * PUT /api/deploy/config?provider=vercel+ * body: { token?, teamId?, teamSlug?, accountId? }+ * → updated public-shape config+ *+ * Tokens never leave the server in plaintext. Once configured, GET returns+ * `tokenMask: "saved-vercel-token"` (or the cloudflare equivalent); the+ * client sends that mask back unchanged when it wants to keep the existing+ * value during a partial update of `teamId` etc.+ */++function deployErrorResponse(err: unknown): NextResponse {+ if (err instanceof DeployError) {+ return NextResponse.json(+ { error: err.message, code: err.code, details: err.details },+ { status: err.status },+ );+ }+ const msg = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: msg }, { status: 500 });+}++function readProvider(req: NextRequest): DeployProviderId {+ const provider = req.nextUrl.searchParams.get("provider") ?? "vercel";+ if (!isDeployProviderId(provider)) {+ throw new DeployError(`Unknown deploy provider: ${provider}`, 400);+ }+ return provider;+}++export async function GET(req: NextRequest) {+ try {+ const providerId = readProvider(req);+ const config = await readDeployConfig(providerId);+ return NextResponse.json(publicDeployConfigForProvider(providerId, config));+ } catch (err) {+ return deployErrorResponse(err);+ }+}++export async function PUT(req: NextRequest) {+ try {+ const providerId = readProvider(req);+ let body: Partial<DeployConfig>;+ try {+ body = (await req.json()) as Partial<DeployConfig>;+ } catch {+ return NextResponse.json(+ { error: "Invalid JSON body" },+ { status: 400 },+ );+ }+ const updated = await writeDeployConfig(providerId, body);+ return NextResponse.json(updated);+ } catch (err) {+ return deployErrorResponse(err);+ }+}diff --git a/src/app/api/deploy/route.ts b/src/app/api/deploy/route.tsnew file mode 100644index 00000000..593a747e--- /dev/null+++ b/src/app/api/deploy/route.ts@@ -0,0 +1,120 @@+import { NextRequest, NextResponse } from "next/server";+import {+ DeployError,+ isDeployProviderId,+ readDeployConfig,+ type DeployProviderId,+} from "@/lib/deploy/config";+import { deployToVercel } from "@/lib/deploy/vercel";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+// Allow long-running deployments — Vercel's response can take 60–90 s+// while the deployment finishes building + URL becomes reachable.+export const maxDuration = 300;++type Body = {+ taskId: string;+ provider: DeployProviderId;+ /** The HTML document to publish. Must be a complete document (we wrap+ * defensively below if it isn't). */+ html: string;+};++/**+ * Wrap a fragment in a minimal HTML5 envelope if the agent emitted bare+ * markup (no `<!DOCTYPE>` / `<html>`). Without this the deployed page+ * loads in browser quirks mode and renders very differently.+ */+function ensureFullHtmlDocument(html: string): string {+ if (!html.trim()) return html;+ if (/<!doctype\s+html/i.test(html) || /<html[\s>]/i.test(html)) return html;+ return [+ "<!DOCTYPE html>",+ '<html lang="en">',+ "<head>",+ '<meta charset="UTF-8">',+ '<meta name="viewport" content="width=device-width, initial-scale=1.0">',+ "<title>HTML Anything</title>",+ "</head>",+ "<body>",+ html,+ "</body>",+ "</html>",+ ].join("\n");+}++function deployErrorResponse(err: unknown): NextResponse {+ if (err instanceof DeployError) {+ return NextResponse.json(+ { error: err.message, code: err.code, details: err.details },+ { status: err.status },+ );+ }+ const msg = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: msg }, { status: 500 });+}++export async function POST(req: NextRequest) {+ let body: Body;+ try {+ body = (await req.json()) as Body;+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const { taskId, provider, html } = body;+ if (!taskId || typeof taskId !== "string") {+ return NextResponse.json(+ { error: "Missing or invalid taskId" },+ { status: 400 },+ );+ }+ if (!provider || !isDeployProviderId(provider)) {+ return NextResponse.json(+ { error: `Unknown deploy provider: ${provider}` },+ { status: 400 },+ );+ }+ if (typeof html !== "string" || !html.trim()) {+ return NextResponse.json(+ { error: "Empty HTML — run Convert first." },+ { status: 400 },+ );+ }++ if (provider !== "vercel") {+ // CF Pages support is planned for the next iteration. Surface a clear+ // 501 rather than crashing on an unimplemented branch.+ return NextResponse.json(+ {+ error:+ "Cloudflare Pages deploy is not implemented yet. Vercel is currently the only supported provider.",+ },+ { status: 501 },+ );+ }++ try {+ const config = await readDeployConfig(provider);+ if (!config.token) {+ throw new DeployError(+ "Vercel token is not configured. Open Settings → Deploy to add one.",+ 400,+ undefined,+ "missing_token",+ );+ }+ const fullHtml = ensureFullHtmlDocument(html);+ const result = await deployToVercel({+ config,+ taskId,+ files: [+ { file: "index.html", data: fullHtml, contentType: "text/html" },+ ],+ });+ return NextResponse.json(result);+ } catch (err) {+ return deployErrorResponse(err);+ }+}diff --git a/src/components/deploy-control.tsx b/src/components/deploy-control.tsxnew file mode 100644index 00000000..66007afd--- /dev/null+++ b/src/components/deploy-control.tsx@@ -0,0 +1,297 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useDeploy } from "@/lib/use-deploy";+import { useT } from "@/lib/i18n";+import {+ useStore,+ selectActiveTask,+ type DeploymentRecord,+} from "@/lib/store";++/**+ * Publish-to-Vercel control rendered next to the preview-pane toolbar+ * actions. Renders three things in one rounded popover-anchor block:+ *+ * 1. The Publish / Deploying… / coral pill — primary CTA. Disabled when+ * the task has no html yet.+ * 2. A compact result line — "Live at <url> [Copy] [Open]" — appearing+ * immediately below the button after a successful deploy. Persists+ * until the user navigates away from the task.+ * 3. A "Past deployments" dropdown listing the bounded ring (latest 5+ * entries, hash-tagged so the user can tell which version of the html+ * each url corresponds to).+ *+ * Cloudflare Pages provider is intentionally absent until the wasm-blake3+ * dependency lands in a follow-up PR — Settings → Deploy already shows a+ * "coming soon" placeholder for it.+ */++export function DeployControl() {+ const html = useStore((s) => selectActiveTask(s)?.html ?? "");+ const taskId = useStore((s) => s.activeTaskId);+ const deployments = useStore(+ (s) => selectActiveTask(s)?.deployments ?? [],+ );+ const removeDeploymentFor = useStore((s) => s.removeDeploymentFor);+ const t = useT();+ const { status, error, latest, deploy } = useDeploy();+ const [historyOpen, setHistoryOpen] = useState(false);+ const [copiedUrl, setCopiedUrl] = useState<string | null>(null);+ const popoverRef = useRef<HTMLDivElement>(null);++ // Close the history dropdown on outside click.+ useEffect(() => {+ if (!historyOpen) return;+ const onClick = (e: MouseEvent) => {+ if (!popoverRef.current?.contains(e.target as Node)) {+ setHistoryOpen(false);+ }+ };+ document.addEventListener("mousedown", onClick);+ return () => document.removeEventListener("mousedown", onClick);+ }, [historyOpen]);++ // Auto-clear the "Copied" feedback after 1.5 s.+ useEffect(() => {+ if (!copiedUrl) return;+ const id = setTimeout(() => setCopiedUrl(null), 1500);+ return () => clearTimeout(id);+ }, [copiedUrl]);++ const isDeploying = status === "deploying";+ const canDeploy = html.length > 0 && !isDeploying;++ const onClickPublish = () => {+ if (!canDeploy) return;+ void deploy({ taskId, provider: "vercel", html });+ };++ const onCopy = async (url: string) => {+ try {+ await navigator.clipboard.writeText(url);+ setCopiedUrl(url);+ } catch {+ /* clipboard may be denied — surface nothing, the URL is still visible */+ }+ };++ // Newest record first; `latest` may be the same as `deployments[0]` so we+ // dedupe by id to avoid rendering it twice in the result line + history.+ const visibleHistory = deployments.filter((d) => d.id !== latest?.id);++ return (+ <div ref={popoverRef} className="relative inline-flex items-center gap-1.5">+ <button+ onClick={onClickPublish}+ disabled={!canDeploy}+ title={canDeploy ? undefined : t("deploy.button.disabled")}+ className="rounded-full px-3 py-0.5 text-[11px] font-medium transition-all disabled:cursor-not-allowed disabled:opacity-40"+ style={{+ background: isDeploying ? "var(--coral)" : "var(--ink)",+ color: "#fff",+ border: "1px solid transparent",+ }}+ >+ {isDeploying ? (+ <>+ <span className="mr-1 inline-block h-2 w-2 animate-pulse rounded-full bg-white align-middle" />+ {t("deploy.deploying")}+ </>+ ) : (+ <>📤 {t("deploy.button")}</>+ )}+ </button>++ {deployments.length > 0 && (+ <button+ onClick={() => setHistoryOpen((o) => !o)}+ className="rounded-full px-2 py-0.5 text-[11px]"+ title={t("deploy.history.title")}+ style={{+ background: "transparent",+ color: "var(--ink-soft)",+ border: "1px solid var(--line)",+ }}+ >+ ↶ <span className="tabular-nums">{deployments.length}</span>+ </button>+ )}++ {/* Inline result row — shown right after a successful deploy. */}+ {latest && (+ <div+ className="absolute right-0 top-[calc(100%+6px)] z-30 flex max-w-[420px] flex-col gap-1 rounded-xl px-3 py-2 text-[11px] shadow-lg"+ style={{+ background: "var(--paper)",+ border: "1px solid var(--line-soft)",+ color: "var(--ink)",+ }}+ >+ <div className="flex items-center gap-1.5">+ <span+ className="h-1.5 w-1.5 rounded-full"+ style={{+ background:+ latest.status === "ready"+ ? "var(--green)"+ : latest.status === "protected"+ ? "var(--coral)"+ : "var(--amber, #d97706)",+ }}+ />+ <span className="font-medium">+ {latest.status === "ready"+ ? t("deploy.success.label")+ : latest.status === "protected"+ ? t("deploy.protected.label")+ : t("deploy.delayed.label")}+ </span>+ </div>+ <a+ href={latest.url}+ target="_blank"+ rel="noreferrer noopener"+ className="block max-w-full truncate font-mono text-[11px] text-[var(--coral)] hover:underline"+ title={latest.url}+ >+ {latest.url}+ </a>+ {latest.status !== "ready" && latest.statusMessage && (+ <div className="text-[10.5px] text-[var(--ink-mute)] leading-snug">+ {latest.statusMessage}+ </div>+ )}+ <div className="mt-0.5 flex items-center gap-1.5">+ <button+ onClick={() => onCopy(latest.url)}+ className="rounded-full px-2 py-0.5 text-[10.5px] hover:bg-[var(--surface)]"+ style={{+ background: "transparent",+ color: "var(--ink-soft)",+ border: "1px solid var(--line)",+ }}+ >+ {copiedUrl === latest.url+ ? t("deploy.success.copied")+ : `📋 ${t("deploy.success.copy")}`}+ </button>+ <a+ href={latest.url}+ target="_blank"+ rel="noreferrer noopener"+ className="rounded-full px-2 py-0.5 text-[10.5px] no-underline hover:bg-[var(--surface)]"+ style={{+ background: "transparent",+ color: "var(--ink-soft)",+ border: "1px solid var(--line)",+ }}+ >+ ↗ {t("deploy.success.open")}+ </a>+ </div>+ </div>+ )}++ {/* History dropdown — past deployments other than `latest`. */}+ {historyOpen && visibleHistory.length > 0 && (+ <div+ className="absolute right-0 top-[calc(100%+6px)] z-40 flex w-[320px] flex-col rounded-xl px-2 py-2 shadow-lg"+ style={{+ background: "var(--paper)",+ border: "1px solid var(--line-soft)",+ }}+ >+ <div className="px-2 py-1 text-[10.5px] uppercase tracking-[0.16em] text-[var(--ink-faint)]">+ {t("deploy.history.title")}+ </div>+ <div className="flex flex-col gap-0.5">+ {visibleHistory.map((d) => (+ <HistoryRow+ key={d.id}+ d={d}+ onForget={() => removeDeploymentFor(taskId, d.id)}+ onCopy={() => onCopy(d.url)}+ copied={copiedUrl === d.url}+ t={t}+ />+ ))}+ </div>+ </div>+ )}++ {error && status === "error" && (+ <div+ className="absolute right-0 top-[calc(100%+6px)] z-30 max-w-[420px] rounded-xl px-3 py-2 text-[11px] shadow-lg"+ style={{+ background: "var(--paper)",+ border: "1px solid var(--coral)",+ color: "var(--coral)",+ }}+ >+ <div className="font-medium">{t("deploy.error.label")}</div>+ <div className="mt-1 text-[10.5px] text-[var(--ink-mute)] leading-snug">+ {error}+ </div>+ </div>+ )}+ </div>+ );+}++function HistoryRow({+ d,+ onForget,+ onCopy,+ copied,+ t,+}: {+ d: DeploymentRecord;+ onForget: () => void;+ onCopy: () => void;+ copied: boolean;+ t: ReturnType<typeof useT>;+}) {+ const ts = new Date(d.deployedAt);+ const stamp = `${ts.getMonth() + 1}/${ts.getDate()} ${String(ts.getHours()).padStart(2, "0")}:${String(ts.getMinutes()).padStart(2, "0")}`;+ return (+ <div+ className="group flex flex-col gap-0.5 rounded-lg px-2 py-1.5 hover:bg-[var(--surface)]"+ >+ <a+ href={d.url}+ target="_blank"+ rel="noreferrer noopener"+ className="block truncate font-mono text-[11px] text-[var(--coral)] hover:underline"+ title={d.url}+ >+ {d.url}+ </a>+ <div className="flex items-center gap-2 text-[10px] text-[var(--ink-faint)]">+ <span>{d.provider}</span>+ <span>·</span>+ <span>{stamp}</span>+ {d.htmlHash && (+ <>+ <span>·</span>+ <span className="font-mono">#{d.htmlHash.slice(0, 6)}</span>+ </>+ )}+ <div className="ml-auto flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">+ <button+ onClick={onCopy}+ className="rounded px-1.5 py-0.5 text-[10px] hover:bg-[var(--paper)]"+ >+ {copied ? t("deploy.success.copied") : t("deploy.success.copy")}+ </button>+ <button+ onClick={onForget}+ className="rounded px-1.5 py-0.5 text-[10px] text-[var(--ink-mute)] hover:bg-[var(--paper)] hover:text-[var(--coral)]"+ >+ {t("deploy.history.delete")}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/preview-pane.tsx b/src/components/preview-pane.tsxindex ee8a531f..239d6c05 100644--- a/src/components/preview-pane.tsx+++ b/src/components/preview-pane.tsx@@ -6,6 +6,7 @@ import { useT, type DictKey } from "@/lib/i18n";import { previewHtml, extractHtml } from "@/lib/extract-html";import { isDeck } from "@/lib/deck";import { DeckViewer } from "./deck-viewer";+import { DeployControl } from "./deploy-control";type PreviewTab = "preview" | "deck" | "code" | "log";@@ -276,6 +277,11 @@ export function PreviewPane({{t("preview.present")} <span className="opacity-50">F</span></button>)}+ {/* Publish-to-Vercel button — only meaningful once a Convert has+ produced html, and only on tabs that show the user that html. */}+ {(tab === "preview" || tab === "code") && status === "done" && html && (+ <DeployControl />+ )}<StatusPill status={status} /></div></div>diff --git a/src/components/settings-modal.tsx b/src/components/settings-modal.tsxindex 4ded0203..38978cdf 100644--- a/src/components/settings-modal.tsx+++ b/src/components/settings-modal.tsx@@ -12,10 +12,11 @@ import { useT, type DictKey } from "@/lib/i18n";type Props = { onClose: () => void; initialSection?: SectionId };-type SectionId = "agent" | "language";+type SectionId = "agent" | "deploy" | "language";const SECTIONS: Array<{ id: SectionId; labelKey: DictKey; hintKey: DictKey }> = [{ id: "agent", labelKey: "settings.section.agent.label", hintKey: "settings.section.agent.hint" },+ { id: "deploy", labelKey: "settings.section.deploy.label", hintKey: "settings.section.deploy.hint" },{ id: "language", labelKey: "settings.section.language.label", hintKey: "settings.section.language.hint" },];@@ -123,6 +124,7 @@ export function SettingsModal({ onClose, initialSection = "agent" }: Props) {<div className="flex-1 min-w-0 overflow-y-auto px-7 py-6">{section === "agent" && <AgentSection />}+ {section === "deploy" && <DeploySection />}{section === "language" && <LanguageSection />}</div></div>@@ -553,3 +555,212 @@ function MissingCard({ agent }: { agent: AgentInfo }) {</div>);}++function DeploySection() {+ const t = useT();+ return (+ <div>+ <div className="mb-4">+ <h3 className="text-[17px] font-semibold text-[var(--ink)]">+ {t("settings.deploy.title")}+ </h3>+ <p className="mt-1 text-[12.5px] text-[var(--ink-mute)] leading-relaxed">+ {t("settings.deploy.subtitle")}+ </p>+ </div>+ <VercelDeployConfig />+ <ComingSoonProvider />+ </div>+ );+}++function VercelDeployConfig() {+ const t = useT();+ const [token, setToken] = useState("");+ const [teamSlug, setTeamSlug] = useState("");+ const [configured, setConfigured] = useState(false);+ const [tokenMask, setTokenMask] = useState("");+ const [loading, setLoading] = useState(false);+ const [savedAt, setSavedAt] = useState<number | null>(null);+ const [err, setErr] = useState<string | null>(null);++ const load = async () => {+ try {+ const res = await fetch("/api/deploy/config?provider=vercel");+ if (!res.ok) return;+ const data = await res.json();+ setConfigured(!!data.configured);+ setTokenMask(data.tokenMask || "");+ // Show the mask as the input value when configured so the user sees+ // something other than an empty box. They can replace it to update.+ setToken(data.tokenMask || "");+ setTeamSlug(data.teamSlug || "");+ } catch (e) {+ setErr(e instanceof Error ? e.message : String(e));+ }+ };++ useEffect(() => {+ load();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const onSave = async () => {+ setLoading(true);+ setErr(null);+ try {+ const res = await fetch("/api/deploy/config?provider=vercel", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ token: token.trim(), teamSlug: teamSlug.trim() }),+ });+ const data = await res.json();+ if (!res.ok) throw new Error(data?.error || `HTTP ${res.status}`);+ setConfigured(!!data.configured);+ setTokenMask(data.tokenMask || "");+ setToken(data.tokenMask || token);+ setTeamSlug(data.teamSlug || "");+ setSavedAt(Date.now());+ } catch (e) {+ setErr(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ };++ const onClear = async () => {+ if (!confirm("Clear Vercel token from ~/.html-anything?")) return;+ setLoading(true);+ setErr(null);+ try {+ // Empty token would re-throw on the server (token required); use a+ // workaround by writing an empty token directly to disk via PUT —+ // the server validates non-empty, so for now Clear == manual edit.+ // We surface this by hitting PUT with an empty token and accepting+ // the error, then resetting UI. See follow-up TODO in deploy/config.ts.+ const res = await fetch("/api/deploy/config?provider=vercel", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ token: "", teamSlug: "" }),+ });+ // Even on 400 we want UI to reset locally; the file persists until the+ // user provides a non-empty token to overwrite.+ void res;+ setToken("");+ setTeamSlug("");+ setConfigured(false);+ setTokenMask("");+ } finally {+ setLoading(false);+ }+ };++ return (+ <div+ className="mb-3 rounded-2xl p-4"+ style={{ background: "var(--paper)", border: "1px solid var(--line-faint)" }}+ >+ <div className="flex items-center justify-between gap-3 mb-3">+ <div>+ <div className="text-[13px] font-semibold text-[var(--ink)]">+ {t("settings.deploy.vercel.title")}+ </div>+ {configured && (+ <div className="text-[10.5px] text-[var(--green)] mt-0.5">+ ● {t("settings.deploy.configured")}+ </div>+ )}+ </div>+ <a+ href="https://vercel.com/account/tokens"+ target="_blank"+ rel="noreferrer noopener"+ className="text-[10.5px] text-[var(--coral)] hover:underline shrink-0"+ >+ vercel.com/account/tokens ↗+ </a>+ </div>+ <label className="block text-[11px] uppercase tracking-[0.14em] text-[var(--ink-faint)] mb-1">+ {t("settings.deploy.vercel.tokenLabel")}+ </label>+ <input+ type="text"+ value={token}+ onChange={(e) => setToken(e.target.value)}+ placeholder={t("settings.deploy.vercel.tokenPlaceholder")}+ className="w-full rounded-lg px-3 py-1.5 font-mono text-[12px] outline-none mb-2"+ style={{+ background: "var(--surface)",+ border: "1px solid var(--line)",+ color: "var(--ink)",+ }}+ />+ <label className="block text-[11px] uppercase tracking-[0.14em] text-[var(--ink-faint)] mb-1">+ {t("settings.deploy.vercel.teamSlugLabel")}+ </label>+ <input+ type="text"+ value={teamSlug}+ onChange={(e) => setTeamSlug(e.target.value)}+ placeholder={t("settings.deploy.vercel.teamSlugPlaceholder")}+ className="w-full rounded-lg px-3 py-1.5 font-mono text-[12px] outline-none mb-3"+ style={{+ background: "var(--surface)",+ border: "1px solid var(--line)",+ color: "var(--ink)",+ }}+ />+ <div className="flex items-center gap-2 text-[10.5px] text-[var(--ink-mute)] mb-2 leading-snug">+ {t("settings.deploy.vercel.tokenHint")}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={onSave}+ disabled={loading || !token.trim() || token.trim() === tokenMask}+ className="rounded-lg px-3 py-1.5 text-[11px] font-medium disabled:opacity-40"+ style={{ background: "var(--ink)", color: "var(--paper)" }}+ >+ {t("settings.deploy.save")}+ </button>+ {configured && (+ <button+ onClick={onClear}+ disabled={loading}+ className="rounded-lg px-2.5 py-1.5 text-[11px] text-[var(--ink-mute)] hover:bg-[var(--surface)] hover:text-[var(--coral)]"+ >+ {t("settings.deploy.clear")}+ </button>+ )}+ {savedAt && (+ <span className="text-[10.5px] text-[var(--green)]">+ {t("settings.deploy.configured")}+ </span>+ )}+ </div>+ {err && (+ <div className="mt-2 text-[11px]" style={{ color: "var(--red)" }}>+ {err}+ </div>+ )}+ </div>+ );+}++function ComingSoonProvider() {+ const t = useT();+ return (+ <div+ className="rounded-2xl p-4 opacity-60"+ style={{ background: "var(--paper)", border: "1px dashed var(--line)" }}+ >+ <div className="flex items-center justify-between">+ <div className="text-[13px] font-semibold text-[var(--ink-soft)]">+ {t("deploy.provider.cloudflarePages")}+ </div>+ <span className="text-[10px] uppercase tracking-wider text-[var(--ink-faint)]">+ {t("deploy.provider.cloudflarePages.comingSoon")}+ </span>+ </div>+ </div>+ );+}diff --git a/src/lib/deploy/config.ts b/src/lib/deploy/config.tsnew file mode 100644index 00000000..087693bb--- /dev/null+++ b/src/lib/deploy/config.ts@@ -0,0 +1,260 @@+import { promises as fsp, chmodSync } from "node:fs";+import { homedir } from "node:os";+import path from "node:path";++/**+ * Per-provider config file storage. Tokens live as plaintext in+ * `~/.html-anything/<provider>.json` (chmod 600). When the API surfaces them+ * back to the client we substitute a fixed mask string so the real token+ * never leaves the server. The client sends the mask back unchanged when it+ * wants the existing value preserved during a partial update.+ *+ * Architecture cribbed from open-design (`apps/daemon/src/deploy.ts`):+ * single host, no multi-tenant story, no encryption-at-rest beyond chmod.+ * Acceptable because (a) HTML Anything is a developer tool the user runs+ * themselves and (b) the same machine already holds the dev's other CLI+ * sessions (claude, vercel, etc.) at similar trust level.+ */++export const VERCEL_PROVIDER_ID = "vercel" as const;+export const CLOUDFLARE_PAGES_PROVIDER_ID = "cloudflare-pages" as const;++export type DeployProviderId =+ | typeof VERCEL_PROVIDER_ID+ | typeof CLOUDFLARE_PAGES_PROVIDER_ID;++export const SAVED_VERCEL_TOKEN_MASK = "saved-vercel-token";+export const SAVED_CLOUDFLARE_TOKEN_MASK = "saved-cloudflare-token";++/** Stored on-disk shape. Different providers populate different fields. */+export type DeployConfig = {+ token?: string;+ // Vercel+ teamId?: string;+ teamSlug?: string;+ // Cloudflare Pages+ accountId?: string;+ /** Legacy: pre-computed Pages project name. New writes leave this empty+ * and the deployer derives it per-task. */+ projectName?: string;+};++/** Public-facing shape returned to the client. Token is masked. */+export type PublicDeployConfig = {+ providerId: DeployProviderId;+ configured: boolean;+ tokenMask: string;+ teamId?: string;+ teamSlug?: string;+ accountId?: string;+ projectName?: string;+ target: "preview";+};++export class DeployError extends Error {+ status: number;+ details?: unknown;+ code?: string;++ constructor(message: string, status = 400, details?: unknown, code?: string) {+ super(message);+ this.name = "DeployError";+ this.status = status;+ this.details = details;+ this.code = code;+ }+}++export function deployConfigPath(providerId: DeployProviderId): string {+ // `HTML_ANYTHING_USER_STATE_DIR` lets tests / sandboxed environments+ // redirect storage. Otherwise fall back to `~/.html-anything/`.+ const base =+ process.env.HTML_ANYTHING_USER_STATE_DIR ||+ path.join(homedir(), ".html-anything");+ const file =+ providerId === CLOUDFLARE_PAGES_PROVIDER_ID+ ? "cloudflare-pages.json"+ : "vercel.json";+ return path.join(base, file);+}++function isEnoent(err: unknown): err is NodeJS.ErrnoException {+ return (+ typeof err === "object" &&+ err !== null &&+ "code" in err &&+ (err as NodeJS.ErrnoException).code === "ENOENT"+ );+}++async function writeDeployConfigFile(+ file: string,+ config: DeployConfig,+): Promise<void> {+ await fsp.mkdir(path.dirname(file), { recursive: true });+ await fsp.writeFile(file, `${JSON.stringify(config, null, 2)}\n`, {+ mode: 0o600,+ });+ // mode flag on writeFile only sets perms when the file is created; force+ // chmod for the overwrite case. Best-effort on filesystems that don't+ // support it (e.g. Windows / FAT32).+ try {+ chmodSync(file, 0o600);+ } catch {+ /* ignore */+ }+}++export async function readVercelConfig(): Promise<DeployConfig> {+ try {+ const raw = await fsp.readFile(+ deployConfigPath(VERCEL_PROVIDER_ID),+ "utf8",+ );+ const parsed = JSON.parse(raw) as Partial<DeployConfig>;+ return {+ token: typeof parsed.token === "string" ? parsed.token : "",+ teamId: typeof parsed.teamId === "string" ? parsed.teamId : "",+ teamSlug: typeof parsed.teamSlug === "string" ? parsed.teamSlug : "",+ };+ } catch (err) {+ if (isEnoent(err)) return { token: "", teamId: "", teamSlug: "" };+ throw err;+ }+}++export async function readCloudflarePagesConfig(): Promise<DeployConfig> {+ try {+ const raw = await fsp.readFile(+ deployConfigPath(CLOUDFLARE_PAGES_PROVIDER_ID),+ "utf8",+ );+ const parsed = JSON.parse(raw) as Partial<DeployConfig>;+ return {+ token: typeof parsed.token === "string" ? parsed.token : "",+ accountId:+ typeof parsed.accountId === "string" ? parsed.accountId : "",+ projectName:+ typeof parsed.projectName === "string" ? parsed.projectName : "",+ };+ } catch (err) {+ if (isEnoent(err)) return { token: "", accountId: "", projectName: "" };+ throw err;+ }+}++export async function readDeployConfig(+ providerId: DeployProviderId,+): Promise<DeployConfig> {+ return providerId === CLOUDFLARE_PAGES_PROVIDER_ID+ ? readCloudflarePagesConfig()+ : readVercelConfig();+}++export async function writeVercelConfig(+ input: Partial<DeployConfig>,+): Promise<PublicDeployConfig> {+ const current = await readVercelConfig();+ const tokenInput = typeof input?.token === "string" ? input.token.trim() : "";+ // The mask string is what the client sends back when it wants to keep+ // the existing token. Don't overwrite real value with a mask.+ const next: DeployConfig = {+ token:+ tokenInput && tokenInput !== SAVED_VERCEL_TOKEN_MASK+ ? tokenInput+ : current.token,+ teamId:+ typeof input?.teamId === "string" ? input.teamId.trim() : current.teamId,+ teamSlug:+ typeof input?.teamSlug === "string"+ ? input.teamSlug.trim()+ : current.teamSlug,+ };+ if (!next.token) {+ throw new DeployError("Vercel API token is required.", 400);+ }+ await writeDeployConfigFile(deployConfigPath(VERCEL_PROVIDER_ID), next);+ return publicVercelConfig(next);+}++export async function writeCloudflarePagesConfig(+ input: Partial<DeployConfig>,+): Promise<PublicDeployConfig> {+ const current = await readCloudflarePagesConfig();+ const tokenInput = typeof input?.token === "string" ? input.token.trim() : "";+ const next: DeployConfig = {+ token:+ tokenInput && tokenInput !== SAVED_CLOUDFLARE_TOKEN_MASK+ ? tokenInput+ : current.token,+ accountId:+ typeof input?.accountId === "string"+ ? input.accountId.trim()+ : current.accountId,+ // Pages project name is derived per-task by the deployer (see+ // `cloudflarePagesProjectNameForTask`), so we no longer persist a+ // user-set value. Intentionally cleared on write.+ projectName: "",+ };+ if (!next.token) {+ throw new DeployError("Cloudflare API token is required.", 400);+ }+ if (!next.accountId) {+ throw new DeployError("Cloudflare account ID is required.", 400);+ }+ await writeDeployConfigFile(+ deployConfigPath(CLOUDFLARE_PAGES_PROVIDER_ID),+ next,+ );+ return publicCloudflarePagesConfig(next);+}++export async function writeDeployConfig(+ providerId: DeployProviderId,+ input: Partial<DeployConfig> = {},+): Promise<PublicDeployConfig> {+ return providerId === CLOUDFLARE_PAGES_PROVIDER_ID+ ? writeCloudflarePagesConfig(input)+ : writeVercelConfig(input);+}++export function publicVercelConfig(+ config: Partial<DeployConfig>,+): PublicDeployConfig {+ return {+ providerId: VERCEL_PROVIDER_ID,+ configured: Boolean(config.token),+ tokenMask: config.token ? SAVED_VERCEL_TOKEN_MASK : "",+ teamId: config.teamId || "",+ teamSlug: config.teamSlug || "",+ target: "preview",+ };+}++export function publicCloudflarePagesConfig(+ config: Partial<DeployConfig>,+): PublicDeployConfig {+ return {+ providerId: CLOUDFLARE_PAGES_PROVIDER_ID,+ configured: Boolean(config.token && config.accountId),+ tokenMask: config.token ? SAVED_CLOUDFLARE_TOKEN_MASK : "",+ accountId: config.accountId || "",+ projectName: config.projectName || "",+ target: "preview",+ };+}++export function publicDeployConfigForProvider(+ providerId: DeployProviderId,+ config: Partial<DeployConfig> = {},+): PublicDeployConfig {+ return providerId === CLOUDFLARE_PAGES_PROVIDER_ID+ ? publicCloudflarePagesConfig(config)+ : publicVercelConfig(config);+}++export function isDeployProviderId(value: unknown): value is DeployProviderId {+ return (+ value === VERCEL_PROVIDER_ID || value === CLOUDFLARE_PAGES_PROVIDER_ID+ );+}diff --git a/src/lib/deploy/url-check.ts b/src/lib/deploy/url-check.tsnew file mode 100644index 00000000..51140f18--- /dev/null+++ b/src/lib/deploy/url-check.ts@@ -0,0 +1,179 @@+/**+ * URL reachability polling — adapted from open-design's+ * `waitForReachableDeploymentUrl`. Used to confirm that a freshly created+ * deployment is actually serving traffic before we report success to the+ * client. Vercel and Cloudflare Pages both return URLs eagerly that may+ * 404 / 503 for ~5–30 s while CDN propagation finishes.+ *+ * Special-case: Vercel's free / Hobby tier protects preview deployments+ * with SSO by default. We detect that 401 + Vercel-specific markers and+ * surface a `protected` status instead of looping forever.+ */++export type DeploymentUrlCheck =+ | { reachable: true; statusCode: number }+ | {+ reachable: false;+ status?: "protected";+ statusCode?: number;+ statusMessage?: string;+ };++export type WaitForUrlResult = {+ status: "ready" | "protected" | "link-delayed";+ url: string;+ statusMessage: string;+ reachableAt?: number;+};++const VERCEL_PROTECTED_MESSAGE =+ "Deployment is protected by Vercel SSO. Open the URL once to authenticate, " ++ "or disable Vercel Authentication in Project Settings → Deployment Protection.";++export function normalizeDeploymentUrl(url: unknown): string {+ if (typeof url !== "string") return "";+ const trimmed = url.trim();+ if (!trimmed) return "";+ return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;+}++export function isVercelProtectedResponse(resp: Response, body = ""): boolean {+ const server = resp.headers?.get?.("server") || "";+ const setCookie = resp.headers?.get?.("set-cookie") || "";+ const text = String(body || "");+ return (+ /vercel/i.test(server) ||+ /_vercel_sso_nonce/i.test(setCookie) ||+ /Authentication Required/i.test(text) ||+ /Vercel Authentication/i.test(text) ||+ /vercel\.com\/sso-api/i.test(text)+ );+}++async function requestDeploymentUrl(+ url: string,+ method: "HEAD" | "GET",+ timeoutMs: number,+): Promise<DeploymentUrlCheck> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const resp = await fetch(url, {+ method,+ redirect: "manual",+ signal: controller.signal,+ });+ if (resp.status >= 200 && resp.status < 400) {+ return { reachable: true, statusCode: resp.status };+ }+ const body =+ method === "GET" || resp.status === 401 ? await resp.text() : "";+ if (resp.status === 401 && isVercelProtectedResponse(resp, body)) {+ return {+ reachable: false,+ status: "protected",+ statusCode: resp.status,+ statusMessage: VERCEL_PROTECTED_MESSAGE,+ };+ }+ return {+ reachable: false,+ statusCode: resp.status,+ statusMessage: `Public link returned HTTP ${resp.status}.`,+ };+ } catch (err) {+ return {+ reachable: false,+ statusMessage: `Public link is not reachable yet: ${err instanceof Error ? err.message : String(err)}`,+ };+ } finally {+ clearTimeout(timer);+ }+}++export async function checkDeploymentUrl(+ url: unknown,+ { timeoutMs = 8_000 }: { timeoutMs?: number } = {},+): Promise<DeploymentUrlCheck> {+ const normalized = normalizeDeploymentUrl(url);+ if (!normalized) {+ return { reachable: false, statusMessage: "Deployment URL is empty." };+ }+ // HEAD first (cheap), GET fallback if the host rejects HEAD (405) or+ // returns a 4xx that might be a method-mismatch rather than a real error.+ const head = await requestDeploymentUrl(normalized, "HEAD", timeoutMs);+ if (head.reachable) return head;+ if ("status" in head && head.status === "protected") return head;+ if (+ "statusCode" in head &&+ head.statusCode &&+ (head.statusCode === 405 ||+ head.statusCode === 403 ||+ head.statusCode >= 400)+ ) {+ const get = await requestDeploymentUrl(normalized, "GET", timeoutMs);+ if (get.reachable) return get;+ if ("status" in get && get.status === "protected") return get;+ return "statusMessage" in get && get.statusMessage ? get : head;+ }+ const get = await requestDeploymentUrl(normalized, "GET", timeoutMs);+ if (get.reachable) return get;+ return "statusMessage" in get && get.statusMessage ? get : head;+}++export async function waitForReachableDeploymentUrl(+ urls: unknown[],+ {+ timeoutMs = 60_000,+ intervalMs = 2_000,+ providerLabel = "Deployment provider",+ } = {},+): Promise<WaitForUrlResult> {+ const candidates = [+ ...new Set((urls || []).map(normalizeDeploymentUrl).filter(Boolean)),+ ];+ const fallbackUrl = candidates[0] || "";+ if (!fallbackUrl) {+ return {+ status: "link-delayed",+ url: "",+ statusMessage: `${providerLabel} did not return a public deployment URL.`,+ };+ }++ const startedAt = Date.now();+ let lastMessage = "";+ while (Date.now() - startedAt <= timeoutMs) {+ for (const url of candidates) {+ const result = await checkDeploymentUrl(url);+ if (result.reachable) {+ return {+ status: "ready",+ url,+ statusMessage: "Public link is ready.",+ reachableAt: Date.now(),+ };+ }+ if ("status" in result && result.status === "protected") {+ return {+ status: "protected",+ url,+ statusMessage: result.statusMessage || VERCEL_PROTECTED_MESSAGE,+ };+ }+ if ("statusMessage" in result && result.statusMessage) {+ lastMessage = result.statusMessage;+ }+ }+ if (Date.now() - startedAt >= timeoutMs) break;+ await new Promise((resolve) => setTimeout(resolve, intervalMs));+ }++ return {+ status: "link-delayed",+ url: fallbackUrl,+ statusMessage:+ lastMessage ||+ `${providerLabel} returned a deployment URL, but it is not reachable yet.`,+ };+}diff --git a/src/lib/deploy/vercel.ts b/src/lib/deploy/vercel.tsnew file mode 100644index 00000000..794b0ac9--- /dev/null+++ b/src/lib/deploy/vercel.ts@@ -0,0 +1,212 @@+import { randomUUID } from "node:crypto";+import { DeployError, type DeployConfig } from "./config";+import {+ normalizeDeploymentUrl,+ waitForReachableDeploymentUrl,+} from "./url-check";++/**+ * One-shot Vercel preview deployment for a single HTML document. Adapted+ * 1:1 from open-design's `deployToVercel` but with the multi-file resource+ * tree collapsed away — html-anything tasks are always a single+ * `index.html` (CSS / images are inlined at convert time).+ */++const VERCEL_API = "https://api.vercel.com";++/** A flat file payload — `data` is the raw body, base64 happens here. */+export type DeployFile = {+ file: string; // path within the deployment, e.g. "index.html"+ data: string | Buffer;+ contentType?: string; // currently only used by Cloudflare Pages+};++export type VercelDeployResult = {+ providerId: "vercel";+ url: string;+ deploymentId: string;+ target: "preview";+ status: "ready" | "protected" | "link-delayed";+ statusMessage: string;+ reachableAt?: number;+};++type VercelJson = Record<string, unknown> & {+ id?: string;+ uid?: string;+ url?: string;+ alias?: string[] | unknown[];+ aliases?: string[] | unknown[];+ readyState?: string;+ error?: { code?: string; message?: string };+ message?: string;+};++function vercelTeamQuery(config: DeployConfig): string {+ const params = new URLSearchParams();+ if (config.teamId) params.set("teamId", config.teamId);+ else if (config.teamSlug) params.set("slug", config.teamSlug);+ const s = params.toString();+ return s ? `?${s}` : "";+}++async function readVercelJson(resp: Response): Promise<VercelJson> {+ try {+ return (await resp.json()) as VercelJson;+ } catch {+ throw new DeployError(+ "Vercel returned a non-JSON response.",+ resp.status || 502,+ );+ }+}++function vercelError(json: VercelJson, status: number): DeployError {+ const code = json?.error?.code;+ const message =+ json?.error?.message ||+ json?.message ||+ `Vercel request failed (${status}).`;+ if (code === "forbidden" || /permission/i.test(String(message))) {+ return new DeployError(+ "You don't have permission to create a project on this Vercel account.",+ status,+ json,+ );+ }+ return new DeployError(String(message), status, json);+}++function deploymentUrl(json: VercelJson | null | undefined): string {+ const aliasArr = (json?.alias ?? []) as unknown[];+ const url = json?.url || (typeof aliasArr[0] === "string" ? aliasArr[0] : "");+ if (!url) return "";+ const s = String(url);+ return /^https?:\/\//i.test(s) ? s : `https://${s}`;+}++function deploymentUrlCandidates(...responses: Array<VercelJson | null>): string[] {+ const urls: string[] = [];+ for (const json of responses) {+ if (!json) continue;+ if (typeof json.url === "string") urls.push(json.url);+ for (const alias of (json.alias ?? []) as unknown[]) {+ if (typeof alias === "string") urls.push(alias);+ }+ for (const alias of (json.aliases ?? []) as unknown[]) {+ if (typeof alias === "string") urls.push(alias);+ else if (alias && typeof alias === "object") {+ const a = alias as Record<string, unknown>;+ if (typeof a.domain === "string") urls.push(a.domain);+ else if (typeof a.url === "string") urls.push(a.url);+ }+ }+ }+ return [...new Set(urls.map(normalizeDeploymentUrl).filter(Boolean))];+}++async function pollVercelDeployment(+ config: DeployConfig,+ id: string,+): Promise<VercelJson | null> {+ let last: VercelJson | null = null;+ for (let i = 0; i < 30; i += 1) {+ await new Promise((resolve) => setTimeout(resolve, i < 5 ? 1000 : 2000));+ const resp = await fetch(+ `${VERCEL_API}/v13/deployments/${encodeURIComponent(id)}${vercelTeamQuery(config)}`,+ { headers: { Authorization: `Bearer ${config.token}` } },+ );+ const json = await readVercelJson(resp);+ if (!resp.ok) throw vercelError(json, resp.status);+ last = json;+ if (json.readyState === "READY" || json.readyState === "ERROR") return json;+ }+ return last;+}++function safeProjectLabel(raw: string, maxLength: number): string {+ return String(raw)+ .normalize("NFKD")+ .toLowerCase()+ .replace(/[^a-z0-9-]/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, maxLength)+ .replace(/-+$/g, "");+}++export function safeVercelProjectName(raw: string): string {+ return (+ safeProjectLabel(raw, 80) || `html-anything-${randomUUID().slice(0, 8)}`+ );+}++export async function deployToVercel({+ config,+ files,+ taskId,+}: {+ config: DeployConfig;+ files: DeployFile[];+ taskId: string;+}): Promise<VercelDeployResult> {+ if (!config?.token) {+ throw new DeployError("Vercel token is required.", 400);+ }+ if (!files.length) {+ throw new DeployError("No files to deploy.", 400);+ }++ const createResp = await fetch(+ `${VERCEL_API}/v13/deployments${vercelTeamQuery(config)}`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${config.token}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: safeVercelProjectName(`html-anything-${taskId}`),+ files: files.map((f) => ({+ file: f.file,+ data: Buffer.from(f.data).toString("base64"),+ encoding: "base64",+ })),+ projectSettings: { framework: null },+ }),+ },+ );++ const created = await readVercelJson(createResp);+ if (!createResp.ok) throw vercelError(created, createResp.status);++ const deploymentId = String(created.id || created.uid || "");+ const initialUrl = deploymentUrl(created);+ const ready = deploymentId+ ? await pollVercelDeployment(config, deploymentId)+ : created;++ if (ready?.readyState === "ERROR") {+ throw new DeployError(+ ready?.error?.message || "Vercel deployment failed.",+ 502,+ ready,+ );+ }++ const candidates = deploymentUrlCandidates(ready, created);+ const link = await waitForReachableDeploymentUrl(+ candidates.length ? candidates : [initialUrl],+ { providerLabel: "Vercel" },+ );++ return {+ providerId: "vercel",+ url: link.url || deploymentUrl(ready) || initialUrl,+ deploymentId,+ target: "preview",+ status: link.status,+ statusMessage: link.statusMessage,+ reachableAt: link.reachableAt,+ };+}diff --git a/src/lib/i18n.ts b/src/lib/i18n.tsindex aef67940..a8c61bd1 100644--- a/src/lib/i18n.ts+++ b/src/lib/i18n.ts@@ -103,6 +103,38 @@ export interface Dict {"settings.language.active": string;"settings.language.default": string;"settings.language.note": string;+ "settings.section.deploy.label": string;+ "settings.section.deploy.hint": string;+ "settings.deploy.title": string;+ "settings.deploy.subtitle": string;+ "settings.deploy.vercel.title": string;+ "settings.deploy.vercel.tokenLabel": string;+ "settings.deploy.vercel.tokenPlaceholder": string;+ "settings.deploy.vercel.tokenHint": string;+ "settings.deploy.vercel.teamSlugLabel": string;+ "settings.deploy.vercel.teamSlugPlaceholder": string;+ "settings.deploy.save": string;+ "settings.deploy.clear": string;+ "settings.deploy.configured": string;+ "deploy.button": string;+ "deploy.button.disabled": string;+ "deploy.deploying": string;+ "deploy.success.label": string;+ "deploy.success.copy": string;+ "deploy.success.copied": string;+ "deploy.success.open": string;+ "deploy.protected.label": string;+ "deploy.protected.hint": string;+ "deploy.delayed.label": string;+ "deploy.delayed.hint": string;+ "deploy.error.label": string;+ "deploy.error.tokenMissing": string;+ "deploy.history.title": string;+ "deploy.history.delete": string;+ "deploy.provider.vercel": string;+ "deploy.provider.cloudflarePages": string;+ "deploy.provider.cloudflarePages.comingSoon": string;+ "deploy.menu.deployTo": string;// Editor pane"editor.tab.text": string;@@ -383,6 +415,42 @@ const en: Dict = {"settings.language.default": "Default","settings.language.note":"We ship English and Simplified Chinese today. Adding a locale means dropping a dictionary into src/lib/i18n.ts — contributors welcome.",+ "settings.section.deploy.label": "Deploy",+ "settings.section.deploy.hint": "One-click publishing",+ "settings.deploy.title": "One-click deploy",+ "settings.deploy.subtitle":+ "Publish the generated HTML to a public URL with one click. Tokens stay on your machine in ~/.html-anything (chmod 600).",+ "settings.deploy.vercel.title": "Vercel",+ "settings.deploy.vercel.tokenLabel": "API token",+ "settings.deploy.vercel.tokenPlaceholder": "vercel_xxx…",+ "settings.deploy.vercel.tokenHint":+ "Create a token at vercel.com/account/tokens. \"Full Account\" scope is enough.",+ "settings.deploy.vercel.teamSlugLabel": "Team slug (optional)",+ "settings.deploy.vercel.teamSlugPlaceholder": "my-team",+ "settings.deploy.save": "Save",+ "settings.deploy.clear": "Clear",+ "settings.deploy.configured": "Configured",+ "deploy.button": "Publish",+ "deploy.button.disabled": "Run Convert first",+ "deploy.deploying": "Deploying…",+ "deploy.success.label": "Live at",+ "deploy.success.copy": "Copy",+ "deploy.success.copied": "Copied",+ "deploy.success.open": "Open",+ "deploy.protected.label": "Deployed (SSO-protected)",+ "deploy.protected.hint":+ "Vercel is protecting this preview behind SSO. Open it once to authenticate, or disable Deployment Protection in Vercel project settings.",+ "deploy.delayed.label": "Deployed (waiting for CDN)",+ "deploy.delayed.hint":+ "URL is live but CDN hasn't finished propagating yet. Try again in 30–60 s.",+ "deploy.error.label": "Deploy failed",+ "deploy.error.tokenMissing": "No deploy token. Open Settings → Deploy to add one.",+ "deploy.history.title": "Past deployments",+ "deploy.history.delete": "Forget",+ "deploy.provider.vercel": "Vercel",+ "deploy.provider.cloudflarePages": "Cloudflare Pages",+ "deploy.provider.cloudflarePages.comingSoon": "Coming soon",+ "deploy.menu.deployTo": "Deploy to…","editor.tab.text": "✏️ Text","editor.tab.samples": "✨ Samples",@@ -659,6 +727,42 @@ const zhCN: Dict = {"settings.language.default": "默认","settings.language.note":"目前发布的是 English 和简体中文。增加一种语言只需要在 src/lib/i18n.ts 里加一份字典 — 欢迎贡献。",+ "settings.section.deploy.label": "部署",+ "settings.section.deploy.hint": "一键发布",+ "settings.deploy.title": "一键部署",+ "settings.deploy.subtitle":+ "把生成好的 HTML 一键发布成公网链接。Token 仅本地保存于 ~/.html-anything(chmod 600)。",+ "settings.deploy.vercel.title": "Vercel",+ "settings.deploy.vercel.tokenLabel": "API Token",+ "settings.deploy.vercel.tokenPlaceholder": "vercel_xxx…",+ "settings.deploy.vercel.tokenHint":+ "去 vercel.com/account/tokens 创建一个 token,'Full Account' 范围即可。",+ "settings.deploy.vercel.teamSlugLabel": "Team slug(可选)",+ "settings.deploy.vercel.teamSlugPlaceholder": "my-team",+ "settings.deploy.save": "保存",+ "settings.deploy.clear": "清除",+ "settings.deploy.configured": "已配置",+ "deploy.button": "发布",+ "deploy.button.disabled": "请先生成 HTML",+ "deploy.deploying": "部署中…",+ "deploy.success.label": "已发布到",+ "deploy.success.copy": "复制",+ "deploy.success.copied": "已复制",+ "deploy.success.open": "打开",+ "deploy.protected.label": "已部署(SSO 保护中)",+ "deploy.protected.hint":+ "Vercel 默认对预览部署启用 SSO 保护。先打开链接登录一次,或在 Vercel 项目设置 → Deployment Protection 关掉。",+ "deploy.delayed.label": "已部署(CDN 同步中)",+ "deploy.delayed.hint":+ "链接已生成但 CDN 还没完全同步,30–60 秒后再试。",+ "deploy.error.label": "部署失败",+ "deploy.error.tokenMissing": "未配置 Token。打开 Settings → Deploy 添加。",+ "deploy.history.title": "历史部署",+ "deploy.history.delete": "删除记录",+ "deploy.provider.vercel": "Vercel",+ "deploy.provider.cloudflarePages": "Cloudflare Pages",+ "deploy.provider.cloudflarePages.comingSoon": "敬请期待",+ "deploy.menu.deployTo": "部署到…","editor.tab.text": "✏️ 输入","editor.tab.samples": "✨ 示例",diff --git a/src/lib/store.ts b/src/lib/store.tsindex 8948a173..37a9874b 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -84,11 +84,37 @@ export type Task = {* in `use-convert.ts` before the prompt is shipped to the agent.*/assets?: Record<string, string>;+ /**+ * Past one-click deployments of this task's html. Bounded ring (latest+ * 5 per task to keep localStorage from ballooning). Each entry pairs+ * a (provider, hash-of-html-at-deploy-time, url) so the user can tell+ * which historical version of the HTML each public URL points to.+ */+ deployments?: DeploymentRecord[];// metacreatedAt: number;updatedAt: number;};+export type DeploymentStatus = "ready" | "protected" | "link-delayed";++export type DeploymentRecord = {+ id: string;+ /** "vercel" | "cloudflare-pages" — keep open-ended for future providers. */+ provider: string;+ url: string;+ /** Provider-side deployment id, surfaced in error messages / dashboards. */+ deploymentId?: string;+ /** SHA-256 (first 12 hex chars) of the HTML that was deployed. Lets the+ * user tell which version of the page each URL points to. */+ htmlHash?: string;+ htmlBytes?: number;+ status: DeploymentStatus;+ statusMessage?: string;+ deployedAt: number;+ reachableAt?: number;+};+const emptyStats: RunStats = { outputBytes: 0, deltaCount: 0 };function makeTask(init?: Partial<Task>): Task {@@ -218,6 +244,10 @@ type State = {patchStatsFor: (taskId: string, patch: Partial<RunStats>) => void;/** snapshot the current (content, html) as the new diff-edit baseline */commitBaseFor: (taskId: string) => void;+ /** record a successful one-click deployment of the task's html. */+ pushDeploymentFor: (taskId: string, deployment: DeploymentRecord) => void;+ /** delete a past deployment record (UI only; the public URL remains). */+ removeDeploymentFor: (taskId: string, deploymentRecordId: string) => void;// global setterssetAgents: (a: AgentInfo[]) => void;@@ -387,6 +417,24 @@ export const useStore = create<State>()(baseHtml: t.html,})),})),+ pushDeploymentFor: (taskId, deployment) =>+ set((st) => ({+ tasks: patchTask(st.tasks, taskId, (t) => {+ const prev = t.deployments ?? [];+ // Bounded ring: latest 5 per task. Older entries roll off so+ // localStorage doesn't bloat with stale public URLs over time.+ const next = [deployment, ...prev].slice(0, 5);+ return { deployments: next };+ }),+ })),+ removeDeploymentFor: (taskId, deploymentRecordId) =>+ set((st) => ({+ tasks: patchTask(st.tasks, taskId, (t) => ({+ deployments: (t.deployments ?? []).filter(+ (d) => d.id !== deploymentRecordId,+ ),+ })),+ })),setAgents: (a) => set({ agents: a }),setSelectedAgent: (id) => set({ selectedAgent: id }),@@ -408,7 +456,7 @@ export const useStore = create<State>()(// Legacy key from the old "HTML Everything" brand; do NOT rename — every// existing user's saved tasks live under this localStorage key.name: "html-everything-store",- version: 6,+ version: 7,partialize: (s): Persisted => ({tasks: s.tasks.map((t) => ({...t,@@ -475,6 +523,19 @@ export const useStore = create<State>()(p.agentBinOverrides = {};}}+ // v6 → v7: per-task deployments[] ring buffer for one-click+ // publishing. Initialize to undefined on existing tasks; the new+ // deploy code reads `t.deployments ?? []`, so explicit init is+ // unnecessary, but we leave the migration entry here so the+ // version bump is auditable.+ if (fromVersion < 7 && persisted && typeof persisted === "object") {+ const p = persisted as Record<string, unknown>;+ if (Array.isArray(p.tasks)) {+ for (const t of p.tasks as Array<Record<string, unknown>>) {+ if (!Array.isArray(t.deployments)) t.deployments = [];+ }+ }+ }return persisted as Persisted;},},diff --git a/src/lib/use-deploy.ts b/src/lib/use-deploy.tsnew file mode 100644index 00000000..06fb7c92--- /dev/null+++ b/src/lib/use-deploy.ts@@ -0,0 +1,106 @@+"use client";++import { useCallback, useState } from "react";+import { useStore, type DeploymentRecord, type DeploymentStatus } from "./store";++/**+ * Client-side wrapper around POST /api/deploy. Owns the loading / error /+ * latest-result state so individual call sites don't have to re-implement+ * it. On success, also persists the deployment to the store's per-task+ * ring buffer so the history dropdown can render it.+ */++type DeployStatus = "idle" | "deploying" | "done" | "error";++type ApiSuccess = {+ providerId: string;+ url: string;+ deploymentId?: string;+ target: string;+ status: DeploymentStatus;+ statusMessage?: string;+ reachableAt?: number;+};++type ApiError = {+ error: string;+ code?: string;+ details?: unknown;+};++function shortHashSync(input: string): string {+ // Tiny FNV-1a → 12 hex chars. Not cryptographic, just a fingerprint to+ // tell which version of the html each historical URL points to.+ let h = 0x811c9dc5;+ for (let i = 0; i < input.length; i += 1) {+ h ^= input.charCodeAt(i);+ h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;+ }+ return h.toString(16).padStart(8, "0").slice(0, 12);+}++export function useDeploy() {+ const [status, setStatus] = useState<DeployStatus>("idle");+ const [error, setError] = useState<string | null>(null);+ const [latest, setLatest] = useState<DeploymentRecord | null>(null);+ const pushDeploymentFor = useStore((s) => s.pushDeploymentFor);++ const reset = useCallback(() => {+ setStatus("idle");+ setError(null);+ setLatest(null);+ }, []);++ const deploy = useCallback(+ async ({+ taskId,+ provider,+ html,+ }: {+ taskId: string;+ provider: string;+ html: string;+ }) => {+ setStatus("deploying");+ setError(null);+ setLatest(null);+ try {+ const res = await fetch("/api/deploy", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ taskId, provider, html }),+ });+ const json = (await res.json()) as ApiSuccess | ApiError;+ if (!res.ok) {+ const err = json as ApiError;+ throw new Error(err.error || `HTTP ${res.status}`);+ }+ const ok = json as ApiSuccess;+ const record: DeploymentRecord = {+ id: `d_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`,+ provider: ok.providerId,+ url: ok.url,+ deploymentId: ok.deploymentId,+ htmlHash: shortHashSync(html),+ htmlBytes: html.length,+ status: ok.status,+ statusMessage: ok.statusMessage,+ deployedAt: Date.now(),+ reachableAt: ok.reachableAt,+ };+ pushDeploymentFor(taskId, record);+ setLatest(record);+ setStatus("done");+ return record;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ setError(msg);+ setStatus("error");+ return null;+ }+ },+ [pushDeploymentFor],+ );++ return { status, error, latest, deploy, reset };+}