Skip to content

Open source CapCut alternative.

TypeScript

fix(site): reconnect the ChatGPT editor session in place

David Lec38a9c6e8a73
diff --git a/docs/guides/chatgpt-app.md b/docs/guides/chatgpt-app.md
index a4d33662..758d2e3a 100644
--- a/docs/guides/chatgpt-app.md
+++ b/docs/guides/chatgpt-app.md
@@ -61,14 +61,10 @@ host bridge. It has no account cookie or OAuth token. Preview rendering uses
no Donkey Cut AI credits. Derived previews remain exempt from storage quota;
retained media uses the account's existing storage allowance.
-Every project card from a connection that can edit is the whole editor. The
-widget frames `donkeycut.com` through a one-use, one-minute link minted with
-each tool result; a card that wakes with a spent link asks for another. The
-link redeems for a partitioned session cookie, signing the editor in inside
-the frame until the connection is revoked; without partitioned cookies the
-frame offers an Open in Donkey Cut link. The editor's skeleton covers the
-frame until the frame reports something to show. `frameDomains` is justified
-as the app's own editor on its own domain.
+Editable cards frame Donkey Cut through a one-use, one-minute link that creates
+a partitioned session cookie. Reconnect renews that link through the tool bridge
+and reloads the editor. Revoking the connection ends its sessions; the editor skeleton
+covers loading, and `frameDomains` permits the app's own domain.
## Account linking
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
index 747bda6c..b265e664 100644
--- a/site/scripts/eval-chatgpt-widget.ts
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -13,6 +13,9 @@ execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i
const downloadBuild = await Bun.build({ entrypoints: [path.join(root, "src/cut/lib/download.ts")], target: "browser" });
assert.ok(downloadBuild.success, "download helper builds");
const downloadScript = await downloadBuild.outputs[0].text();
+const sessionBuild = await Bun.build({ entrypoints: [path.join(root, "scripts/lib/chatgpt-session-fixture.tsx")], target: "browser" });
+assert.ok(sessionBuild.success, "session recovery component builds");
+const sessionScript = await sessionBuild.outputs[0].text();
const downloadRequests: { method: string; cookie: string | null; query: string }[] = [];
const mediaRequests: string[] = [];
const mediaServer = Bun.serve({ port: 0, fetch(request) {
@@ -23,6 +26,7 @@ const signedDownload = `http://127.0.0.1:${mediaServer.port}/export.mp4?e=fixtur
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 === "/session.js") return new Response(sessionScript, { headers: { "Content-Type": "text/javascript" } });
if (url.pathname === "/download.js") return new Response(downloadScript, { headers: { "Content-Type": "text/javascript" } });
if (url.pathname.startsWith("/api/cut-cloud/")) {
downloadRequests.push({ method: request.method, cookie: request.headers.get("cookie"), query: url.search });
@@ -31,6 +35,7 @@ const server = Bun.serve({ port: 0, fetch(request) {
return Response.redirect(signedDownload);
}
if (url.pathname === "/preview.mp4") return new Response(Bun.file(video));
+ if (url.pathname === "/embed" && url.searchParams.get("code") === "signed-out") return new Response('<!doctype html><div id="session"></div><script type="module" src="/session.js"></script>', { headers: { "Content-Type": "text/html" } });
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><p id="inset"></p><p id="mode"></p><button id="full" onclick="parent.postMessage({ type: 'donkeycut:fullscreen' }, '*')">Fullscreen</button><script>addEventListener('message', (e) => { if (e.source === parent && e.data.type === 'donkeycut:host') { document.getElementById('inset').textContent = String(e.data.insetBottom); document.getElementById('mode').textContent = e.data.displayMode; } }); parent.postMessage({ type: 'donkeycut:host?' }, '*'); setTimeout(() => parent.postMessage({ type: 'donkeycut:ready' }, '*'), parent.parent.readyMs);</script><script type="module">import { downloadFromUrl, downloadFile } from '/download.js'; window.downloadFromUrl = downloadFromUrl; window.downloadFile = downloadFile;</script>`, { headers: { "Content-Type": "text/html", "Set-Cookie": "editor-session=fixture; Path=/api/cut-cloud/; HttpOnly; SameSite=Lax" } });
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" } });
@@ -39,7 +44,7 @@ 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 = []; window.modes = []; window.editable = false; window.holdMs = 0; window.readyMs = 0; window.freshCard = false;
+window.calls = []; window.links = []; window.modes = []; window.editable = false; window.holdMs = 0; window.readyMs = 0; window.freshCard = false; window.signedOut = false; window.failOpen = false; window.editorCodes = 0;
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,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;
@@ -48,7 +53,7 @@ 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=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(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});
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',displayMode:'inline',availableDisplayModes:['inline','fullscreen'],safeAreaInsets:{top:0,right:0,bottom:120,left:0}}});
@@ -56,7 +61,7 @@ window.addEventListener('message', ({source,data}) => {
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') setTimeout(() => reply(data.id, window.editable ? result(view(true),null,{url:location.origin+'/embed?embed=chatgpt&code=one-use&project=project',expiresAt:Date.now()+60000}) : result(view(true))), window.holdMs);
+ if(name === 'open_project') setTimeout(() => reply(data.id, window.failOpen ? {isError:true} : window.editable ? result(view(true),null,{url:location.origin+'/embed?embed=chatgpt&code=one-use-'+ ++window.editorCodes +'&project=project',expiresAt:Date.now()+60000}) : result(view(true))), window.holdMs);
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;
@@ -145,7 +150,7 @@ try {
// A card rehydrated with a spent link holds the editor's space, inline and
// without controls, while it mints a fresh link. The held reply outlasts the
// stale playback's one-second renewal, so a poll would show up in the calls.
- type Host = { calls: string[]; modes: string[]; holdMs: number; readyMs: number; freshCard: boolean };
+ type Host = { calls: string[]; modes: string[]; holdMs: number; readyMs: number; freshCard: boolean; signedOut: boolean; failOpen: boolean; links: string[] };
await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.holdMs = 1500; });
await frame.evaluate(() => { location.reload(); });
await page.waitForFunction(() => (window as unknown as Host).calls.length === 1);
@@ -167,8 +172,36 @@ try {
await app.frameLocator("iframe.editor").locator("#mode").filter({ hasText: /^inline$/ }).waitFor();
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).modes), ["fullscreen"], "a newly opened card opens inline");
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), [], "a live link needs no second call");
+ // Render the real signed-out control inside the editor frame.
+ await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.links = []; host.signedOut = true; host.readyMs = 0; host.holdMs = 300; });
+ await frame.evaluate(() => { location.reload(); });
+ const signedOutEditor = app.frameLocator("iframe.editor");
+ await signedOutEditor.getByRole("button", { name: "Reconnect", exact: true }).waitFor();
+ await app.locator(".skeleton").waitFor({ state: "detached" });
+ // The host page has the wrong source: it cannot request a session renewal.
+ await page.evaluate(() => document.querySelector("iframe")!.contentWindow!.postMessage({ type: "donkeycut:reconnect" }, "*"));
+ assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), [], "foreign frames cannot renew the editor session");
+ await signedOutEditor.getByRole("button", { name: "Reconnect", exact: true }).evaluate((button) => {
+ for (let i = 0; i < 3; i++) (button as HTMLButtonElement).click();
+ });
+ await app.locator(".skeleton").waitFor();
+ await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "one-use" }).waitFor();
+ await app.locator(".skeleton").waitFor({ state: "detached" });
+ assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), ["open_project"], "reconnect mints a fresh link once");
+ assert.equal(await page.evaluate(() => (window as unknown as Host).links.length), 0, "reconnect stays inside ChatGPT");
+
+ // Failure is visible and retry replaces the failed frame with a fresh link.
+ await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.failOpen = true; });
+ await frame.evaluate(() => { location.reload(); });
+ await signedOutEditor.getByRole("button", { name: "Reconnect", exact: true }).click();
+ await app.getByRole("alert").filter({ hasText: "Donkey Cut could not complete this request" }).waitFor();
+ assert.equal(await app.locator("iframe.editor").count(), 0, "failed recovery releases the signed-out frame");
+ await page.evaluate(() => { (window as unknown as Host).failOpen = false; });
+ await app.getByRole("button", { name: "Try again", exact: true }).click();
+ await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "one-use" }).waitFor();
+ assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), ["open_project", "open_project"], "manual retry recovers without a browser refresh");
assert.deepEqual(errors, []);
- console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, editor in the card, authenticated download redirects, download errors, skeleton until ready, waking editor card, 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, authenticated download redirects, download errors, skeleton until ready, waking editor card, session renewal and retry, decoder teardown, lazy HLS.");
} finally {
await browser.close(); server.stop(true); mediaServer.stop(true); await rm(scratch, { recursive: true, force: true });
}
diff --git a/site/scripts/lib/chatgpt-session-fixture.tsx b/site/scripts/lib/chatgpt-session-fixture.tsx
new file mode 100644
index 00000000..35b242c4
--- /dev/null
+++ b/site/scripts/lib/chatgpt-session-fixture.tsx
@@ -0,0 +1,4 @@
+import { createRoot } from "react-dom/client";
+import { EmbeddedSignInFallback } from "../../src/cut/components/EmbeddedSignInFallback";
+
+createRoot(document.getElementById("session")!).render(<EmbeddedSignInFallback />);
diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.ts
index 93824536..82f592cf 100644
--- a/site/src/clients/chatgpt/server/mcp.ts
+++ b/site/src/clients/chatgpt/server/mcp.ts
@@ -55,7 +55,7 @@ export const SERVER_INSTRUCTIONS = [
"You plan the edit with the user and interpret the footage; Donkey Cut supplies media inspection, signal measurements and editing commands. Use the user's assets and references. Ask for missing files, links or creative decisions when they are needed to fulfill the request. Use list_commands and describe_commands as the capability and input contract, and read_skill for guidance tailored to this ChatGPT client.",
"Workflow: list_projects or create_project → open_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.",
"Every edit runs inside the Donkey Cut editor in the card, on the document the user is looking at: open_project puts that editor in the card, timeline and panels included, when the connection can edit, and edit_project, inspect_project, import_media, undo and redo answer that no card is open until it is. A read-only connection sees the current preview playing. Call render_preview only after an edit or when the card reports no current preview.",
- "If a tool reports no card open, ask the user to open the project card and keep it open, then resume when it is ready. When the catalog lacks an operation, explain the limit and ask for the required media or a user action in Donkey Cut.",
+ "If the editor shows Reconnect, ask the user to click it to renew the embedded session and reload the editor in ChatGPT. If a tool reports no card open, ask the user to open the project card and keep it open, then resume when it is ready. When the catalog lacks an operation, explain the limit and ask for the required media or a user action in Donkey Cut.",
"Inspect before editing. Watch and listen to the relevant media before content-based cuts; use silence, beat, level and color measurements for timing and adjustments. Commands marked reads run through inspect_project; observations saved with note_source and other writes run through edit_project. Verify changes with the returned state, frames and audio, and give the user a preview to review. Claim only coverage and completed work confirmed by tool results.",
"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");
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index 228cf290..34518146 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -19,7 +19,7 @@ export function PreviewApp() {
if (view ? project && view.canEdit : !error) {
const loading = !editor || shown !== editor.url;
return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={loading}>
- {editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} />}
+ {editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}
{downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>Dismiss</button></div>}
{error && project && !editor
? <div className="waiting">
@@ -80,7 +80,7 @@ function EditorSkeleton() {
* 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, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError }: { url: string; name: string; inset: number; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void }) {
+function EditorFrame({ url, name, inset, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; name: string; inset: number; 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 }) {
const frame = useRef<HTMLIFrameElement>(null);
const origin = new URL(url).origin;
const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);
@@ -91,6 +91,7 @@ function EditorFrame({ url, name, inset, fullscreen, onReady, onFullscreen, onOp
if (event.data?.type === "donkeycut:host?") tell();
if (event.data?.type === "donkeycut:ready") onReady();
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);
// The frame is the editor on this origin, so what it asks to open is
// the editor's own link — a project page, an export, the post a clip
diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.ts
index 78d384a8..41811930 100644
--- a/site/src/clients/chatgpt/ui/useProjectApp.ts
+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts
@@ -20,6 +20,7 @@ export function useProjectApp() {
const [hostInset, setHostInset] = useState(0);
const [editorRequest, setEditorRequest] = useState<string | null>(null);
const requested = useRef<string | null>(null);
+ const reconnecting = useRef(false);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [visible, setVisible] = useState(!document.hidden);
@@ -151,8 +152,15 @@ export function useProjectApp() {
requested.current = editorRequest;
void run("open_project", { projectId: editorRequest }, false);
}, [ready, editorRequest, editor, run]);
- /** Asks again for the link a waking card could not get. */
- const retryEditor = () => { if (view?.project) void run("open_project", { projectId: view.project.id }); };
+ /** A fresh one-use link replaces the frame and renews its session cookie. */
+ const retryEditor = () => {
+ if (!ready || busy || reconnecting.current || !projectId) return;
+ reconnecting.current = true;
+ requested.current = projectId;
+ setEditorRequest(null);
+ setEditor(null);
+ void run("open_project", { projectId }).finally(() => { reconnecting.current = false; });
+ };
// The editor's own button asks for the whole window; the host grants what it supports.
const requestFullscreen = useCallback(async () => {
diff --git a/site/src/cut/components/EmbeddedSignInFallback.tsx b/site/src/cut/components/EmbeddedSignInFallback.tsx
new file mode 100644
index 00000000..8d96041d
--- /dev/null
+++ b/site/src/cut/components/EmbeddedSignInFallback.tsx
@@ -0,0 +1,17 @@
+"use client";
+
+import { reconnectThroughHost, useHostReady } from "@/cut/lib/hostBridge";
+
+export function EmbeddedSignInFallback() {
+ useHostReady(true);
+ return (
+ <div className="fixed inset-0 z-[60] 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">Reconnect to continue editing here.</p>
+ <button type="button" className="rounded-md border px-3 py-2 text-sm" onClick={reconnectThroughHost}>
+ Reconnect
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index b39e1be5..9f40447b 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -3,7 +3,7 @@ import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge } from "
import { useEffect, type ReactNode } from "react";
import { useEnvironment } from "@/cut/lib/environment";
-import { openExternal, projectPageUrl, useHostReady } from "@/cut/lib/hostBridge";
+import { EmbeddedSignInFallback } from "@/cut/components/EmbeddedSignInFallback";
import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
import {
@@ -29,8 +29,7 @@ export function RequireSession({ children }: { children: ReactNode }) {
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.
+ // a browser that dropped it renews it through the card's tool bridge.
const { chatgpt: embedded } = useEnvironment();
useAppLoaded("cut", session?.user);
@@ -75,25 +74,3 @@ export function RequireSession({ children }: { children: ReactNode }) {
if (signedOut && embedded) return <EmbeddedSignInFallback />;
return <>{children}</>;
}
-
-// Above the app's loading cover, which waits on an account this frame never
-// gets.
-function EmbeddedSignInFallback() {
- useHostReady(true);
- return (
- <div className="fixed inset-0 z-[60] 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">
- You’re signed out.
- </p>
- <button
- type="button"
- className="inline-block rounded-md border px-3 py-2 text-sm"
- onClick={() => openExternal(projectPageUrl())}
- >
- Open in Donkey Cut
- </button>
- </div>
- </div>
- );
-}
diff --git a/site/src/cut/lib/hostBridge.ts b/site/src/cut/lib/hostBridge.ts
index b33c10f0..06d3ff13 100644
--- a/site/src/cut/lib/hostBridge.ts
+++ b/site/src/cut/lib/hostBridge.ts
@@ -33,6 +33,12 @@ export function requestHostFullscreen() {
window.parent.postMessage({ type: "donkeycut:fullscreen" }, "*");
}
+/** Renew the frame's partitioned session through the authenticated tool bridge. */
+export function reconnectThroughHost() {
+ if (editorHost() !== "chatgpt") return;
+ window.parent.postMessage({ type: "donkeycut:reconnect" }, "*");
+}
+
/**
* Open a page in a tab the host owns. Answers whether the host took it, so a
* caller on the web falls through to its own navigation.