Open source CapCut alternative.
TypeScript
fix(cut): persist chat turns and synchronize project work [rebuild]
David Le75317cfbebd9
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.mdindex 9bb59568..24195c5e 100644--- a/docs/guides/cut/ai-assistant.md+++ b/docs/guides/cut/ai-assistant.md@@ -29,9 +29,11 @@ user message + @attachments + fresh <editor_state> snapshotturn job runs the whole turn in the worker container```-On the engine path, the chat route holds one streaming response open per turn. The provider sees a single MCP server named `cut`: a small stdio proxy the provider harness spawns, which forwards every tool listing and call to the engine over HTTP. The engine writes each call into the open chat stream; the tab executes it on the editor store and posts the result back; the engine hands it to the waiting provider. A call the tab never answers times out after two minutes.+The Mac engine serves native Bun Request/Response streams and drains each turn into a disk journal independently of its readers. Reopening an unfinished turn replays that journal under the same assistant message id; saved completed replies stay settled. Stop explicitly cancels the provider. The provider sees a single MCP server named `cut`: a small stdio proxy the provider harness spawns, which forwards every tool listing and call to the engine over HTTP. The engine writes each call into the open chat stream; the tab executes it on the editor store and posts the result back; the engine hands it to the waiting provider. A call the tab never answers times out after two minutes.-A turn outlives its tab. The bridge remembers each session's project, so a call arriving after the editor stream closed runs in the engine itself: the doc on disk hydrates into the same editor store, the tool runs, and the result lands back on disk — re-read fresh each call, so a page save between turns survives. Tools that need the page's decoders or its hosted sign-in answer with a typed refusal, and the mapping drops when the provider run settles so a reloaded tab never races a leftover executor.+A Claude or Codex turn can outlive its tab while the Mac engine remains running. The bridge retains the session's project after its last reader disconnects and executes subsequent document tools against that project on disk. Running threads keep their editor connection when the chat panel is hidden or another thread is selected. Tool claims let one attached tab execute each call; a disconnected call with an uncertain result returns that uncertainty to the model. Headless calls serialize access to the engine's editor store, and every call records its result in the journal. The Next.js development server invokes the same executor through Bun, which can load the shared editor modules. Tools that need the page's media primitives or hosted sign-in still return a typed error when detached.++Gemini's interactive turn runs in the browser. Its active turn survives panel and project navigation within that page, saves its final transcript after unmount, and waits for its original project before executing another editor tool. Opening another project waits for tools already using the store. Closing the browser tab ends this loop; the cloud worker's queued-turn API is a separate execution path. Project residency stays fixed throughout these transitions.The Gemini path skips the engine entirely — the same carve-out as AI media generation. The loop runs on the pi agent harness (the `@earendil-works` packages) in the browser: a custom transport speaks Donkey's hosted responses route with the user's session, tools execute directly against the store, and each thread's conversation persists as the harness's own structured history — past tool calls replay as real tool records, so no bookkeeping rides as prose the model could imitate. Gemini's quirks live in that transport: thought signatures replay exactly with each call, tool media returns as its own following turn, and an empty round retries before it surfaces as an error.@@ -98,11 +100,11 @@ With a tab attached, tool calls execute in it against the same store the user isMost generation tools make one asset — an image, a video clip, a voiceover, or a music track (`generate_music`, a vocal-free bed by default and a full sung song on request, scene-aware enough to score a whole video, and able to match a track to a reference the user attaches — an audio clip to emulate or a video whose tone it should carry, since the music model reads only text a multimodal pass turns the reference into the sound description it renders from). `generate_scene` makes a whole cut: it writes a script, breaks it into shots, and — once the user approves — renders each shot and lays them on the timeline. The video model speaks each shot's line, so the clips carry their own narration; a music bed sits under them. It is genre-agnostic; the look comes from the brief and any references. It can also animate audio the project already has (`from_audio_asset_id`), tiling shots over that spine with no script written.-Because a scene renders many paid shots, the tool plans and then stops. `generate_scene` returns a shot list and waits; `approve_scene` starts the renders; `regenerate_shot`, `recut_scene`, and `restyle_scene` revise afterward; `cancel_scene` kills the active run. A plan created this turn cannot be approved in the same turn — the harness blocks that call whatever the model decides, so the money gate is structural. The plan the user approves is the plan that renders: voicing runs after the gate and only rescales the approved shots to the real voice lengths (a line longer than one clip splits its shot). The run is browser-side like every generation here, held in a small store beside the panels (`lib/genScene.ts`) so switching tabs never orphans it; leaving the project pauses it, its persisted plan (`ProjectDoc.genvideo`) resumes on the next open, and a run that dies persists as failed so a reload never resumes it. Nothing runs behind the user's back: cancelling, dismissing an unrendered plan, or deleting the chat thread that asked all stop the run and clear its plan — clips already placed stay on the timeline. Progress shows on a card in the chat while the timeline fills on its own. The shots ride under one consistent AI voice with the video model's own audio off; this version has no talking-head lip-sync.+Because a scene renders many paid shots, the tool plans and then stops. `generate_scene` returns a shot list and waits; `approve_scene` starts the renders; `regenerate_shot`, `recut_scene`, and `restyle_scene` revise afterward; `cancel_scene` kills the active run. A plan created this turn cannot be approved in the same turn — the harness blocks that call whatever the model decides, so the money gate is structural. The plan the user approves is the plan that renders: voicing runs after the gate and only rescales the approved shots to the real voice lengths (a line longer than one clip splits its shot). The scene coordinator lives beside the panels (`lib/genScene.ts`) and keeps working across project navigation while its page is alive. Its persisted plan (`ProjectDoc.genvideo`) lets a returning page resume planning or rendering. Each operation acquires project ownership: Web Locks for browser storage, an engine lease for Mac projects, and a database lease for cloud projects. Other tabs follow the saved plan. A resumed scene clears the chat tool's stale interruption, and reaching the storyboard gate settles that call. Failed plans retain their failure until an explicit retry. Nothing runs behind the user's back: cancelling, dismissing an unrendered plan, or deleting the chat thread that asked all stop the run and clear its plan — clips already placed stay on the timeline. Progress shows on a card in the chat while the timeline fills on its own. The shots ride under one consistent AI voice with the video model's own audio off; this version has no talking-head lip-sync.## Context across turns-Threads persist per project in the browser's local storage — the newest 30, titled by their first message. A cloud project also mirrors each thread to the hosted chat routes (Postgres, keyed to the account), merging the server copy back into local storage on open, so its history follows the account across devices. What a returning thread remembers depends on the provider:+Threads persist per project in the browser's local storage — the newest 30, titled by their first message. A cloud project also mirrors each thread to the hosted chat routes (Postgres, keyed to the account), merging the server copy on open and periodically while visible, so its history follows the account across devices. Polls read revision metadata and fetch changed conversations. Deletion records prevent late completions and offline copies from restoring removed threads. Storage events update other tabs on the same origin, including their provider sessions. Idle editors also follow saved project revisions, preserving the playhead and waiting while playback, unsaved edits, or editor tools are active. This follows committed snapshots; it does not merge simultaneous edits to the same document. What a returning thread remembers depends on the provider:- **Claude and Codex hold their own history.** Each turn sends only the newest message plus the fresh snapshot; prior turns live in the provider's native session, whose id is saved on the thread and resumed. The engine never replays conversation history itself.- **Gemini replays its own session.** The pi harness keeps the thread's conversation as structured history — real tool calls and their results — and saves it with the thread, so a reload picks it back up. Every call is replayed from that history with only the newest snapshot kept and media trimmed to budget; a thread with no saved session falls back to a text-only replay of what the panel shows.@@ -133,7 +135,7 @@ A hidden hermetic test provider exercises the full engine bridge — context, toA live eval scores the chat brain's behavior and speed together. Each of its cases replays a real composer turn against the live model — through the same loop code production runs — and asserts what came back: the reply, the tools called, the gate verdict, tools that must stay sheathed, and the reply's shape (no leaked scaffolding, no trailing upsell), with a light-model judge leaving tone notes beside the pass/fail. All of it is timed: the gate call, time to first token, every round, every tool serve. Cases carry a bucket (chat turns, single-tool edits, multi-tool composed edits) so the numbers aggregate by the kind of turn a user feels.-The committed report at `evals/cut-chat.latest-report.json` is the baseline. The improvement loop: make one change — a model role, a prompt line, a tool description — run the eval, and keep the change only when pass rates hold and the medians improve; the new report commits with the change, so the baseline always describes what ships. This is how the complexity router and the batched-round cutting flow earned their way in. Run it with the dev server up: `npm run eval:cut-chat` (add `--matrix --runs 3` to compare model configs); the README beside the harness under the site's `scripts/lib/cut-eval/` folder covers the flags, the report schema, and how to add a case. The tab-less paths have their own end-to-end scripts, which drive a real turn against a seeded cloud project through the headless session and through the queued turn job.+The committed report at `evals/cut-chat.latest-report.json` is the baseline. The improvement loop: make one change — a model role, a prompt line, a tool description — run the eval, and keep the change only when pass rates hold and the medians improve; the new report commits with the change, so the baseline always describes what ships. This is how the complexity router and the batched-round cutting flow earned their way in. Run it with the dev server up: `npm run eval:cut-chat` (add `--matrix --runs 3` to compare model configs); the README beside the harness under the site's `scripts/lib/cut-eval/` folder covers the flags, the report schema, and how to add a case. Run `node scripts/check-chat-continuity.mjs /path/to/compiled-engine` to verify disconnect recovery, replay, and the native HTTP media boundary without tokens. The tab-less paths also have end-to-end scripts, which drive a real turn against a seeded cloud project through the headless session and through the queued turn job.Two mechanical paths are guarded without a model at all, because no ear settles them from a preview: caption timing (`npm run eval:cut-sync`) and speech-cut placement (`npm run eval:cut-edges`). Both build their own truth — a take of known words rendered to audio — run the production code over it, and enforce budgets on the result, so a regression in either shows up in seconds with no network and no credits.diff --git a/site/scripts/check-chat-continuity.mjs b/site/scripts/check-chat-continuity.mjsnew file mode 100644index 00000000..5de4a445--- /dev/null+++ b/site/scripts/check-chat-continuity.mjs@@ -0,0 +1,87 @@+import assert from 'node:assert/strict';+import { request } from 'node:http';+import { spawn } from 'node:child_process';+import { mkdtemp, rm, readdir, readFile } from 'node:fs/promises';+import { createServer } from 'node:net';+import { once } from 'node:events';+import path from 'node:path';+import os from 'node:os';++// Run against a freshly compiled engine; all projects and journals are temporary.+const binary = process.argv[2];+if (!binary) throw new Error('Usage: node scripts/check-chat-continuity.mjs /path/to/engine');+const root = await mkdtemp(path.join(os.tmpdir(), 'donkey-chat-http-'));+const probe = createServer();+probe.listen(0, '127.0.0.1');+await once(probe, 'listening');+const port = probe.address().port;+await new Promise(resolve => probe.close(resolve));+const engine = spawn(path.resolve(binary), [], { env: { ...process.env, DONKEY_CUT_DATA_DIR: root, DONKEY_CUT_PORT: String(port) }, stdio: ['ignore', 'pipe', 'pipe'] });+const logs = [];+engine.stdout.on('data', data => logs.push(data.toString()));+engine.stderr.on('data', data => logs.push(data.toString()));+const base = `http://127.0.0.1:${port}/api/cut`;+const pause = () => new Promise(resolve => setTimeout(resolve, 100));+try {+ let ready = false;+ for (let i = 0; i < 100; i++) {+ if (await fetch(`${base}/projects`).then(r => r.ok).catch(() => false)) { ready = true; break; }+ await pause();+ }+ assert(ready, 'engine started');+ const made = await fetch(`${base}/projects`, { method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify({name: 'Closed tab fixture'}) });+ assert(made.ok);+ const project = await made.json();+ const head = await fetch(`${base}/projects/${project.id}`, { method: 'HEAD', headers: { origin: 'https://donkeycut.com' } });+ assert(head.headers.get('x-cut-doc-version'));+ assert(head.headers.get('access-control-expose-headers')?.includes('x-cut-doc-version'));+ assert.equal(await head.text(), '');+ const opened = await fetch(`${base}/projects/${project.id}`);+ assert.equal(opened.headers.get('x-cut-doc-version'), head.headers.get('x-cut-doc-version'));+ const saved = await fetch(`${base}/projects/${project.id}`, {+ method: 'PUT', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name: 'Closed tab fixture renamed' }),+ }).then(response => response.json());+ const changedHead = await fetch(`${base}/projects/${project.id}`, { method: 'HEAD' });+ assert.equal(changedHead.headers.get('x-cut-doc-version'), saved.revision);+ assert.notEqual(saved.revision, head.headers.get('x-cut-doc-version'));++ const blocked = await fetch(`${base}/projects`, {headers:{origin:'https://example.com'}});+ assert.equal(blocked.status, 403);+ const preflight = await fetch(`${base}/projects`, {method:'OPTIONS',headers:{origin:'https://donkeycut.com','access-control-request-headers':'content-type'}});+ assert.equal(preflight.status, 204);+ const media = new FormData();+ media.set('file',new File(['0123456789'], 'continuity.txt', {type:'text/plain'}));+ const upload = await fetch(`${base}/projects/${project.id}/media`, {method:'POST',body:media});+ assert(upload.ok, 'multipart media upload');+ const {fileName} = await upload.json();+ const range = await fetch(`${base}/projects/${project.id}/media/${encodeURIComponent(fileName)}`, {headers:{range:'bytes=2-5'}});+ assert.equal(range.status,206);+ assert.equal(await range.text(),'2345');+ const threadId = 'http-check';+ await new Promise((resolve,reject) => {+ const req = request(`${base}/ai/chat`, { method:'POST', agent:false, headers:{'content-type':'application/json'} }, response => {+ assert.equal(response.statusCode,200);+ response.once('data', () => { response.destroy(); req.destroy(); resolve(); });+ });+ req.on('error', error => { if (error.code !== 'ECONNRESET') reject(error); });+ req.end(JSON.stringify({threadId, model:'cut-test', runtime:{syncIntervalMs:5000,sceneLeaseMs:30000,journalBytes:8388608},context:{project:{id:project.id}},messages:[{id:'ask',role:'user',parts:[{type:'text',text:'Add the test title.'}]}]}));+ });+ let doc;+ for (let i = 0; i < 100; i++) {+ doc = await fetch(`${base}/projects/${project.id}`).then(r => r.json());+ if (doc.overlays?.some(o => o.text === 'TESTMARK title')) break;+ await pause();+ }+ assert.equal(doc.overlays.filter(o => o.text === 'TESTMARK title').length, 1);+ const journal = await fetch(`${base}/ai/chat/${threadId}/stream?projectId=${project.id}`).then(r => r.text());+ assert(journal.includes('Done: TESTMARK title added.'));+ assert(journal.includes('data: [DONE]'));+ assert(!journal.includes('"type":"tool-output-error"'));+ console.log('PASS: detached chat completion, single tool application, journal replay, cross-origin revision headers, CORS, multipart upload, and media range reads.');+} catch (error) { console.error(logs.join('')); for(const file of await readdir(root+'/chat-streams').catch(()=>[])) console.error(await readFile(root+'/chat-streams/'+file,'utf8')); throw error; }+finally {+ engine.kill('SIGTERM');+ await once(engine, 'close');+ await rm(root, {recursive:true,force:true});+}diff --git a/site/src/cut/engine/serve.ts b/site/src/cut/engine/serve.tsindex 7e92d2e0..8bf81571 100644--- a/site/src/cut/engine/serve.ts+++ b/site/src/cut/engine/serve.ts@@ -1,6 +1,3 @@-import { createServer, type IncomingMessage, type ServerResponse } from "node:http";-import { Readable } from "node:stream";-import { allowedOrigin, corsHeaders, preflightHeaders } from "../server/cors";import { matchCutRoute, runCutRoute } from "../server/http/routes";import { flattenCutUsers, migrateCutDataDir } from "../server/migrateDataDir";@@ -12,50 +9,15 @@ import { enginePort } from "./config";// binding a random port the client would never find.const PORT = enginePort();-function toWebRequest(req: IncomingMessage, signal: AbortSignal): Request {- const headers = new Headers();- for (const [k, v] of Object.entries(req.headers)) {- if (Array.isArray(v)) for (const x of v) headers.append(k, x);- else if (typeof v === "string") headers.set(k, v);- }- const method = req.method ?? "GET";- const hasBody = method !== "GET" && method !== "HEAD";- const init: RequestInit = {- method,- headers,- signal,- ...(hasBody ? { body: Readable.toWeb(req) as unknown as BodyInit, duplex: "half" } : {}),- } as RequestInit;- return new Request(`http://127.0.0.1:${PORT}${req.url ?? "/"}`, init);-}--async function writeResponse(- res: Response,- out: ServerResponse,- cors: string | null,- headOnly: boolean-) {- if (cors) for (const [k, v] of Object.entries(corsHeaders(cors))) out.setHeader(k, v);- out.statusCode = res.status;- res.headers.forEach((v, k) => out.setHeader(k, v));- // A HEAD reply carries the GET headers but no body.- if (headOnly || !res.body) {- void res.body?.cancel();- out.end();- return;- }- await new Promise<void>((resolve) => {- const stream = Readable.fromWeb(res.body as never);- stream.on("error", () => out.destroy());- out.on("close", () => {- // Client hung up mid-response: tear down the source so its file- // descriptor / handle is released instead of reading on to nowhere.- if (!out.writableFinished) stream.destroy();- resolve();- });- stream.pipe(out);- });-}+// The engine's native HTTP boundary preserves Request.signal and stream cancellation.+// The hosted site's TypeScript build has DOM types; this is the Bun API the binary uses.+const native = (globalThis as unknown as { Bun: { serve(options: {+ hostname: string;+ port: number;+ idleTimeout: number;+ maxRequestBodySize: number;+ fetch: (request: Request) => Promise<Response>;+}): unknown } }).Bun;/** The engine never outlives the app that spawned it: a survivor would keep* the port and serve a stale build after an app update. The app passes its@@ -88,78 +50,43 @@ async function start() {if (claude) process.env.DONKEY_CUT_CLAUDE = claude;}- const server = createServer((req, res) => {- const origin = req.headers.origin ?? "";- const cors = allowedOrigin(origin);-- // A present-but-unlisted Origin is a foreign site's browser tab; refuse it- // before any handler runs so a malicious page can't drive the local engine.- // No Origin header means a same-machine / non-browser caller — allowed.- if (origin && !cors) {- res.writeHead(403);- res.end("Cross-origin request refused.");- return;- }-- if (req.method === "OPTIONS") {- if (cors) {- const requested = req.headers["access-control-request-headers"];- res.writeHead(204, preflightHeaders(cors, typeof requested === "string" ? requested : null));- } else {- res.writeHead(204);- }- res.end();- return;- }-- const method = req.method ?? "GET";- const pathname = (req.url ?? "/").split("?")[0];- const match = matchCutRoute(method, pathname);- if (!match) {- res.writeHead(404, cors ? corsHeaders(cors) : {});- res.end("Not found.");- return;- }- if ("methodNotAllowed" in match) {- res.writeHead(405, { Allow: match.methodNotAllowed.join(", "), ...(cors ? corsHeaders(cors) : {}) });- res.end("Method not allowed.");- return;- }-- // Abort only on a real client disconnect. On node:http, req 'close' fires- // once the request body is fully read — not on hang-up — so keying the- // abort off req would cancel every turn the instant its body arrived.- const aborter = new AbortController();- res.on("close", () => {- if (!res.writableFinished) aborter.abort();- });-- void (async () => {+ native.serve({+ hostname: "127.0.0.1",+ port: PORT,+ idleTimeout: 0,+ // Project media streams to disk and can exceed Bun's default body limit.+ maxRequestBodySize: Number.MAX_SAFE_INTEGER,+ async fetch(req) {+ const origin = req.headers.get("origin") ?? "";+ const cors = allowedOrigin(origin);+ if (origin && !cors) return new Response("Cross-origin request refused.", { status: 403 });+ if (req.method === "OPTIONS") return new Response(null, {+ status: 204,+ headers: cors ? preflightHeaders(cors, req.headers.get("access-control-request-headers")) : {},+ });+ const headers = cors ? corsHeaders(cors) : {};+ const match = matchCutRoute(req.method, new URL(req.url).pathname);+ if (!match) return new Response("Not found.", { status: 404, headers });+ if ("methodNotAllowed" in match) return new Response("Method not allowed.", {+ status: 405, headers: { ...headers, Allow: match.methodNotAllowed.join(", ") },+ });try {- const webReq = toWebRequest(req, aborter.signal);- const webRes = await runCutRoute(webReq, match);- await writeResponse(webRes, res, cors, match.head);- } catch (err) {- if (!res.headersSent) {- res.writeHead(500, {- "Content-Type": "application/json",- ...(cors ? corsHeaders(cors) : {}),- });- }- res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }));+ const response = await runCutRoute(req, match);+ const merged = new Headers(response.headers);+ for (const [key, value] of Object.entries(headers)) merged.set(key, value);+ if (match.head) await response.body?.cancel();+ return new Response(match.head ? null : response.body, {+ status: response.status, statusText: response.statusText, headers: merged,+ });+ } catch (error) {+ return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500, headers });}- })();- });-- // Exit on a failed bind (typically EADDRINUSE while another session still- // holds the port) so the supervisor's backoff drives the retry.- server.on("error", (err) => {- console.error(`donkey-cut-engine could not listen on 127.0.0.1:${PORT}: ${err.message}`);- process.exit(1);- });- server.listen(PORT, "127.0.0.1", () => {- console.log(`donkey-cut-engine listening on http://127.0.0.1:${PORT}`);+ },});+ console.log(`donkey-cut-engine listening on http://127.0.0.1:${PORT}`);}-void start();+void start().catch((error) => {+ console.error(`donkey-cut-engine could not start: ${error instanceof Error ? error.message : String(error)}`);+ process.exit(1);+});diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex 44445396..8f6cca66 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -864,20 +864,21 @@ export function selectionRefTokens(s: EntitySources & {* Names are unique within the list (first scope wins) so a mention resolves* to one asset. Library items mention by name; stock ids are already short* (`@nature-dunes`). */-export function useRefCandidates(): AssetRef[] {- const assets = useEditor((s) => s.assets);- const clips = useEditor((s) => s.clips);- const audioClips = useEditor((s) => s.audioClips);- const overlays = useEditor((s) => s.overlays);- const transitions = useEditor((s) => s.transitions);- const subtitles = useEditor((s) => s.subtitles);- const projectTemplates = useEditor((s) => s.templates);+export function useRefCandidates(enabled = true): AssetRef[] {+ const assets = useEditor((s) => enabled ? s.assets : null);+ const clips = useEditor((s) => enabled ? s.clips : null);+ const audioClips = useEditor((s) => enabled ? s.audioClips : null);+ const overlays = useEditor((s) => enabled ? s.overlays : null);+ const transitions = useEditor((s) => enabled ? s.transitions : null);+ const subtitles = useEditor((s) => enabled ? s.subtitles : null);+ const projectTemplates = useEditor((s) => enabled ? s.templates : null);// The same listing the Library panel and the Camera Roll read, so a clip// uploaded from the phone or a template just pushed to the shelf is// mentionable the moment it lands.- const lib = useLibrary().data ?? EMPTY_LIBRARY;+ const lib = useLibrary({ enabled }).data ?? EMPTY_LIBRARY;return useMemo(() => {+ if (!assets || !clips || !audioClips || !overlays || !transitions || !subtitles || !projectTemplates) return [];const project = projectRefs(assets);const seen = new Set<string>();const out: AssetRef[] = [];diff --git a/site/src/cut/lib/backend/browser/opfs.ts b/site/src/cut/lib/backend/browser/opfs.tsindex f316f5eb..eaa990b8 100644--- a/site/src/cut/lib/backend/browser/opfs.ts+++ b/site/src/cut/lib/backend/browser/opfs.ts@@ -167,16 +167,25 @@ export async function updateIndex(mutate: (idx: StoreIndex) => StoreIndex | void// --- docs ---+export async function docFile(id: string): Promise<File | null> {+ return readFileAt(await projectDir(id), "project.json");+}+export async function readDoc(id: string): Promise<ProjectDoc | null> {return readJson<ProjectDoc>(await projectDir(id), "project.json");}-export async function writeDoc(id: string, doc: ProjectDoc): Promise<void> {- const dir = await projectDir(id, true);- if (!dir) throw new Error("Browser storage is unavailable.");- doc.id = id;- doc.updatedAt = Date.now();- await writeFileAt(dir, "project.json", JSON.stringify(doc));+export async function writeDoc(id: string, doc: ProjectDoc): Promise<string> {+ return withStoreLock(`doc:${id}`, async () => {+ const dir = await projectDir(id, true);+ if (!dir) throw new Error("Browser storage is unavailable.");+ doc.id = id;+ doc.updatedAt = Date.now();+ await writeFileAt(dir, "project.json", JSON.stringify(doc));+ const file = await readFileAt(dir, "project.json");+ if (!file) throw new Error("Could not read the saved project.");+ return String(file.lastModified);+ });}/** Every project id in the store (directories holding a readable doc). */diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.tsindex 2e04ce09..05fcdeeb 100644--- a/site/src/cut/lib/backend/browser/router.ts+++ b/site/src/cut/lib/backend/browser/router.ts@@ -114,8 +114,8 @@ async function putProject(req: Request, id: string): Promise<Response> {genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,renders: Array.isArray(body.renders) ? body.renders : existing.renders,};- await store.writeDoc(id, doc);- return json({ ok: true, updatedAt: doc.updatedAt });+ const revision = await store.writeDoc(id, doc);+ return json({ ok: true, updatedAt: doc.updatedAt, revision });} catch (e) {return caught(e, "Could not save project.");}@@ -386,9 +386,11 @@ export async function dispatchBrowserRoute(// /projects/:idif (rest.length === 2) {if (method === "HEAD" || method === "GET") {- const doc = await store.readDoc(id);- if (!doc) return err("Project not found.", 404);- return method === "HEAD" ? new Response(null, { status: 200 }) : json(doc);+ const file = await store.docFile(id);+ if (!file) return err("Project not found.", 404);+ const headers = { "x-cut-doc-version": String(file.lastModified) };+ if (method === "HEAD") return new Response(null, { headers });+ return new Response(file, { headers: { ...headers, "Content-Type": "application/json" } });}if (method === "PUT") return putProject(req(), id);if (method === "DELETE") {diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.tsindex 948459bd..e972d9fc 100644--- a/site/src/cut/lib/backend/cloud.ts+++ b/site/src/cut/lib/backend/cloud.ts@@ -4,7 +4,7 @@// Media bytes ride presigned R2 URLs minted by those routes, not this// transport.import { emitStorageQuota } from "../storageQuota";-import type { CutBackend } from "./types";+import type { CutBackend, CutRequestInit } from "./types";const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");@@ -71,10 +71,11 @@ const docGets = new Map<string, Promise<void>>();// /projects/:id only — /projects/folders is the folder collection, not a doc.const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;-async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {+async function cloudFetch(path: string, options?: CutRequestInit): Promise<Response> {+ const { observe, ...init } = options ?? {};const doc = PROJECT_DOC.exec(path);const method = (init?.method ?? "GET").toUpperCase();- if (!doc || (method !== "GET" && method !== "PUT")) return cloudRequest(cloudPath(path), init);+ if (observe || !doc || (method !== "GET" && method !== "PUT")) return cloudRequest(cloudPath(path), init);const projectId = decodeURIComponent(doc[1]);if (method === "GET") {diff --git a/site/src/cut/lib/backend/types.ts b/site/src/cut/lib/backend/types.tsindex 65a41c15..b484f78a 100644--- a/site/src/cut/lib/backend/types.ts+++ b/site/src/cut/lib/backend/types.ts@@ -25,11 +25,14 @@ export type CutCaps = {watch: boolean;};+/** Observational reads leave the next document save based on the loaded version. */+export type CutRequestInit = RequestInit & { observe?: boolean };+export interface CutBackend {kind: CutMode;caps: CutCaps;/** fetch() against this backend, preserving the engine route shapes. */- fetch(path: string, init?: RequestInit): Promise<Response>;+ fetch(path: string, init?: CutRequestInit): Promise<Response>;/** Absolute-or-relative URL for a backend API path (media src, downloads). */url(path: string): string;}diff --git a/site/src/cut/lib/browserChatTurns.test.ts b/site/src/cut/lib/browserChatTurns.test.tsnew file mode 100644index 00000000..fb782440--- /dev/null+++ b/site/src/cut/lib/browserChatTurns.test.ts@@ -0,0 +1,15 @@+import { expect, test } from "bun:test";+import { beginBrowserChat, browserChatRunning, cancelBrowserChat } from "./browserChatTurns";++test("a reopened panel sees and stops the existing browser turn", () => {+ const turn = beginBrowserChat("original", "chat");+ expect(browserChatRunning("original", "chat")).toBe(true);+ expect(browserChatRunning("other", "chat")).toBe(false);+ let rejected = false;+ try { beginBrowserChat("original", "chat"); } catch { rejected = true; }+ expect(rejected).toBe(true);+ cancelBrowserChat("original", "chat");+ expect(turn.signal.aborted).toBe(true);+ turn.finish();+ expect(browserChatRunning("original", "chat")).toBe(false);+});diff --git a/site/src/cut/lib/browserChatTurns.ts b/site/src/cut/lib/browserChatTurns.tsnew file mode 100644index 00000000..4181e790--- /dev/null+++ b/site/src/cut/lib/browserChatTurns.ts@@ -0,0 +1,36 @@+/** Active browser turns outlive their panel; a reopened panel observes the same run. */+const turns = new Map<string, AbortController>();+const listeners = new Set<() => void>();+const keyFor = (projectId: string, threadId: string) => `${projectId}/${threadId}`;+const publish = () => { for (const listener of listeners) listener(); };++export function watchBrowserChatTurns(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++export function browserChatRunning(projectId: string, threadId: string): boolean {+ return turns.has(keyFor(projectId, threadId));+}++export function cancelBrowserChat(projectId: string, threadId: string): void {+ turns.get(keyFor(projectId, threadId))?.abort();+}++export function beginBrowserChat(projectId: string, threadId: string, source?: AbortSignal) {+ const key = keyFor(projectId, threadId);+ if (turns.has(key)) throw new Error("This conversation is already working.");+ const controller = new AbortController();+ const abort = () => controller.abort();+ source?.addEventListener("abort", abort, { once: true });+ if (source?.aborted) abort();+ turns.set(key, controller);+ publish();+ return {+ signal: controller.signal,+ finish: () => {+ source?.removeEventListener("abort", abort);+ if (turns.get(key) === controller) { turns.delete(key); publish(); }+ },+ };+}diff --git a/site/src/cut/lib/chatCloud.test.ts b/site/src/cut/lib/chatCloud.test.tsnew file mode 100644index 00000000..47f489a8--- /dev/null+++ b/site/src/cut/lib/chatCloud.test.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { bindCutMode, releaseCutMode } from "./backend";+import { cloudBackend, knownDocVersion } from "./backend/cloud";+import { ensureCloudThreads } from "./chatCloud";+import { chatThreadDeleted, deleteStoredThread, readProjectThreads, writeProjectThreads } from "./chatThreads";++const originalFetch = globalThis.fetch;+const storage = new Map<string, string>();+let storageReads = 0;+beforeEach(() => {+ storage.clear();+ storageReads = 0;+ Object.assign(globalThis, { localStorage: {+ getItem: (key: string) => { storageReads++; return storage.get(key) ?? null; },+ setItem: (key: string, value: string) => { storage.set(key, value); },+ removeItem: (key: string) => { storage.delete(key); },+ } });+ bindCutMode("cloud");+});+afterEach(() => { globalThis.fetch = originalFetch; releaseCutMode(); });++const stubFetch = (fn: (url: URL, init?: RequestInit) => Response) => {+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) =>+ fn(new URL(String(input), "https://example.test"), init)) as typeof fetch;+};++test("unchanged polls read metadata without loading transcripts or local history", async () => {+ let bodyReads = 0;+ stubFetch((url) => {+ if (url.searchParams.has("revisions")) return Response.json([{ id: "a", revision: "1" }]);+ bodyReads++;+ return Response.json([{ id: "a", updatedAt: 1 }]);+ });+ await ensureCloudThreads("unchanged", true);+ expect(bodyReads).toBe(1);+ storageReads = 0;+ await ensureCloudThreads("unchanged", true);+ expect(bodyReads).toBe(1);+ expect(storageReads).toBe(0);+});++test("a remote deletion wins over a newer stale local transcript", async () => {+ writeProjectThreads("deleted", [{ id: "a", updatedAt: 100 }]);+ let puts = 0;+ stubFetch((url, init) => {+ if (init?.method === "PUT") puts++;+ return Response.json(url.searchParams.has("revisions")+ ? [{ id: "a", revision: "2" }]+ : [{ id: "a", updatedAt: 2, deleted: true }]);+ });+ await ensureCloudThreads("deleted", true);+ expect(chatThreadDeleted("deleted", "a")).toBe(true);+ expect(puts).toBe(0);+});++test("an offline deletion is sent before an old server copy can return", async () => {+ writeProjectThreads("offline-delete", [{ id: "a", updatedAt: 1 }]);+ deleteStoredThread("offline-delete", "a");+ let deletes = 0;+ stubFetch((url, init) => {+ if (init?.method === "DELETE") { deletes++; return Response.json({ ok: true }); }+ return Response.json(url.searchParams.has("revisions")+ ? [{ id: "a", revision: "1" }]+ : [{ id: "a", updatedAt: 1 }]);+ });+ await ensureCloudThreads("offline-delete", true);+ expect(deletes).toBe(1);+ expect(readProjectThreads("offline-delete")[0].deleted).toBe(true);+});++test("observing a newer scene document preserves the loaded cloud save base", async () => {+ let version = "1";+ let putBase: string | null = null;+ stubFetch((url, init) => {+ if (init?.method === "PUT") {+ putBase = url.searchParams.get("v");+ return Response.json({ version: 3 });+ }+ return Response.json({}, { headers: { "x-cut-doc-version": version } });+ });+ const path = "/api/cut/projects/observe-scene";+ await cloudBackend.fetch(path);+ version = "2";+ await cloudBackend.fetch(path, { observe: true });+ expect(knownDocVersion("observe-scene")).toBe("1");+ await cloudBackend.fetch(path, { method: "PUT", body: "{}" });+ expect(putBase).toBe("1");+});diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.tsindex 0d713418..5f4573d3 100644--- a/site/src/cut/lib/chatCloud.ts+++ b/site/src/cut/lib/chatCloud.ts@@ -6,6 +6,8 @@import { cutMode, getBackend, type CutBackend } from "./backend";import { cloudBackend } from "./backend/cloud";import {+ chatThreadDeleted,+ deleteStoredThread,isStoredThread,mergeThreads,readProjectThreads,@@ -13,7 +15,14 @@ import {type StoredThread,} from "./chatThreads";-const seeded = new Map<string, Promise<void>>();+let syncState: {+ projectId: string;+ backend: CutBackend;+ versions: Map<string, string>;+ pending?: Promise<void>;+ seeded: boolean;+ dirty: boolean;+} | undefined;/** A cloud project's threads as the server holds them. Takes its backend, so a* project copy can read the residency it is copying from rather than the one@@ -46,46 +55,60 @@ export async function putCloudThread(headers: { "Content-Type": "application/json" },body: JSON.stringify(thread),});+ if (res.status === 410) { deleteStoredThread(projectId, thread.id); return; }if (!res.ok) throw new Error("Could not save a chat thread.");}-/** Bring a cloud project's chat history and the server's copy into agreement,- * per thread the newer updatedAt winning, and push back whatever the server is- * missing or trailing on. The push is what makes the mirror hold: a save that- * never landed — offline, a request that failed, a thread written before this- * project moved to the cloud — would otherwise stay local forever, and a share- * link would show a project with no chat at all. Resolves immediately for local- * projects; memoized per project, but a failure clears the memo so the next- * panel mount retries. */-export function ensureCloudThreads(projectId: string): Promise<void> {- // Shared viewers sync too, read-only: syncThreads pushes nothing back, and- // the saves and deletes below are cloud-only.- if (cutMode() === "local" || cutMode() === "browser") return Promise.resolve();- let p = seeded.get(projectId);- if (!p) {- p = syncThreads(projectId).catch(() => {- seeded.delete(projectId);- });- seeded.set(projectId, p);- }- return p;+/** Merge changed conversations and retry local saves, including offline deletions. */+export function ensureCloudThreads(projectId: string, refresh = false): Promise<void> {+ const backend = getBackend();+ if (backend.kind === "local" || backend.kind === "browser") return Promise.resolve();+ if (!syncState || syncState.projectId !== projectId || syncState.backend !== backend)+ syncState = { projectId, backend, versions: new Map(), seeded: false, dirty: true };+ const state = syncState;+ if (state.pending) return state.pending;+ if (state.seeded && !refresh) return Promise.resolve();+ state.pending = syncThreads(state).then(() => { state.seeded = true; }).catch(() => {+ state.seeded = false;+ }).finally(() => { state.pending = undefined; });+ return state.pending;}-async function syncThreads(projectId: string): Promise<void> {- const backend = getBackend();- const remote = await fetchCloudThreads(backend, projectId);- // A viewer's list is the owner's list — there is nothing of their own to- // merge, so the share's threads stand alone (in memory, per chatThreads).- if (backend.kind === "shared") {- writeProjectThreads(projectId, remote);- return;+async function syncThreads(state: NonNullable<typeof syncState>): Promise<void> {+ const { projectId, backend, versions } = state;+ const path = `/api/cut/projects/${projectId}/chats`;+ const response = await backend.fetch(`${path}?revisions=1`);+ if (!response.ok) throw new Error("Could not read the project's chats.");+ const index = await response.json() as { id: string; revision: string }[];+ const remoteIds = new Set(index.map((row) => row.id));+ for (const row of index) {+ if (versions.get(row.id) === row.revision) continue;+ const res = await backend.fetch(`${path}?id=${encodeURIComponent(row.id)}&revision=${encodeURIComponent(row.revision)}`);+ if (!res.ok) throw new Error("Could not read the conversation.");+ const remote = (await res.json() as unknown[]).filter(isStoredThread);+ const local = readProjectThreads(projectId);+ const merged = mergeThreads(remote, local);+ writeProjectThreads(projectId, merged);+ const incoming = remote.find((t) => t.id === row.id);+ const outgoing = merged.find((t) => t.id === row.id);+ if (backend.kind === "cloud" && outgoing && incoming &&+ (outgoing.deleted && !incoming.deleted || !outgoing.deleted && (outgoing.updatedAt ?? 0) > (incoming.updatedAt ?? 0))) {+ await saveCloudThread(backend, projectId, outgoing);+ }+ versions.set(row.id, row.revision);+ }+ if (backend.kind === "cloud" && state.dirty) {+ for (const thread of readProjectThreads(projectId)) {+ if (!remoteIds.has(thread.id)) await saveCloudThread(backend, projectId, thread);+ }+ state.dirty = false;}- const merged = mergeThreads(remote, readProjectThreads(projectId));- writeProjectThreads(projectId, merged);- const stored = new Map(remote.map((t) => [t.id, t.updatedAt ?? 0]));- const behind = merged.filter((t) => (stored.get(t.id) ?? -1) < (t.updatedAt ?? 0));- // One at a time: a full history can be a few megabytes of transcript.- for (const thread of behind) await putCloudThread(backend, projectId, thread);+}++async function saveCloudThread(backend: CutBackend, projectId: string, thread: StoredThread): Promise<void> {+ if (!thread.deleted) return putCloudThread(backend, projectId, thread);+ const res = await backend.fetch(`/api/cut/projects/${projectId}/chats/${thread.id}`, { method: "DELETE" });+ if (!res.ok) throw new Error("Could not delete the conversation.");}// Saves debounce per thread: while a turn streams, the panel re-saves on every@@ -106,7 +129,11 @@ let pageHideHooked = false;const saveKey = (projectId: string, threadId: string) => `${projectId}/${threadId}`;export function queueCloudThreadSave(projectId: string, thread: StoredThread): void {- if (cutMode() !== "cloud") return;+ if (cutMode() !== "cloud" || chatThreadDeleted(projectId, thread.id)) return;+ if (syncState?.projectId === projectId) {+ syncState.versions.delete(thread.id);+ syncState.dirty = true;+ }const key = saveKey(projectId, thread.id);const prev = pending.get(key);if (prev) clearTimeout(prev.timer);@@ -132,13 +159,19 @@ async function flushOne(key: string, keepalive = false): Promise<void> {// a cloud project, and by the time the debounce fires the user may have// closed it — with the Mac app running, the ambient backend is then the// engine, which has no chats route and no copy of this project.- await cloudBackend.fetch(`/api/cut/projects/${entry.projectId}/chats/${entry.threadId}`, {+ const response = await cloudBackend.fetch(`/api/cut/projects/${entry.projectId}/chats/${entry.threadId}`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify(entry.data),keepalive,});+ if (response.status === 410) deleteStoredThread(entry.projectId, entry.threadId);+ else if (!response.ok) throw new Error("Could not save the conversation.");} catch {+ if (syncState?.projectId === entry.projectId) {+ syncState.versions.delete(entry.threadId);+ syncState.dirty = true;+ }// The thread is still in localStorage; the next sync pushes it up.}}@@ -151,6 +184,10 @@ export function flushCloudThreadSaves(keepalive = false): void {/** Delete the server copy of a thread (deleted or pruned locally). */export function deleteCloudThread(projectId: string, threadId: string): void {if (cutMode() !== "cloud") return;+ if (syncState?.projectId === projectId) {+ syncState.versions.delete(threadId);+ syncState.dirty = true;+ }const entry = pending.get(saveKey(projectId, threadId));if (entry) {clearTimeout(entry.timer);@@ -159,7 +196,6 @@ export function deleteCloudThread(projectId: string, threadId: string): void {void cloudBackend.fetch(`/api/cut/projects/${projectId}/chats/${threadId}`, {method: "DELETE",}).catch(() => {- // Offline delete — the copy resurfaces on the next merge; the user can- // delete it again.+ // The durable tombstone retries on the next sync.});}diff --git a/site/src/cut/lib/chatRecovery.test.ts b/site/src/cut/lib/chatRecovery.test.tsnew file mode 100644index 00000000..52e58cee--- /dev/null+++ b/site/src/cut/lib/chatRecovery.test.ts@@ -0,0 +1,34 @@+import { expect, test } from "bun:test";+import type { UIMessage } from "ai";+import type { VideoProject } from "./genvideo/types";+import { recoverSceneCall } from "./chatRecovery";++const messages = (errorText = "Interrupted."): UIMessage[] => [{ id: "reply", role: "assistant", parts: [+ { type: "dynamic-tool", toolName: "generate_scene", toolCallId: "scene", state: "output-error", input: {}, errorText },+] }];+const scene = (phase: VideoProject["phase"]): VideoProject => ({ chatId: "chat", phase, shots: [], breakdownApproved: false } as unknown as VideoProject);++test("a resumed plan clears interruption and later settles successfully", () => {+ const resumed = recoverSceneCall(messages(), "chat", scene("keyframes"));+ expect((resumed[0].parts[0] as { state: string }).state).toBe("input-available");+ expect("errorText" in resumed[0].parts[0]).toBe(false);+ expect((recoverSceneCall(resumed, "chat", scene("storyboard"))[0].parts[0] as { state: string }).state).toBe("output-available");+});++test("another thread and genuine tool failures retain their errors", () => {+ const input = messages();+ expect(recoverSceneCall(input, "another", scene("done"))).toBe(input);+ expect((recoverSceneCall(messages("Out of credits."), "chat", scene("done"))[0].parts[0] as { errorText: string }).errorText).toBe("Out of credits.");+});++test("a failed scene remains failed", () => {+ expect((recoverSceneCall(messages(), "chat", scene("failed"))[0].parts[0] as { state: string }).state).toBe("output-error");+});++test("an older scene cannot settle a later call for a different brief", () => {+ const input = messages();+ const tool = input[0].parts[0] as { input: unknown };+ tool.input = { brief: "A different video" };+ const result = recoverSceneCall(input, "chat", { ...scene("done"), brief: "The earlier video" });+ expect((result[0].parts[0] as { errorText: string }).errorText).toBe("Interrupted.");+});diff --git a/site/src/cut/lib/chatRecovery.ts b/site/src/cut/lib/chatRecovery.tsnew file mode 100644index 00000000..590157ec--- /dev/null+++ b/site/src/cut/lib/chatRecovery.ts@@ -0,0 +1,32 @@+import type { UIMessage } from "ai";+import type { VideoProject } from "./genvideo/types";++/** Reconcile the latest scene call with its persisted job after reconnecting. */+export function recoverSceneCall(+ messages: UIMessage[],+ threadId: string,+ scene: VideoProject | undefined,+): UIMessage[] {+ if (!scene || scene.chatId !== threadId) return messages;+ let recovered = false;+ return messages.toReversed().map((message) => {+ const parts = message.parts.toReversed().map((part) => {+ const tool = part as { type: string; toolName?: string; state?: string; errorText?: string; input?: { brief?: string; from_audio_asset_id?: string } };+ const name = tool.type === "dynamic-tool" ? tool.toolName : tool.type.slice(5);+ if (recovered || name !== "generate_scene") return part;+ recovered = true;+ if (typeof tool.input?.brief === "string" && tool.input.brief.trim() !== scene.brief) return part;+ if (typeof tool.input?.from_audio_asset_id === "string" && tool.input.from_audio_asset_id !== scene.audioAssetId) return part;+ if (tool.state === "output-available") return part;+ if (tool.state === "output-error" && tool.errorText !== "Interrupted.") return part;+ const { errorText: _error, ...rest } = part as typeof part & { errorText?: string };+ void _error;+ if (scene.phase === "failed")+ return { ...rest, state: "output-error", errorText: "The video run failed. See its progress card." } as typeof part;+ if (scene.phase === "storyboard" || scene.breakdownApproved || scene.phase === "done")+ return { ...rest, state: "output-available", output: { planned: true, shots: scene.shots.length } } as typeof part;+ return { ...rest, state: "input-available" } as typeof part;+ }).toReversed();+ return parts.every((part, i) => part === message.parts[i]) ? message : { ...message, parts };+ }).toReversed();+}diff --git a/site/src/cut/lib/chatReplay.test.ts b/site/src/cut/lib/chatReplay.test.tsnew file mode 100644index 00000000..5ccfdf27--- /dev/null+++ b/site/src/cut/lib/chatReplay.test.ts@@ -0,0 +1,76 @@+import { expect, test } from "bun:test";+import type { UIMessageChunk } from "ai";+import { replayChatStream } from "./chatReplay";++test("replay identifies the saved reply before exposing any chunks", async () => {+ let prepared = false;+ const source = new ReadableStream<UIMessageChunk>({ start(controller) {+ controller.enqueue({ type: "start", messageId: "reply", messageMetadata: { requestMessageId: "ask" } });+ controller.enqueue({ type: "finish" });+ controller.close();+ } });+ const replay = await replayChatStream(source, (id, request) => {+ expect(id).toBe("reply");+ expect(request).toBe("ask");+ prepared = true;+ return true;+ }, () => {});+ expect(prepared).toBe(true);+ const reader = replay!.getReader();+ expect((await reader.read()).value?.type).toBe("start");+ expect((await reader.read()).value?.type).toBe("finish");+ expect((await reader.read()).done).toBe(true);+ expect(source.locked).toBe(false);+});++test("a stale journal cancels its reader without replaying another turn", async () => {+ let cancelled = false;+ const source = new ReadableStream<UIMessageChunk>({+ start(controller) { controller.enqueue({ type: "start", messageId: "old" }); },+ cancel() { cancelled = true; },+ });+ expect(await replayChatStream(source, () => false, () => {})).toBe(null);+ expect(cancelled).toBe(true);+ expect(source.locked).toBe(false);+});++test("unmount closes a replay even while it is waiting for the next event", async () => {+ let close!: () => void;+ let cancelled = false;+ const source = new ReadableStream<UIMessageChunk>({+ start(controller) { controller.enqueue({ type: "start", messageId: "reply" }); },+ cancel() { cancelled = true; },+ });+ const replay = await replayChatStream(source, () => true, (fn) => { close = fn; });+ const reader = replay!.getReader();+ await reader.read();+ const waiting = reader.read();+ close();+ expect((await waiting).done).toBe(true);+ expect(cancelled).toBe(true);+});+++test("a saved completed reply is never cleared or replayed on reopen", async () => {+ let cancelled = false;+ const source = new ReadableStream<UIMessageChunk>({+ start(controller) { controller.enqueue({ type: "start", messageId: "complete" }); },+ cancel() { cancelled = true; },+ });+ const replay = await replayChatStream(source, () => {+ throw new Error("A completed reply must keep its saved parts");+ }, () => {}, "complete");+ expect(replay).toBe(null);+ expect(cancelled).toBe(true);+});++test("a new reply resumes after the previous reply was completed", async () => {+ const source = new ReadableStream<UIMessageChunk>({ start(controller) {+ controller.enqueue({ type: "start", messageId: "new" });+ controller.enqueue({ type: "finish" });+ controller.close();+ } });+ const replay = await replayChatStream(source, () => true, () => {}, "previous");+ expect(replay).not.toBe(null);+ await replay!.cancel();+});diff --git a/site/src/cut/lib/chatReplay.ts b/site/src/cut/lib/chatReplay.tsnew file mode 100644index 00000000..6c72d0c0--- /dev/null+++ b/site/src/cut/lib/chatReplay.ts@@ -0,0 +1,41 @@+import type { UIMessageChunk } from "ai";++/** Read the journal identity before the SDK snapshots its current assistant message. */+export async function replayChatStream(+ source: ReadableStream<UIMessageChunk>,+ prepare: (messageId: string, requestId: string | undefined) => boolean,+ attach: (close: () => void) => void,+ completedMessageId?: string,+): Promise<ReadableStream<UIMessageChunk> | null> {+ const reader = source.getReader();+ const cancel = async () => { try { await reader.cancel(); } finally { reader.releaseLock(); } };+ const first = await reader.read().catch((error) => { reader.releaseLock(); throw error; });+ if (first.done || first.value.type !== "start" || !first.value.messageId || first.value.messageId === completedMessageId || !prepare(+ first.value.messageId,+ (first.value.messageMetadata as { requestMessageId?: string } | undefined)?.requestMessageId,+ )) {+ await cancel();+ return null;+ }+ let closed = false;+ return new ReadableStream<UIMessageChunk>({+ start(controller) {+ controller.enqueue(first.value);+ attach(() => {+ if (closed) return;+ closed = true;+ void cancel().catch(() => {});+ controller.close();+ });+ },+ async pull(controller) {+ try {+ const next = await reader.read();+ if (closed) return;+ if (next.done) { closed = true; controller.close(); reader.releaseLock(); }+ else controller.enqueue(next.value);+ } catch (error) { if (!closed) { closed = true; reader.releaseLock(); controller.error(error); } }+ },+ async cancel() { closed = true; await cancel(); },+ });+}diff --git a/site/src/cut/lib/chatRuntime.ts b/site/src/cut/lib/chatRuntime.tsnew file mode 100644index 00000000..136c77fa--- /dev/null+++ b/site/src/cut/lib/chatRuntime.ts@@ -0,0 +1,8 @@+import { SETTINGS, type Settings } from "@/lib/config/registry";++let runtime: Settings["chatRuntime"] = SETTINGS.chatRuntime.default;+export function bindChatRuntime(value: unknown): void {+ const parsed = SETTINGS.chatRuntime.schema.safeParse(value);+ if (parsed.success) runtime = parsed.data;+}+export function chatRuntime(): Settings["chatRuntime"] { return runtime; }diff --git a/site/src/cut/lib/chatThreads.test.ts b/site/src/cut/lib/chatThreads.test.tsindex eaa0bf5c..bd750e28 100644--- a/site/src/cut/lib/chatThreads.test.ts+++ b/site/src/cut/lib/chatThreads.test.ts@@ -1,6 +1,8 @@import { beforeEach, describe, expect, test } from "bun:test";import {+ chatThreadDeleted,+ deleteStoredThread,clearProjectThreads,mergeThreads,readProjectThreads,@@ -60,3 +62,12 @@ describe("mergeThreads", () => {expect(mergeThreads([{ id: "a" }], []).map((t) => t.id)).toEqual(["a"]);});});++test("a deleted thread stays deleted after a late completion or stale remote save", () => {+ writeProjectThreads("p", [{ id: "a", updatedAt: 1 }]);+ deleteStoredThread("p", "a");+ writeProjectThreads("p", [{ id: "a", updatedAt: Date.now() + 10_000 }]);+ expect(chatThreadDeleted("p", "a")).toBe(true);+ expect(readThreadIds("p").has("a")).toBe(false);+ expect(mergeThreads([{ id: "a", deleted: true }], [{ id: "a", updatedAt: 999 }])[0].deleted).toBe(true);+});diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.tsindex 8694c432..8d5795a2 100644--- a/site/src/cut/lib/chatThreads.ts+++ b/site/src/cut/lib/chatThreads.ts@@ -11,6 +11,17 @@ export const threadsKey = (projectId: string) => `cut-ai-threads-${projectId}`;// The open chat survives hiding the panel — only the + button starts a new one.export const activeChatKey = (projectId: string) => `cut-ai-active-${projectId}`;+const changes = new Set<(projectId: string) => void>();+export function subscribeChatThreads(projectId: string, onChange: () => void): () => void {+ const local = (id: string) => { if (id === projectId) onChange(); };+ const remote = (event: StorageEvent) => {+ if (event.key === threadsKey(projectId)) onChange();+ };+ changes.add(local);+ window.addEventListener("storage", remote);+ return () => { changes.delete(local); window.removeEventListener("storage", remote); };+}+// Where the threads live. An owner's are durable in localStorage; a shared// viewer holds the owner's copy in memory for the tab, so reading someone// else's project leaves nothing in this browser — and an owner opening their@@ -25,7 +36,7 @@ export function holdThreadsInMemory(): void {/** A saved thread as this module handles it: an opaque record read only for its* id and modified time, so history, the cloud mirror, and project copies can* move threads around without knowing the panel's payload. */-export type StoredThread = { id: string; updatedAt?: number };+export type StoredThread = { id: string; updatedAt?: number; deleted?: boolean };export const isStoredThread = (v: unknown): v is StoredThread =>!!v && typeof v === "object" && typeof (v as StoredThread).id === "string";@@ -44,12 +55,17 @@ export function readRawThreads(projectId: string): unknown[] {/** Replace a project's thread list, payload untouched. */export function writeRawThreads(projectId: string, list: unknown[]): void {+ // Deletion wins over callbacks and remote copies still holding the old thread.+ const deleted = readRawThreads(projectId).filter(isStoredThread).filter((t) => t.deleted);+ if (deleted.length) list = mergeThreads(list.filter(isStoredThread), deleted);if (memory) {memory.threads.set(projectId, list);+ for (const onChange of changes) onChange(projectId);return;}try {localStorage.setItem(threadsKey(projectId), JSON.stringify(list));+ for (const onChange of changes) onChange(projectId);} catch {// Storage full/blocked — history just won't persist.}@@ -92,7 +108,7 @@ export function mergeThreads(...lists: StoredThread[][]): StoredThread[] {const byId = new Map<string, StoredThread>();for (const t of lists.flat()) {const prev = byId.get(t.id);- if (!prev || (t.updatedAt ?? 0) >= (prev.updatedAt ?? 0)) byId.set(t.id, t);+ if (!prev || t.deleted || (!prev.deleted && (t.updatedAt ?? 0) >= (prev.updatedAt ?? 0))) byId.set(t.id, t);}return [...byId.values()].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));}@@ -102,7 +118,7 @@ export function mergeThreads(...lists: StoredThread[][]): StoredThread[] {* (deleted, or its whole project deleted, which clears these keys) is dismissed* rather than landed, so a reload can't resurrect media the user removed. */export function readThreadIds(projectId: string): Set<string> {- return new Set(readProjectThreads(projectId).map((t) => t.id));+ return new Set(readProjectThreads(projectId).filter((t) => !t.deleted).map((t) => t.id));}/** Drop a project's chat history and active-thread pointer — called when the@@ -120,3 +136,12 @@ export function clearProjectThreads(projectId: string): void {// Storage blocked — nothing to clear.}}++export function chatThreadDeleted(projectId: string, threadId: string): boolean {+ return readProjectThreads(projectId).some((t) => t.id === threadId && t.deleted === true);+}++export function deleteStoredThread(projectId: string, threadId: string): void {+ const threads = readProjectThreads(projectId).filter((t) => t.id !== threadId);+ writeProjectThreads(projectId, [{ id: threadId, updatedAt: Date.now(), deleted: true }, ...threads]);+}diff --git a/site/src/cut/lib/editorWork.test.ts b/site/src/cut/lib/editorWork.test.tsnew file mode 100644index 00000000..3285d74f--- /dev/null+++ b/site/src/cut/lib/editorWork.test.ts@@ -0,0 +1,42 @@+import { expect, test } from "bun:test";+import { editorIsLoading, holdEditorLoad, trackEditorTool } from "./editorWork";++test("a project load waits for an in-flight tool and holds new work", async () => {+ let finish!: () => void;+ const tool = trackEditorTool(() => new Promise<void>((resolve) => { finish = resolve; }));+ let entered = false;+ const load = holdEditorLoad().then((release) => { entered = true; return release; });+ await Promise.resolve();+ expect(entered).toBe(false);+ expect(editorIsLoading()).toBe(true);+ finish();+ await tool;+ const release = await load;+ expect(entered).toBe(true);+ release();+ expect(editorIsLoading()).toBe(false);+});++test("closing saves after active tools and holds the replacement load until saved", async () => {+ const { finishEditorWork } = await import("./editorWork");+ let finishTool!: () => void;+ let finishSave!: () => void;+ let saveStarted!: () => void;+ const saving = new Promise<void>((resolve) => { saveStarted = resolve; });+ const tool = trackEditorTool(() => new Promise<void>((resolve) => { finishTool = resolve; }));+ const close = finishEditorWork(async () => {+ saveStarted();+ await new Promise<void>((resolve) => { finishSave = resolve; });+ });+ let reopened = false;+ const load = holdEditorLoad().then((release) => { reopened = true; release(); });+ finishTool();+ await tool;+ await saving;+ expect(reopened).toBe(false);+ expect(editorIsLoading()).toBe(true);+ finishSave();+ await Promise.all([close, load]);+ expect(reopened).toBe(true);+ expect(editorIsLoading()).toBe(false);+});diff --git a/site/src/cut/lib/editorWork.ts b/site/src/cut/lib/editorWork.tsnew file mode 100644index 00000000..4385d100--- /dev/null+++ b/site/src/cut/lib/editorWork.ts@@ -0,0 +1,66 @@+/** A document load waits for tools already using its editor state to settle. */+const active = new Set<Promise<unknown>>();+let loading = 0;+const listeners = new Set<() => void>();++export function editorIsLoading(): boolean { return loading > 0; }+export function editorToolsActive(): boolean { return active.size > 0; }++export function watchEditorWork(fn: () => void): () => void {+ listeners.add(fn);+ return () => { listeners.delete(fn); };+}++export async function holdEditorLoad(): Promise<() => void> {+ loading++;+ await Promise.allSettled([...active]);+ return () => {+ loading--;+ for (const fn of listeners) fn();+ };+}++export function trackEditorTool<T>(work: () => Promise<T>): Promise<T> {+ const result = work();+ active.add(result);+ void result.finally(() => active.delete(result)).catch(() => {});+ return result;+}++// The mounted editor owns its save queue. Scene work drains that same queue.+let editorSave: { projectId: string; flush: () => Promise<void> } | null = null;++export function registerEditorSave(projectId: string, flush: () => Promise<void>): () => void {+ const entry = { projectId, flush };+ editorSave = entry;+ return () => { if (editorSave === entry) editorSave = null; };+}++export async function flushEditorSave(projectId: string): Promise<void> {+ if (editorSave?.projectId === projectId) await editorSave.flush();+}++/** Closing drains tools and saves before a replacement editor can load. */+export function finishEditorWork(work: () => Promise<void>): Promise<void> {+ const ready = holdEditorLoad();+ return trackEditorTool(async () => {+ const release = await ready;+ try { await work(); } finally { release(); }+ });+}++const chats = new Map<string, number>();++export function editorChatActive(projectId: string): boolean {+ return chats.has(projectId);+}++/** Revision polling waits until this editor's conversations settle. */+export function holdEditorChat(projectId: string): () => void {+ chats.set(projectId, (chats.get(projectId) ?? 0) + 1);+ return () => {+ const remaining = (chats.get(projectId) ?? 1) - 1;+ if (remaining) chats.set(projectId, remaining);+ else chats.delete(projectId);+ };+}diff --git a/site/src/cut/lib/engineChat.ts b/site/src/cut/lib/engineChat.tsnew file mode 100644index 00000000..62100f90--- /dev/null+++ b/site/src/cut/lib/engineChat.ts@@ -0,0 +1,17 @@+import { localBackend } from "./backend/local";++export async function claimEngineTool(sessionKey: string | null, toolCallId: string): Promise<boolean> {+ const response = await localBackend.fetch("/api/cut/ai/tool-claim", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ sessionKey, toolCallId }),+ });+ if (!response.ok) throw new Error("The Mac app could not attach this editor to the chat. Update the app and reconnect.");+ return (await response.json() as { claimed: boolean }).claimed;+}++export async function cancelEngineChat(projectId: string, threadId: string): Promise<void> {+ const response = await localBackend.fetch(`/api/cut/ai/chat/${encodeURIComponent(threadId)}/cancel`, {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ projectId }),+ });+ if (!response.ok) throw new Error("Could not stop the chat on this Mac.");+}diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex 5c50341b..0e55ff39 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -1,16 +1,20 @@"use client";+import { chatRuntime } from "./chatRuntime";import { create } from "zustand";import { apiFetch, apiJson } from "./backend";import { useGenerate } from "./generate";import { realSuite } from "./genvideo/adapters";import { GEN_FPS, StoreEditorBridge } from "./genvideo/editorBridge";import { VideoOrchestrator } from "./genvideo/orchestrator";+import { ownScene, SceneOwnedElsewhere } from "./genvideo/sceneOwnership";+import { projectBackend } from "./residency";+type SceneOrchestrator = ReturnType<typeof ownScene>;import { onActivity } from "./genvideo/activity";import { projectWriteMode, withProjectDoc } from "./genvideo/docWriter";import type { RefAsset, Shot, VideoEvent, VideoPhase, VideoProject } from "./genvideo/types";import { useEditor } from "./store";-import { nearestAspect, type Aspect } from "./types";+import { nearestAspect } from "./types";import { defaultVideoAspects } from "./videoModels";// Brief-to-video ("generate a video") controller. It owns one VideoOrchestrator@@ -84,7 +88,7 @@ export interface StartSceneParams {// the OPEN project only. A run keeps rendering when the user switches away —// its placements land in the project's persisted doc (see StoreEditorBridge)// and the mirror re-attaches when they come back.-const orchestrators = new Map<string, VideoOrchestrator>();+const orchestrators = new Map<string, SceneOrchestrator>();useEditor.subscribe((s, prev) => {// The card mirrors the open project's run only; the orchestrator itself@@ -98,7 +102,7 @@ useEditor.subscribe((s, prev) => {// paid run resumes (and its media re-tags) even when the AI panel never// mounts. loadProject flips `loaded` false→true in the same set() that// fills genvideo, so the edge fires once per open.- if (!s.loaded || prev.loaded || !s.projectId) return;+ if (!s.loaded || (prev.loaded && s.loadEpoch === prev.loadEpoch) || !s.projectId) return;// A headless process (the turn runner, an eval) opens projects to run one// job; resuming a persisted plan there would spend credits on a render the// page is already resuming for its user.@@ -107,7 +111,7 @@ useEditor.subscribe((s, prev) => {// adopt or resume it (resuming would render on the viewer's account).if (s.readOnly) return;const live = orchestrators.get(s.projectId);- if (live && !live.isAborted && !isTerminal(statusFor(live.project))) {+ if (live?.working && !live.isAborted) {// The run is still working: its clips loaded as ordinary content — re-mark// them render-owned, then mirror the live run. A run that FINISHED while// the project was closed falls through instead: its clips belong to the@@ -119,7 +123,6 @@ useEditor.subscribe((s, prev) => {return;}if (!s.genvideo) return;- if (useGenScene.getState().run?.projectId === s.projectId) return;useGenScene.getState().hydrate(s.projectId, s.genvideo);});@@ -214,9 +217,9 @@ function killRun(projectId: string): void {useEditor.getState().setGenvideo(undefined);useEditor.getState().releaseGenClips();} else {- void withProjectDoc(projectId, (doc) => {+ void projectBackend(projectId).then((backend) => withProjectDoc(projectId, (doc) => {doc.genvideo = undefined;- }).catch(() => {});+ }, backend)).catch(() => {});}const run = useGenScene.getState().run;if (run?.projectId === projectId) useGenScene.setState({ run: null });@@ -568,13 +571,23 @@ function fail(projectId: string, message: string): void {/** Settle handlers scoped to one orchestrator: a superseded run's late* resolution must never touch the run mirror — by the time it settles, the* project's slot may belong to a fresh run. */-function settled(projectId: string, orch: VideoOrchestrator): () => void {+function settled(projectId: string, orch: SceneOrchestrator): () => void {return () => {if (orchestrators.get(projectId) === orch && !orch.isAborted) syncFromProject(projectId);};}-function failed(projectId: string, orch: VideoOrchestrator): (e: unknown) => void {+function failed(projectId: string, orch: SceneOrchestrator): (e: unknown) => void {return (e) => {+ if (e instanceof SceneOwnedElsewhere) {+ if (orchestrators.get(projectId) !== orch) return;+ orchestrators.delete(projectId);+ setTimeout(() => {+ const s = useEditor.getState();+ if (s.projectId === projectId && s.loaded && s.genvideo && !s.readOnly && !orchestrators.has(projectId))+ useGenScene.getState().hydrate(projectId, s.genvideo);+ }, chatRuntime().syncIntervalMs);+ return;+ }if (orchestrators.get(projectId) === orch && !orch.isAborted) {fail(projectId, e instanceof Error ? e.message : String(e));}@@ -596,8 +609,8 @@ function resumeDoneRun(): boolean {return true;}-function buildOrchestrator(projectId: string, project: VideoProject): VideoOrchestrator {- return new VideoOrchestrator(project, {+function buildOrchestrator(projectId: string, project: VideoProject, fresh = false): SceneOrchestrator {+ return ownScene(projectId, new VideoOrchestrator(project, {editor: new StoreEditorBridge(projectId),// project.chatId (persisted) owns the run's media, so tagging survives a// reload/resume, not just the initial turn.@@ -608,16 +621,17 @@ function buildOrchestrator(projectId: string, project: VideoProject): VideoOrche// keeps its plan durable wherever the user is. Routed through// projectWriteMode so a plan save never races a load's doc fetch.persist: async (p) => {- if ((await projectWriteMode(projectId)) === "store") {+ if ((await projectWriteMode(projectId)) === "store" &&+ useEditor.getState().projectId === projectId && useEditor.getState().loaded) {useEditor.getState().setGenvideo(p);return;}return withProjectDoc(projectId, (doc) => {doc.genvideo = { ...p };- }).catch(() => {});+ }, await projectBackend(projectId));},concurrency: CONCURRENCY,- });+ }), fresh);}interface GenSceneState {@@ -680,7 +694,7 @@ export const useGenScene = create<GenSceneState>((set, get) => ({// Supersede this project's previous run so two orchestrators never write// the same project at once; runs in other projects keep going.orchestrators.get(projectId)?.abort();- const orch = buildOrchestrator(projectId, project);+ const orch = buildOrchestrator(projectId, project, true);orchestrators.set(projectId, orch);set({run: {@@ -871,6 +885,10 @@ export const useGenScene = create<GenSceneState>((set, get) => ({},hydrate: (projectId, project) => {+ if (orchestrators.get(projectId)?.working) {+ mirrorRun(projectId, orchestrators.get(projectId)!.project);+ return;+ }// Re-assert chat ownership over the run's media before anything else, so// even a finished run's leftovers never sit in the generate panels.claimRunMedia(projectId, project);diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex e14cd919..268d15d7 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -440,7 +440,8 @@ export const useGenerate = create<GenerateState>((set, get) => {};const backend = jobBackend(j);void (async () => {- if ((await projectWriteMode(j.projectId)) === "store")+ if ((await projectWriteMode(j.projectId)) === "store" &&+ useEditor.getState().projectId === j.projectId && useEditor.getState().loaded)useEditor.getState().upsertRender(record);else await upsertRenderInDoc(j.projectId, record, backend);})().catch(() => {});@@ -452,7 +453,8 @@ export const useGenerate = create<GenerateState>((set, get) => {const ids = mirrored.map((j) => j.id);const backend = jobBackend(mirrored[0]);void (async () => {- if ((await projectWriteMode(projectId)) === "store")+ if ((await projectWriteMode(projectId)) === "store" &&+ useEditor.getState().projectId === projectId && useEditor.getState().loaded)useEditor.getState().removeRenders(ids);else await removeRendersInDoc(projectId, ids, backend);})().catch(() => {});diff --git a/site/src/cut/lib/genvideo/docWriter.ts b/site/src/cut/lib/genvideo/docWriter.tsindex 0465e0e7..364499cd 100644--- a/site/src/cut/lib/genvideo/docWriter.ts+++ b/site/src/cut/lib/genvideo/docWriter.ts@@ -16,7 +16,7 @@ import { retimeOf } from "@donkeycut/effects-kit";* the doc is just the other end of the same contract.*/-import { apiJson, getBackend, type CutBackend } from "../backend";+import { apiJson, type CutBackend } from "../backend";import { storedMediaUrl } from "../mediaSync";import { projectBackend } from "../residency";import { footprints, nextFreeStart, placeInRun, RENDERS_CAP, storedAssets, useEditor } from "../store";@@ -36,15 +36,16 @@ export function withProjectDoc(mutate: (doc: ProjectDoc) => void,// Background writes can outlive navigation into a project of the other// residency; callers that know their backend pin it here.- backend: CutBackend = getBackend()+ backend?: CutBackend): Promise<void> {const prev = chains.get(projectId) ?? Promise.resolve();const next = prev.then(async () => {- const res = await backend.fetch(`/api/cut/projects/${projectId}`);+ const owner = backend ?? await projectBackend(projectId);+ const res = await owner.fetch(`/api/cut/projects/${projectId}`);const doc = await apiJson<ProjectDoc>(res);if (!res.ok) throw new Error(doc?.error ?? "Could not read the project.");mutate(doc);- const put = await backend.fetch(`/api/cut/projects/${projectId}`, {+ const put = await owner.fetch(`/api/cut/projects/${projectId}`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify(doc),diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.tsindex 953ca217..157f603e 100644--- a/site/src/cut/lib/genvideo/editorBridge.ts+++ b/site/src/cut/lib/genvideo/editorBridge.ts@@ -105,7 +105,7 @@ export class StoreEditorBridge implements EditorBridge {endFrame: number,opts?: { srcInSec?: number; muted?: boolean; anchorAfterIds?: string[]; followClipIds?: string[] }): Promise<string> {- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {const id = useEditor.getState().placeGenClip(mediaId, toSec(startFrame), toSec(endFrame), opts);if (!id) throw new Error(`placeClip: no placeable asset ${mediaId}`);return id;@@ -119,7 +119,7 @@ export class StoreEditorBridge implements EditorBridge {}async replaceClipMedia(clipId: string, mediaId: string): Promise<void> {- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {useEditor.getState().updateClip(clipId, { assetId: mediaId });return;}@@ -129,7 +129,7 @@ export class StoreEditorBridge implements EditorBridge {}async retimeClip(clipId: string, durationFrames: number): Promise<void> {- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {const clip = useEditor.getState().clips.find((c) => c.id === clipId);if (!clip) return;// Trim the tail so the footprint matches, at whatever rate the clip carries.@@ -145,7 +145,7 @@ export class StoreEditorBridge implements EditorBridge {}async removeClip(clipId: string): Promise<void> {- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {useEditor.getState().removeClipById(clipId);return;}@@ -158,7 +158,7 @@ export class StoreEditorBridge implements EditorBridge {const safeStyle: TransitionStyle = TRANSITION_STYLE_IDS.includes(style as TransitionStyle)? (style as TransitionStyle): "crossfade";- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {useEditor.getState().setClipTransition(clipId, toSec(durationFrames), safeStyle);return;}@@ -180,7 +180,7 @@ export class StoreEditorBridge implements EditorBridge {...(opts?.lane !== undefined ? { lane: opts.lane } : {}),...(opts?.volume !== undefined ? { volume: opts.volume } : {}),};- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {const id = useEditor.getState().placeGenAudio(mediaId, toSec(startFrame), toSec(durationFrames), audioOpts);@@ -196,7 +196,7 @@ export class StoreEditorBridge implements EditorBridge {}async removeAudio(clipId: string): Promise<void> {- if ((await this.mode()) === "store") {+ if ((await this.mode()) === "store" && this.open()) {useEditor.getState().removeAudioById(clipId);return;}diff --git a/site/src/cut/lib/genvideo/sceneLease.test.ts b/site/src/cut/lib/genvideo/sceneLease.test.tsnew file mode 100644index 00000000..346573e0--- /dev/null+++ b/site/src/cut/lib/genvideo/sceneLease.test.ts@@ -0,0 +1,46 @@+import { expect, test } from "bun:test";+import { SceneOwnedElsewhere, withSceneLease } from "./sceneLease";++test("a second scene owner cannot start work", async () => {+ let ran = false;+ const run = withSceneLease(async () => false, async () => { ran = true; }, () => {}, 1);+ expect(await run.catch((error) => error) instanceof SceneOwnedElsewhere).toBe(true);+ expect(ran).toBe(false);+});++test("a pending renewal completes before the lease is released", async () => {+ const events: string[] = [];+ let renewed!: () => void;+ let started!: () => void;+ const renewalStarted = new Promise<void>((resolve) => { started = resolve; });+ let finish!: () => void;+ let acquired = false;+ const result = withSceneLease(async (release) => {+ if (release) { events.push("released"); return false; }+ if (!acquired) { acquired = true; return true; }+ started();+ await new Promise<void>((resolve) => { renewed = resolve; });+ events.push("renewed");+ return true;+ }, () => new Promise<void>((resolve) => { finish = resolve; }), () => {}, 1);+ await renewalStarted;+ finish();+ await Promise.resolve();+ expect(events.length).toBe(0);+ renewed();+ await result;+ expect(events).toEqual(["renewed", "released"]);+});++test("losing the lease stops the current owner", async () => {+ let acquired = false;+ let finish!: () => void;+ let stopped = false;+ const result = withSceneLease(async (release) => {+ if (release || acquired) return false;+ acquired = true;+ return true;+ }, () => new Promise<void>((resolve) => { finish = resolve; }), () => { stopped = true; finish(); }, 1);+ expect(await result.catch((error) => error) instanceof SceneOwnedElsewhere).toBe(true);+ expect(stopped).toBe(true);+});diff --git a/site/src/cut/lib/genvideo/sceneLease.ts b/site/src/cut/lib/genvideo/sceneLease.tsnew file mode 100644index 00000000..f25c4a6c--- /dev/null+++ b/site/src/cut/lib/genvideo/sceneLease.ts@@ -0,0 +1,34 @@+export class SceneOwnedElsewhere extends Error {+ constructor() { super("This video is already working in another tab. Its progress will appear here."); }+}++/** Keep the lease until its last renewal and the operation have both settled. */+export async function withSceneLease<T>(+ lease: (release?: boolean) => Promise<boolean>,+ work: () => Promise<T>,+ lost: () => void,+ intervalMs: number | (() => number),+): Promise<T> {+ if (!(await lease())) throw new SceneOwnedElsewhere();+ let stopped = false;+ let renewal: Promise<void> = Promise.resolve();+ let timer: ReturnType<typeof setTimeout>;+ let lostLease = false;+ const renew = async () => {+ try { lostLease = !(await lease()); } catch { lostLease = true; }+ if (lostLease) lost();+ else if (!stopped) schedule();+ };+ const schedule = () => { timer = setTimeout(() => { renewal = renew(); }, typeof intervalMs === "function" ? intervalMs() : intervalMs); };+ schedule();+ try {+ const result = await work();+ if (lostLease) throw new SceneOwnedElsewhere();+ return result;+ } finally {+ stopped = true;+ clearTimeout(timer!);+ await renewal;+ await lease(true);+ }+}diff --git a/site/src/cut/lib/genvideo/sceneOwnership.test.ts b/site/src/cut/lib/genvideo/sceneOwnership.test.tsnew file mode 100644index 00000000..7367255b--- /dev/null+++ b/site/src/cut/lib/genvideo/sceneOwnership.test.ts@@ -0,0 +1,66 @@+import { afterEach, expect, test } from "bun:test";+import { cloudBackend, knownDocVersion } from "../backend/cloud";+import { registerEditorSave } from "../editorWork";+import { noteProjectRevision } from "../projectRevision";+import { useEditor } from "../store";+import type { VideoOrchestrator } from "./orchestrator";+import type { VideoProject } from "./types";+import { ownScene } from "./sceneOwnership";++const originalFetch = globalThis.fetch;+afterEach(() => { globalThis.fetch = originalFetch; });++function scene(id: string, run: (project: VideoProject) => void) {+ const project = { id, phase: "brief", updatedAt: 1 } as VideoProject;+ const mockScene = {+ project, isAborted: false,+ abort: () => { mockScene.isAborted = true; },+ run: async () => { run(mockScene.project); return mockScene.project; },+ };+ return mockScene as unknown as VideoOrchestrator;+}++test("scene ownership cannot advance the save base of a stale editor", async () => {+ const id = "stale-scene-editor";+ let version = "1";+ let writes = 0;+ let ran = false;+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {+ if (String(url).endsWith("/scene-lease")) return Response.json({ acquired: true });+ if (init?.method === "PUT") writes++;+ return Response.json({ name: "Another tab's title" }, { headers: { "x-cut-doc-version": version } });+ }) as typeof fetch;+ await cloudBackend.fetch(`/api/cut/projects/${id}`);+ noteProjectRevision(id, "1");+ useEditor.setState({ projectId: id, loaded: true, projectName: "Old title", saveState: "saved" });+ version = "2";+ const result = await ownScene(id, scene("new-scene", () => { ran = true; }), true).run().catch((error: unknown) => error);+ expect(result instanceof Error && result.message.includes("changed in another tab")).toBe(true);+ expect(knownDocVersion(id)).toBe("1");+ expect(writes).toBe(0);+ expect(ran).toBe(false);+});++test("a new scene drains the cancellation save before checking the persisted plan", async () => {+ const id = "cancel-then-start";+ let persisted: VideoProject | undefined = { id: "cancelled", phase: "storyboard" } as VideoProject;+ let ran = false;+ useEditor.setState({ projectId: id, loaded: true, genvideo: undefined, saveState: "dirty" });+ noteProjectRevision(id, "1");+ const unregister = registerEditorSave(id, async () => {+ persisted = useEditor.getState().genvideo;+ useEditor.getState().setSaveState("saved");+ });+ globalThis.fetch = (async (url: string | URL | Request) => {+ if (String(url).endsWith("/scene-lease")) return Response.json({ acquired: true });+ return Response.json({ genvideo: persisted }, { headers: { "x-cut-doc-version": "1" } });+ }) as typeof fetch;+ try {+ await ownScene(id, scene("next-scene", (project) => {+ ran = true;+ useEditor.getState().setGenvideo(project);+ }), true).run();+ expect(ran).toBe(true);+ expect(persisted?.id).toBe("next-scene");+ } finally { unregister(); }+});diff --git a/site/src/cut/lib/genvideo/sceneOwnership.ts b/site/src/cut/lib/genvideo/sceneOwnership.tsnew file mode 100644index 00000000..a510a447--- /dev/null+++ b/site/src/cut/lib/genvideo/sceneOwnership.ts@@ -0,0 +1,82 @@+import { flushEditorSave } from "../editorWork";+import { chatRuntime } from "../chatRuntime";+import { projectBackend } from "../residency";+import { useEditor } from "../store";+import { projectRevision } from "../projectRevision";+import type { ProjectDoc } from "../types";+import { docWriterIdle } from "./docWriter";+import { VideoOrchestrator } from "./orchestrator";+import { SceneOwnedElsewhere, withSceneLease } from "./sceneLease";+export { SceneOwnedElsewhere } from "./sceneLease";++/** Every entry into a scene takes the project's lease, including reload recovery. */+export function ownScene(projectId: string, scene: VideoOrchestrator, fresh = false) {+ let busy = false;+ const run = async (work: () => ReturnType<VideoOrchestrator["run"]>) => {+ if (busy) throw new SceneOwnedElsewhere();+ busy = true;+ try {+ const backend = await projectBackend(projectId);+ const owner = crypto.randomUUID();+ const route = `/api/cut/projects/${encodeURIComponent(projectId)}/scene-lease`;+ let leaseMs = chatRuntime().sceneLeaseMs;+ const lease = async (release = false) => {+ const res = await backend.fetch(route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ owner, release, leaseMs: chatRuntime().sceneLeaseMs }) });+ if (!res.ok) throw new Error("Could not reserve the video run.");+ const result = await res.json() as { acquired: boolean; leaseMs?: number };+ if (result.leaseMs) leaseMs = result.leaseMs;+ return result.acquired;+ };+ const execute = async () => {+ await flushEditorSave(projectId);+ await docWriterIdle(projectId);+ const res = await backend.fetch(`/api/cut/projects/${encodeURIComponent(projectId)}`, { observe: true });+ if (!res.ok) throw new Error("Could not read the video run.");+ const doc = await res.json() as ProjectDoc;+ const current = useEditor.getState();+ const revision = res.headers.get("x-cut-doc-version");+ if (backend.kind === "cloud" && current.projectId === projectId && current.loaded &&+ revision && projectRevision(projectId) !== revision)+ throw new Error("The project changed in another tab. Reload it before continuing the video run.");+ if (!fresh && doc.genvideo?.id !== scene.project.id) {+ scene.abort();+ return scene.project;+ }+ if (fresh && doc.genvideo && doc.genvideo.phase !== "done" && doc.genvideo.phase !== "failed")+ throw new SceneOwnedElsewhere();+ if (doc.genvideo?.id === scene.project.id && doc.genvideo.updatedAt > scene.project.updatedAt)+ scene.project = structuredClone(doc.genvideo);+ if (scene.isAborted) return scene.project;+ const result = await work();+ fresh = false;+ if (scene.isAborted) return result;+ await flushEditorSave(projectId);+ await docWriterIdle(projectId);+ return result;+ };+ if (backend.kind === "browser") {+ if (typeof navigator === "undefined" || !navigator.locks) throw new Error("This browser cannot coordinate background video runs.");+ return await navigator.locks.request(`cut-scene:${projectId}`, { ifAvailable: true }, async (lock) => {+ if (!lock) throw new SceneOwnedElsewhere();+ return execute();+ });+ }+ return await withSceneLease(lease, execute, () => scene.abort(), () => leaseMs / 3);+ } finally { busy = false; }+ };+ return {+ get project() { return scene.project; },+ get isAborted() { return scene.isAborted; },+ get working() { return busy; },+ abort: () => scene.abort(),+ shotIdByNumber: (n: number) => scene.shotIdByNumber(n),+ run: () => run(() => scene.run()),+ approveBreakdown: () => run(() => scene.approveBreakdown()),+ retryFailed: () => run(() => scene.retryFailed()),+ regenerateShots: (ids: string[]) => run(() => scene.regenerateShots(ids)),+ applyShotNote: (id: string, note: string) => run(() => scene.applyShotNote(id, note)),+ reviseStoryboardFrame: (id: string, note?: string) => run(() => scene.reviseStoryboardFrame(id, note)),+ recutShots: (ids: string[], instruction: string) => run(() => scene.recutShots(ids, instruction)),+ changeStyle: (style: string) => run(() => scene.changeStyle(style)),+ };+}diff --git a/site/src/cut/lib/pi/prodDeps.ts b/site/src/cut/lib/pi/prodDeps.tsindex 5faa6bd7..03896836 100644--- a/site/src/cut/lib/pi/prodDeps.ts+++ b/site/src/cut/lib/pi/prodDeps.ts@@ -4,6 +4,8 @@ import { geminiModelRoleNames } from "@/lib/inference/gemini-models";import { AI_SKILL_INDEX, AI_SKILLS } from "@/cut/server/ai/catalog";import { buildAiContext } from "../aiContext";import { runAiTool } from "../aiTools";+import { runProjectChatTool, withChatProject } from "../projectChatTools";+import { useEditor } from "../store";import { normalizeRef } from "../assetRef";import { NO_CREDITS_MESSAGE } from "../credits";import { useGenerate } from "../generate";@@ -17,7 +19,8 @@ import { currentDebris } from "./debris";// cutAgent itself stays importable anywhere — the eval runs the same loop in// Bun with its own deps.-export function productionDeps(): CutAgentDeps {+export function productionDeps(projectId?: string, signal?: AbortSignal): CutAgentDeps {+ const context = buildAiContext();return {post: (payload, signal) => hostedPost("/api/inference/responses", payload, signal),execTool: async (name, args) => {@@ -27,19 +30,20 @@ export function productionDeps(): CutAgentDeps {if (!doc) throw new Error(`No such skill. Available: ${AI_SKILL_INDEX.join(", ")}`);return doc;}- return runAiTool(name, args);+ return projectId ? runProjectChatTool(projectId, name, args, signal) : runAiTool(name, args);},models: {simple: geminiModelRoleNames.chatSimple,complex: geminiModelRoleNames.chat,gate: geminiModelRoleNames.fastDecision,},- buildContext: () => buildAiContext(),+ buildContext: () => context,resolveRefs: async (meta) => {const refs = meta.map(normalizeRef).filter((r) => r !== null);- return (await refsToParts(refs)).parts;+ const resolve = async () => (await refsToParts(refs)).parts;+ return projectId ? withChatProject(projectId, resolve, signal) : resolve();},- debris: currentDebris,+ debris: () => !projectId || useEditor.getState().projectId === projectId ? currentDebris() : [],onAuthFail: () => useGenerate.getState().probe(),noCreditsMessage: NO_CREDITS_MESSAGE,hooks: {diff --git a/site/src/cut/lib/projectChatTools.test.ts b/site/src/cut/lib/projectChatTools.test.tsnew file mode 100644index 00000000..7e13e321--- /dev/null+++ b/site/src/cut/lib/projectChatTools.test.ts@@ -0,0 +1,29 @@+import { expect, test } from "bun:test";+import { useEditor } from "./store";+import { withChatProject } from "./projectChatTools";++test("a suspended tool waits for its own project and cannot edit the replacement", async () => {+ useEditor.setState({ projectId: "replacement", loaded: true, projectName: "Unchanged" });+ let ran = false;+ const tool = withChatProject("original", async () => {+ ran = true;+ useEditor.getState().setProjectName("Original edited");+ });+ await Promise.resolve();+ expect(ran).toBe(false);+ expect(useEditor.getState().projectName).toBe("Unchanged");+ useEditor.setState({ projectId: "original", loaded: true });+ await tool;+ expect(useEditor.getState().projectName).toBe("Original edited");+});++test("Stop cancels a tool waiting for a project to reopen", async () => {+ useEditor.setState({ projectId: "replacement", loaded: true });+ const abort = new AbortController();+ let ran = false;+ const tool = withChatProject("original", async () => { ran = true; }, abort.signal);+ abort.abort();+ const result = await tool.catch((error: unknown) => error);+ expect(result instanceof DOMException && result.name === "AbortError").toBe(true);+ expect(ran).toBe(false);+});diff --git a/site/src/cut/lib/projectChatTools.ts b/site/src/cut/lib/projectChatTools.tsnew file mode 100644index 00000000..f2c1028c--- /dev/null+++ b/site/src/cut/lib/projectChatTools.ts@@ -0,0 +1,34 @@+import { runAiTool } from "./aiTools";+import { editorIsLoading, trackEditorTool, watchEditorWork } from "./editorWork";+import { useEditor } from "./store";++/** A suspended turn waits for its own project to reopen before its next tool. */+export function waitForChatProject(projectId: string, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ let stopStore = () => {};+ let stopWork = () => {};+ const clean = () => { stopStore(); stopWork(); signal?.removeEventListener("abort", check); };+ const check = () => {+ if (signal?.aborted) { clean(); reject(new DOMException("Stopped.", "AbortError")); return; }+ const s = useEditor.getState();+ if (!editorIsLoading() && s.projectId === projectId && s.loaded) { clean(); resolve(); }+ };+ stopStore = useEditor.subscribe(check);+ stopWork = watchEditorWork(check);+ signal?.addEventListener("abort", check, { once: true });+ check();+ });+}++export async function runProjectChatTool(projectId: string, name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {+ return withChatProject(projectId, () => runAiTool(name, args), signal);+}++export async function withChatProject<T>(projectId: string, work: () => Promise<T>, signal?: AbortSignal): Promise<T> {+ for (;;) {+ await waitForChatProject(projectId, signal);+ signal?.throwIfAborted();+ if (editorIsLoading() || useEditor.getState().projectId !== projectId) continue;+ return trackEditorTool(work);+ }+}diff --git a/site/src/cut/lib/projectRevision.ts b/site/src/cut/lib/projectRevision.tsnew file mode 100644index 00000000..dac25d79--- /dev/null+++ b/site/src/cut/lib/projectRevision.ts@@ -0,0 +1,9 @@+let loaded: { projectId: string; revision: string } | null = null;++export function noteProjectRevision(projectId: string, revision: string | null): void {+ if (revision) loaded = { projectId, revision };+}++export function projectRevision(projectId: string): string | null {+ return loaded?.projectId === projectId ? loaded.revision : null;+}diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.tsindex c463225d..cecf0c18 100644--- a/site/src/cut/lib/queries.ts+++ b/site/src/cut/lib/queries.ts@@ -143,7 +143,7 @@ const LIBRARY_LIVE_MS = 6000;* timer and re-read the moment the window comes back to the front, so a* recording made on the phone shows up here without a reload. The timer only* runs while this tab is the focused one. */-export function useLibrary({ live = false }: { live?: boolean } = {}) {+export function useLibrary({ live = false, enabled = true }: { live?: boolean; enabled?: boolean } = {}) {// Not read for the query itself — the backend binding decides which// residencies are reachable, so a mode change re-keys and re-reads.useCutMode();@@ -152,11 +152,12 @@ export function useLibrary({ live = false }: { live?: boolean } = {}) {const snap = snapshotKey(scope, "library");useEffect(- () => seedFromSnapshot<LibraryData>(client, libraryKey(scope), snap),- [client, scope, snap]+ () => { if (enabled) return seedFromSnapshot<LibraryData>(client, libraryKey(scope), snap); },+ [client, scope, snap, enabled]);return useQuery<LibraryData>({+ enabled,queryKey: libraryKey(scope),queryFn: async () => {const data = await fetchLibrary({ remembered: true });diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.tsindex 8d09a3e5..b24c5055 100644--- a/site/src/cut/lib/store.test.ts+++ b/site/src/cut/lib/store.test.ts@@ -2132,3 +2132,62 @@ describe("repairAssetDuration", () => {expect(clipById("c").out).toBe(2);});});++for (const outcome of ["document", "deleted", "network error"] as const) {+ test(`a superseded load cannot change the next project after ${outcome}`, async () => {+ const { engineGateOpen } = await import("./api");+ engineGateOpen();+ const originalFetch = globalThis.fetch;+ let finish!: (response: Response) => void;+ let fail!: (error: Error) => void;+ let started!: () => void;+ const ready = new Promise<void>((resolve) => { started = resolve; });+ const doc = { name: "Old project", assets: [], clips: [], audioClips: [], overlays: [] };+ globalThis.fetch = (async (url: string | URL | Request) => {+ if (String(url).includes("/projects/old-project")) {+ started();+ return new Promise<Response>((resolve, reject) => { finish = resolve; fail = reject; });+ }+ return Response.json({});+ }) as typeof fetch;+ try {+ const pending = s().loadProject("old-project", { inPlace: true });+ await ready;+ await s().openProjectDoc("next-project", { name: "Next project" }, []);+ if (outcome === "network error") fail(new Error("Disconnected"));+ else finish(Response.json(doc, { status: outcome === "deleted" ? 404 : 200 }));+ await pending;+ expect(s().projectId).toBe("next-project");+ expect(s().projectName).toBe("Next project");+ expect(s().loaded).toBe(true);+ expect(s().loadError).toBeNull();+ } finally {+ globalThis.fetch = originalFetch;+ }+ });+}++test("closing a project invalidates its pending load and releases its editor identity", async () => {+ const { engineGateOpen } = await import("./api");+ engineGateOpen();+ const originalFetch = globalThis.fetch;+ let finish!: (response: Response) => void;+ let started!: () => void;+ const ready = new Promise<void>((resolve) => { started = resolve; });+ globalThis.fetch = (async (url: string | URL | Request) => {+ if (String(url).includes("/projects/closing-project")) {+ started();+ return new Promise<Response>((resolve) => { finish = resolve; });+ }+ return Response.json({});+ }) as typeof fetch;+ try {+ const pending = s().loadProject("closing-project", { inPlace: true });+ await ready;+ s().closeProject("closing-project");+ finish(Response.json({ name: "Closed project", assets: [], clips: [], audioClips: [], overlays: [] }));+ await pending;+ expect(s().projectId).toBeNull();+ expect(s().loaded).toBe(false);+ } finally { globalThis.fetch = originalFetch; }+});diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 11084c1a..9bdb1785 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -1,4 +1,5 @@"use client";+import { noteProjectRevision } from "./projectRevision";import { EMPTY_GUIDE_LINES, sanitizeGuideLines, sanitizeGuides, type GuideId, type GuideLines } from "./guides";import {@@ -419,6 +420,7 @@ export interface EditorState {/** Open a project from an already-fetched document. The headless runner's* open: resets the store, drains pending doc writes, and hydrates straight* from the given document. */+ closeProject: (id: string) => void;openProjectDoc: (id: string, doc: Partial<ProjectDoc>, assets: MediaAsset[]) => Promise<void>;setProjectName: (name: string) => void;setSaveState: (s: SaveState) => void;@@ -1676,79 +1678,86 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {/** Reset to an empty, loading project and drain any background doc writes* still queued for it, so no open ever reads a half-written document. */- const resetForOpen = async (id: string, viewer: boolean) => {- // Blob URLs minted for the project being left go with it; the next open- // of that project re-registers what its store holds. A re-open of the- // same project keeps them — its state still points at them.- const prev = get().projectId;- if (prev && prev !== id) revokeRegistered(`/api/cut/projects/${prev}/`);- // Coming back to a project whose revoke is still waiting on an in-flight- // render's hold: the subtree is live again, so the revoke no longer- // applies — hydration is about to reuse those registrations.- cancelRevoke(`/api/cut/projects/${id}/`);- history.length = 0;- future.length = 0;- pending = null;- // A fresh project owns no live run — any prior run's render-owned ids are- // stale, and the loaded clips are ordinary, fully-undoable content.- genClipIds.clear();- genAudioIds.clear();- hydrating = true;- set({- projectId: id,- loaded: false,- loadError: null,- saveState: "saved",- resumePush: false,- // A share view is the one that refuses edits, and the surface opening- // the project is what knows it is one. Every other open clears the flag:- // left standing, it follows a tab out of a share link and back into that- // person's own projects, where a read-only editor keeps the mouse and- // loses the keyboard — which reads as a keyboard that has stopped- // working.- readOnly: viewer,- sharedFeatures: viewer ? get().sharedFeatures : null,- selectedKey: null,- assets: [],- loadingMedia: new Set<string>(),- clips: [],- transitions: [],- audioClips: [],- overlays: [],- templates: [],- mediaFolders: [],- aspect: lastChosenAspect() ?? "9:16",- aspectTouched: lastChosenAspect() !== null,- guides: [],- guidesHidden: false,- guideLines: EMPTY_GUIDE_LINES,- fadeIn: 0,- fadeOut: 0,- background: DEFAULT_BACKGROUND,- selection: null,- multiSelection: [],- playing: false,- buffering: false,- previewStopAt: null,- removalPeek: null,- subtitles: emptySubtitles(),- subtitleLane: 0,- subtitleStatus: "idle",- subtitleError: null,- exportOpen: false,- genvideo: undefined,- renders: [],- firstOpen: undefined,- });- hydrating = false;- // A background scene run may still be writing this project's doc — drain- // its queued writes so the open never reads a half-written doc. Ordering- // matters: projectId is set (loaded false) BEFORE this await, so a write- // arriving during the drain waits for the load (projectWriteMode) instead- // of queueing a doc write the drain would miss — nothing can land between- // the drain and the fetch that follows. Lazy import: docWriter reads store- // helpers, so a static import would be a cycle.- await import("./genvideo/docWriter").then((m) => m.docWriterIdle(id)).catch(() => {});+ let loadGeneration = 0;+ let loadTarget: string | null = null;+ const resetForOpen = async (id: string, viewer: boolean, generation: number) => {+ const { holdEditorLoad } = await import("./editorWork");+ const release = await holdEditorLoad();+ try {+ if (generation !== loadGeneration) return;+ // Blob URLs minted for the project being left go with it; the next open+ // of that project re-registers what its store holds. A re-open of the+ // same project keeps them — its state still points at them.+ const prev = get().projectId;+ if (prev && prev !== id) revokeRegistered(`/api/cut/projects/${prev}/`);+ // Coming back to a project whose revoke is still waiting on an in-flight+ // render's hold: the subtree is live again, so the revoke no longer+ // applies — hydration is about to reuse those registrations.+ cancelRevoke(`/api/cut/projects/${id}/`);+ history.length = 0;+ future.length = 0;+ pending = null;+ // A fresh project owns no live run — any prior run's render-owned ids are+ // stale, and the loaded clips are ordinary, fully-undoable content.+ genClipIds.clear();+ genAudioIds.clear();+ hydrating = true;+ set({+ projectId: id,+ loaded: false,+ loadError: null,+ saveState: "saved",+ resumePush: false,+ // A share view is the one that refuses edits, and the surface opening+ // the project is what knows it is one. Every other open clears the flag:+ // left standing, it follows a tab out of a share link and back into that+ // person's own projects, where a read-only editor keeps the mouse and+ // loses the keyboard — which reads as a keyboard that has stopped+ // working.+ readOnly: viewer,+ sharedFeatures: viewer ? get().sharedFeatures : null,+ selectedKey: null,+ assets: [],+ loadingMedia: new Set<string>(),+ clips: [],+ transitions: [],+ audioClips: [],+ overlays: [],+ templates: [],+ mediaFolders: [],+ aspect: lastChosenAspect() ?? "9:16",+ aspectTouched: lastChosenAspect() !== null,+ guides: [],+ guidesHidden: false,+ guideLines: EMPTY_GUIDE_LINES,+ fadeIn: 0,+ fadeOut: 0,+ background: DEFAULT_BACKGROUND,+ selection: null,+ multiSelection: [],+ playing: false,+ buffering: false,+ previewStopAt: null,+ removalPeek: null,+ subtitles: emptySubtitles(),+ subtitleLane: 0,+ subtitleStatus: "idle",+ subtitleError: null,+ exportOpen: false,+ genvideo: undefined,+ renders: [],+ firstOpen: undefined,+ });+ hydrating = false;+ // A background scene run may still be writing this project's doc — drain+ // its queued writes so the open never reads a half-written doc. Ordering+ // matters: projectId is set (loaded false) BEFORE this await, so a write+ // arriving during the drain waits for the load (projectWriteMode) instead+ // of queueing a doc write the drain would miss — nothing can land between+ // the drain and the fetch that follows. Lazy import: docWriter reads store+ // helpers, so a static import would be a cycle.+ await import("./genvideo/docWriter").then((m) => m.docWriterIdle(id)).catch(() => {});+ } finally { release(); }};return {@@ -1808,7 +1817,11 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {// clicking back in — is not a re-read, and gets the snapshot's head// start like any other open.const inPlace = opts?.inPlace === true;- await resetForOpen(id, opts?.viewer === true);+ const generation = ++loadGeneration;+ loadTarget = id;+ const current = () => generation === loadGeneration;+ await resetForOpen(id, opts?.viewer === true, generation);+ if (!current()) return;// One shape of hydration, used by both the snapshot painted below and// the live document that replaces it, so the legacy migrations happen@@ -1823,7 +1836,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {const sweepEnrich = () =>void import("./media").then((m) => {- if (get().projectId !== id || !get().loaded) return;+ if (!current() || get().projectId !== id || !get().loaded) return;for (const a of get().assets) void m.enrichAsset(a);}).catch(() => {});@@ -1853,7 +1866,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {? [null, null]: await Promise.all([readCachedDoc(id), uiReq]);const stored = cached?.doc;- const openable = () => !landed && get().projectId === id && !get().loaded;+ const openable = () => current() && !landed && get().projectId === id && !get().loaded;if (stored && ui && openable()) {const stale = stored.assets ?? [];// Signed R2 links are cached alongside the doc, so a snapshot open@@ -1913,6 +1926,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {try {const [res, ui] = await Promise.all([docReq, uiReq]);+ if (!current()) return;if (!res.ok) {// Gone, or no longer ours to read: the server is the authority on// that, so retire the snapshot and show the error even when it is@@ -1927,6 +1941,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {throw new Error("This project could not be loaded.");}const doc = (await res.json()) as ProjectDoc;+ if (!current()) return;+ if (get().projectId === id) noteProjectRevision(id, res.headers.get("x-cut-doc-version"));// The strips and peaks the snapshot's sweep already filled ride// across the replacement — the landing document names the same// assets, and blanking them would gray the timeline it just painted.@@ -1957,8 +1973,10 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}));}+ if (!current()) return;const missing = assets.filter((a) => !held.has(a.fileName));const signed = await fetchSignedMediaUrls(id, missing.map((a) => a.fileName));+ if (!current()) return;for (const a of assets) {a.url = held.get(a.fileName) ?? signed.urls.get(a.fileName) ?? a.url;}@@ -2000,7 +2018,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {});prefetchCloudMedia(id, queue, (fileName, url) => {const st = get();- if (st.projectId !== id) return;+ if (!current() || st.projectId !== id) return;if (url) st.applyMediaUrls(new Map([[fileName, url]]));// Video was never in the set; re-seating it would hand every// subscriber a new Set identity for no change.@@ -2060,11 +2078,11 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {// better answer than an error page: the project is open and editable,// a version behind at worst, and autosave retries until the link is// back.- if (!paintedFromCache) {+ if (current() && !paintedFromCache) {set({ loadError: err instanceof Error ? err.message : String(err) });}} finally {- hydrating = false;+ if (current()) hydrating = false;}},@@ -2182,8 +2200,16 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}},+ closeProject: (id) => {+ if (loadTarget === id) { loadGeneration++; loadTarget = null; }+ if (get().projectId === id) set({ projectId: null, loaded: false, playing: false });+ },+openProjectDoc: async (id, doc, assets) => {- await resetForOpen(id, false);+ const generation = ++loadGeneration;+ loadTarget = id;+ await resetForOpen(id, false, generation);+ if (generation !== loadGeneration) return;get().applyDocState(doc, assets, {});},diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.tsindex 841b34b0..79d07f83 100644--- a/site/src/cut/server/ai/bridge.ts+++ b/site/src/cut/server/ai/bridge.ts@@ -14,11 +14,15 @@ export interface UIChunkWriter {interface Waiter {resolve: (r: { output?: unknown; errorText?: string }) => void;timer: ReturnType<typeof setTimeout>;+ claimed: boolean;+ toolName: string;+ input: unknown;}interface Session {writer: UIChunkWriter;waiters: Map<string, Waiter>;+ attached: boolean;}// Survives dev-server module reloads.@@ -32,10 +36,29 @@ const g2 = globalThis as unknown as { __veditorAiProjects?: Map<string, string>const sessionProjects = (g2.__veditorAiProjects ??= new Map<string, string>());export function registerSession(key: string, writer: UIChunkWriter, projectId?: string) {- sessions.set(key, { writer, waiters: new Map() });+ sessions.set(key, { writer, waiters: new Map(), attached: true });if (projectId) sessionProjects.set(key, projectId);}+export function attachSession(key: string): void {+ const session = sessions.get(key);+ if (session) session.attached = true;+}++export function detachSession(key: string): void {+ const session = sessions.get(key);+ if (!session) return;+ session.attached = false;+ for (const waiter of session.waiters.values()) {+ clearTimeout(waiter.timer);+ const projectId = sessionProjects.get(key);+ if (!waiter.claimed && projectId)+ void detachedTool(projectId, waiter.toolName, waiter.input).then(waiter.resolve);+ else waiter.resolve({ errorText: "The editor disconnected before recording this result. Check the project state before repeating the operation." });+ }+ session.waiters.clear();+}+export function unregisterSession(key: string) {const s = sessions.get(key);if (s) {@@ -54,6 +77,12 @@ export function unregisterSession(key: string) {const TOOL_TIMEOUT_MS = 120_000; // subtitles generation can take a while+function detachedTool(projectId: string, toolName: string, input: unknown): Promise<{ output?: unknown; errorText?: string }> {+ return import("./headlessRuntime").then((module) => module.callDetachedTool(projectId, toolName, input)).catch((error: unknown) => ({+ errorText: error instanceof Error ? error.message : String(error),+ }));+}+/*** Forward a tool call to the browser via the chat stream and wait for the* result. Returns { output } or { errorText }.@@ -64,14 +93,21 @@ export function callBrowserTool(input: unknown): Promise<{ output?: unknown; errorText?: string }> {const session = sessions.get(sessionKey);- if (!session) {+ if (!session || !session.attached) {// The tab is gone (closed mid-turn) or the key is stale. A session whose// project is known finishes headless: the engine hydrates the doc and// runs the tool itself, so the turn completes and lands on disk.const projectId = sessionProjects.get(sessionKey);if (projectId) {console.log(`[cut-ai] ${toolName}: no editor tab for ${sessionKey}; running headless on ${projectId}`);- return import("./headlessTools").then((m) => m.callHeadlessTool(projectId, toolName, input));+ const toolCallId = crypto.randomUUID();+ session?.writer.write({ type: "tool-input-available", toolCallId, toolName, input });+ return detachedTool(projectId, toolName, input).then((result) => {+ session?.writer.write(result.errorText !== undefined+ ? { type: "tool-output-error", toolCallId, errorText: result.errorText }+ : { type: "tool-output-available", toolCallId, output: result.output ?? null });+ return result;+ });}console.warn(`[cut-ai] ${toolName}: no live editor session for ${sessionKey}; live: ${[...sessions.keys()].join(", ") || "none"}`@@ -90,6 +126,9 @@ export function callBrowserTool(}, TOOL_TIMEOUT_MS);session.waiters.set(toolCallId, {timer,+ claimed: false,+ toolName,+ input,resolve: (r) => {if (r.errorText !== undefined) {session.writer.write({ type: "tool-output-error", toolCallId, errorText: r.errorText });@@ -102,6 +141,13 @@ export function callBrowserTool(});}+export function claimBrowserTool(sessionKey: string, toolCallId: string): boolean {+ const waiter = sessions.get(sessionKey)?.waiters.get(toolCallId);+ if (!waiter || waiter.claimed) return false;+ waiter.claimed = true;+ return true;+}+/** Called by /api/cut/ai/tool-result when the browser finishes a tool. */export function resolveBrowserTool(sessionKey: string,diff --git a/site/src/cut/server/ai/headless-entry.ts b/site/src/cut/server/ai/headless-entry.tsnew file mode 100644index 00000000..ed9fc6b9--- /dev/null+++ b/site/src/cut/server/ai/headless-entry.ts@@ -0,0 +1,13 @@+import { writeSync } from "node:fs";+import { callHeadlessTool } from "./headlessTools";++// A separate result channel leaves tool diagnostics on stderr.+const chunks: Buffer[] = [];+for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));+const { projectId, toolName, input } = JSON.parse(Buffer.concat(chunks).toString()) as {+ projectId: string; toolName: string; input: unknown;+};+let result: { output?: unknown; errorText?: string };+try { result = await callHeadlessTool(projectId, toolName, input); }+catch (error) { result = { errorText: error instanceof Error ? error.message : String(error) }; }+writeSync(3, JSON.stringify(result));diff --git a/site/src/cut/server/ai/headlessRuntime.ts b/site/src/cut/server/ai/headlessRuntime.tsnew file mode 100644index 00000000..7306d558--- /dev/null+++ b/site/src/cut/server/ai/headlessRuntime.ts@@ -0,0 +1,36 @@+import { spawn } from "node:child_process";+import path from "node:path";+import { chatRuntime } from "../../lib/chatRuntime";++type ToolResult = { output?: unknown; errorText?: string };+let idle: Promise<unknown> = Promise.resolve();++/** Next's development server uses Bun for the shared editor's client-marked modules. */+export function callDetachedTool(projectId: string, toolName: string, input: unknown): Promise<ToolResult> {+ if (process.versions.bun)+ return import("./headlessTools").then((module) => module.callHeadlessTool(projectId, toolName, input));+ const result = idle.then(() => new Promise<ToolResult>((resolve, reject) => {+ const child = spawn(path.join(process.cwd(), "node_modules", ".bin", "bun"), [+ path.join(process.cwd(), "src", "cut", "server", "ai", "headless-entry.ts"),+ ], { stdio: ["pipe", "ignore", "inherit", "pipe"], timeout: 120_000 });+ const output: Buffer[] = [];+ let bytes = 0;+ const channel = child.stdio[3];+ if (!channel || !("on" in channel)) { child.kill(); reject(new Error("Could not open the editor tool channel.")); return; }+ channel.on("data", (data: Buffer) => {+ bytes += data.length;+ if (bytes > chatRuntime().journalBytes) { child.kill(); reject(new Error("The editor tool result is too large.")); return; }+ output.push(data);+ });+ child.on("error", reject);+ child.on("close", (code) => {+ if (code !== 0) { reject(new Error("The editor tool process stopped.")); return; }+ try { resolve(JSON.parse(Buffer.concat(output).toString()) as ToolResult); }+ catch { reject(new Error("The editor tool returned an invalid result.")); }+ });+ child.stdin!.on("error", reject);+ child.stdin!.end(JSON.stringify({ projectId, toolName, input }));+ }));+ idle = result.catch(() => {});+ return result;+}diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.tsindex 7a52e4e1..3ac8e670 100644--- a/site/src/cut/server/ai/headlessTools.ts+++ b/site/src/cut/server/ai/headlessTools.ts@@ -122,7 +122,7 @@ async function flush(doc: OpenDoc): Promise<void> {/** Run one tool call against the engine-held store for `projectId`,* persisting the doc after it. The bridge calls this when no editor tab is* attached to the chat session. */-export async function callHeadlessTool(+async function executeHeadlessTool(projectId: string,toolName: string,input: unknown@@ -154,3 +154,11 @@ export async function callHeadlessTool(return { errorText: err instanceof Error ? err.message : String(err) };}}++let toolsIdle: Promise<unknown> = Promise.resolve();+/** The engine's editor store belongs to one tool invocation at a time. */+export function callHeadlessTool(projectId: string, toolName: string, input: unknown): Promise<{ output?: unknown; errorText?: string }> {+ const result = toolsIdle.then(() => executeHeadlessTool(projectId, toolName, input));+ toolsIdle = result.catch(() => {});+ return result;+}diff --git a/site/src/cut/server/ai/sceneLease.ts b/site/src/cut/server/ai/sceneLease.tsnew file mode 100644index 00000000..018d728f--- /dev/null+++ b/site/src/cut/server/ai/sceneLease.ts@@ -0,0 +1,23 @@+import { SETTINGS } from "@/lib/config/registry";+import { z } from "zod";+import { projectFileRevision } from "../projects";++const globalLeases = globalThis as unknown as { __cutSceneLeases?: Map<string, { owner: string; until: number }> };+const leases = (globalLeases.__cutSceneLeases ??= new Map<string, { owner: string; until: number }>());+const schema = z.object({ owner: z.string().uuid(), release: z.boolean().optional(), leaseMs: SETTINGS.chatRuntime.schema.shape.sceneLeaseMs });++export async function localSceneLease(projectId: string, req: Request): Promise<Response> {+ if (!(await projectFileRevision(projectId))) return new Response(null, { status: 404 });+ const parsed = schema.safeParse(await req.json().catch(() => null));+ if (!parsed.success) return new Response(null, { status: 400 });+ const now = Date.now();+ for (const [id, lease] of leases) if (lease.until <= now) leases.delete(id);+ const current = leases.get(projectId);+ if (parsed.data.release) {+ if (current?.owner === parsed.data.owner) leases.delete(projectId);+ return Response.json({ acquired: false });+ }+ if (current && current.owner !== parsed.data.owner) return Response.json({ acquired: false });+ leases.set(projectId, { owner: parsed.data.owner, until: now + parsed.data.leaseMs });+ return Response.json({ acquired: true });+}diff --git a/site/src/cut/server/ai/turnStreams.test.ts b/site/src/cut/server/ai/turnStreams.test.tsnew file mode 100644index 00000000..07f8368e--- /dev/null+++ b/site/src/cut/server/ai/turnStreams.test.ts@@ -0,0 +1,95 @@+import { afterAll, expect, test } from "bun:test";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { UIMessageChunk } from "ai";+import { cancelTurnStream, followTurnStream, startTurnStream } from "./turnStreams";+import { callBrowserTool, claimBrowserTool, detachSession, registerSession, unregisterSession } from "./bridge";+import { createProject, readProject } from "../projects";++const root = await mkdtemp(path.join(os.tmpdir(), "donkey-chat-test-"));+const original = process.env.DONKEY_CUT_DATA_DIR;+process.env.DONKEY_CUT_DATA_DIR = root;+afterAll(async () => {+ if (original === undefined) delete process.env.DONKEY_CUT_DATA_DIR;+ else process.env.DONKEY_CUT_DATA_DIR = original;+ await rm(root, { recursive: true, force: true });+});++test("the engine completes with no readers and replays the finished journal", async () => {+ let output!: ReadableStreamDefaultController<UIMessageChunk>;+ let signal!: AbortSignal;+ let detached = 0;+ const response = await startTurnStream("project", "chat", (abort) => {+ signal = abort;+ return new ReadableStream({ start(controller) { output = controller; controller.enqueue({ type: "start", messageId: "reply" }); } });+ }, () => {}, () => { detached++; });+ await response.body!.cancel();+ expect(detached).toBe(1);+ expect(signal.aborted).toBe(false);+ output.enqueue({ type: "text-start", id: "text" });+ output.enqueue({ type: "text-delta", id: "text", delta: "Finished after closing the tab." });+ output.enqueue({ type: "text-end", id: "text" });+ output.enqueue({ type: "finish" });+ output.close();+ const replay = await followTurnStream("project", "chat");+ expect(await replay.text()).toContain("Finished after closing the tab.");+});++test("Stop cancels the run explicitly", async () => {+ let signal!: AbortSignal;+ const response = await startTurnStream("project", "stop", (abort) => {+ signal = abort;+ return new ReadableStream({ start(controller) { abort.addEventListener("abort", () => controller.close()); } });+ }, () => {}, () => {});+ cancelTurnStream("project", "stop");+ expect(signal.aborted).toBe(true);+ await response.text();+});++test("only one tab can claim a tool, and detached calls are not replayed", async () => {+ const chunks: Record<string, unknown>[] = [];+ registerSession("session", { write: (chunk) => chunks.push(chunk) });+ const pending = callBrowserTool("session", "get_state", {});+ const id = String(chunks[0].toolCallId);+ expect(claimBrowserTool("session", id)).toBe(true);+ expect(claimBrowserTool("session", id)).toBe(false);+ detachSession("session");+ expect((await pending).errorText).toContain("disconnected");+ expect(claimBrowserTool("session", id)).toBe(false);+ unregisterSession("session");+});++test("detached tools edit their original documents and journal their results", async () => {+ const first = await createProject("First chat test");+ const second = await createProject("Second chat test");+ const chunks: Record<string, unknown>[] = [];+ registerSession("first-project", { write: (chunk) => chunks.push(chunk) }, first.id);+ registerSession("second-project", { write: (chunk) => chunks.push(chunk) }, second.id);+ detachSession("first-project");+ detachSession("second-project");+ const results = await Promise.all([+ callBrowserTool("first-project", "set_project_name", { name: "First completed" }),+ callBrowserTool("second-project", "set_project_name", { name: "Second completed" }),+ ]);+ expect(results.every((result) => result.errorText === undefined)).toBe(true);+ expect((await readProject(first.id))?.name).toBe("First completed");+ expect((await readProject(second.id))?.name).toBe("Second completed");+ expect(chunks.filter((chunk) => chunk.type === "tool-output-available").length).toBe(2);+ unregisterSession("first-project");+ unregisterSession("second-project");+});++test("an unclaimed tool transfers to the engine when the tab disconnects", async () => {+ const project = await createProject("Unclaimed tool test");+ const chunks: Record<string, unknown>[] = [];+ registerSession("unclaimed", { write: (chunk) => chunks.push(chunk) }, project.id);+ const result = callBrowserTool("unclaimed", "set_project_name", { name: "Transferred" });+ const id = String(chunks[0].toolCallId);+ detachSession("unclaimed");+ expect(claimBrowserTool("unclaimed", id)).toBe(false);+ expect((await result).errorText).toBe(undefined);+ expect((await readProject(project.id))?.name).toBe("Transferred");+ expect(chunks.filter((chunk) => chunk.toolCallId === id).map((chunk) => chunk.type)).toEqual(["tool-input-available", "tool-output-available"]);+ unregisterSession("unclaimed");+});diff --git a/site/src/cut/server/ai/turnStreams.ts b/site/src/cut/server/ai/turnStreams.tsnew file mode 100644index 00000000..a2cdf62e--- /dev/null+++ b/site/src/cut/server/ai/turnStreams.ts@@ -0,0 +1,129 @@+import { chatRuntime } from "../../lib/chatRuntime";+import { mkdir, open, stat } from "node:fs/promises";+import { createHash } from "node:crypto";+import path from "node:path";+import type { UIMessageChunk } from "ai";+import { cutDataRoot } from "../dataDir";++type Turn = { abort: AbortController; clients: number; finished: boolean; detached: () => void; attached: () => void };+const globalTurns = globalThis as unknown as { __cutChatTurns?: Map<string, Turn> };+const running = (globalTurns.__cutChatTurns ??= new Map<string, Turn>());+const keyFor = (projectId: string, threadId: string) => createHash("sha256").update(`${projectId}/${threadId}`).digest("hex");+const fileFor = (key: string) => path.join(cutDataRoot(), "chat-streams", `${key}.sse`);++/** The engine drains a turn into its journal independently of its viewers. */+export async function startTurnStream(+ projectId: string,+ threadId: string,+ source: (signal: AbortSignal) => ReadableStream<UIMessageChunk>,+ attached: () => void,+ detached: () => void,+ journalBytes = chatRuntime().journalBytes,+ readerSignal?: AbortSignal,+): Promise<Response> {+ const key = keyFor(projectId, threadId);+ if (running.has(key)) return Response.json({ error: "This chat is already working." }, { status: 409 });+ const turn: Turn = { abort: new AbortController(), clients: 0, finished: false, attached, detached };+ running.set(key, turn);+ try {+ await mkdir(path.dirname(fileFor(key)), { recursive: true });+ const file = await open(fileFor(key), "w", 0o600);+ let reader: ReadableStreamDefaultReader<UIMessageChunk>;+ try { reader = source(turn.abort.signal).getReader(); }+ catch (error) { await file.close(); turn.abort.abort(); throw error; }+ void (async () => {+ let bytes = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ const data = `data: ${JSON.stringify(value)}\n\n`;+ bytes += Buffer.byteLength(data);+ if (bytes > journalBytes) throw new Error("This chat turn exceeded its saved transcript limit.");+ await file.write(data);+ }+ } catch (error) {+ turn.abort.abort();+ await file.write(`data: ${JSON.stringify({ type: "error", errorText: error instanceof Error ? error.message : "Chat stopped." })}\n\n`);+ } finally {+ try { await file.write("data: [DONE]\n\n"); }+ finally {+ turn.finished = true;+ running.delete(key);+ reader.releaseLock();+ await file.close();+ }+ }+ })().catch((error) => console.error("[cut-ai] Could not finish the chat journal:", error));+ return followTurnStream(projectId, threadId, readerSignal);+ } catch (error) {+ running.delete(key);+ throw error;+ }+}++/** Each reader follows the same journal from its beginning; message ids merge on reconnect. */+export async function followTurnStream(projectId: string, threadId: string, signal?: AbortSignal): Promise<Response> {+ const key = keyFor(projectId, threadId);+ const fileName = fileFor(key);+ if (!(await stat(fileName).catch(() => null))) return new Response(null, { status: 204 });+ const file = await open(fileName, "r");+ const turn = running.get(key);+ if (turn) { turn.clients++; turn.attached(); }+ let closed = false;+ let position = 0;+ let lastWrite = Date.now();+ let output: ReadableStreamDefaultController<Uint8Array>;+ const disconnected = () => {+ void close().finally(() => { try { output.close(); } catch { /* The reader already closed. */ } }).catch(() => {});+ };+ const close = async () => {+ if (closed) return;+ closed = true;+ signal?.removeEventListener("abort", disconnected);+ await file.close();+ if (turn && --turn.clients === 0 && !turn.finished) turn.detached();+ };+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ output = controller;+ signal?.addEventListener("abort", disconnected, { once: true });+ if (signal?.aborted) disconnected();+ },+ async pull(controller) {+ try {+ while (!closed) {+ const buffer = Buffer.alloc(16 * 1024);+ const read = await file.read(buffer, 0, buffer.length, position);+ if (closed) return;+ if (read.bytesRead) {+ lastWrite = Date.now();+ position += read.bytesRead;+ controller.enqueue(buffer.subarray(0, read.bytesRead));+ return;+ }+ if (!turn || turn.finished) { await close(); controller.close(); return; }+ // A heartbeat also lets the HTTP adapter observe a vanished reader while a tool waits.+ if (Date.now() - lastWrite >= chatRuntime().syncIntervalMs) {+ lastWrite = Date.now();+ controller.enqueue(new TextEncoder().encode(": keepalive\n\n"));+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ } catch (error) {+ if (!closed) { await close(); controller.error(error); }+ }+ },+ cancel: close,+ });+ return new Response(stream, { headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ "x-vercel-ai-ui-message-stream": "v1",+ } });+}++export function cancelTurnStream(projectId: string, threadId: string): void {+ running.get(keyFor(projectId, threadId))?.abort.abort();+}diff --git a/site/src/cut/server/cloud/chats.ts b/site/src/cut/server/cloud/chats.tsindex e25b04b1..a2447a75 100644--- a/site/src/cut/server/cloud/chats.ts+++ b/site/src/cut/server/cloud/chats.ts@@ -4,36 +4,60 @@// thread as an opaque JSON blob keyed by (projectId, thread id).import { prisma } from "@/lib/prisma";import type { Prisma } from "@/generated/prisma/client";-import { getProject } from "./projects";+import { caught, err } from "./util";// Well above a slimmed thread (data-URL frames are stripped client-side), well// below anything that could hurt the database.const MAX_THREAD_BYTES = 4_000_000;+/** Polling reads row versions; transcript bodies are fetched only after a change. */+export async function listChatThreads(+ userId: string, projectId: string, req: Request,+ headersFor?: (updatedAt: Date | undefined) => Record<string, string>,+) {+ const query = new URL(req.url).searchParams;+ const where = { userId, projectId, ...(query.has("id") ? { id: query.get("id")! } : {}) };+ if (query.has("revisions")) {+ const rows = await prisma.cutChatThread.findMany({ where, orderBy: { updatedAt: "desc" }, select: { id: true, updatedAt: true } });+ return Response.json(rows.map((row) => ({ id: row.id, revision: row.updatedAt.toISOString() })), { headers: headersFor?.(rows[0]?.updatedAt) });+ }+ const rows = await prisma.cutChatThread.findMany({+ where, orderBy: { updatedAt: "desc" }, select: { data: true, updatedAt: true },+ });+ return Response.json(rows.map((row) => row.data), { headers: headersFor?.(rows[0]?.updatedAt) });+}++const ownsProject = (userId: string, id: string) =>+ prisma.cutProject.findFirst({ where: { id, userId }, select: { id: true } });+export const chatsCloud = {- async list(userId: string, projectId: string) {- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);- const rows = await prisma.cutChatThread.findMany({- where: { userId, projectId },- orderBy: { updatedAt: "desc" },- select: { data: true },- });- return Response.json(rows.map((r) => r.data));+ async list(userId: string, projectId: string, req: Request) {+ if (!(await ownsProject(userId, projectId))) return err("Project not found.", 404);+ return listChatThreads(userId, projectId, req);},async put(userId: string, projectId: string, chatId: string, req: Request) {try {- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ if (!(await ownsProject(userId, projectId))) return err("Project not found.", 404);const text = await req.text();if (text.length > MAX_THREAD_BYTES) return err("Chat thread too large.", 413);const body = JSON.parse(text) as Record<string, unknown>;const data = { ...body, id: chatId } as Prisma.InputJsonValue;- await prisma.cutChatThread.upsert({- where: { projectId_id: { projectId, id: chatId } },- create: { projectId, id: chatId, userId, data },- update: { data },- });+ const stored = await prisma.cutChatThread.findUnique({ where: { projectId_id: { projectId, id: chatId } } });+ const previous = stored?.data as { updatedAt?: number; deleted?: boolean } | null;+ if (previous?.deleted) return err("This conversation was deleted.", 410);+ if (stored && typeof body.updatedAt === "number" && body.updatedAt <= (previous?.updatedAt ?? 0))+ return Response.json({ ok: true });+ if (stored) {+ const { count } = await prisma.cutChatThread.updateMany({+ where: { projectId, id: chatId, userId, updatedAt: stored.updatedAt }, data: { data },+ });+ if (!count) return err("The conversation changed. Reload it before saving.", 409);+ } else {+ const { count } = await prisma.cutChatThread.createMany({ data: [{ projectId, id: chatId, userId, data }], skipDuplicates: true });+ if (!count) return err("The conversation changed. Reload it before saving.", 409);+ }return Response.json({ ok: true });} catch (e) {return caught(e, "Could not save chat thread.");@@ -42,8 +66,12 @@ export const chatsCloud = {async remove(userId: string, projectId: string, chatId: string) {try {- await prisma.cutChatThread.deleteMany({- where: { userId, projectId, id: chatId },+ if (!(await ownsProject(userId, projectId))) return err("Project not found.", 404);+ const data = { id: chatId, deleted: true, updatedAt: Date.now() };+ await prisma.cutChatThread.upsert({+ where: { projectId_id: { projectId, id: chatId } },+ create: { userId, projectId, id: chatId, data },+ update: { data },});return Response.json({ ok: true });} catch (e) {diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex 79ac7ad0..88b1b2cb 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -183,7 +183,12 @@ export const projectsCloud = {}},- async get(userId: string, id: string) {+ async get(userId: string, id: string, req: Request) {+ if (req.method === "HEAD") {+ const row = await prisma.cutProject.findFirst({ where: { id, userId }, select: { version: true } });+ if (!row) return err("Project not found.", 404);+ return new Response(null, { headers: { "x-cut-doc-version": String(row.version) } });+ }const row = await getProject(userId, id);if (!row) return err("Project not found.", 404);return Response.json(docOf(row), {diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex f9dc845b..55fd0b43 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -18,6 +18,7 @@ import { notesCloud } from "./notes";import { notePhoneClient, phoneApi } from "./phone";import { projectsCloud } from "./projects";import { turnsCloud } from "./turns";+import { cloudSceneLease } from "./sceneLease";import { shareCloud } from "./share";import { transcribeCloud } from "./transcribe";import { usageApi } from "./usage";@@ -41,7 +42,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "PUT", path: "/api/cut-cloud/projects/folders/:id", handler: (r, u, p) => projectsCloud.updateFolder(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/folders/:id", handler: (_r, u, p) => projectsCloud.deleteFolder(u, p.id) },{ method: "POST", path: "/api/cut-cloud/projects/:id/move", handler: (r, u, p) => projectsCloud.move(u, p.id, r) },- { method: "GET", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.get(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/projects/:id", handler: (r, u, p) => projectsCloud.get(u, p.id, r) },{ method: "PUT", path: "/api/cut-cloud/projects/:id", handler: (r, u, p) => projectsCloud.put(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.remove(u, p.id) },{ method: "POST", path: "/api/cut-cloud/projects/:id/duplicate", handler: (_r, u, p) => copyJobs.requestDuplicate(u, p.id) },@@ -58,7 +59,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "GET", path: "/api/cut-cloud/projects/:id/share", handler: (_r, u, p) => shareCloud.get(u, p.id) },{ method: "PUT", path: "/api/cut-cloud/projects/:id/share", handler: (r, u, p) => shareCloud.put(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id/share", handler: (_r, u, p) => shareCloud.remove(u, p.id) },- { method: "GET", path: "/api/cut-cloud/projects/:id/chats", handler: (_r, u, p) => chatsCloud.list(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/chats", handler: (r, u, p) => chatsCloud.list(u, p.id, r) },{ method: "PUT", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (r, u, p) => chatsCloud.put(u, p.id, p.chatId, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (_r, u, p) => chatsCloud.remove(u, p.id, p.chatId) },{ method: "POST", path: "/api/cut-cloud/projects/:id/image", handler: (r, u, p) => mediaCloud.importImage(u, p.id, r) },@@ -103,6 +104,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "GET", path: "/api/cut-cloud/export/:jobId/file", handler: (_r, u, p) => jobsCloud.exportFile(u, p.jobId) },{ method: "GET", path: "/api/cut-cloud/jobs/:jobId", handler: (_r, u, p) => jobsCloud.status(u, p.jobId) },{ method: "POST", path: "/api/cut-cloud/projects/:id/turns", handler: (r, u, p) => turnsCloud.queue(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/scene-lease", handler: (r, u, p) => cloudSceneLease(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },{ method: "GET", path: "/api/cut-cloud/notes", handler: (_r, u) => notesCloud.list(u) },diff --git a/site/src/cut/server/cloud/sceneLease.ts b/site/src/cut/server/cloud/sceneLease.tsnew file mode 100644index 00000000..35873187--- /dev/null+++ b/site/src/cut/server/cloud/sceneLease.ts@@ -0,0 +1,27 @@+import { z } from "zod";+import { prisma } from "@/lib/prisma";+import { getGlobalSetting } from "@/lib/config/effective";++export const sceneLeaseSchema = z.object({ owner: z.string().uuid(), release: z.boolean().optional() });++export async function cloudSceneLease(userId: string, projectId: string, req: Request): Promise<Response> {+ if (!(await prisma.cutProject.findFirst({ where: { id: projectId, userId }, select: { id: true } }))) return new Response(null, { status: 404 });+ const parsed = sceneLeaseSchema.safeParse(await req.json().catch(() => null));+ if (!parsed.success) return new Response(null, { status: 400 });+ const { owner, release } = parsed.data;+ const { sceneLeaseMs } = await getGlobalSetting("chatRuntime");+ const id = `scene-lease-${projectId}`;+ if (release) {+ await prisma.cutRenderJob.deleteMany({ where: { id, userId, outName: owner, state: "held" } });+ return Response.json({ acquired: false });+ }+ await prisma.cutRenderJob.createMany({+ data: [{ id, userId, projectId, kind: "scene_lease", state: "held", spec: {}, outName: owner }],+ skipDuplicates: true,+ });+ const { count } = await prisma.cutRenderJob.updateMany({+ where: { id, userId, state: "held", OR: [{ outName: owner }, { updatedAt: { lt: new Date(Date.now() - sceneLeaseMs) } }] },+ data: { outName: owner, updatedAt: new Date() },+ });+ return Response.json({ acquired: count === 1, leaseMs: sceneLeaseMs });+}diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex 3ece086c..a418b549 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -1,3 +1,4 @@+import { listChatThreads } from "./chats";// Viewer-side reads of a shared cloud project. Every handler resolves the// share token first, then reads the OWNER's rows and presigns the owner's R2// keys — the viewer's session (if any) only ever gates access. The server is@@ -237,15 +238,7 @@ export const sharedView = {const view = await resolveShare(token, req);if (view instanceof Response) return view;if (id !== view.share.projectId || !view.features.chat) return err("Not found.", 404);- const rows = await prisma.cutChatThread.findMany({- where: { userId: view.share.userId, projectId: id },- orderBy: { updatedAt: "desc" },- select: { data: true, updatedAt: true },- });- return Response.json(- rows.map((r) => r.data),- { headers: shareCacheHeaders(view.share, rows[0]?.updatedAt) }- );+ return listChatThreads(view.share.userId, id, req, (updatedAt) => shareCacheHeaders(view.share, updatedAt));},/**diff --git a/site/src/cut/server/cors.ts b/site/src/cut/server/cors.tsindex a58f77a5..95f3ec4c 100644--- a/site/src/cut/server/cors.ts+++ b/site/src/cut/server/cors.ts@@ -29,5 +29,9 @@ export function preflightHeaders(/** Response headers that expose an allowed origin on a normal response. */export function corsHeaders(origin: string): Record<string, string> {- return { "Access-Control-Allow-Origin": origin, Vary: "Origin" };+ return {+ "Access-Control-Allow-Origin": origin,+ "Access-Control-Expose-Headers": "x-cut-doc-version, x-cut-poll-after",+ Vary: "Origin",+ };}diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex 944b8471..c6b89d8a 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -1,11 +1,17 @@import { spawn, execFile } from "node:child_process";import os from "node:os";+import { z } from "zod";+import { SETTINGS } from "@/lib/config/registry";+import { startTurnStream, followTurnStream, cancelTurnStream } from "../ai/turnStreams";import path from "node:path";import { query } from "@anthropic-ai/claude-agent-sdk";-import { createUIMessageStream, createUIMessageStreamResponse, type UIMessage } from "ai";+import { createUIMessageStream, type UIMessage } from "ai";import {callBrowserTool,+ attachSession,+ detachSession,+ claimBrowserTool,registerSession,resolveBrowserTool,unregisterSession,@@ -16,6 +22,7 @@ import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../ai/catalog";interface ChatBody {+ threadId: string;messages: UIMessage[];model: string;context?: unknown;@@ -68,6 +75,7 @@ async function runClaude(sessionKey: string,signal: AbortSignal) {+ signal.throwIfAborted();const q = query({prompt,options: {@@ -163,6 +171,7 @@ async function runCodex(sessionKey: string,signal: AbortSignal) {+ signal.throwIfAborted();const mcp = mcpCommand(base, sessionKey);const session = body.providerSession;const args = ["exec"];@@ -386,14 +395,23 @@ export const aiApi = {},async chat(req: Request) {- const body = (await req.json()) as ChatBody;+ const body = (await req.json().catch(() => null)) as ChatBody;+ const identity = z.object({+ threadId: z.string().min(1).max(200),+ model: z.string().min(1).max(200),+ messages: z.array(z.object({ id: z.string(), role: z.enum(["user", "assistant", "system"]), parts: z.array(z.object({ type: z.string() })) })),+ runtime: SETTINGS.chatRuntime.schema,+ context: z.object({ project: z.object({ id: z.string().min(1).max(200) }) }),+ }).safeParse(body);+ if (!identity.success) return Response.json({ error: "A project and chat are required." }, { status: 400 });+ const projectId = identity.data.context.project.id;const base = new URL(req.url).origin;const sessionKey = crypto.randomUUID();const userText = lastUserText(body.messages);const attachments = lastUserAttachments(body.messages);const prompt = `${userText}${attachedAssetsBlock(attachments)}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;- const stream = createUIMessageStream({+ return startTurnStream(projectId, body.threadId, (signal) => createUIMessageStream({execute: async ({ writer }) => {const emit: UIChunkWriter["write"] = (chunk) =>writer.write(chunk as Parameters<typeof writer.write>[0]);@@ -401,16 +419,18 @@ export const aiApi = {// turn whose tab closes finishes through the engine's own executor.const projectId = (body.context as { project?: { id?: string } } | undefined)?.project?.id;registerSession(sessionKey, { write: emit }, typeof projectId === "string" ? projectId : undefined);- emit({ type: "start" });+ emit({ type: "start", messageId: `turn-${sessionKey}`, messageMetadata: {+ requestMessageId: body.messages.findLast((message) => message.role === "user")?.id,+ } });// The browser posts tool outputs back to /api/cut/ai/tool-result with this key.emit({ type: "data-session", data: { sessionKey }, transient: true });try {if (body.model.startsWith("claude")) {- await runClaude(emit, prompt, body, base, sessionKey, req.signal);+ await runClaude(emit, prompt, body, base, sessionKey, signal);} else if (body.model === "cut-test") {await runFake(emit, sessionKey, userText);} else {- await runCodex(emit, prompt, body, base, sessionKey, req.signal);+ await runCodex(emit, prompt, body, base, sessionKey, signal);}} catch (err) {emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });@@ -419,9 +439,26 @@ export const aiApi = {emit({ type: "finish" });}},- });+ }), () => attachSession(sessionKey), () => detachSession(sessionKey), identity.data.runtime.journalBytes, req.signal);+ },++ async resumeChat(req: Request, threadId: string) {+ const projectId = new URL(req.url).searchParams.get("projectId");+ if (!projectId) return Response.json({ error: "A project is required." }, { status: 400 });+ return followTurnStream(projectId, threadId, req.signal);+ },++ async cancelChat(req: Request, threadId: string) {+ const body = z.object({ projectId: z.string().min(1).max(200) }).safeParse(await req.json().catch(() => null));+ if (!body.success) return Response.json({ error: "A project is required." }, { status: 400 });+ cancelTurnStream(body.data.projectId, threadId);+ return Response.json({ ok: true });+ },- return createUIMessageStreamResponse({ stream });+ async claimTool(req: Request) {+ const body = z.object({ sessionKey: z.string().min(1).max(200), toolCallId: z.string().min(1).max(200) }).safeParse(await req.json().catch(() => null));+ if (!body.success) return Response.json({ error: "A chat session and tool call are required." }, { status: 400 });+ return Response.json({ claimed: claimBrowserTool(body.data.sessionKey, body.data.toolCallId) });},async models() {diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex 7116760e..bb54415e 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -18,6 +18,7 @@ import {moveProjectToFolder,previewPath,readProject,+ projectFileRevision,updateProjectFolder,saveMedia,sweepOrphanMedia,@@ -98,11 +99,15 @@ export const projectsApi = {}},- async get(_req: Request, { id }: { id: string }) {+ async get(req: Request, { id }: { id: string }) {+ const revision = await projectFileRevision(id);+ if (!revision) return err("Project not found.", 404);+ const headers = { "x-cut-doc-version": revision };+ if (req.method === "HEAD") return new Response(null, { headers });const doc = await readProject(id).catch(() => null);if (!doc) return err("Project not found.", 404);void sweepOrphanMedia(id, doc).catch(() => {});- return Response.json(doc);+ return Response.json(doc, { headers });},async put(req: Request, { id }: { id: string }) {@@ -157,8 +162,8 @@ export const projectsApi = {genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,renders: Array.isArray(body.renders) ? body.renders : existing.renders,};- await writeProject(id, doc);- return Response.json({ ok: true, updatedAt: doc.updatedAt });+ const revision = await writeProject(id, doc);+ return Response.json({ ok: true, updatedAt: doc.updatedAt, revision });} catch (e) {return caught(e, "Could not save project.");}diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 69458977..df51ab46 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -1,5 +1,6 @@import { matchRouteTable } from "./match";import { aiApi } from "./ai";+import { localSceneLease } from "../ai/sceneLease";import { convertApi } from "./convert";import { engineApi } from "./engine";import { exportApi } from "./export";@@ -93,6 +94,10 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/mic/:id/cancel", handler: (req, p) => micApi.cancel(req, { id: p.id }) },{ method: "POST", path: "/api/cut/ai/chat", handler: (req) => aiApi.chat(req) },+ { method: "POST", path: "/api/cut/projects/:id/scene-lease", handler: (req, p) => localSceneLease(p.id, req) },+ { method: "GET", path: "/api/cut/ai/chat/:id/stream", handler: (req, p) => aiApi.resumeChat(req, p.id) },+ { method: "POST", path: "/api/cut/ai/chat/:id/cancel", handler: (req, p) => aiApi.cancelChat(req, p.id) },+ { method: "POST", path: "/api/cut/ai/tool-claim", handler: (req) => aiApi.claimTool(req) },{ method: "POST", path: "/api/cut/ai/captions", handler: (req) => aiApi.captions(req) },{ method: "POST", path: "/api/cut/ai/visual-subtitles", handler: (req) => aiApi.visualSubtitles(req) },{ method: "GET", path: "/api/cut/ai/models", handler: () => aiApi.models() },diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex a11860f3..da0f97f0 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -313,6 +313,12 @@ export async function sweepOrphanMedia(id: string, doc: ProjectDoc): Promise<voiconst docPath = (id: string) => path.join(projectDir(id), "project.json");+/** Filesystem metadata makes unchanged-document polls independent of project size. */+export async function projectFileRevision(id: string): Promise<string | null> {+ const info = await stat(docPath(id)).catch(() => null);+ return info ? String(info.mtimeMs) : null;+}+export async function readProject(id: string): Promise<ProjectDoc | null> {const file = docPath(id);let raw: string;@@ -343,8 +349,9 @@ export async function readProject(id: string): Promise<ProjectDoc | null> {export async function writeProject(id: string, doc: ProjectDoc) {doc.id = id;doc.updatedAt = Date.now();- await writeJsonAtomic(docPath(id), doc);+ const revision = await writeJsonAtomic(docPath(id), doc);followName(id, doc.name);+ return revision;}export async function createProject(diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.tsindex 4a228970..75a327d4 100644--- a/site/src/cut/server/util.ts+++ b/site/src/cut/server/util.ts@@ -26,7 +26,9 @@ export async function writeJsonAtomic(filePath: string, value: unknown) {const tmp = `${filePath}.${crypto.randomUUID().slice(0, 8)}.tmp`;await writeFile(tmp, json);await writeFile(`${filePath}.bak`, json).catch(() => {});+ const revision = String((await stat(tmp)).mtimeMs);await rename(tmp, filePath);+ return revision;}/** First executable *file* named `name` on PATH, or null. Directories carry thediff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex 2f3ddfc5..dc5d9137 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -20,6 +20,17 @@ import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/t// tune ships its setting here in the same change.export const SETTINGS = defineSettings({+ chatRuntime: {+ schema: z.object({+ syncIntervalMs: z.number().int().min(1000).max(30000),+ sceneLeaseMs: z.number().int().min(15000).max(120000),+ journalBytes: z.number().int().min(1048576).max(33554432),+ }).strict(),+ default: { syncIntervalMs: 5000, sceneLeaseMs: 30000, journalBytes: 8388608 },+ public: true,+ title: "Chat continuity",+ description: "Project and conversation refresh cadence, scene ownership expiry, and saved engine transcript size.",+ },experimentResults: {schema: z.object({