Skip to content

Open source CapCut alternative.

TypeScript

fix(chatgpt): resolve downloads within the editor session

David Le598515fb3d47
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
index 2aba6357..747bda6c 100644
--- a/site/scripts/eval-chatgpt-widget.ts
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -10,11 +10,28 @@ const root = path.resolve(import.meta.dir, "..");
const scratch = await mkdtemp(path.join(os.tmpdir(), "donkey-chatgpt-widget-"));
const video = path.join(scratch, "preview.mp4");
execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=blue:s=640x360:r=24", "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", video]);
+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 downloadRequests: { method: string; cookie: string | null; query: string }[] = [];
+const mediaRequests: string[] = [];
+const mediaServer = Bun.serve({ port: 0, fetch(request) {
+ mediaRequests.push(request.method);
+ return new Response(null, { headers: { "Access-Control-Allow-Origin": "*", "Content-Disposition": 'attachment; filename="export.mp4"' } });
+} });
+const signedDownload = `http://127.0.0.1:${mediaServer.port}/export.mp4?e=fixture&s=signed&d=export.mp4`;
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 === "/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 });
+ if (!request.headers.get("cookie")?.includes("editor-session=fixture")) return new Response(null, { status: 401 });
+ if (url.pathname.endsWith("/missing.mp4")) return new Response(null, { status: 404 });
+ return Response.redirect(signedDownload);
+ }
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><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>`, { 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" } });
} });
@@ -31,7 +48,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?code=card&project=project',expiresAt:Date.now()+60000} : {url:location.origin+'/embed?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=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}}});
@@ -39,7 +56,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?code=one-use&project=project',expiresAt:Date.now()+60000}) : result(view(true))), window.holdMs);
+ 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 === '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;
@@ -91,6 +108,39 @@ try {
await app.frameLocator("iframe.editor").locator("#mode").filter({ hasText: /^fullscreen$/ }).waitFor();
await app.frameLocator("iframe.editor").locator("#inset").filter({ hasText: /^120$/ }).waitFor();
assert.deepEqual(await page.evaluate(() => (window as unknown as { modes: string[] }).modes), ["fullscreen"], "the editor's button asks for the whole window");
+ const editorFrame = page.frames().find((f) => f.url().includes("/embed?"))!;
+ type Downloads = { downloadFromUrl: (url: string, name: string) => void; downloadFile: (url: string, name: string) => void };
+ await editorFrame.waitForFunction(() => "downloadFromUrl" in window);
+ await editorFrame.evaluate(() => (window as unknown as Downloads).downloadFromUrl("/api/cut-cloud/projects/project/exports/export.mp4?v=123", "export.mp4"));
+ await page.waitForFunction(() => (window as unknown as { links: string[] }).links.length === 2);
+ assert.equal(await page.evaluate(() => (window as unknown as { links: string[] }).links.at(-1)), signedDownload, "the host receives the signed URL");
+ assert.deepEqual(downloadRequests, [{ method: "HEAD", cookie: "editor-session=fixture", query: "?v=123&download=1" }], "resolve in the authenticated frame");
+ assert.deepEqual(mediaRequests, ["HEAD"], "resolving a download reads no media body");
+ await editorFrame.evaluate(() => (window as unknown as Downloads).downloadFromUrl("/api/cut-cloud/projects/project/exports/missing.mp4", "missing.mp4"));
+ await app.getByRole("alert").filter({ hasText: "Could not download missing.mp4" }).waitFor();
+ assert.equal(await page.evaluate(() => (window as unknown as { links: string[] }).links.length), 2, "a failed resolution opens no broken link");
+ await app.getByRole("button", { name: "Dismiss" }).click();
+ await app.getByRole("alert").waitFor({ state: "detached" });
+ await editorFrame.evaluate((url) => (window as unknown as Downloads).downloadFile(url, "export.mp4"), signedDownload);
+ await page.waitForFunction(() => (window as unknown as { links: string[] }).links.length === 3);
+ assert.equal(downloadRequests.length, 2, "already signed downloads open directly");
+ await page.context().clearCookies();
+ await editorFrame.evaluate(() => (window as unknown as Downloads).downloadFile("/api/cut-cloud/export/job/file", "export.mp4"));
+ await app.getByRole("alert").filter({ hasText: "Could not download export.mp4" }).waitFor();
+ assert.equal(await page.evaluate(() => (window as unknown as { links: string[] }).links.length), 3, "an expired session opens no link");
+ await app.getByRole("button", { name: "Dismiss" }).click();
+
+ const webPage = await browser.newPage();
+ await webPage.goto(`http://localhost:${server.port}/embed`);
+ await webPage.waitForFunction(() => "downloadFromUrl" in window);
+ const [download] = await Promise.all([
+ webPage.waitForEvent("download"),
+ webPage.evaluate(() => (window as unknown as Downloads).downloadFromUrl("/api/cut-cloud/projects/project/exports/export.mp4?v=123", "export.mp4")),
+ ]);
+ assert.equal(download.suggestedFilename(), "export.mp4");
+ assert.equal(downloadRequests.at(-1)?.method, "GET", "the standalone editor still downloads directly");
+ assert.equal(mediaRequests.at(-1), "GET");
+ await webPage.close();
await page.screenshot({ path: "/tmp/donkey-chatgpt-widget-editor.png" });
// 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
@@ -118,7 +168,7 @@ try {
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");
assert.deepEqual(errors, []);
- console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, editor in the card, 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, decoder teardown, lazy HLS.");
} finally {
- await browser.close(); server.stop(true); await rm(scratch, { recursive: true, force: true });
+ await browser.close(); server.stop(true); mediaServer.stop(true); await rm(scratch, { recursive: true, force: true });
}
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index 9a21b3f8..228cf290 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -10,6 +10,7 @@ export function PreviewApp() {
const rendering = preview?.status === "queued" || preview?.status === "running";
// The frame whose editor has said it is on screen.
const [shown, setShown] = useState<string | null>(null);
+ const [downloadError, setDownloadError] = useState<string | null>(null);
// 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
@@ -18,7 +19,8 @@ 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} />}
+ {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} />}
+ {downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>Dismiss</button></div>}
{error && project && !editor
? <div className="waiting">
<p role="alert">{error}</p>
@@ -78,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 }: { url: string; name: string; inset: number; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void }) {
+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 }) {
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);
@@ -89,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: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
// came from. Only the scheme is worth checking.
diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.css
index 0e899635..34d09e80 100644
--- a/site/src/clients/chatgpt/ui/preview.css
+++ b/site/src/clients/chatgpt/ui/preview.css
@@ -3,6 +3,7 @@
*{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;position:relative;height:560px;background:#fff;color:#20201e;color-scheme:light;--line:#dddcd6;--panel:#fff}[data-mode=fullscreen].editing{height:100vh}.editor{display:block;width:100%;height:100%;border:0;background:#fff}
.waiting,.skeleton{position:absolute;inset:0;background:#fff}.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 #e5e5e5}.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%}
diff --git a/site/src/cut/lib/download.ts b/site/src/cut/lib/download.ts
index 665ebb30..856db2e7 100644
--- a/site/src/cut/lib/download.ts
+++ b/site/src/cut/lib/download.ts
@@ -1,6 +1,7 @@
"use client";
import { openThroughHost, saveThroughHost } from "./hostBridge";
+import { editorHost } from "@/cut/lib/environment";
/**
* Save a served media file to the user's Downloads folder.
@@ -22,10 +23,31 @@ export function downloadFromUrl(url: string, name: string) {
* own and the browser saves it there.
*/
export function downloadFile(href: string, name: string) {
+ const url = new URL(href, window.location.href);
+ if (editorHost() === "chatgpt" && url.origin === window.location.origin && url.pathname.startsWith("/api/cut-cloud/")) {
+ void downloadThroughHost(url, name);
+ return;
+ }
if (openThroughHost(href)) return;
clickAnchor(window, href, name);
}
+/** Resolve cloud media while the frame's partitioned session is available.
+ * HEAD follows the signed redirect without reading the file into memory. */
+async function downloadThroughHost(url: URL, name: string) {
+ const report = (message: string | null) => window.parent.postMessage(
+ { type: "donkeycut:download-error", message }, "*"
+ );
+ report(null);
+ try {
+ const response = await fetch(url, { method: "HEAD", credentials: "same-origin", cache: "no-store" });
+ if (!response.ok || !response.redirected) throw new Error(`Download failed (${response.status}).`);
+ openThroughHost(response.url);
+ } catch {
+ report(`Could not download ${name}. Try again.`);
+ }
+}
+
/** Save text made in this tab — a captions file — to the user's Downloads
* folder. The blob is same-origin, so the anchor's own name is honored; inside
* the card the text goes to the host, which has no origin to be blocked by. */