From a7b2d827ef8bddfd6825a4522b5bc3c323416a01 Mon Sep 17 00:00:00 2001 From: princepride Date: Mon, 23 Nov 2026 15:24:14 +0000 Subject: [PATCH 1/3] [bugfix] canvas: recover a lapsed project lease instead of rejecting every save MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seen on a long canvas session: the page's lease renewals stopped (the last one at 15:03:30), the 60 s lease lapsed, and from then on every save and generate was rejected with 409 '工程已关闭或会话已过期' while the page kept resending the same commands. - Renewals run one at a time in the session-change queue; a renewal stuck on a dropped connection held back every later one. Each renewal now gives up after 10 s, so the next interval renews again. - The lapsed-lease rejection carries code session_expired (with an English message). request() renews the active project's lease and resends the rejected write once; nothing was applied, and commands are deduplicated by commandId. A refused renewal (project taken by another window), a second rejection, non-project paths and other 409s still surface as before. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/opendirector_api/localization.py | 1 + .../infrastructure/creation_projects.py | 3 +- src/backend/api.ts | 32 +++++++++++- src/backend/projects.ts | 29 ++++++++--- tests/sessionLease.test.ts | 49 +++++++++++++++++++ tests/test_creation_storage.py | 16 ++++++ 6 files changed, 122 insertions(+), 8 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index ca5ae3605..eb3efb1fd 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -104,6 +104,7 @@ "operation_rejected": "The operation was rejected. Reload the item and try again.", "storage_busy": "Project storage is busy. Try again shortly.", "project_open_elsewhere": "This project is open in another window. Close it there and try again.", + "session_expired": "This project was closed or its session expired. Reopen it and save again.", "local_only": "Only this computer can access the project service.", "cross_origin": "File access from another site is not allowed.", "invalid_local_request": "This is not a valid local app request.", diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index 170baba9f..022b81174 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -87,7 +87,8 @@ def _lease(self, db, project_id, path, session): lease = db.execute('SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?', (session, str(project_id), time.time())).fetchone() if lease is None: - raise ProjectError('工程已关闭或会话已过期,请重新打开后保存。', 409) + # A stable code lets the page renew its lease and resend instead of failing every save. + raise ProjectError('工程已关闭或会话已过期,请重新打开后保存。', 409, code='session_expired') if lease['path'] != str(path): raise ProjectError('工程目录已在应用外改名或移动,请复制未保存内容并重新打开。', 409) diff --git a/src/backend/api.ts b/src/backend/api.ts index 3995a908f..1a4f4e745 100644 --- a/src/backend/api.ts +++ b/src/backend/api.ts @@ -107,9 +107,25 @@ export async function responseError(response: Response) { ); } +type LeaseRecovery = (projectId: string) => Promise; +let leaseRecovery: LeaseRecovery | undefined; + +/** Installed by the project session owner: renew this page's lease on `projectId`. + * + * A lease lapses when renewals stop for a minute (a suspended page, a renewal + * stuck on a dropped connection). The server rejects the write with + * `session_expired` before applying anything, so one renewal and one resend of + * the same request is safe; commands are also deduplicated by commandId. */ +export function setLeaseRecovery(recover: LeaseRecovery | undefined) { + leaseRecovery = recover; +} + +const PROJECT_PATH = /^\/creation\/projects\/([^/?]+)\//; + export async function request( path: string, options: RequestInit = {}, + leaseRenewed = false, ): Promise { await sessionReady; let response: Response; @@ -122,7 +138,21 @@ export async function request( if (options.signal?.aborted) throw failure; throw new ApiError(tNow("api.networkError"), null, "network_error"); } - if (!response.ok) throw await responseError(response); + if (!response.ok) { + const error = await responseError(response); + const projectId = PROJECT_PATH.exec(path)?.[1]; + if ( + error.status === 409 && + error.code === "session_expired" && + !leaseRenewed && + projectId && + leaseRecovery && + !options.signal?.aborted && + (await leaseRecovery(projectId).catch(() => false)) + ) + return request(path, options, true); + throw error; + } if (response.status === 204) return undefined as T; return (await response.json()) as T; } diff --git a/src/backend/projects.ts b/src/backend/projects.ts index f2ae14929..bdd9d9060 100644 --- a/src/backend/projects.ts +++ b/src/backend/projects.ts @@ -4,6 +4,7 @@ import { json, request, sessionId, + setLeaseRecovery, storageRequest, } from "./api.ts"; import { creationClient } from "./creationClient.ts"; @@ -23,18 +24,34 @@ let active: string | null = null; let opening: Promise | null = null; let heartbeat: number | undefined; +/** A renewal that has not answered by then is abandoned. Renewals run one at a + * time in the session-change queue, so a request stuck on a dropped connection + * would otherwise hold back every later renewal until the 60 s lease lapsed. */ +export const RENEWAL_TIMEOUT_MS = 10_000; + +function renewLease(projectId: string) { + return storageRequest(`/creation/sessions/${sessionId}`, { + ...json("PUT", { projectId }), + signal: AbortSignal.timeout(RENEWAL_TIMEOUT_MS), + }); +} + +// A write rejected for a lapsed lease renews the visible project's lease and is +// resent once. Only the active project is renewed: a stale editor must never +// move the lease back to a project this page has left. +setLeaseRecovery(async (projectId) => { + if (active !== projectId) return false; + await renewLease(projectId); + return active === projectId; +}); + function keepAlive() { if (heartbeat !== undefined) return; heartbeat = window.setInterval(() => { if (active && !opening) { const projectId = active; // A pending renewal must finish before an explicit close or project switch. - void serializeSessionChange(() => - storageRequest( - `/creation/sessions/${sessionId}`, - json("PUT", { projectId }), - ), - ).catch(() => {}); + void serializeSessionChange(() => renewLease(projectId)).catch(() => {}); } }, 15000); window.addEventListener("pagehide", () => { diff --git a/tests/sessionLease.test.ts b/tests/sessionLease.test.ts index 581b842f2..52d9debec 100644 --- a/tests/sessionLease.test.ts +++ b/tests/sessionLease.test.ts @@ -65,3 +65,52 @@ test("a previous page that is still unloading is released once its lock is gone" ); assert.deepEqual(released, ["old"]); }); + +test("a write rejected for a lapsed lease renews it and is resent once", async () => { + const { request, setLeaseRecovery } = await import("../src/backend/api.ts"); + const original = globalThis.fetch; + const calls: string[] = []; + const renewed: string[] = []; + const expired = () => + new Response(JSON.stringify({ detail: "会话已过期", code: "session_expired" }), { status: 409 }); + try { + let answers = [expired(), new Response(JSON.stringify({ status: "applied" }), { status: 200 })]; + globalThis.fetch = (async (url: string) => { + calls.push(String(url)); + return answers.shift()!; + }) as typeof fetch; + setLeaseRecovery(async (projectId) => { + renewed.push(projectId); + return true; + }); + assert.deepEqual(await request("/creation/projects/p1/commands", { method: "POST", body: "{}" }), { + status: "applied", + }); + assert.deepEqual(renewed, ["p1"]); + assert.deepEqual(calls, ["/api/creation/projects/p1/commands", "/api/creation/projects/p1/commands"]); + + // A second rejection after renewing is reported, not retried forever. + answers = [expired(), expired()]; + await assert.rejects(request("/creation/projects/p1/commands", { method: "POST" }), { code: "session_expired" }); + assert.equal(renewed.length, 2); + + // A renewal the server refuses (another window took the project) surfaces the original error. + setLeaseRecovery(async () => false); + answers = [expired()]; + await assert.rejects(request("/creation/projects/p1/commands", { method: "POST" }), { code: "session_expired" }); + + // Paths outside a project, and other 409s, are never renewed. + setLeaseRecovery(async (projectId) => { + renewed.push(projectId); + return true; + }); + answers = [expired()]; + await assert.rejects(request("/creation/sessions/s1", { method: "PUT" }), { code: "session_expired" }); + answers = [new Response(JSON.stringify({ code: "revision_conflict" }), { status: 409 })]; + await assert.rejects(request("/creation/projects/p1/commands", { method: "POST" }), { code: "revision_conflict" }); + assert.equal(renewed.length, 2); + } finally { + globalThis.fetch = original; + setLeaseRecovery(undefined); + } +}); diff --git a/tests/test_creation_storage.py b/tests/test_creation_storage.py index f0939544b..6b68264e8 100644 --- a/tests/test_creation_storage.py +++ b/tests/test_creation_storage.py @@ -1177,3 +1177,19 @@ def decode(raw, **kwargs): assert len(cold._records_cache) == 1 assert cold._records_cache_bytes == sum( entry[0][2] for entry in cold._records_cache.values()) + + +def test_a_lapsed_lease_has_a_stable_code_and_a_heartbeat_restores_it(projects): + created = create(projects) + session = str(uuid4()) + projects.open(created.projectId, session) + client = uuid4() + view = {'projectId': str(created.projectId), 'clientId': str(client)} + with projects.local.transaction() as db: + db.execute('UPDATE sessions SET expires=0') + with pytest.raises(ProjectError) as lapsed: + projects.view(created.projectId, client, view, session=session) + # The page renews and resends on this code instead of failing every save. + assert lapsed.value.status == 409 and lapsed.value.code == 'session_expired' + projects.heartbeat(session, created.projectId) + projects.view(created.projectId, client, view, session=session) From 49f2ad0b5c961f958cbb89219cac6dc9e5d3ff36 Mon Sep 17 00:00:00 2001 From: princepride Date: Mon, 23 Nov 2026 15:52:29 +0000 Subject: [PATCH 2/3] [bugfix] canvas: send asset uploads through the lease-recovering request layer Uploads used a raw fetch and so skipped the renew-and-resend added for a lapsed lease. Seen right after the previous fix: rendering a 25 s timeline kept the page busy for about a minute, renewals paused for 79 s, and the finished MP4's upload at 15:50:02 got 409 session_expired, failing the output. importBlob and the timeline package upload now use request(), which renews the lease and resends the same file once. Co-Authored-By: Claude Opus 5.5 --- src/backend/creationClient.ts | 6 ++--- src/backend/timelinePackages.ts | 9 +++---- tests/creationClient.test.ts | 45 +++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 56e05c494..3f769045a 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -469,17 +469,17 @@ export class CreationClient { signal?.throwIfAborted(); const path = `${creationPath(this.id)}/uploads/${handle}`; try { - const response = await fetch(`/api${path}`, { + // Through request(): an upload after a long local render can meet a + // lease that lapsed while the page was busy; it is renewed and resent. + await request(path, { method: "PUT", headers: { - ...headers, "X-Asset-Name": encodeURIComponent(name), "X-Asset-Kind": kind, }, body: blob, signal, }); - if (!response.ok) throw await responseError(response); signal?.throwIfAborted(); } catch (error) { if (signal?.aborted) { diff --git a/src/backend/timelinePackages.ts b/src/backend/timelinePackages.ts index efa90512c..9c507cd0f 100644 --- a/src/backend/timelinePackages.ts +++ b/src/backend/timelinePackages.ts @@ -6,6 +6,7 @@ import { ApiError, headers, json, + request as apiRequest, responseError, storageRequest, } from "./api.ts"; @@ -83,20 +84,18 @@ export class TimelinePackageImport { return this.finish(recovered); } if (!this.request) { - const response = await fetch( - `/api${creationPath(this.client.id)}/uploads/${this.uploadHandle}`, + // Through request() so a lapsed lease is renewed and the upload resent. + const uploaded = await apiRequest<{ fingerprint: string }>( + `${creationPath(this.client.id)}/uploads/${this.uploadHandle}`, { method: "PUT", headers: { - ...headers, "X-Asset-Name": encodeURIComponent(this.file.name), "X-Asset-Kind": "file", }, body: this.file, }, ); - if (!response.ok) throw await responseError(response); - const uploaded = (await response.json()) as { fingerprint: string }; this.request = { operationId: this.operationId, uploadHandle: this.uploadHandle, diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts index 81dc7be3c..15c320b05 100644 --- a/tests/creationClient.test.ts +++ b/tests/creationClient.test.ts @@ -1553,3 +1553,48 @@ test("canvas video and audio import upload the original File and use Host media assert.equal(resource.src, "blob:registered-media"); } }); + +test("an upload rejected for a lapsed lease is renewed and resent with the same file", async () => { + const { setLeaseRecovery } = await import("../src/backend/api.ts"); + const snapshot = empty(); + const client = new CreationClient(snapshot.project.id); + client.install(snapshot); + const signal = new AbortController(); + const handle = crypto.randomUUID(); + const path = `/api/creation/projects/${snapshot.project.id}/uploads/${handle}`; + const blob = new Blob(["rendered timeline"]); + const puts: { body: unknown; name: string | null; session: string | null }[] = []; + const renewed: string[] = []; + const fetch = globalThis.fetch; + setLeaseRecovery(async (projectId) => { + renewed.push(projectId); + return true; + }); + globalThis.fetch = async (url, options) => { + if ((options?.method ?? "GET") !== "PUT") return Response.json({}); + assert.equal(String(url), path); + const headers = new Headers(options?.headers); + puts.push({ body: options?.body, name: headers.get("X-Asset-Name"), session: headers.get("X-OpenDirector-Session") }); + if (puts.length === 1) + return Response.json({ detail: "会话已过期", code: "session_expired" }, { status: 409 }); + // Stop before registration; the resend itself is what is under test. + signal.abort(); + return Response.json({ fingerprint: "sha256:x" }); + }; + try { + await assert.rejects( + client.importBlob(blob, "合回原声 2.mp4", "video", handle, "edited", signal.signal), + { name: "AbortError" }, + ); + assert.deepEqual(renewed, [snapshot.project.id]); + assert.equal(puts.length, 2); + for (const put of puts) { + assert.equal(put.body, blob); + assert.equal(put.name, encodeURIComponent("合回原声 2.mp4")); + assert.ok(put.session); + } + } finally { + globalThis.fetch = fetch; + setLeaseRecovery(undefined); + } +}); From 0fc47092a79df7363380c8abb4b84285626122be Mon Sep 17 00:00:00 2001 From: princepride Date: Tue, 24 Nov 2026 01:14:27 +0000 Subject: [PATCH 3/3] [bugfix] canvas: renew a lapsed lease inside the session-change queue The recovery renewal ran outside the session-change queue. A save from the editor being left, rejected while a project switch's close was in flight, still saw that project as active and sent PUT /sessions for it; since a heartbeat is an open, that renewal could move the lease back to the project the page was leaving. The renewal now waits in the queue like the heartbeat, so it sees the switch and renews nothing. Writes rejected together for one lapsed lease now share a single renewal instead of one open each. Co-Authored-By: Claude Fable 5.2 --- src/backend/projects.ts | 26 +++++++++++++---- tests/sessionClose.test.ts | 59 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/src/backend/projects.ts b/src/backend/projects.ts index bdd9d9060..eb59b69f5 100644 --- a/src/backend/projects.ts +++ b/src/backend/projects.ts @@ -38,11 +38,27 @@ function renewLease(projectId: string) { // A write rejected for a lapsed lease renews the visible project's lease and is // resent once. Only the active project is renewed: a stale editor must never -// move the lease back to a project this page has left. -setLeaseRecovery(async (projectId) => { - if (active !== projectId) return false; - await renewLease(projectId); - return active === projectId; +// move the lease back to a project this page has left. The renewal runs in the +// session-change queue, like the heartbeat, so it cannot land after a queued +// close or switch has released the project. Writes rejected together share one +// renewal. No queued operation issues a lease-checked write, so this cannot +// wait on itself. +let recovering: { projectId: string; renewed: Promise } | null = null; +setLeaseRecovery((projectId) => { + if (recovering?.projectId === projectId) return recovering.renewed; + const renewed = serializeSessionChange(async () => { + if (active !== projectId) return false; + await renewLease(projectId); + return active === projectId; + }); + const current = { projectId, renewed }; + recovering = current; + void renewed + .finally(() => { + if (recovering === current) recovering = null; + }) + .catch(() => {}); + return renewed; }); function keepAlive() { diff --git a/tests/sessionClose.test.ts b/tests/sessionClose.test.ts index f87f7eb72..1cebb0647 100644 --- a/tests/sessionClose.test.ts +++ b/tests/sessionClose.test.ts @@ -6,6 +6,7 @@ import { flushChatDraft, rememberChat, } from "../src/backend/chatDrafts.ts"; +import { request } from "../src/backend/api.ts"; import { openBackendProject, releaseBackendProject, @@ -247,3 +248,61 @@ test("unified projects retain their own session endpoint for switches and page e false, ); }); + +const expired = () => + Response.json({ detail: "会话已过期", code: "session_expired" }, { status: 409 }); + +test("a lapsed-lease recovery waits for a pending switch and never reacquires the project left", async (t) => { + const f = fixture(t), + id = crypto.randomUUID(), + next = crypto.randomUUID(); + await openBackendProject(id, "A"); + let release!: () => void, entered!: () => void; + const closing = new Promise((resolve) => { + entered = resolve; + }); + const blocked = new Promise((resolve) => { + release = resolve; + }); + f.intercept(async (path, options) => { + if (path.includes("/sessions/") && options.method === "DELETE") { + entered(); + await blocked; + } + if (path.endsWith(`/${id}/commands`)) return expired(); + return undefined; + }); + const switching = openBackendProject(next, "B"); + await closing; + // A save from the editor being left is rejected while the close is in flight. + const save = request(`/creation/projects/${id}/commands`, { method: "POST", body: "{}" }); + await new Promise((resolve) => setImmediate(resolve)); + release(); + await switching; + await assert.rejects(save, { code: "session_expired" }); + assert.equal(f.lease(), next); + assert.equal( + f.calls.some((call) => call.method === "PUT" && call.value.projectId === id), + false, + ); +}); + +test("writes rejected together for a lapsed lease share one renewal", async (t) => { + const f = fixture(t), + id = crypto.randomUUID(); + await openBackendProject(id, "A"); + f.expire(); + f.intercept(async (path) => + path.endsWith(`/${id}/commands`) + ? f.lease() === id + ? Response.json({ status: "applied" }) + : expired() + : undefined, + ); + const saves = [1, 2, 3].map(() => + request(`/creation/projects/${id}/commands`, { method: "POST", body: "{}" }), + ); + assert.deepEqual(await Promise.all(saves), [1, 2, 3].map(() => ({ status: "applied" }))); + assert.equal(f.calls.filter((call) => call.method === "PUT").length, 1); + assert.equal(f.lease(), id); +});