Open source CapCut alternative.
TypeScript
feat(site): frame the projects home in the card
David Le1ff6d42098e3
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.tsindex b771e889..7dad1d3d 100644--- a/site/scripts/eval-chatgpt-widget.ts+++ b/site/scripts/eval-chatgpt-widget.ts@@ -55,7 +55,9 @@ const reply = (id, result) => frame.contentWindow.postMessage({jsonrpc:'2.0',id,// A card ChatGPT shows again after a reload replays its own result: a stale// preview with an expired playback link, and an editor link whose minute is// spent unless the fixture says the card was just opened.-const cardResult = () => !window.editable ? result(view(false)) : result(view(true,{id:'job',status:'done',progress:1,revision:'cloud:1'}),{url:location.origin+'/preview.mp4?stale',expiresAt:Date.now()-1},window.freshCard ? {url:location.origin+'/embed?embed=chatgpt&code='+ (window.signedOut ? 'signed-out' : 'card') +'&project=project',expiresAt:Date.now()+60000} : {url:location.origin+'/embed?embed=chatgpt&code=spent&project=project',expiresAt:Date.now()-1});+const cardResult = () => !window.editable ? result(view(true)) : result(view(true,{id:'job',status:'done',progress:1,revision:'cloud:1'}),{url:location.origin+'/preview.mp4?stale',expiresAt:Date.now()-1},window.freshCard ? {url:location.origin+'/embed?embed=chatgpt&code='+ (window.signedOut ? 'signed-out' : 'card') +'&project=project',expiresAt:Date.now()+60000} : {url:location.origin+'/embed?embed=chatgpt&code=spent&project=project',expiresAt:Date.now()-1});+// A tool result the host hands the card after it is open: the projects view.+window.showProjects = () => frame.contentWindow.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-result',params:result(view(false),null,window.editable ? {url:location.origin+'/embed?embed=chatgpt&code=one-use-'+ ++window.editorCodes,expiresAt:Date.now()+60000} : null)},'*');window.addEventListener('message', ({source,data}) => {if(source !== frame.contentWindow || !data.method) return;if(data.method === 'ui/initialize') reply(data.id,{protocolVersion:data.params.protocolVersion,hostInfo:{name:'fixture',version:'1'},hostCapabilities:{serverTools:{},openLinks:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:'light',displayMode:'inline',availableDisplayModes:['inline','fullscreen'],safeAreaInsets:{top:0,right:0,bottom:120,left:0}}});@@ -84,7 +86,6 @@ try {page.on("request", (request) => requests.push(request.url()));await page.goto(`http://localhost:${server.port}`);const app = page.frameLocator("iframe");- await app.getByRole("button", { name: "Launch film" }).click();await app.getByRole("button", { name: "Render preview", exact: true }).click();await app.locator("video").waitFor();const frame = page.frames().find((f) => f.url().endsWith("/widget"))!;@@ -102,18 +103,25 @@ try {await page.waitForFunction(() => (window as unknown as { links: string[] }).links.length === 1);assert.deepEqual(await page.evaluate(() => (window as unknown as { links: string[] }).links), ["https://donkeycut.com/app/p/project"]);await page.screenshot({ path: "/tmp/donkey-chatgpt-widget.png" });- await app.getByRole("button", { name: "Projects", exact: true }).click();+ // A read-only connection has no projects home to frame.+ await page.evaluate(() => (window as unknown as { showProjects: () => void }).showProjects());await app.locator("video").waitFor({ state: "detached" });- assert.equal(await app.locator("video").count(), 0, "project picker releases the video");- await page.evaluate(() => { (window as unknown as { editable: boolean }).editable = true; });- await app.getByRole("button", { name: "Launch film" }).click();- await app.frameLocator("iframe.editor").locator("#editor").waitFor();+ assert.equal(await app.locator("video").count(), 0, "the projects view releases the video");+ await app.getByRole("status").filter({ hasText: "Ask ChatGPT to open one of your projects" }).waitFor();+ assert.equal(await app.locator("iframe.editor").count(), 0, "a read-only projects card frames nothing");+ // An editing connection's projects view is the projects home, framed.+ await page.evaluate(() => { const host = window as unknown as { editable: boolean; showProjects: () => void }; host.editable = true; host.showProjects(); });+ await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "Editor for null" }).waitFor();await app.locator(".skeleton").waitFor({ state: "detached" });+ assert.equal(await app.locator("iframe.editor").getAttribute("aria-label"), "Your Donkey Cut projects");assert.deepEqual(await page.evaluate(() => (window as unknown as { modes: string[] }).modes), [], "an opened editor stays inline");- // A project picked in the card reaches the model, which never saw that call.- const contexts = await page.evaluate(() => (window as unknown as { contexts: { content?: unknown[]; structuredContent?: { projectId?: string } }[] }).contexts);- assert.deepEqual(contexts.at(-2)?.content, [], "the picker clears the card's context");- assert.equal(contexts.at(-1)?.structuredContent?.projectId, "project", "the model knows which project the card shows");+ // A project opened inside the frame reaches the model, which never saw that call.+ type Contexts = { contexts: { content?: unknown[]; structuredContent?: { projectId?: string; name?: string } }[] };+ assert.deepEqual(await page.evaluate(() => (window as unknown as Contexts).contexts.at(-1)?.content), [], "the projects home clears the card's context");+ const homeFrame = page.frames().find((f) => f.url().includes("/embed?"))!;+ await homeFrame.evaluate(() => parent.postMessage({ type: "donkeycut:page", projectId: "project", name: "Launch film" }, "*"));+ await page.waitForFunction(() => (window as unknown as Contexts).contexts.at(-1)?.structuredContent?.projectId === "project");+ assert.equal(await page.evaluate(() => (window as unknown as Contexts).contexts.at(-1)?.structuredContent?.name), "Launch film", "the model knows which project the frame shows");assert.equal(await app.locator("button").count(), 0, "the editor card has no controls of its own");assert.equal(await app.locator("main.editing").evaluate((m) => getComputedStyle(m).borderTopWidth), "0px", "an inline card keeps the host's own border");await app.frameLocator("iframe.editor").locator("#inset").filter({ hasText: /^0$/ }).waitFor();@@ -226,7 +234,6 @@ try {await frame.evaluate(() => { location.reload(); });await app.getByRole("status").filter({ hasText: "This project was deleted." }).waitFor();assert.equal(await app.locator("iframe.editor").count(), 0, "a deleted project shows no editor frame");- assert.equal(await app.getByText("Your projects").count(), 0, "a deleted project shows no projects home");await page.evaluate(() => { (window as unknown as Host).missing = false; });await app.getByRole("button", { name: "Create New Project", exact: true }).click();await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "one-use" }).waitFor();diff --git a/site/src/app/[locale]/cut/app/(home)/layout.tsx b/site/src/app/[locale]/cut/app/(home)/layout.tsxindex 21277025..c938da2c 100644--- a/site/src/app/[locale]/cut/app/(home)/layout.tsx+++ b/site/src/app/[locale]/cut/app/(home)/layout.tsx@@ -1,6 +1,6 @@import { Suspense } from "react";-import { AppSidebar } from "@/cut/components/AppSidebar";+import { HomeNav } from "@/cut/components/CardRail";import { ClaimCreditsDialog } from "@/cut/components/ClaimCreditsDialog";import { StorageUpgradeDialog } from "@/cut/components/StorageUpgradeDialog";import { UpgradeDialog } from "@/cut/components/UpgradeDialog";@@ -8,7 +8,7 @@ import { UpgradeDialog } from "@/cut/components/UpgradeDialog";export default function HomeLayout({ children }: { children: React.ReactNode }) {return (<div className="flex h-full bg-background">- <AppSidebar />+ <HomeNav /><main className="min-w-0 flex-1 overflow-y-auto">{children}</main>{/* Every home surface uploads — projects, library — so the quota wallanswers from the layout rather than from each page. */}diff --git a/site/src/app/[locale]/cut/app/layout.tsx b/site/src/app/[locale]/cut/app/layout.tsxindex 4f368cf5..c57462ff 100644--- a/site/src/app/[locale]/cut/app/layout.tsx+++ b/site/src/app/[locale]/cut/app/layout.tsx@@ -2,6 +2,7 @@ import { Suspense, type ReactNode } from "react";import { NoSessionReplay } from "@/app/_components/NoSessionReplay";import { NoTranslate } from "@/app/_components/NoTranslate";+import { CardHost } from "@/cut/components/CardHost";import { ConnectGate } from "@/cut/components/ConnectGate";import { ExportsDock } from "@/cut/components/ExportsDock";import { CutOnboarding } from "@/cut/components/onboarding/CutOnboarding";@@ -51,6 +52,7 @@ export default function CutAppLayout({ children }: { children: ReactNode }) {<Suspense fallback={<AppLoading />}><RequireSession><LocaleSync />+ <CardHost />{/* A phone gets the page that asks for a computer in the app's place. */}<PhoneGate><ConnectGate>diff --git a/site/src/clients/chatgpt/plugin.ts b/site/src/clients/chatgpt/plugin.tsindex a87475be..3de7d12c 100644--- a/site/src/clients/chatgpt/plugin.ts+++ b/site/src/clients/chatgpt/plugin.ts@@ -24,7 +24,7 @@ Open Donkey Cut from the sidebar or beside a conversation to pick a project, or// one comma-separated string.const POSITIVE = [{- description: "Lists the account's cloud projects and opens the picker.",+ description: "Lists the account's cloud projects and opens the projects home.",prompt: "Show me my Donkey Cut projects.",tools_triggered: "list_projects",expected_behavior: "Lists the connected account's cloud projects with their names, most recent first.",diff --git a/site/src/clients/chatgpt/server/embed.ts b/site/src/clients/chatgpt/server/embed.tsindex d9ce0184..40ffcd0b 100644--- a/site/src/clients/chatgpt/server/embed.ts+++ b/site/src/clients/chatgpt/server/embed.ts@@ -36,8 +36,9 @@ type RefusalKey = keyof Messages["chatgpt"]["embed"];type Refuse = (key: RefusalKey, status: number, retryAfter?: string) => Response;/**- * GET /api/chatgpt/embed?code=…&project=…: the card's frame redeems its one-use- * code for a session and lands on the editor. The session cookie is+ * GET /api/chatgpt/embed?code=…[&project=…]: the card's frame redeems its+ * one-use code for a session and lands on the editor, or on the projects home+ * when no project is named. The session cookie is* partitioned, so it exists only inside that frame under ChatGPT: the account's* own sign-in never crosses into the frame, and the frame's never leaves it.*/@@ -62,8 +63,8 @@ async function redeem(request: Request, refuse: Refuse) {if (limited) return refuse("tooMany", 429, limited.headers.get("Retry-After") ?? undefined);const params = new URL(request.url).searchParams;- const project = params.get("project") ?? "";- if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) return refuse("badRequest", 400);+ const project = params.get("project");+ if (project !== null && !/^[A-Za-z0-9_-]{1,128}$/.test(project)) return refuse("badRequest", 400);const redeemed = await redeemEditorCode(params.get("code") ?? "", config);if (!redeemed) return refuse("expired", 403);try {@@ -90,7 +91,7 @@ async function redeem(request: Request, refuse: Refuse) {headers: {...NO_STORE_HEADERS,"Set-Cookie": cookie,- Location: `${config.issuer}/app/p/${encodeURIComponent(project)}?embed=chatgpt`,+ Location: project === null ? `${config.issuer}/app?embed=chatgpt` : `${config.issuer}/app/p/${encodeURIComponent(project)}?embed=chatgpt`,},});}diff --git a/site/src/clients/chatgpt/server/mcp.test.ts b/site/src/clients/chatgpt/server/mcp.test.tsindex 2edf1a83..752fe614 100644--- a/site/src/clients/chatgpt/server/mcp.test.ts+++ b/site/src/clients/chatgpt/server/mcp.test.ts@@ -140,7 +140,7 @@ describe("ChatGPT MCP protocol", () => {destructiveHint: false,openWorldHint: false,});- // The sidebar and thread panel open the picker; the composer's @-menu+ // The sidebar and thread panel open the projects home; the composer's @-menu// searches projects through an app-only read.expect(tools.find((tool) => tool.name === "open_project")?._meta).toMatchObject({"openai/ui": { entrypoints: [{ type: "global" }, { type: "thread" }] },diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.tsindex fbd1264d..9a0cfb06 100644--- a/site/src/clients/chatgpt/server/mcp.ts+++ b/site/src/clients/chatgpt/server/mcp.ts@@ -194,7 +194,8 @@ export function createChatgptServer(const { view, playback, download, editor } = await projects.withEditor(await run());const media = liftMedia(view);liftDisplay(view);- const text = describeProjectView(view) + (editor ? "\nThe Donkey Cut editor is open in the card." : "");+ const opened = view.project ? "\nThe Donkey Cut editor is open in the card." : "\nThe Donkey Cut projects home is open in the card.";+ const text = describeProjectView(view) + (editor ? opened : "");return {content: [{ type: "text" as const, text }, ...media],structuredContent: view,@@ -235,12 +236,12 @@ export function createChatgptServer(server.registerTool("open_project",{- // The sidebar and the thread panel open the picker under this title and+ // The sidebar and the thread panel open the projects home under this title and// paint the donkey glyph in the menu's own ink.title: "Donkey Cut",icons: [{ src: `${config.issuer}/chatgpt-entry.svg`, mimeType: "image/svg+xml", sizes: ["any"] }],description:- "Open a cloud project initially, switch projects, or recover a missing card. Keep the existing card during edits and preview checks: reopening creates a fresh editor with empty undo history. The editable card holds the full editor, timeline, media panel, inspector and preview. A read-only connection sees the preview; use render_preview when its revision is stale or missing. With no projectId, show the project picker. A deleted project answers view \"missing\" and the card offers to create a new one.",+ "Open a cloud project initially, switch projects, or recover a missing card. Keep the existing card during edits and preview checks: reopening creates a fresh editor with empty undo history. The editable card holds the full editor, timeline, media panel, inspector and preview. A read-only connection sees the preview; use render_preview when its revision is stale or missing. With no projectId, show the projects home, where the user opens or starts a project or browses their library; the card then tells you which project it shows. A deleted project answers view \"missing\" and the card offers to create a new one.",inputSchema: z.object({ projectId: idSchema.optional() }),outputSchema: viewSchema,annotations: readOnlyAnnotations,@@ -535,7 +536,7 @@ export function createChatgptServer(// entrypoints always open fullscreen."openai/ui": { availableDisplayModes: ["inline", "fullscreen"], preferredDisplayMode: "inline" },"openai/widgetDescription":- "Donkey Cut cloud project picker and video preview with render progress, export download, and an Open in Donkey Cut link.",+ "Donkey Cut projects home and editor, or a video preview with render progress, export download, and an Open in Donkey Cut link.",},},],diff --git a/site/src/clients/chatgpt/server/projects.test.ts b/site/src/clients/chatgpt/server/projects.test.tsindex af565fc0..9e021beb 100644--- a/site/src/clients/chatgpt/server/projects.test.ts+++ b/site/src/clients/chatgpt/server/projects.test.ts@@ -133,12 +133,14 @@ describe("ChatGPT cloud projects", () => {expect(rendered.view.preview?.id).toBe("job");expect(rendered.playback?.url).toContain("proxy");});- test("a project card with write scope carries a one-use editor link; read scope and the list get none", async () => {+ test("a card with write scope carries a one-use link to the editor or the projects home; read scope gets none", async () => {const readOnly = createTestContext();expect((await readOnly.tools.withEditor(await readOnly.tools.status("mine"))).editor).toBeUndefined();+ expect((await readOnly.tools.withEditor(await readOnly.tools.list())).editor).toBeUndefined();expect(readOnly.db.chatgptToken.create).not.toHaveBeenCalled();const { tools, db } = createTestContext(["projects:read", "projects:write"]);- expect((await tools.withEditor(await tools.list())).editor).toBeUndefined();+ const home = await tools.withEditor(await tools.list());+ expect(/^https:\/\/donkeycut\.com\/api\/chatgpt\/embed\?code=[A-Za-z0-9_-]{43}$/.test(home.editor?.url ?? "")).toBe(true);const result = await tools.withEditor(await tools.status("mine"));expect(/^https:\/\/donkeycut\.com\/api\/chatgpt\/embed\?code=[A-Za-z0-9_-]{43}&project=mine$/.test(result.editor?.url ?? "")).toBe(true);expect(db.chatgptToken.create.mock.calls[0][0].data).toMatchObject({ grantId: "grant", kind: "embed" });diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.tsindex eb9345f3..dda8c4ca 100644--- a/site/src/clients/chatgpt/server/projects.ts+++ b/site/src/clients/chatgpt/server/projects.ts@@ -427,13 +427,16 @@ export function projectTools(if (!row) return { view: { ...emptyProjectView(), view: "missing", missing: { id: projectId } }, playback: null };return previewStatus(row);},- /** A project card is the full editor, signed in through a one-use link,- * whenever the connection can edit; a read-only one shows the preview. */+ /** A project card is the full editor, and a projects card is the+ * projects home, signed in through a one-use link whenever the connection+ * can edit; a read-only one shows the preview. */async withEditor(result: ProjectResult): Promise<ProjectResult> {const projectId = result.view.project?.id;- if (!canEdit || !projectId || result.editor) return result;+ const home = result.view.view === "projects";+ if (!canEdit || (!projectId && !home) || result.editor) return result;const code = await createEditorCode(identity.grantId, db);- const url = `${config.issuer}/api/chatgpt/embed?code=${code}&project=${encodeURIComponent(projectId)}`;+ const target = projectId ? `&project=${encodeURIComponent(projectId)}` : "";+ const url = `${config.issuer}/api/chatgpt/embed?code=${code}${target}`;return { ...result, editor: { url, expiresAt: Date.now() + 60_000 } };},async render(projectId: string): Promise<ProjectResult> {diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsxindex 9e25cff4..c0388813 100644--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx@@ -1,12 +1,14 @@import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";import { useEffect, useRef, useState } from "react";import { useTranslations } from "use-intl";-import { useProjectApp, type HostEdges, type HostTheme } from "./useProjectApp";+import { useProjectApp, type FramePage, type HostEdges, type HostTheme } from "./useProjectApp";import "./preview.css";export function PreviewApp() {- const { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject } = useProjectApp();+ const { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject, framePage } = useProjectApp();const project = view?.project;+ // An editable projects card is the projects home, framed like the editor.+ const home = view?.view === "projects" && view.canEdit;const preview = view?.preview;const rendering = preview?.status === "queued" || preview?.status === "running";// The frame whose editor has said it is on screen.@@ -26,37 +28,30 @@ export function PreviewApp() {</div></main>;}- // An editable project is the editor, and its own chrome carries every- // control. The card holds the editor's inline space from the first paint,- // so a card ChatGPT shows again after a reload is the editor while it- // fetches a fresh link. The editor's skeleton covers the frame until the- // frame reports something to see.- if (view ? project && view.canEdit : !error) {+ // An editable project is the editor, and an editable projects card is the+ // projects home; their own chrome carries every control. The card holds the+ // editor's inline space from the first paint, so a card ChatGPT shows again+ // after a reload is the editor while it fetches a fresh link. A skeleton in+ // the page's shape covers the frame until the frame reports something to see.+ if (view ? (project && view.canEdit) || home : !error) {const loading = !editor || shown !== editor.url;return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} style={edgePadding(edges)} aria-busy={loading}>- {editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} theme={theme} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}+ {editor && (project || home) && <EditorFrame key={editor.url} url={editor.url} label={project ? t("editing", { name: project.name }) : t("home")} inset={hostInset} theme={theme} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onPage={framePage} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}{downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>{t("dismiss")}</button></div>}- {error && project && !editor+ {error && (project || home) && !editor? <div className="waiting"><p role="alert">{problem}</p><button disabled={busy || !ready} onClick={retryEditor}>{t("tryAgain")}</button></div>- : loading && <EditorSkeleton />}+ : loading && (home ? <HomeSkeleton /> : <EditorSkeleton />)}</main>;}- return <main style={pickerPadding(edges, hostInset)} aria-busy={busy}>+ // A read-only connection has no projects home: the model opens a project+ // and the card plays its preview.+ return <main style={cardPadding(edges, hostInset)} aria-busy={busy}>{problem && <p role="alert" className="error">{problem}</p>}- {!view && <p role="status">{ready ? t("chooseProject") : t("connecting")}</p>}- {!view && ready && <button onClick={() => void run("list_projects", {})}>{t("loadProjects")}</button>}- {view?.view === "projects" && <>- <h1>{t("yourProjects")}</h1>- {view.projects.length === 0 && <p>{t("noProjects")}</p>}- <div className="projects">{view.projects.map((p) => <button key={p.id} disabled={busy || !ready} onClick={() => void run("open_project", { projectId: p.id })}>- <span>{p.name}</span><span aria-hidden="true">→</span>- </button>)}</div>- <nav>{view.nextCursor && <button disabled={busy} onClick={() => void run("list_projects", { cursor: view.nextCursor! })}>{t("moreProjects")}</button>}- <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>{t("refreshList")}</button></nav>- </>}+ {!view && ready && <button onClick={() => void run("open_project", {})}>{t("tryAgain")}</button>}+ {view?.view === "projects" && <p role="status">{t("readOnlyHome")}</p>}{project && <><h1>{project.name}</h1>{playback && <ArtifactVideo src={playback.url} format="file" active={visible} onError={playbackFailed} aria-label={t("previewOf", { name: project.name })} />}@@ -68,7 +63,6 @@ export function PreviewApp() {<nav>{view.canRender && <button className="primary" disabled={busy || rendering || !ready} onClick={() => void run("render_preview", { projectId: project.id })}>{t("renderPreview")}</button>}<button disabled={!ready} onClick={() => openDonkey()}>{t("openInDonkey")}</button>- <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>{t("projects")}</button>{error && <button disabled={busy || !ready} onClick={() => void run("open_project", { projectId: project.id })}>{t("tryAgain")}</button>}</nav></>}@@ -78,14 +72,14 @@ export function PreviewApp() {/** Keeps the editor out of the bands the host draws over. */const edgePadding = (edges: HostEdges) => ({ paddingTop: edges.top, paddingRight: edges.right, paddingLeft: edges.left });-/** The picker's own 20px margin inside those bands, with its last rows+/** The preview card's own 20px margin inside those bands, with its last rows* scrolling clear of the host's composer. */-const PICKER_GAP = 20;-const pickerPadding = (edges: HostEdges, bottom: number) => ({- paddingTop: PICKER_GAP + edges.top,- paddingRight: PICKER_GAP + edges.right,- paddingBottom: PICKER_GAP + bottom,- paddingLeft: PICKER_GAP + edges.left,+const CARD_GAP = 20;+const cardPadding = (edges: HostEdges, bottom: number) => ({+ paddingTop: CARD_GAP + edges.top,+ paddingRight: CARD_GAP + edges.right,+ paddingBottom: CARD_GAP + bottom,+ paddingLeft: CARD_GAP + edges.left,});/** The editor's shape in the host's theme while it loads: the top bar, the tab@@ -103,14 +97,23 @@ function EditorSkeleton() {</div>;}-/** The editor, framed. It learns the host's display mode, its theme and how+/** The projects home's shape while it loads: the card rail and a shelf of+ * project tiles. */+function HomeSkeleton() {+ const t = useTranslations("chatgpt.widget");+ return <div className="skeleton home" role="status" aria-label={t("openingHome")}>+ <div className="rail">{[0, 1, 2].map((i) => <i key={i} className="slab" />)}</div>+ <div className="tiles"><i className="slab head" />{[0, 1, 2, 3, 4, 5].map((i) => <i key={i} className="slab" />)}</div>+ </div>;+}++/** The editor, or the projects home, framed. It learns the host's display mode, its theme and how* tall the bottom overlay is when it loads, whenever that changes, and whenever it* asks; it says when it has something on screen, and its own toolbar asks* for fullscreen, for a tab on donkeycut.com, and for the saves the sandbox* blocks inside the frame. */-function EditorFrame({ url, name, inset, theme, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; name: string; inset: number; theme: HostTheme; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void; onReconnect: () => void }) {+function EditorFrame({ url, label, inset, theme, fullscreen, onReady, onPage, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; label: string; inset: number; theme: HostTheme; fullscreen: boolean; onReady: () => void; onPage: (url: string, page: FramePage) => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void; onReconnect: () => void }) {const frame = useRef<HTMLIFrameElement>(null);- const t = useTranslations("chatgpt.widget");const origin = new URL(url).origin;const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, theme, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);useEffect(tell, [inset, theme, fullscreen, origin]);@@ -119,6 +122,11 @@ function EditorFrame({ url, name, inset, theme, fullscreen, onReady, onFullscreeif (event.origin !== origin || event.source !== frame.current?.contentWindow) return;if (event.data?.type === "donkeycut:host?") tell();if (event.data?.type === "donkeycut:ready") onReady();+ // The page the frame moved to on its own: a project, or null for home.+ if (event.data?.type === "donkeycut:page") {+ const { projectId, name: projectName } = event.data as { projectId?: unknown; name?: unknown };+ if (projectId === null || typeof projectId === "string") onPage(url, { projectId, name: typeof projectName === "string" ? projectName : null });+ }if (event.data?.type === "donkeycut:fullscreen") onFullscreen();if (event.data?.type === "donkeycut:reconnect") onReconnect();if (event.data?.type === "donkeycut:download-error" && (event.data.message === null || typeof event.data.message === "string")) onDownloadError(event.data.message);@@ -137,5 +145,5 @@ function EditorFrame({ url, name, inset, theme, fullscreen, onReady, onFullscreewindow.addEventListener("message", onMessage);return () => window.removeEventListener("message", onMessage);});- return <iframe ref={frame} className="editor" src={url} onLoad={tell} aria-label={t("editing", { name })} allow="fullscreen; clipboard-read; clipboard-write" />;+ return <iframe ref={frame} className="editor" src={url} onLoad={tell} aria-label={label} allow="fullscreen; clipboard-read; clipboard-write" />;}diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.cssindex 78758089..2e9813be 100644--- a/site/src/clients/chatgpt/ui/preview.css+++ b/site/src/clients/chatgpt/ui/preview.css@@ -3,13 +3,15 @@/* The editor's own surfaces (globals.css), light and dark, so the frame and its skeleton match the editor they hold. */:root{--bar-edge:#e5e5e5;--editor-bg:#fff;--editor-fg:#20201e;--editor-edge:#e5e5e5;--slab:#eaeaec;--slab-pulse:#dcdce1;--slab-highlight:#f5f5f6}:root[data-theme=dark]{--bar-edge:#2e2e2e;--editor-bg:#0a0a0a;--editor-fg:#fafafa;--editor-edge:#ffffff1a;--slab:#262626;--slab-pulse:#1e1e1e;--slab-highlight:#3b3b3b}-*{box-sizing:border-box}body{margin:0}main{padding:20px;max-width:840px;margin:auto}h1{font-size:22px;line-height:1.2;margin:0 0 16px;overflow-wrap:anywhere}video{width:100%;max-height:65vh;display:block;border-radius:12px;background:#000}button{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 14px;cursor:pointer}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:2px solid #5d80cc;outline-offset:3px}.primary{background:#eac36a;color:#242018;border-color:#eac36a}nav{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px}.projects{display:grid;gap:8px}.projects button{display:flex;justify-content:space-between;gap:16px;text-align:left}.projects button span:first-child{overflow-wrap:anywhere;min-width:0}.muted{color:var(--muted);font-size:12px}.error{color:#ba453b}progress{width:100%;accent-color:#d8a743}p{overflow-wrap:anywhere}+*{box-sizing:border-box}body{margin:0}main{padding:20px;max-width:840px;margin:auto}h1{font-size:22px;line-height:1.2;margin:0 0 16px;overflow-wrap:anywhere}video{width:100%;max-height:65vh;display:block;border-radius:12px;background:#000}button{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 14px;cursor:pointer}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:2px solid #5d80cc;outline-offset:3px}.primary{background:#eac36a;color:#242018;border-color:#eac36a}nav{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px}.muted{color:var(--muted);font-size:12px}.error{color:#ba453b}progress{width:100%;accent-color:#d8a743}p{overflow-wrap:anywhere}.editing{padding:0;max-width:none;position:relative;height:560px;background:var(--editor-bg);color:var(--editor-fg)}[data-mode=fullscreen].editing{height:100vh;border-top:1px solid var(--bar-edge)}.editor{display:block;width:100%;height:100%;border:0;background:var(--editor-bg)}.waiting,.skeleton{position:absolute;inset:0;background:var(--editor-bg)}.waiting{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:20px;text-align:center}.download-error{position:absolute;top:12px;left:12px;right:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px;background:var(--panel);border:1px solid var(--line);border-radius:10px}.download-error p{margin:0}.skeleton{display:grid;grid-template:46px minmax(0,1fr) min(272px,55%)/68px minmax(0,1fr);overflow:hidden;--edge:1px solid var(--editor-edge)}.bar{grid-column:1/-1;display:flex;align-items:center;gap:10px;padding:0 12px;border-bottom:var(--edge)}.bar span{flex:1}.bar .slab{height:22px;width:64px}.bar .slab:first-child{width:22px}.bar .slab:nth-child(2){width:140px}.bar .slab:last-child{width:84px}.rail{display:flex;flex-direction:column;align-items:center;gap:16px;padding-top:12px;border-right:var(--edge);overflow:hidden}.rail .slab{flex:none;width:36px;height:36px;border-radius:8px}.stage{display:grid;place-items:center;padding:16px;min-height:0}.stage .slab{height:100%;max-width:100%;aspect-ratio:16/9;border-radius:4px}.timeline{grid-column:1/-1;display:flex;flex-direction:column;gap:10px;padding:10px 12px;border-top:var(--edge);overflow:hidden}.controls{display:flex;justify-content:center;gap:10px;margin-bottom:6px}.controls .slab{width:28px;height:22px}.track{display:flex;gap:4px;flex:none}.track .slab{height:40px;width:34%}.track .slab:last-child{width:22%}.track:nth-child(3) .slab:first-child{width:52%}.track:nth-child(4) .slab:first-child{width:18%;margin-left:12%}.track:nth-child(4) .slab:last-child{width:28%}+/* The projects home: the card rail beside a shelf of tiles. */+.skeleton.home{grid-template:minmax(0,1fr)/68px minmax(0,1fr)}.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));align-content:start;gap:16px;padding:28px 32px;overflow:hidden}.tiles .slab{aspect-ratio:16/10;border-radius:12px}.tiles .head{grid-column:1/-1;width:120px;height:22px;aspect-ratio:auto}/* The site's skeleton (globals.css): an opaque slab breathing between two neutrals with a highlight sweeping across it. */.slab{display:block;position:relative;overflow:hidden;border-radius:6px;background:var(--slab);animation:slab-pulse 1.6s ease-in-out infinite}.slab::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,var(--slab-highlight) 50%,transparent);animation:slab-shimmer 1.6s ease-in-out infinite}@keyframes slab-shimmer{0%{transform:translateX(-100%)}to{transform:translateX(100%)}}@keyframes slab-pulse{0%,to{background-color:var(--slab)}50%{background-color:var(--slab-pulse)}}@media (prefers-reduced-motion:reduce){.slab,.slab::after{animation:none}}diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.tsindex bf341634..34dd6557 100644--- a/site/src/clients/chatgpt/ui/useProjectApp.ts+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts@@ -31,6 +31,15 @@ export type HostTheme = "light" | "dark";export type HostEdges = { top: number; right: number; left: number };const NO_EDGES: HostEdges = { top: 0, right: 0, left: 0 };+/** The page the frame shows after moving on its own: a project, or null on+ * the projects home. */+export type FramePage = { projectId: string | null; name: string | null };++/** What a frame link opens: a project id, or HOME for the projects home. No+ * project id is empty, so the two never collide. */+const HOME = "";+const openArgs = (target: string): Record<string, string> => (target === HOME ? {} : { projectId: target });+/** The host carries authentication; the iframe only calls the MCP Apps bridge. */export function useProjectApp() {const appRef = useRef<App | null>(null);@@ -44,6 +53,8 @@ export function useProjectApp() {const [edges, setEdges] = useState<HostEdges>(NO_EDGES);const [theme, setTheme] = useState<HostTheme>("light");const [editorRequest, setEditorRequest] = useState<string | null>(null);+ // Tied to the frame that reported it, so a new frame starts from its link.+ const [page, setPage] = useState<{ url: string } & FramePage | null>(null);const requested = useRef<string | null>(null);const reconnecting = useRef(false);const [error, setError] = useState<CardProblem | null>(null);@@ -58,19 +69,21 @@ export function useProjectApp() {if (result.isError) throw new CardError("requestFailed");const parsed = viewSchema.safeParse(result.structuredContent);if (!parsed.success) throw new CardError("unreadable");- // An editable project is the editor. Its link is good for one minute, so- // the card's own result counts it only inside that minute.- const editable = parsed.data.canEdit && parsed.data.project ? parsed.data.project.id : null;+ // An editable project is the editor and an editable projects view is the+ // projects home. A link is good for one minute, so the card's own result+ // counts it only inside that minute.+ const home = parsed.data.view === "projects" ? HOME : null;+ const editable = parsed.data.canEdit ? parsed.data.project?.id ?? home : null;const embed = editorSchema.safeParse(result._meta?.editor);const link = embed.success && (origin !== "card" || embed.data.expiresAt > Date.now()) ? embed.data : null;- if (origin === "call" && editable && !link) throw new CardError("editorFailed");+ if (origin === "call" && editable !== null && !link) throw new CardError("editorFailed");const media = playbackSchema.safeParse(result._meta?.playback);const interval = result._meta?.pollMs;if (typeof interval === "number" && interval >= 1000 && interval <= 30000) setPollMs(interval);setView(parsed.data);setPlayback(media.success ? media.data : null);- if (editable && link) setEditor((current) => current ?? link);- setEditorRequest(editable && !link ? editable : null);+ if (editable !== null && link) setEditor((current) => current ?? link);+ setEditorRequest(editable !== null && !link ? editable : null);setError(null);}, []);@@ -151,22 +164,26 @@ export function useProjectApp() {return () => window.clearTimeout(timeout);}, [ready, visible, busy, error, framed, projectId, jobId, status, playback, pollMs, run, view]);- // The model sees the tool calls it made, never a project picked in the- // card, so the card tells it what it shows. "Make this square" then edits- // the project on screen, e.g. one opened from the Codex sidebar.- const projectName = view?.project?.name;+ // The model sees the tool calls it made, never a project opened inside the+ // card, so the card tells it what the frame shows. "Make this square" then+ // edits the project on screen, e.g. one opened from the projects home.+ const reported = page && page.url === editor?.url ? page : null;+ const shownId = reported ? reported.projectId : projectId ?? null;+ const shownName = reported ? reported.name ?? (shownId === projectId ? view?.project?.name : null) : view?.project?.name;+ const framePage = useCallback((url: string, next: FramePage) => { setPage({ url, ...next }); }, []);useEffect(() => {const app = appRef.current;if (!app || !ready || !view || !app.getHostCapabilities()?.updateModelContext) return;- // The picker clears what the card said, so the composer carries no chip- // until a project opens.- if (!projectId) {+ // The projects home clears what the card said, so the composer carries no+ // chip until a project opens.+ if (!shownId) {void app.updateModelContext({ content: [] }).catch(() => {});return;}- const text = `The Donkey Cut card shows the project "${projectName}" (projectId ${projectId}). Requests about this project or video mean this one.`;- void app.updateModelContext({ content: [{ type: "text", text }], structuredContent: { projectId, name: projectName } }).catch(() => {});- }, [ready, view, projectId, projectName]);+ const named = shownName ? `"${shownName}" ` : "";+ const text = `The Donkey Cut card shows the project ${named}(projectId ${shownId}). Requests about this project or video mean this one.`;+ void app.updateModelContext({ content: [{ type: "text", text }], structuredContent: { projectId: shownId, name: shownName ?? null } }).catch(() => {});+ }, [ready, view, shownId, shownName]);const playbackFailed = useCallback(() => {if (!projectId || !jobId) return;@@ -200,18 +217,20 @@ export function useProjectApp() {}, []);useEffect(() => {- if (!ready || !editorRequest || editor || requested.current === editorRequest) return;+ if (!ready || editorRequest === null || editor || requested.current === editorRequest) return;requested.current = editorRequest;- void run("open_project", { projectId: editorRequest }, false);+ void run("open_project", openArgs(editorRequest), false);}, [ready, editorRequest, editor, run]);- /** A fresh one-use link replaces the frame and renews its session cookie. */+ /** A fresh one-use link replaces the frame and renews its session cookie,+ * on the page the frame was showing. */const retryEditor = () => {- if (!ready || busy || reconnecting.current || !projectId) return;+ const target = reported ? reported.projectId ?? HOME : projectId ?? (view?.view === "projects" ? HOME : null);+ if (!ready || busy || reconnecting.current || target === null) return;reconnecting.current = true;- requested.current = projectId;+ requested.current = target;setEditorRequest(null);setEditor(null);- void run("open_project", { projectId }).finally(() => { reconnecting.current = false; });+ void run("open_project", openArgs(target)).finally(() => { reconnecting.current = false; });};/** The way forward from a project the account no longer has: a new cloud@@ -230,5 +249,5 @@ export function useProjectApp() {setHostInset(full ? (app.getHostContext()?.safeAreaInsets?.bottom ?? 120) : 0);} catch { /* the inline card still works */ }}, []);- return { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject };+ return { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject, framePage };}diff --git a/site/src/cut/components/CardHost.tsx b/site/src/cut/components/CardHost.tsxnew file mode 100644index 00000000..3ebb44a3--- /dev/null+++ b/site/src/cut/components/CardHost.tsx@@ -0,0 +1,27 @@+"use client";++import { useEffect } from "react";+import { usePathname } from "next/navigation";+import { reportHostPage, useHostBridge } from "@/cut/lib/hostBridge";+import { useEditor } from "@/cut/lib/store";++// The editor's address names its project: /app/p/<id>.+const PROJECT_PATH = /\/p\/([^/?#]+)/;++/**+ * The frame's line to the ChatGPT card on every page of the app: the host's+ * theme and bands come in, and the page the frame shows goes out. Outside the+ * card both are inert.+ */+export function CardHost() {+ useHostBridge();+ const projectId = usePathname().match(PROJECT_PATH)?.[1] ?? null;+ const name = useEditor((s) => (projectId && s.projectId === projectId ? s.projectName || null : null));++ // Each page change, and the name once the editor has loaded it.+ useEffect(() => {+ reportHostPage(projectId, name);+ }, [projectId, name]);++ return null;+}diff --git a/site/src/cut/components/CardRail.tsx b/site/src/cut/components/CardRail.tsxnew file mode 100644index 00000000..48bc3adc--- /dev/null+++ b/site/src/cut/components/CardRail.tsx@@ -0,0 +1,73 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import { useTranslations } from "next-intl";+import { Clapperboard, FolderOpen, Plus } from "lucide-react";+import { AppSidebar } from "@/cut/components/AppSidebar";+import { useCardCreate } from "@/cut/components/EmbeddedNewProject";+import { useEnvironment } from "@/cut/lib/environment";+import { useHostReady } from "@/cut/lib/hostBridge";+import { homeHref, useCutBase, type CutTab } from "@/cut/lib/nav";+import { cn } from "@/lib/utils";++const CARD_TABS: { tab: CutTab; label: "projects" | "library"; icon: typeof Clapperboard }[] = [+ { tab: "projects", label: "projects", icon: Clapperboard },+ { tab: "library", label: "library", icon: FolderOpen },+];++// The editor rail's tile: an icon chip over a small label.+const TILE = "flex w-full min-w-0 shrink-0 flex-col items-center gap-1 rounded-lg px-1 py-1.5 text-muted-foreground outline-none transition-colors hover:text-foreground disabled:opacity-50";+const CHIP = "grid size-9 place-items-center rounded-lg transition-colors";+const LABEL = "w-full truncate text-center text-[10px] font-medium tracking-tight";++/** The home's navigation: the full sidebar on the web, the card's rail in+ * ChatGPT. */+export function HomeNav() {+ const { chatgpt } = useEnvironment();+ return chatgpt ? <CardRail /> : <AppSidebar />;+}++/**+ * The projects home inside the ChatGPT card. The host draws the app's name and+ * owns the account, so the rail carries only the way to a new project and the+ * two shelves, in the editor rail's size.+ */+function CardRail() {+ const t = useTranslations("home");+ const pathname = usePathname();+ const base = useCutBase();+ const { create, busy, error } = useCardCreate();+ useHostReady(true);++ return (+ <nav className="relative flex w-[68px] shrink-0 flex-col items-center gap-1 border-r border-border bg-card px-1 py-3">+ <button type="button" className={TILE} disabled={busy} onClick={() => void create()}>+ <span className={cn(CHIP, "hover:bg-muted/60")}>+ <Plus className="size-4.5" />+ </span>+ <span className={LABEL}>{t("newProject.button")}</span>+ </button>+ <div aria-hidden className="my-1 h-px w-8 shrink-0 bg-border" />+ {CARD_TABS.map(({ tab, label, icon: Icon }) => {+ const href = homeHref(base, tab);+ const active = pathname === href;+ return (+ <Link key={tab} href={href} className={TILE} aria-current={active ? "page" : undefined}>+ <span className={cn(CHIP, active ? "bg-foreground/10 text-foreground" : "hover:bg-muted/60")}>+ <Icon className="size-4.5" />+ </span>+ <span className={cn(LABEL, active && "text-foreground")}>{t(`tabs.${label}`)}</span>+ </Link>+ );+ })}+ {/* The rail is too narrow for a sentence, so a failed create speaks+ beside it. */}+ {error && (+ <p role="alert" className="absolute top-3 left-[76px] z-10 w-56 rounded-md border border-border bg-popover p-2 text-xs text-destructive shadow-md">+ {error}+ </p>+ )}+ </nav>+ );+}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 8cefb3fa..d2dc52de 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -1,7 +1,7 @@"use client";import { CHAT_RUNTIME } from "@/cut/lib/chatRuntime";-import { useHostBridge, useHostReady } from "@/cut/lib/hostBridge";+import { useHostReady } from "@/cut/lib/hostBridge";import { useCutMode } from "@/cut/lib/backend/hooks";import { usePhoneInbox } from "@/cut/hooks/usePhoneInbox";import { useTabTitle } from "@/cut/hooks/useTabTitle";@@ -170,7 +170,6 @@ export function Editor({const aiOpen = useEditor((s) => s.aiOpen);const timelineOpen = useEditor((s) => s.timelineOpen);const sharedFeatures = useEditor((s) => s.sharedFeatures);- useHostBridge();// The timeline's height is bounded by the window, and the window changes// size under it: a browser resize, or the ChatGPT card leaving fullscreen.// The clamp is for this window only, so the height the user chose staysdiff --git a/site/src/cut/components/EmbeddedNewProject.tsx b/site/src/cut/components/EmbeddedNewProject.tsxindex 02b44acc..21cfe6a5 100644--- a/site/src/cut/components/EmbeddedNewProject.tsx+++ b/site/src/cut/components/EmbeddedNewProject.tsx@@ -18,10 +18,9 @@ import { errorFromBody } from "@/cut/lib/userError";import { useDescribeError } from "@/i18n/describeError";import { track } from "@/lib/analytics";-// The card's way forward when the project it was opened on can't be shown.-// The card is the whole surface, so there is no projects home to go back to:-// a new cloud project is made and opened here in its place.-export function EmbeddedNewProject() {+/** Make an untitled cloud project and open it in the card: the card rail's+ * New project, and the way forward from a project that can't be shown. */+export function useCardCreate() {const t = useTranslations("home.embeddedNewProject");const describeError = useDescribeError();const router = useRouter();@@ -48,12 +47,22 @@ export function EmbeddedNewProject() {const project = (await res.json()) as ProjectSummary;seedNewProjectDoc(project.id, project.name, "cloud", aspect);track("project_created", { source: "chatgpt_card" });- router.replace(framedHref(projectHref(base, project.id, "projects")));+ router.push(framedHref(projectHref(base, project.id, "projects")));} catch (e) {setError(describeError(e, t("failed")));- setBusy(false);}+ // The projects home stays mounted behind the editor, so its button is+ // ready again on the way back.+ setBusy(false);};+ return { create, busy, error };+}++// The card's way forward when the project it was opened on can't be shown: a+// new cloud project is made and opened here in its place.+export function EmbeddedNewProject() {+ const t = useTranslations("home.embeddedNewProject");+ const { create, busy, error } = useCardCreate();return (<>diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex 903067ed..a1e40d8e 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -494,7 +494,7 @@ export function TopBar({// toward whichever side has slack instead of colliding with the rail.<header ref={headerRef} className="relative flex items-center border-b border-border bg-card"><div ref={leftRef} className="flex shrink-0 items-center gap-1 pl-2">- {!chatgpt && <Button+ <Buttonvariant="ghost"size="icon-sm"aria-label={t("backTo", { tab: back.tab })}@@ -502,7 +502,7 @@ export function TopBar({render={<Link href={back.href} />}><ChevronLeft />- </Button>}+ </Button>{logo}{editing ? (<inputdiff --git a/site/src/cut/lib/environment.ts b/site/src/cut/lib/environment.tsindex 74d9bef3..922c9cf5 100644--- a/site/src/cut/lib/environment.ts+++ b/site/src/cut/lib/environment.ts@@ -11,9 +11,34 @@ import { useSyncExternalStore } from "react";*/export type EditorHost = "web" | "chatgpt";+// The frame remembers it is the card for the rest of its session, so a page+// it navigates to on its own (a project opened from its projects home) is+// still the card without the flag in its address.+const CARD_KEY = "cut-embed";+export function editorHost(): EditorHost {if (typeof window === "undefined" || window.self === window.top) return "web";- return new URLSearchParams(window.location.search).get("embed") === "chatgpt" ? "chatgpt" : "web";+ if (new URLSearchParams(window.location.search).get("embed") === "chatgpt") {+ rememberCard();+ return "chatgpt";+ }+ return rememberedCard() ? "chatgpt" : "web";+}++function rememberCard() {+ try {+ if (sessionStorage.getItem(CARD_KEY) !== "chatgpt") sessionStorage.setItem(CARD_KEY, "chatgpt");+ } catch {+ // Storage blocked: the flag in the address is all the frame has.+ }+}++function rememberedCard(): boolean {+ try {+ return sessionStorage.getItem(CARD_KEY) === "chatgpt";+ } catch {+ return false;+ }}const subscribe = () => () => {};diff --git a/site/src/cut/lib/hostBridge.ts b/site/src/cut/lib/hostBridge.tsindex 45a823b0..505e84a3 100644--- a/site/src/cut/lib/hostBridge.ts+++ b/site/src/cut/lib/hostBridge.ts@@ -82,6 +82,13 @@ export function useHostReady(ready: boolean) {}, [ready]);}+/** Tell the card which project the frame shows, null on the projects home,+ * so the model's context follows a project opened inside the frame. */+export function reportHostPage(projectId: string | null, name: string | null) {+ if (editorHost() !== "chatgpt") return;+ window.parent.postMessage({ type: "donkeycut:page", projectId, name }, "*");+}+/** An address the frame itself navigates to keeps the embed flag, so the page* it lands on is still the card. On the web the address is returned as is. */export function framedHref(href: string): string {diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.tsindex 36a55474..5630c99d 100644--- a/site/src/cut/lib/residency.ts+++ b/site/src/cut/lib/residency.ts@@ -21,6 +21,7 @@ import { localBackend } from "./backend/local";import type { CutBackend, CutMode } from "./backend/types";import { readSnapshot, snapshotKey } from "./cache";import type { ProjectSummary } from "./types";+import { editorHost } from "./environment";/** Where a piece of the user's own data lives. ("shared" is a view of someone* else's cloud project, never a residency of yours, so it never lists here.) */@@ -50,6 +51,9 @@ export const RESIDENCY_LABEL: Record<Residency, string> = {* before the gate opens would hang on its latch.*/export function availableResidencies(): Residency[] {+ // The card's tools reach cloud projects only, so the card lists and makes+ // nothing else.+ if (editorHost() === "chatgpt") return ["cloud"];const out: Residency[] = [];if (servedFromEngine() || engineOrigin() !== "") out.push("local");if (supportsBrowserStore()) out.push("browser");diff --git a/site/src/i18n/messages/.source-lock.json b/site/src/i18n/messages/.source-lock.jsonindex cf4676e6..b193bcb4 100644--- a/site/src/i18n/messages/.source-lock.json+++ b/site/src/i18n/messages/.source-lock.json@@ -234,13 +234,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -249,8 +242,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -3260,13 +3255,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -3275,8 +3263,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -6286,13 +6276,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -6301,8 +6284,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -9312,13 +9297,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -9327,8 +9305,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -12338,13 +12318,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -12353,8 +12326,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -15364,13 +15339,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -15379,8 +15347,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",@@ -18390,13 +18360,6 @@"widget.createNewProject": "7610152b22b6","widget.dismiss": "70afe9eff3f2","widget.tryAgain": "042c862e4467",- "widget.chooseProject": "42291036a3f8",- "widget.connecting": "440e79de55eb",- "widget.loadProjects": "f0fa0a004dfe",- "widget.yourProjects": "352b9eb7541f",- "widget.noProjects": "5b909f175ca7",- "widget.moreProjects": "78dfec443d61",- "widget.refreshList": "7fe6bbe7e67e","widget.previewOf": "b5b8b81dc3a3","widget.waitingToRender": "3bd965d8b81c","widget.rendering": "ee929d9acc44",@@ -18405,8 +18368,10 @@"widget.earlierEdit": "222f5537c31a","widget.renderPreview": "8d33aab6d7b6","widget.openInDonkey": "db825aac5df0",- "widget.projects": "53e890d5f0ff","widget.openingEditor": "964d91f0b8f9",+ "widget.openingHome": "5ef0af1eb043",+ "widget.home": "3afe1a97031c",+ "widget.readOnlyHome": "b291ba2e9063","widget.editing": "bd3f65129ac4","widget.untitled": "621521f9a878","widget.problems.requestFailed": "2b9776101a8b",diff --git a/site/src/i18n/messages/de/chatgpt.json b/site/src/i18n/messages/de/chatgpt.jsonindex d0d5bdfb..a2cf62fc 100644--- a/site/src/i18n/messages/de/chatgpt.json+++ b/site/src/i18n/messages/de/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "Neues Projekt erstellen","dismiss": "Verwerfen","tryAgain": "Erneut versuchen",- "chooseProject": "Wähle ein Projekt für die Vorschau aus.",- "connecting": "Verbindung zu Donkey Cut wird hergestellt…",- "loadProjects": "Projekte laden",- "yourProjects": "Deine Projekte",- "noProjects": "Speichere ein Projekt in Donkey Cut in der Cloud, um es hier anzusehen.",- "moreProjects": "Weitere Projekte",- "refreshList": "Liste aktualisieren","previewOf": "Vorschau von {name}","waitingToRender": "Warten auf Rendering…","rendering": "Vorschau wird gerendert… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "Diese Vorschau stammt möglicherweise aus einer früheren Bearbeitung.","renderPreview": "Vorschau rendern","openInDonkey": "In Donkey Cut öffnen ↗",- "projects": "Projekte","openingEditor": "Editor wird geöffnet",+ "openingHome": "Deine Projekte werden geöffnet",+ "home": "Deine Donkey Cut-Projekte",+ "readOnlyHome": "Bitte ChatGPT, eines deiner Projekte zu öffnen, um die Vorschau hier anzusehen.","editing": "{name} bearbeiten","untitled": "Ohne Titel","problems": {diff --git a/site/src/i18n/messages/en/chatgpt.json b/site/src/i18n/messages/en/chatgpt.jsonindex 53275e60..702b1049 100644--- a/site/src/i18n/messages/en/chatgpt.json+++ b/site/src/i18n/messages/en/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "Create New Project","dismiss": "Dismiss","tryAgain": "Try again",- "chooseProject": "Choose a project to preview.",- "connecting": "Connecting to Donkey Cut…",- "loadProjects": "Load projects",- "yourProjects": "Your projects",- "noProjects": "Save a project to the cloud in Donkey Cut to preview it here.",- "moreProjects": "More projects",- "refreshList": "Refresh list","previewOf": "Preview of {name}","waitingToRender": "Waiting to render…","rendering": "Rendering preview… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "This preview may be from an earlier edit.","renderPreview": "Render preview","openInDonkey": "Open in Donkey Cut ↗",- "projects": "Projects","openingEditor": "Opening the editor",+ "openingHome": "Opening your projects",+ "home": "Your Donkey Cut projects",+ "readOnlyHome": "Ask ChatGPT to open one of your projects to watch its preview here.","editing": "Editing {name}","untitled": "Untitled","problems": {diff --git a/site/src/i18n/messages/es/chatgpt.json b/site/src/i18n/messages/es/chatgpt.jsonindex a0c79a0d..6ffbe36b 100644--- a/site/src/i18n/messages/es/chatgpt.json+++ b/site/src/i18n/messages/es/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "Crear nuevo proyecto","dismiss": "Descartar","tryAgain": "Reintentar",- "chooseProject": "Elige un proyecto para previsualizar.",- "connecting": "Conectando con Donkey Cut…",- "loadProjects": "Cargar proyectos",- "yourProjects": "Tus proyectos",- "noProjects": "Guarda un proyecto en la nube en Donkey Cut para previsualizarlo aquí.",- "moreProjects": "Más proyectos",- "refreshList": "Actualizar lista","previewOf": "Vista previa de {name}","waitingToRender": "Esperando para renderizar…","rendering": "Renderizando vista previa… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "Esta vista previa puede ser de una edición anterior.","renderPreview": "Renderizar vista previa","openInDonkey": "Abrir en Donkey Cut ↗",- "projects": "Proyectos","openingEditor": "Abriendo el editor",+ "openingHome": "Abriendo tus proyectos",+ "home": "Tus proyectos de Donkey Cut",+ "readOnlyHome": "Pídele a ChatGPT que abra uno de tus proyectos para ver su vista previa aquí.","editing": "Editando {name}","untitled": "Sin título","problems": {diff --git a/site/src/i18n/messages/fr/chatgpt.json b/site/src/i18n/messages/fr/chatgpt.jsonindex d7b095f8..6e4264db 100644--- a/site/src/i18n/messages/fr/chatgpt.json+++ b/site/src/i18n/messages/fr/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "Créer un nouveau projet","dismiss": "Ignorer","tryAgain": "Réessayer",- "chooseProject": "Choisissez un projet à prévisualiser.",- "connecting": "Connexion à Donkey Cut…",- "loadProjects": "Charger les projets",- "yourProjects": "Vos projets",- "noProjects": "Enregistrez un projet sur le cloud dans Donkey Cut pour le prévisualiser ici.",- "moreProjects": "Plus de projets",- "refreshList": "Actualiser la liste","previewOf": "Aperçu de {name}","waitingToRender": "En attente du rendu…","rendering": "Rendu de l'aperçu… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "Cet aperçu peut provenir d'une modification antérieure.","renderPreview": "Générer l'aperçu","openInDonkey": "Ouvrir dans Donkey Cut ↗",- "projects": "Projets","openingEditor": "Ouverture de l'éditeur",+ "openingHome": "Ouverture de vos projets",+ "home": "Vos projets Donkey Cut",+ "readOnlyHome": "Demandez à ChatGPT d'ouvrir l'un de vos projets pour en voir l'aperçu ici.","editing": "Modification de {name}","untitled": "Sans titre","problems": {diff --git a/site/src/i18n/messages/ja/chatgpt.json b/site/src/i18n/messages/ja/chatgpt.jsonindex 4cfd9899..c7326a83 100644--- a/site/src/i18n/messages/ja/chatgpt.json+++ b/site/src/i18n/messages/ja/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "新規プロジェクトを作成","dismiss": "閉じる","tryAgain": "再試行",- "chooseProject": "プレビューするプロジェクトを選択してください。",- "connecting": "Donkey Cut に接続中…",- "loadProjects": "プロジェクトを読み込む",- "yourProjects": "あなたのプロジェクト",- "noProjects": "ここでプレビューするには、Donkey Cut でプロジェクトをクラウドに保存してください。",- "moreProjects": "その他のプロジェクト",- "refreshList": "リストを更新","previewOf": "{name} のプレビュー","waitingToRender": "レンダリング待機中…","rendering": "プレビューをレンダリング中… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "このプレビューは以前の編集内容である可能性があります。","renderPreview": "プレビューをレンダリング","openInDonkey": "Donkey Cut で開く ↗",- "projects": "プロジェクト","openingEditor": "エディタを開いています",+ "openingHome": "プロジェクトを開いています",+ "home": "Donkey Cut プロジェクト",+ "readOnlyHome": "ここでプレビューを確認するには、ChatGPTにプロジェクトを開くよう依頼してください。","editing": "{name} を編集中","untitled": "無題","problems": {diff --git a/site/src/i18n/messages/ko/chatgpt.json b/site/src/i18n/messages/ko/chatgpt.jsonindex df251b4a..17fe1481 100644--- a/site/src/i18n/messages/ko/chatgpt.json+++ b/site/src/i18n/messages/ko/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "새 프로젝트 만들기","dismiss": "닫기","tryAgain": "다시 시도",- "chooseProject": "미리 볼 프로젝트를 선택하세요.",- "connecting": "Donkey Cut에 연결하는 중…",- "loadProjects": "프로젝트 불러오기",- "yourProjects": "내 프로젝트",- "noProjects": "여기서 미리 보려면 Donkey Cut의 프로젝트를 클라우드에 저장하세요.",- "moreProjects": "프로젝트 더보기",- "refreshList": "목록 새로고침","previewOf": "{name} 미리보기","waitingToRender": "렌더링 대기 중…","rendering": "미리보기 렌더링 중… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "이 미리보기는 이전 편집본일 수 있어요.","renderPreview": "미리보기 렌더링","openInDonkey": "Donkey Cut에서 열기 ↗",- "projects": "프로젝트","openingEditor": "에디터 여는 중",+ "openingHome": "프로젝트를 여는 중이에요",+ "home": "내 Donkey Cut 프로젝트",+ "readOnlyHome": "여기서 미리보기를 보려면 ChatGPT에 프로젝트를 열어 달라고 요청해 보세요.","editing": "{name} 편집 중","untitled": "제목 없음","problems": {diff --git a/site/src/i18n/messages/pt-BR/chatgpt.json b/site/src/i18n/messages/pt-BR/chatgpt.jsonindex 707d59ec..0ac3e02f 100644--- a/site/src/i18n/messages/pt-BR/chatgpt.json+++ b/site/src/i18n/messages/pt-BR/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "Criar novo projeto","dismiss": "Dispensar","tryAgain": "Tentar novamente",- "chooseProject": "Escolha um projeto para pré-visualizar.",- "connecting": "Conectando ao Donkey Cut…",- "loadProjects": "Carregar projetos",- "yourProjects": "Seus projetos",- "noProjects": "Salve um projeto na nuvem no Donkey Cut para pré-visualizá-lo aqui.",- "moreProjects": "Mais projetos",- "refreshList": "Atualizar lista","previewOf": "Pré-visualização de {name}","waitingToRender": "Aguardando renderização…","rendering": "Renderizando pré-visualização… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "Esta pré-visualização pode ser de uma edição anterior.","renderPreview": "Renderizar pré-visualização","openInDonkey": "Abrir no Donkey Cut ↗",- "projects": "Projetos","openingEditor": "Abrindo o editor",+ "openingHome": "Abrindo seus projetos",+ "home": "Seus projetos do Donkey Cut",+ "readOnlyHome": "Peça ao ChatGPT para abrir um dos seus projetos para ver a prévia aqui.","editing": "Editando {name}","untitled": "Sem título","problems": {diff --git a/site/src/i18n/messages/zh-CN/chatgpt.json b/site/src/i18n/messages/zh-CN/chatgpt.jsonindex 0b216e38..05b56de8 100644--- a/site/src/i18n/messages/zh-CN/chatgpt.json+++ b/site/src/i18n/messages/zh-CN/chatgpt.json@@ -4,13 +4,6 @@"createNewProject": "新建项目","dismiss": "忽略","tryAgain": "重试",- "chooseProject": "选择一个项目进行预览。",- "connecting": "正在连接至 Donkey Cut…",- "loadProjects": "加载项目",- "yourProjects": "你的项目",- "noProjects": "在 Donkey Cut 中将项目保存到云端,即可在此处预览。",- "moreProjects": "更多项目",- "refreshList": "刷新列表","previewOf": "{name} 预览","waitingToRender": "等待渲染…","rendering": "正在渲染预览… {percent}%",@@ -19,8 +12,10 @@"earlierEdit": "此预览可能来自较早的编辑版本。","renderPreview": "渲染预览","openInDonkey": "在 Donkey Cut 中打开 ↗",- "projects": "项目","openingEditor": "正在打开编辑器",+ "openingHome": "正在打开你的项目",+ "home": "你的 Donkey Cut 项目",+ "readOnlyHome": "让 ChatGPT 打开你的一个项目,即可在此观看预览。","editing": "正在编辑 {name}","untitled": "未命名","problems": {