Open source CapCut alternative.
TypeScript
feat(chatgpt): opening a project puts the full editor in the card
David Le7d9e1a0c68f1
diff --git a/docs/guides/chatgpt-app.md b/docs/guides/chatgpt-app.mdindex 211c3644..c1c07702 100644--- a/docs/guides/chatgpt-app.md+++ b/docs/guides/chatgpt-app.md@@ -74,6 +74,16 @@ host bridge. It has no account cookie or OAuth token. Preview rendering usesno Donkey Cut AI credits. Derived previews remain exempt from storage quota;retained media uses the account's existing storage allowance.+Opening a project from a connection that can edit puts the whole editor in+the card: the widget frames `donkeycut.com` through a one-use, one-minute+link the tool mints on the connection, and that link redeems for a+partitioned session cookie scoped to the frame, so the editor is signed in+there and nowhere else. Revoking the+connection ends those sessions. A browser without partitioned cookies shows+an Open in Donkey Cut link inside the frame. Public submission has to justify+`frameDomains`; the justification is that the frame is the app's own editor+on its own domain.+## Account linkingDonkey Cut is the OAuth authorization server and MCP resource server. The account@@ -139,7 +149,8 @@ the submission portal when that challenge is issued.Run the client tests with `bun test src/clients/chatgpt`. The browser fixture`bun run scripts/eval-chatgpt-widget.ts` checks selection, repeated polling,-playback, URL recovery, hidden playback, and teardown against a mock host. With+playback, URL recovery, hidden playback, the editor frame, and teardown+against a mock host. Withthe dev server and a local worker up, `bun run scripts/eval-chatgpt-workflow.ts`drives the whole editing workflow through the MCP tools in process: create,import, inspect, edit, preview, undo, redo, export.diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.tsindex 4005d530..44e81727 100644--- a/site/scripts/eval-chatgpt-widget.ts+++ b/site/scripts/eval-chatgpt-widget.ts@@ -14,6 +14,7 @@ const server = Bun.serve({ port: 0, fetch(request) {const url = new URL(request.url);if (url.pathname === "/widget") return new Response(widgetHtml(url.origin), { headers: { "Content-Type": "text/html" } });if (url.pathname === "/preview.mp4") return new Response(Bun.file(video));+ if (url.pathname === "/embed") return new Response(`<!doctype html><title>editor</title><p id="editor">Editor for ${url.searchParams.get("project")} via ${url.searchParams.get("code")}</p>`, { headers: { "Content-Type": "text/html" } });if (url.pathname.startsWith("/clients/chatgpt/")) return new Response(Bun.file(path.join(root, "public/clients/chatgpt", path.basename(url.pathname))));return new Response(hostHtml, { headers: { "Content-Type": "text/html" } });} });@@ -21,20 +22,20 @@ const hostHtml = `<!doctype html><html><body><iframe title="Donkey Cut preview"const frame = document.querySelector('iframe');const project = {id:'project',name:'Launch film',revision:'cloud:2',url:'https://donkeycut.com/app/p/project'};let count = 0, renewals = 0;-window.calls = []; window.links = [];-const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true,canEdit:false,export:null,job:null,results:[],changed:false,history:null,account:null});+window.calls = []; window.links = []; window.modes = []; window.editable = false;+const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true,canEdit:window.editable,export:null,job:null,results:[],changed:false,history:null,account:null});// ChatGPT's sandbox drops null-valued keys before the widget sees a result.const dropNulls = (value) => Array.isArray(value) ? value.map(dropNulls) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null).map(([k, v]) => [k, dropNulls(v)])) : value;-const result = (data, playback = null) => dropNulls({content:[{type:'text',text:'Preview'}],structuredContent:data,_meta:{playback,pollMs:1000}});+const result = (data, playback = null, editor = null) => dropNulls({content:[{type:'text',text:'Preview'}],structuredContent:data,_meta:{playback,editor,pollMs:1000}});const reply = (id, result) => frame.contentWindow.postMessage({jsonrpc:'2.0',id,result},'*');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:{}},hostContext:{theme:'light'}});+ if(data.method === 'ui/initialize') reply(data.id,{protocolVersion:data.params.protocolVersion,hostInfo:{name:'fixture',version:'1'},hostCapabilities:{serverTools:{},openLinks:{}},hostContext:{theme:'light',availableDisplayModes:['inline','fullscreen']}});if(data.method === 'ui/notifications/initialized') frame.contentWindow.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-result',params:result(view(false))},'*');if(data.method === 'tools/call') {const name = data.params.name; window.calls.push(name);if(name === 'list_projects') reply(data.id,result(view(false)));- if(name === 'open_project') reply(data.id,result(view(true)));+ if(name === 'open_project') reply(data.id, window.editable ? result(view(true),null,{url:location.origin+'/embed?code=one-use&project=project',expiresAt:Date.now()+60000}) : result(view(true)));if(name === 'render_preview') { count=0; reply(data.id,result(view(true,{id:'job',status:'queued',progress:0,revision:'cloud:2'}))); }if(name === 'get_preview_status') {count++; const done = count >= 3;@@ -42,6 +43,7 @@ window.addEventListener('message', ({source,data}) => {}}if(data.method === 'ui/open-link') { window.links.push(data.params.url); reply(data.id,{}); }+ if(data.method === 'ui/request-display-mode') { window.modes.push(data.params.mode); reply(data.id,{mode:data.params.mode}); }});</script></body></html>`;const browser = await chromium.launch({ headless: true });@@ -73,8 +75,14 @@ try {await app.getByRole("button", { name: "Projects", exact: true }).click();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("button").count(), 0, "the editor card has no buttons of its own");+ assert.deepEqual(await page.evaluate(() => (window as unknown as { modes: string[] }).modes), ["fullscreen"], "the editor asks for the whole window");+ await page.screenshot({ path: "/tmp/donkey-chatgpt-widget-editor.png" });assert.deepEqual(errors, []);- console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, decoder teardown, lazy HLS.");+ console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, editor in the card, decoder teardown, lazy HLS.");} finally {await browser.close(); server.stop(true); await rm(scratch, { recursive: true, force: true });}diff --git a/site/scripts/eval-chatgpt-workflow.ts b/site/scripts/eval-chatgpt-workflow.tsindex 71ce36d1..de392cc8 100644--- a/site/scripts/eval-chatgpt-workflow.ts+++ b/site/scripts/eval-chatgpt-workflow.ts@@ -36,7 +36,7 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const config = SETTINGS.chatgptApp.schema.parse({ ...SETTINGS.chatgptApp.default, enabled: true, commandWaitMs: 120_000 });const server = createChatgptServer(- { userId: USER_ID, scopes: ["projects:read", "previews:render", "projects:write"] },+ { userId: USER_ID, scopes: ["projects:read", "previews:render", "projects:write"], grantId: "eval" },config);const client = new Client({ name: "eval", version: "1" });diff --git a/site/src/clients/chatgpt/contracts.ts b/site/src/clients/chatgpt/contracts.tsindex b7ce4769..378ff24e 100644--- a/site/src/clients/chatgpt/contracts.ts+++ b/site/src/clients/chatgpt/contracts.ts@@ -24,6 +24,9 @@ export const viewSchema = z.object({});export const playbackSchema = z.object({ url: z.url(), expiresAt: z.number() });export const downloadSchema = z.object({ url: z.url(), expiresAt: z.number(), name: z.string() });+/** A one-use link the card frames to sign the editor in; spent once loaded. */+export const editorSchema = z.object({ url: z.url(), expiresAt: z.number() });export type ProjectView = z.infer<typeof viewSchema>;export type Playback = z.infer<typeof playbackSchema>;export type Download = z.infer<typeof downloadSchema>;+export type Editor = z.infer<typeof editorSchema>;diff --git a/site/src/clients/chatgpt/server/mcp.test.ts b/site/src/clients/chatgpt/server/mcp.test.tsindex 8927b6e6..647f2a27 100644--- a/site/src/clients/chatgpt/server/mcp.test.ts+++ b/site/src/clients/chatgpt/server/mcp.test.ts@@ -53,6 +53,7 @@ const fakeProjects = (overrides: Partial<Projects> = {}): Projects => {list: answer,status: answer,render: answer,+ open: answer,create: answer,inspect: answer,edit: answer,@@ -70,7 +71,7 @@ const fakeProjects = (overrides: Partial<Projects> = {}): Projects => {describe("ChatGPT MCP protocol", () => {test("tools validate inputs, expose their safety annotations, and keep signed URLs out of model content", async () => {const server = createChatgptServer(- { userId: "owner", scopes: ["projects:read", "previews:render"] },+ { userId: "owner", scopes: ["projects:read", "previews:render"], grantId: "grant" },config,fakeProjects(),);@@ -138,6 +139,7 @@ describe("ChatGPT MCP protocol", () => {ui: {csp: {resourceDomains: [config.issuer, "https://media.donkeycut.com"],+ frameDomains: [config.issuer],},},});@@ -150,7 +152,7 @@ describe("ChatGPT MCP protocol", () => {test("render scope requests a reconnect through the MCP authentication challenge", async () => {const server = createChatgptServer(- { userId: "owner", scopes: ["projects:read"] },+ { userId: "owner", scopes: ["projects:read"], grantId: "grant" },config,fakeProjects({render: async () => {@@ -191,7 +193,7 @@ const http = async (headers: Record<string, string> = {},) => {const handler = chatgptHttpHandler(- { userId: "owner", scopes: ["projects:read"] },+ { userId: "owner", scopes: ["projects:read"], grantId: "grant" },config,projects,);@@ -342,7 +344,7 @@ test("edit results reach the model as text and structure, and captured frames be};let received: unknown = null;const server = createChatgptServer(- { userId: "owner", scopes: ["projects:read", "projects:write"] },+ { userId: "owner", scopes: ["projects:read", "projects:write"], grantId: "grant" },config,fakeProjects({edit: async (_projectId, commands, label) => {diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.tsindex 042f9e46..a16b2b75 100644--- a/site/src/clients/chatgpt/server/mcp.ts+++ b/site/src/clients/chatgpt/server/mcp.ts@@ -53,7 +53,7 @@ export const SERVER_INSTRUCTIONS = [`Donkey Cut is an open-source video editor (Apache 2.0, ${REPOSITORY_URL}). Edit the connected account's cloud projects: import footage, inspect it, cut it, caption it, preview, undo, export.`,"Editing, previews and exports are free. Hosted AI (voiceover, music, images, caption rewriting, transcription past the monthly allowance) spends the account's credits. Imports and exports use the account's cloud storage.","Workflow: list_projects or create_project → import_media → inspect_project → list_commands once, describe_commands for the ones you need → edit_project (batches, one undo step each) → render_preview → undo/redo → export_video.",- "open_project plays the project's current preview at once; call render_preview only after an edit or when the card reports no current preview.",+ "open_project puts the full Donkey Cut editor in the card, timeline and panels included, when the connection can edit; a read-only connection sees the current preview playing. Call render_preview only after an edit or when the card reports no current preview.","Times are seconds; ids come from inspect_project. A batch stops at its first failed command. A tool that answers with a job still running is finished by get_job_status.",].join("\n");@@ -91,7 +91,7 @@ function liftMedia(view: ProjectView): MediaBlock[] {return blocks;}-type Identity = { userId: string; scopes: string[] };+type Identity = { userId: string; scopes: string[]; grantId: string };export function createChatgptServer(identity: Identity,config: ChatgptConfig,@@ -130,13 +130,13 @@ export function createChatgptServer(});const runTool = async (run: () => Promise<ProjectResult>) => {try {- const { view, playback, download } = await run();+ const { view, playback, download, editor } = await run();const media = liftMedia(view);- const text = describeProjectView(view);+ const text = describeProjectView(view) + (editor ? "\nThe Donkey Cut editor is open in the card." : "");return {content: [{ type: "text" as const, text }, ...media],structuredContent: view,- _meta: { playback, download: download ?? null, pollMs: config.pollMs },+ _meta: { playback, download: download ?? null, editor: editor ?? null, pollMs: config.pollMs },};} catch (error) {if (!(error instanceof ProjectToolError)) {@@ -173,16 +173,16 @@ export function createChatgptServer(server.registerTool("open_project",{- title: "Open a Donkey Cut preview",+ title: "Open a Donkey Cut project",description:- "Show a selected cloud project with its preview playing in the card. A preview whose revision matches the project is current; one from an earlier revision, or none, needs render_preview. With no projectId, show the project picker.",+ "Open a selected cloud project in the card. When the connection can edit, the card holds the full Donkey Cut editor, timeline, media panel, inspector and preview, signed in on its own. A read-only connection sees the preview playing; a preview whose revision matches the project is current, and one from an earlier revision, or none, needs render_preview. With no projectId, show the project picker.",inputSchema: z.object({ projectId: idSchema.optional() }),outputSchema: viewSchema,annotations: readOnlyAnnotations,_meta: { ...readMetadata, ui: { resourceUri: WIDGET_URI } },},({ projectId }) =>- runTool(() => (projectId ? projects.status(projectId) : projects.list())),+ runTool(() => (projectId ? projects.open(projectId) : projects.list())),);server.registerTool(@@ -473,6 +473,7 @@ export function createChatgptServer(csp: {connectDomains: ["https://media.donkeycut.com"],resourceDomains: [config.issuer, "https://media.donkeycut.com"],+ frameDomains: [config.issuer],},},"openai/widgetDescription":diff --git a/site/src/clients/chatgpt/server/projects.test.ts b/site/src/clients/chatgpt/server/projects.test.tsindex e72858a4..3958dd12 100644--- a/site/src/clients/chatgpt/server/projects.test.ts+++ b/site/src/clients/chatgpt/server/projects.test.ts@@ -24,6 +24,9 @@ function createTestContext(scopes: string[] = ["projects:read"]) {}),},cutRenderJob: { findFirst: jobs },+ chatgptToken: {+ create: mock(async (args: { data: { hash: string; grantId: string; kind: string } }) => args.data),+ },cutMediaObject: {findFirst: mock(async (args: unknown) => {void args;@@ -34,7 +37,7 @@ function createTestContext(scopes: string[] = ["projects:read"]) {return {db,tools: projectTools(- { userId: "owner", scopes },+ { userId: "owner", scopes, grantId: "grant" },config,db as unknown as typeof prisma,),@@ -103,6 +106,16 @@ describe("ChatGPT cloud projects", () => {expect(rendered.view.preview?.id).toBe("job");expect(rendered.playback?.url).toContain("proxy");});+ test("opening a project with write scope carries a one-use editor link; read scope gets the preview", async () => {+ const readOnly = createTestContext();+ expect((await readOnly.tools.open("mine")).editor).toBeUndefined();+ expect(readOnly.db.chatgptToken.create).not.toHaveBeenCalled();+ const { tools, db } = createTestContext(["projects:read", "projects:write"]);+ const result = await tools.open("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" });+ expect(result.view.project?.id).toBe("mine");+ });test("list returns only public project metadata and paging state", async () => {const { tools, db } = createTestContext();const result = await tools.list();diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.tsindex 8dfc95be..a8fc5df4 100644--- a/site/src/clients/chatgpt/server/projects.ts+++ b/site/src/clients/chatgpt/server/projects.ts@@ -13,13 +13,14 @@ import { mediaObjectUrl, mediaUrlLifetime } from "@/cut/server/cloud/mediaCdn";import { usageBytes } from "@/cut/server/cloud/usage";import { wakeRenderWorker } from "@/cut/server/cloud/wake";import type { ImportUrlResult } from "@/cut/worker/importUrlJob";-import type { Download, Playback, ProjectView } from "@/clients/chatgpt/contracts";+import type { Download, Editor, Playback, ProjectView } from "@/clients/chatgpt/contracts";+import { createEditorCode } from "@/clients/chatgpt/server/oauthTokens";import type { ChatgptConfig } from "@/clients/chatgpt/server/config";import { READ_COMMANDS, unknownCommandNames } from "@/clients/chatgpt/server/catalog";-type Identity = { userId: string; scopes: string[] };+type Identity = { userId: string; scopes: string[]; grantId: string };export class ProjectToolError extends Error {}-export type ProjectResult = { view: ProjectView; playback: Playback | null; download?: Download | null };+export type ProjectResult = { view: ProjectView; playback: Playback | null; download?: Download | null; editor?: Editor | null };/** A queue helper's refusal, read out of its Response as a message. */async function refusal(res: Response): Promise<never> {@@ -282,6 +283,15 @@ export function projectTools(};},status: getPreviewStatus,+ /** The project as the card shows it: the full editor, signed in through a+ * one-use link, when the connection can edit; its preview otherwise. */+ async open(projectId: string): Promise<ProjectResult> {+ const current = await getPreviewStatus(projectId);+ if (!canEdit) return current;+ const code = await createEditorCode(identity.grantId, db);+ const url = `${config.issuer}/api/chatgpt/embed?code=${code}&project=${encodeURIComponent(projectId)}`;+ return { ...current, editor: { url, expiresAt: Date.now() + 60_000 } };+ },async render(projectId: string): Promise<ProjectResult> {if (!canRender) {throw new ProjectToolError(diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsxindex 38466aab..8ac9fda1 100644--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx@@ -3,12 +3,16 @@ import { useProjectApp } from "./useProjectApp";import "./preview.css";export function PreviewApp() {- const { ready, view, playback, download, error, busy, visible, run, playbackFailed, openDonkey, openDownload } = useProjectApp();+ const { ready, view, playback, download, editor, error, busy, visible, run, playbackFailed, openDonkey, openDownload } = useProjectApp();const project = view?.project;const preview = view?.preview;const rendering = preview?.status === "queued" || preview?.status === "running";const exp = view?.export;const exporting = exp?.status === "queued" || exp?.status === "running";+ // The editor is the card: its own chrome carries every control.+ if (editor && project) return <main className="editing">+ <iframe className="editor" src={editor.url} title={`Editing ${project.name}`} allow="fullscreen; clipboard-read; clipboard-write" />+ </main>;return <main aria-busy={busy}><header><span className="brand">Donkey Cut</span><span>Cloud projects</span></header>{error && <p role="alert" className="error">{error}</p>}diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.cssindex de4a21ad..cbc91c61 100644--- a/site/src/clients/chatgpt/ui/preview.css+++ b/site/src/clients/chatgpt/ui/preview.css@@ -1,3 +1,4 @@:root{font:14px/1.5 system-ui,sans-serif;color:#20201e;background:#faf9f7;color-scheme:light;--line:#dddcd6;--muted:#66645e;--panel:#fff}:root[data-theme=dark]{color:#eeede8;background:#20201e;color-scheme:dark;--line:#45443f;--muted:#b6b3a8;--panel:#292925}*{box-sizing:border-box}body{margin:0}main{padding:20px;max-width:840px;margin:auto}header{display:flex;justify-content:space-between;color:var(--muted);font-size:12px}.brand{font-weight:800;font-size:16px;color:inherit}h1{font-size:22px;line-height:1.2;margin:24px 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}+.editing{padding:0;max-width:none}.editor{display:block;width:100%;height:100vh;min-height:600px;border:0;background:#000}diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.tsindex 0278c6d2..1b020d8b 100644--- a/site/src/clients/chatgpt/ui/useProjectApp.ts+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts@@ -1,6 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";import { App } from "@modelcontextprotocol/ext-apps";-import { downloadSchema, playbackSchema, viewSchema, type Download, type Playback, type ProjectView } from "../contracts";+import { downloadSchema, editorSchema, playbackSchema, viewSchema, type Download, type Editor, type Playback, type ProjectView } from "../contracts";type ToolResult = { isError?: boolean; structuredContent?: unknown; _meta?: Record<string, unknown>; content?: unknown[] };@@ -12,6 +12,7 @@ export function useProjectApp() {const [view, setView] = useState<ProjectView | null>(null);const [playback, setPlayback] = useState<Playback | null>(null);const [download, setDownload] = useState<Download | null>(null);+ const [editor, setEditor] = useState<Editor | null>(null);const [error, setError] = useState<string | null>(null);const [busy, setBusy] = useState(false);const [visible, setVisible] = useState(!document.hidden);@@ -29,6 +30,10 @@ export function useProjectApp() {setView(parsed.data);setPlayback(media.success ? media.data : null);setDownload(file.success ? file.data : null);+ // A one-use link that has already had its minute is a spent one: a card+ // rehydrated later shows the preview, and Edit here mints a fresh link.+ const embed = editorSchema.safeParse(result._meta?.editor);+ if (embed.success && embed.data.expiresAt > Date.now()) setEditor(embed.data);setError(null);}, []);@@ -76,26 +81,26 @@ export function useProjectApp() {const jobId = view?.preview?.id;const status = view?.preview?.status;useEffect(() => {- if (!ready || !visible || busy || error || !projectId || !jobId) return;+ if (!ready || !visible || busy || error || editor || !projectId || !jobId) return;const waiting = status === "queued" || status === "running";if (!waiting && !playback) return;const delay = waiting ? pollMs : Math.max(1000, playback!.expiresAt - Date.now() - 60000);const timeout = window.setTimeout(() => { void run("get_preview_status", { projectId, jobId }, false); }, delay);return () => window.clearTimeout(timeout);- }, [ready, visible, busy, error, projectId, jobId, status, playback, pollMs, run, view]);+ }, [ready, visible, busy, error, editor, projectId, jobId, status, playback, pollMs, run, view]);// An export in flight polls the same way; a finished one renews its// download link before it expires.const exportId = view?.export?.id;const exportStatus = view?.export?.status;useEffect(() => {- if (!ready || !visible || busy || error || !exportId) return;+ if (!ready || !visible || busy || error || editor || !exportId) return;const waiting = exportStatus === "queued" || exportStatus === "running";if (!waiting && !download) return;const delay = waiting ? pollMs : Math.max(1000, download!.expiresAt - Date.now() - 60000);const timeout = window.setTimeout(() => { void run("get_export_status", { jobId: exportId }, false); }, delay);return () => window.clearTimeout(timeout);- }, [ready, visible, busy, error, exportId, exportStatus, download, pollMs, run, view]);+ }, [ready, visible, busy, error, editor, exportId, exportStatus, download, pollMs, run, view]);const playbackFailed = useCallback(() => {if (!projectId || !jobId) return;@@ -111,5 +116,13 @@ export function useProjectApp() {};const openDonkey = () => { if (view?.project) void openLink(view.project.url, "Could not open Donkey Cut."); };const openDownload = () => { if (download) void openLink(download.url, "Could not open the download."); };- return { ready, view, playback, download, error, busy, visible, run, playbackFailed, openDonkey, openDownload };++ // The editor wants the whole window; the host grants what it supports.+ const requestMode = useCallback(async (mode: "fullscreen") => {+ const app = appRef.current;+ if (!app || !app.getHostContext()?.availableDisplayModes?.includes(mode)) return;+ try { await app.requestDisplayMode({ mode }); } catch { /* the inline card still works */ }+ }, []);+ useEffect(() => { if (editor) void requestMode("fullscreen"); }, [editor, requestMode]);+ return { ready, view, playback, download, editor, error, busy, visible, run, playbackFailed, openDonkey, openDownload };}diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 587b2620..3d42e980 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -1,7 +1,7 @@"use client";import { bindChatRuntime } from "@/cut/lib/chatRuntime";-import { useEffect, type ReactNode } from "react";+import { useEffect, useMemo, type ReactNode } from "react";import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";import {@@ -26,6 +26,14 @@ export function RequireSession({ children }: { children: ReactNode }) {const signedOut = !isPending && !session;const userId = session?.user.id;+ // Framed by the ChatGPT card, the page carries its own partitioned session;+ // a browser that dropped it gets a link out, since sign-in cannot run in a+ // frame.+ const embedded = useMemo(+ () => typeof window !== "undefined" && window.self !== window.top && new URLSearchParams(window.location.search).get("embed") === "chatgpt",+ [],+ );+useAppLoaded("cut", session?.user);// The account's configuration — public settings after overrides and@@ -56,11 +64,32 @@ export function RequireSession({ children }: { children: ReactNode }) {}, [userId]);useEffect(() => {- if (!signedOut) return;+ if (!signedOut || embedded) return;forgetRememberedEngineUser();const here = window.location.pathname + window.location.search;window.location.replace(authHrefFor("/sign-in", here));- }, [signedOut]);+ }, [signedOut, embedded]);+ if (signedOut && embedded) return <EmbeddedSignInFallback />;return <>{children}</>;}++function EmbeddedSignInFallback() {+ return (+ <div className="fixed inset-0 z-50 grid place-items-center bg-background p-6 text-center">+ <div className="max-w-sm space-y-3">+ <p className="text-sm text-muted-foreground">+ This browser keeps the editor signed out inside ChatGPT.+ </p>+ <a+ className="inline-block rounded-md border px-3 py-2 text-sm"+ href={window.location.pathname}+ target="_blank"+ rel="noopener"+ >+ Open in Donkey Cut+ </a>+ </div>+ </div>+ );+}