From efe75c3224246b6355fd29988f7a073d6a2af4eb Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Thu, 26 Nov 2026 19:51:08 +0800 Subject: [PATCH 1/2] [bugfix] projects: retain edit ownership until takeover Signed-off-by: Weiming Liao --- apps/api/src/opendirector_api/creation.py | 18 ++-- .../infrastructure/creation_projects.py | 20 ++-- .../infrastructure/local_projects.py | 70 +++----------- src/backend/api.ts | 95 +++++++------------ src/backend/creationClient.ts | 2 +- src/backend/editSession.ts | 30 +++--- src/backend/projects.ts | 52 ++++------ src/canvas/CanvasWorkspace.tsx | 8 +- src/canvas/workspace/EditSession.tsx | 44 +-------- src/canvas/workspace/WorkspaceView.tsx | 5 +- src/canvas/workspace/edit-session.css | 47 +-------- src/i18n/messages/en-US/canvasWorkspace.ts | 6 -- src/i18n/messages/zh-CN/canvasWorkspace.ts | 6 -- tests/browser/manifest.json | 2 +- tests/browser/session_lease.mjs | 46 ++++----- tests/sessionLease.test.ts | 66 ------------- tests/test_creation_api.py | 27 ++++++ 17 files changed, 146 insertions(+), 398 deletions(-) diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 7137d5fc6..d2a685de4 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -36,11 +36,6 @@ from opendirector_api.localization import localized_error_for_language -class EditHandoffDecision(BaseModel): - requester: UUID - accept: bool - - class FontCoverageResponse(BaseModel): fingerprint: str = Field(pattern=r'^sha256:[0-9a-f]{64}$') # One bit per Unicode scalar position: fixed 139,264 bytes / 185,688 base64 chars. @@ -132,7 +127,10 @@ def snapshot(project_id: UUID): return projects.snapshot(project_id) @router.post('/projects/{project_id}/open', response_model=ProjectSnapshot) - def open_project(project_id: UUID, x_opendirector_session: UUID = Header()): + def open_project(project_id: UUID, x_opendirector_session: UUID = Header(), + x_opendirector_persistent: bool = Header(default=False)): + if x_opendirector_persistent: + return projects.open(project_id, str(x_opendirector_session), persistent=True) return projects.open(project_id, str(x_opendirector_session)) @router.post('/projects/{project_id}/open-canvas') @@ -157,12 +155,8 @@ def edit_session(project_id: UUID, x_opendirector_session: UUID = Header()): return projects.editing_state(project_id, str(x_opendirector_session)) @router.post('/projects/{project_id}/edit-session') - def request_edit_session(project_id: UUID, x_opendirector_session: UUID = Header()): - return projects.request_edit(project_id, str(x_opendirector_session)) - - @router.put('/projects/{project_id}/edit-session') - def resolve_edit_session(project_id: UUID, value: EditHandoffDecision, x_opendirector_session: UUID = Header()): - return projects.resolve_edit(project_id, str(x_opendirector_session), str(value.requester), value.accept) + def take_edit_ownership(project_id: UUID, x_opendirector_session: UUID = Header()): + return projects.take_edit_ownership(project_id, str(x_opendirector_session)) @router.put('/sessions/{session_id}') def heartbeat(session_id: UUID, value: Session): diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index 4440788d8..4c5a45ff8 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -122,7 +122,7 @@ def view(self, project_id, client_id, value=None, *, session=None, missing_ok=Fa return None if missing_ok else ViewState(projectId=project_id, clientId=client_id) def open_canvas( - self, project_id: UUID | str, session: str, *, allow_preview: bool, + self, project_id: UUID | str, session: str, *, allow_preview: bool, persistent: bool = False, ) -> tuple[ProjectSnapshot, dict[str, str | None]]: with self.local.transaction() as db: self._recover() @@ -131,12 +131,11 @@ def open_canvas( if allow_preview: editor = self.local.editor(db, str(project_id)) if editor and editor['id'] != session: - self.local.clear_other_edit_requests(db, str(project_id), session) db.execute("DELETE FROM sessions WHERE id=?", (session,)) else: - self.local.acquire_edit_lease(db, project, session) + self.local.acquire_edit_lease(db, project, session, persistent=True) else: - self.local.acquire_edit_lease(db, project, session) + self.local.acquire_edit_lease(db, project, session, persistent=persistent) state = self.local.editing_state(db, str(project_id), session) record, validated = self._current_record(db, project_id, path, manifest) if not validated: @@ -145,23 +144,18 @@ def open_canvas( self._schedule_warm(path, manifest) return record.snapshot.model_copy(deep=True), state - def open(self, project_id: UUID | str, session: str) -> ProjectSnapshot: - snapshot, _ = self.open_canvas(project_id, session, allow_preview=False) + def open(self, project_id: UUID | str, session: str, *, persistent=False) -> ProjectSnapshot: + snapshot, _ = self.open_canvas(project_id, session, allow_preview=False, persistent=persistent) return snapshot def editing_state(self, project_id, session): with self.local.transaction() as db: return self.local.editing_state(db, str(project_id), session) - def request_edit(self, project_id, session): + def take_edit_ownership(self, project_id, session): with self.local.transaction() as db: path, _ = self._find(db, project_id) - return self.local.request_edit(db, dict(id=str(project_id), path=str(path)), session) - - def resolve_edit(self, project_id, session, requester, accept): - with self.local.transaction() as db: - path, _ = self._find(db, project_id) - return self.local.resolve_edit(db, dict(id=str(project_id), path=str(path)), session, requester, accept) + return self.local.take_edit_ownership(db, dict(id=str(project_id), path=str(path)), session) def heartbeat(self, session, project_id): self.open(project_id, session) diff --git a/packages/core/src/opendirector/infrastructure/local_projects.py b/packages/core/src/opendirector/infrastructure/local_projects.py index a2bef6425..3777bc550 100644 --- a/packages/core/src/opendirector/infrastructure/local_projects.py +++ b/packages/core/src/opendirector/infrastructure/local_projects.py @@ -76,8 +76,6 @@ class LocalProjects: # separate key lets browsers open or release their own editing session. _AGENT_SESSION_PREFIX = "agent:" - HANDOFF_SECONDS = 120 - def __init__(self, repository: Path): self.repository = repository.resolve() self.root = self.repository / "projects" @@ -91,10 +89,6 @@ def __init__(self, repository: Path): id TEXT PRIMARY KEY, project_id TEXT NOT NULL, expires REAL NOT NULL, path TEXT NOT NULL DEFAULT '' ); - CREATE TABLE IF NOT EXISTS edit_handoffs ( - project_id TEXT PRIMARY KEY, owner TEXT NOT NULL, - requester TEXT NOT NULL, expires REAL NOT NULL - ); """) db.execute("DELETE FROM sessions WHERE expires<=?", (time.time(),)) @@ -128,24 +122,18 @@ def _conflict(parent: Path, name: str, source: Path | None = None): raise ProjectError("该位置已有同名文件或文件夹,请使用其他名称。", 409) - def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str) -> None: + def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str, *, persistent=False) -> None: identifier(session) project_id = project["id"] - self.clear_other_edit_requests(db, project_id, session) if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND id NOT LIKE ? AND expires>?", (project_id, session, self._AGENT_SESSION_PREFIX + "%", time.time())).fetchone(): raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere") - lease = db.execute("SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone() + lease = db.execute("SELECT path, expires FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone() if lease and lease["path"] != project["path"]: raise ProjectError("项目目录已在应用外改名或移动,请复制未保存内容并刷新页面。", 409) - db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, time.time() + self.LEASE_SECONDS, project["path"])) - + expires = float("inf") if persistent or (lease and lease["expires"] == float("inf")) else time.time() + self.LEASE_SECONDS + db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, expires, project["path"])) - def clear_other_edit_requests(self, db, project_id, session): - db.execute( - "DELETE FROM edit_handoffs WHERE project_id!=? AND (owner=? OR requester=?)", - (project_id, session, session), - ) def editor(self, db, project_id, *, now=None): return db.execute( @@ -153,45 +141,16 @@ def editor(self, db, project_id, *, now=None): (project_id, self._AGENT_SESSION_PREFIX + "%", time.time() if now is None else now), ).fetchone() - def editing_state(self, db, project_id, session, *, now=None): - now = time.time() if now is None else now - editor = self.editor(db, project_id, now=now) - if editor is None: - return {'mode': 'preview', 'handoff': 'available'} - owner = editor['id'] - pending = db.execute( - "SELECT requester FROM edit_handoffs WHERE project_id=? AND owner=? AND expires>?", - (project_id, owner, now), - ).fetchone() - if owner == session: - return {'mode': 'edit', 'requester': pending['requester'] if pending else None} - return {'mode': 'preview', 'handoff': ( - 'requested' if pending and pending['requester'] == session - else 'busy' if pending else 'occupied' - )} - - def request_edit(self, db, project, session): - project_id = project['id'] - now = time.time() - state = self.editing_state(db, project_id, session, now=now) - if state == {'mode': 'preview', 'handoff': 'available'}: - self.acquire_edit_lease(db, project, session) - elif state == {'mode': 'preview', 'handoff': 'occupied'}: - db.execute(""" - INSERT INTO edit_handoffs(project_id,owner,requester,expires) VALUES (?,?,?,?) - ON CONFLICT(project_id) DO UPDATE SET owner=excluded.owner, - requester=excluded.requester, expires=excluded.expires - """, (project_id, self.editor(db, project_id, now=now)['id'], session, now + self.HANDOFF_SECONDS)) - return self.editing_state(db, project_id, session) - - def resolve_edit(self, db, project, session, requester, accept): - project_id = project['id'] - if self.editing_state(db, project_id, session) == {'mode': 'edit', 'requester': requester}: - db.execute("DELETE FROM edit_handoffs WHERE project_id=?", (project_id,)) - if accept: - db.execute("DELETE FROM sessions WHERE id=?", (session,)) - self.acquire_edit_lease(db, project, requester) - return self.editing_state(db, project_id, session) + def editing_state(self, db, project_id, session): + editor = self.editor(db, project_id) + return {'mode': 'edit' if editor and editor['id'] == session else 'preview'} + + def take_edit_ownership(self, db, project, session): + editor = self.editor(db, project['id']) + if editor and editor['id'] != session: + db.execute("DELETE FROM sessions WHERE id=?", (editor['id'],)) + self.acquire_edit_lease(db, project, session, persistent=True) + return self.editing_state(db, project['id'], session) def agent_session_key(self, session: str) -> str: return self._AGENT_SESSION_PREFIX + identifier(session) @@ -215,5 +174,4 @@ def release_agent_session(self, session: str): def release(self, session: str): with self.transaction() as db: - db.execute("DELETE FROM edit_handoffs WHERE owner=? OR requester=?", (session, session)) db.execute("DELETE FROM sessions WHERE id=?", (session,)) diff --git a/src/backend/api.ts b/src/backend/api.ts index 1a4f4e745..0f19b2551 100644 --- a/src/backend/api.ts +++ b/src/backend/api.ts @@ -3,48 +3,7 @@ import { detectLocale } from "../i18n/locale.ts"; import type { Locale } from "../i18n/types.ts"; import { tNow } from "../i18n/messages.ts"; -export const sessionId = crypto.randomUUID(); -globalThis.window?.opendirectorDesktop?.registerSession(sessionId); - const SESSION_KEY = "opendirector.session.v1"; -const lockName = (id: string) => `opendirector.session.${id}`; - -interface SessionLocks { - request(name: string, callback: () => Promise): Promise; - query(): Promise<{ held?: { name?: string }[] }>; -} - -/** Release this tab's previous page lease after a reload or crash. - * - * Each page load uses a new session. When the previous page could not send its - * release (crash, killed process, lost keepalive), its lease would otherwise - * block the reloaded tab as "another window" until it expires. The previous - * session is released only when no live page still holds its Web Lock, so a - * duplicated tab, which copies sessionStorage, never releases a live window. - * Without Web Locks nothing is released and the lease simply expires. */ -export async function releaseStaleSession( - previous: string | null, - current: string, - locks: SessionLocks | undefined, - release: (id: string) => Promise, - pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)), -) { - if (!locks) return false; - // Hold this page's lock for its lifetime; the browser drops it on unload. - void locks.request(lockName(current), () => new Promise(() => {})).catch(() => {}); - if (!previous || previous === current) return false; - for (let attempt = 0; attempt < 8; attempt++) { - // A reloading page may still be tearing down; look again briefly. - if (attempt) await pause(250); - const state = await locks.query().catch(() => null); - if (!state) return false; - if (!state.held?.some((lock) => lock.name === lockName(previous))) { - await release(previous).catch(() => {}); - return true; - } - } - return false; -} function tabStorage(): Storage | null { try { @@ -55,25 +14,40 @@ function tabStorage(): Storage | null { } const previousSession = tabStorage()?.getItem(SESSION_KEY) ?? null; -/** This page replaced an earlier page of the same tab (reload or reconnect). */ export const reloadedTab = previousSession !== null; -try { - tabStorage()?.setItem(SESSION_KEY, sessionId); -} catch { - // Private modes may refuse storage; the lease then just expires. +export let sessionId = previousSession ?? crypto.randomUUID(); + +async function claimSession(id: string): Promise { + if (!globalThis.navigator?.locks) return true; + return new Promise((resolve, reject) => { + void navigator.locks.request(`opendirector.session.${id}`, { ifAvailable: true }, async (lock) => { + resolve(Boolean(lock)); + if (lock) await new Promise(() => {}); + }).catch(reject); + }); } -/** Requests wait until a stale lease from this tab's previous page is gone. */ -const sessionReady = releaseStaleSession( - previousSession, - sessionId, - (globalThis.navigator as { locks?: SessionLocks } | undefined)?.locks, - (id) => - fetch(`/api/creation/sessions/${id}`, { - method: "DELETE", - headers: { "X-OpenDirector-Request": "1" }, - }), -).catch(() => false); +function installSession(id: string) { + sessionId = id; + headers["X-OpenDirector-Session"] = id; + try { + tabStorage()?.setItem(SESSION_KEY, id); + } catch { + // Storage can be disabled in the browser. + } + globalThis.window?.opendirectorDesktop?.registerSession(id); +} + +export async function rotateSession() { + const id = crypto.randomUUID(); + await claimSession(id); + installSession(id); +} + +const sessionReady = (async () => { + if (await claimSession(sessionId).catch(() => true)) installSession(sessionId); + else await rotateSession(); +})(); export class ApiError extends Error { status: number | null; @@ -128,6 +102,7 @@ export async function request( leaseRenewed = false, ): Promise { await sessionReady; + const requestedSession = sessionId; let response: Response; try { response = await fetch(`/api${path}`, { @@ -145,12 +120,14 @@ export async function request( error.status === 409 && error.code === "session_expired" && !leaseRenewed && + requestedSession === sessionId && projectId && leaseRecovery && !options.signal?.aborted && (await leaseRecovery(projectId).catch(() => false)) - ) - return request(path, options, true); + ) { + if (requestedSession === sessionId) return request(path, options, true); + } throw error; } if (response.status === 204) return undefined as T; diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 679643d45..90447e4cc 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -179,7 +179,7 @@ export class CreationClient { if ("editing" in opened) installEditingState(this.id, parseEditingState(opened.editing)); else - installEditingState(this.id, { mode: "edit", requester: null }); + installEditingState(this.id, { mode: "edit" }); canvas = "snapshot" in opened ? opened : undefined; if (canvas) this.referenceStates = new Map( diff --git a/src/backend/editSession.ts b/src/backend/editSession.ts index 6b2588854..4fb3832ac 100644 --- a/src/backend/editSession.ts +++ b/src/backend/editSession.ts @@ -1,19 +1,11 @@ -import { json, request } from "./api.ts"; +import { request, rotateSession } from "./api.ts"; -export type EditingState = - | { mode: "edit"; requester: string | null } - | { mode: "preview"; handoff: "available" | "occupied" | "requested" | "busy" }; +export type EditingState = { mode: "edit" | "preview" }; export function parseEditingState(value: unknown): EditingState { - if (typeof value === "object" && value !== null && "mode" in value) { - if (value.mode === "edit" && "requester" in value && - (value.requester === null || typeof value.requester === "string")) - return { mode: value.mode, requester: value.requester }; - if (value.mode === "preview" && "handoff" in value && - (value.handoff === "available" || value.handoff === "occupied" || - value.handoff === "requested" || value.handoff === "busy")) - return { mode: value.mode, handoff: value.handoff }; - } + if (typeof value === "object" && value !== null && "mode" in value && + (value.mode === "edit" || value.mode === "preview")) + return { mode: value.mode }; throw new TypeError("Invalid editing session response"); } @@ -31,9 +23,7 @@ export function getEditingState(projectId: string) { export function installEditingState(projectId: string, state: EditingState) { const previous = getEditingState(projectId); - if (previous?.mode === "edit" && state.mode === "edit" && previous.requester === state.requester || - previous?.mode === "preview" && state.mode === "preview" && previous.handoff === state.handoff) - return; + if (previous?.mode === state.mode) return; current = { projectId, state }; for (const listener of listeners) listener(); } @@ -42,6 +32,8 @@ export async function readEditingState(projectId: string, init?: RequestInit) { return parseEditingState(await request(`/creation/projects/${projectId}/edit-session`, init)); } -export const requestEditing = (projectId: string) => readEditingState(projectId, { method: "POST" }); -export const resolveEditing = (projectId: string, requester: string, accept: boolean) => - readEditingState(projectId, json("PUT", { requester, accept })); +export async function takeEditingOwnership(projectId: string) { + // Each takeover uses a fresh write identity, even when returning to the same tab. + await rotateSession(); + return readEditingState(projectId, { method: "POST", signal: AbortSignal.timeout(10000) }); +} diff --git a/src/backend/projects.ts b/src/backend/projects.ts index d5e9bcf57..a685b37db 100644 --- a/src/backend/projects.ts +++ b/src/backend/projects.ts @@ -48,7 +48,7 @@ let recovering: { projectId: string; renewed: Promise } | null = null; setLeaseRecovery((projectId) => { if (recovering?.projectId === projectId) return recovering.renewed; const renewed = serializeSessionChange(async () => { - if (active !== projectId || getEditingState(projectId)?.mode === "preview") return false; + if (active !== projectId || getEditingState(projectId) !== undefined) return false; await renewLease(projectId); return active === projectId; }); @@ -65,26 +65,19 @@ setLeaseRecovery((projectId) => { function keepAlive() { if (heartbeat !== undefined) return; heartbeat = window.setInterval(() => { - if (active && !opening && getEditingState(active)?.mode !== "preview") { + if (active && !opening && getEditingState(active) === undefined) { const projectId = active; // A pending renewal must finish before an explicit close or project switch. void serializeSessionChange(async () => { - if (active !== projectId || getEditingState(projectId)?.mode === "preview") return; + if (active !== projectId || getEditingState(projectId) !== undefined) return; await renewLease(projectId); }).catch(() => {}); } }, 15000); - window.addEventListener("pagehide", () => { - if (!active) return; - void closeProjectSession(true).catch(() => {}); - }); } -function closeProjectSession(keepalive = false) { - return request(`/creation/sessions/${sessionId}`, { - method: "DELETE", - keepalive, - }); +function closeProjectSession() { + return request(`/creation/sessions/${sessionId}`, { method: "DELETE" }); } export function serializeSessionChange(operation: () => Promise): Promise { @@ -131,9 +124,7 @@ function activateBackendProject( if (switching && previousMode?.mode === "preview") active = previous; if (switching && previousMode?.mode !== "preview") { try { - await request(`/creation/projects/${previous}/open`, { - method: "POST", - }); + await openEditingProject(previous); active = previous; } catch (restoreFailure) { throw new Error( @@ -153,24 +144,22 @@ function activateBackendProject( }); } -/** Opening again renews a lease that lapsed while the page was suspended. */ +function openEditingProject(projectId: string) { + return request(`/creation/projects/${projectId}/open`, { + method: "POST", + headers: { "X-OpenDirector-Persistent": "true" }, + }); +} + export function openBackendProject(documentId: string, _title: string) { const id = backendProjectId(documentId); return activateBackendProject(id, async () => { - await request(`/creation/projects/${id}/open`, { method: "POST" }); - installEditingState(id, { mode: "edit", requester: null }); + await openEditingProject(id); + installEditingState(id, { mode: "edit" }); return id; }); } -/** Longest canvas read that can rely on the lease it acquired at the start. - * - * The server grants a 60 s lease, and heartbeat renewal is suppressed while a - * read owns the session-change queue. A media-heavy read can stream for longer - * than that (one asset read is bounded at 120 s per attempt), so a read that - * outlived this window renews the lease before adoption. */ -const LEASE_RECONFIRM_MS = 30_000; - /** Read a canvas and adopt the session lease that read acquires. * * `CreationClient.open()` reads through POST /open-canvas, which moves this @@ -188,16 +177,9 @@ export function openBackendProjectCanvas( return serializeSessionChange(async () => { const previous = active; const previousMode = previous ? getEditingState(previous) : undefined; - const startedAt = Date.now(); let value: T; try { value = await read(); - if (Date.now() - startedAt >= LEASE_RECONFIRM_MS && getEditingState(id)?.mode !== "preview") - // Hydration kept the normal heartbeat from running. Renewing here keeps - // the lease alive when it outlived the 60 s grant; if another window has - // taken over the expired lease the server rejects this renewal and the - // open fails instead of adopting a session we no longer own. - await request(`/creation/sessions/${sessionId}`, json("PUT", { projectId: id })); } catch (failure) { // read() moves this window's session before it finishes the view. A // failure after that acceptance would leave the lease on `id` while @@ -210,9 +192,7 @@ export function openBackendProjectCanvas( installEditingState(previous, previousMode); } else if (previous && previous !== id) { try { - await request(`/creation/projects/${previous}/open`, { - method: "POST", - }); + await openEditingProject(previous); } catch (restoreFailure) { throw new Error( tNow("errors.backend.openFailed", { diff --git a/src/canvas/CanvasWorkspace.tsx b/src/canvas/CanvasWorkspace.tsx index b5f1769cf..a334c575a 100644 --- a/src/canvas/CanvasWorkspace.tsx +++ b/src/canvas/CanvasWorkspace.tsx @@ -1,6 +1,6 @@ import { useSyncExternalStore } from "react"; import { getEditingState, subscribeEditingState } from "../backend/editSession.ts"; -import { EditHandoff, useEditSession } from "./workspace/EditSession.tsx"; +import { useEditSession } from "./workspace/EditSession.tsx"; import { ReactFlowProvider } from "@xyflow/react"; import { TooltipProvider } from "./TooltipButton"; import { WorkspaceView } from "./workspace/WorkspaceView.tsx"; @@ -35,9 +35,5 @@ function Workspace() { useWorkspaceGeneration(rt, readOnly || editSession.working); useWorkspaceTransfer(rt, readOnly); useWorkspaceInteraction(rt, readOnly); - return <> - - {rt.ready && editing?.mode === "edit" && editing.requester && - } - ; + return ; } diff --git a/src/canvas/workspace/EditSession.tsx b/src/canvas/workspace/EditSession.tsx index 90521ebc5..017bd8fd2 100644 --- a/src/canvas/workspace/EditSession.tsx +++ b/src/canvas/workspace/EditSession.tsx @@ -1,9 +1,7 @@ import { useEffect, useRef, useState } from "react"; -import { flushChatDraft } from "../../backend/chatDrafts.ts"; import { errorMessage } from "../../backend/api.ts"; -import { readEditingState, installEditingState, requestEditing, resolveEditing } from "../../backend/editSession.ts"; +import { readEditingState, installEditingState, takeEditingOwnership } from "../../backend/editSession.ts"; import { activeBackendProjectId, serializeSessionChange } from "../../backend/projects.ts"; -import { persistCurrentDocument } from "../projectManagement.ts"; import type { WorkspaceRuntime } from "./runtimeTypes.ts"; import "./edit-session.css"; @@ -60,47 +58,9 @@ export function useEditSession(rt: WorkspaceRuntime) { error, request: () => run(() => serializeSessionChange(async () => { if (activeBackendProjectId() === doc.id) - installEditingState(doc.id, await requestEditing(doc.id)); + installEditingState(doc.id, await takeEditingOwnership(doc.id)); })), - decide: (requester: string, accept: boolean) => run(async () => { - if (rt.switchPending.current) return; - if (accept && (rt.editing || rt.activeAction || rt.editorSaving.current || - rt.historyRef.current.transaction || rt.historyReplayQueue.current)) { - throw new Error(rt.t("canvas.workspace.preview.closeEditor")); - } - rt.switchPending.current = true; - rt.invalidateScheduledAutosave(); - try { - if (accept) { - if (!await persistCurrentDocument(() => rt.historyRef.current.present, rt.persist)) - throw new Error(rt.saveError.current || rt.t("canvas.workspace.error.switchSaveFailed")); - await flushChatDraft(doc.id); - } - await serializeSessionChange(async () => { - if (activeBackendProjectId() === doc.id) - installEditingState(doc.id, await resolveEditing(doc.id, requester, accept)); - }); - } finally { - rt.switchPending.current = false; - } - }), }; } export type EditSession = ReturnType; - -export function EditHandoff({ rt, requester, session }: { - rt: WorkspaceRuntime; - requester: string; - session: EditSession; -}) { - const t = rt.t; - return ; -} diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 1003d2b46..e617abdc8 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1147,11 +1147,10 @@ export function WorkspaceView({ rt, editingState, editSession }: { {editSession.error && {editSession.error}} : diff --git a/src/canvas/workspace/edit-session.css b/src/canvas/workspace/edit-session.css index e2321047c..21d7e0acd 100644 --- a/src/canvas/workspace/edit-session.css +++ b/src/canvas/workspace/edit-session.css @@ -1,53 +1,14 @@ -.cw-edit-handoff { - position: fixed; - z-index: 1200; - top: 76px; - left: 50%; - transform: translateX(-50%); - display: flex; - align-items: center; - gap: 8px; - width: max-content; - max-width: calc(100% - 32px); - padding: 6px 8px; - border: 1px solid var(--cw-border, #ffffff20); - border-radius: 10px; - background: var(--cw-surface, #202022); - color: #ededee; - box-shadow: 0 4px 16px #0002; -} - -.cw-edit-handoff button, .cw-edit-request { cursor: pointer; color: inherit; -} - -.cw-edit-handoff button { - padding: 4px 8px; - background: transparent; - border: 1px solid var(--cw-border, #ffffff20); - border-radius: 6px; -} - -.cw-edit-request { font-size: 12px; white-space: nowrap; -} - -:root[data-theme="light"] .cw-edit-handoff { - --cw-surface: #fff; - --cw-border: #dfe2e7; - color: #24262a; -} - -.cw-preview-selection-controls { - display: contents; -} - -.cw-edit-request { background: transparent; border: 1px solid var(--cw-border); border-radius: 6px; padding: 4px 8px; } + +.cw-preview-selection-controls { + display: contents; +} diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index 3409a776c..7c2ddf326 100644 --- a/src/i18n/messages/en-US/canvasWorkspace.ts +++ b/src/i18n/messages/en-US/canvasWorkspace.ts @@ -1,12 +1,6 @@ export const canvasWorkspace = { "canvas.workspace.preview.mode": "Preview mode", "canvas.workspace.preview.request": "Edit in this window", - "canvas.workspace.preview.requested": "Edit access requested", - "canvas.workspace.preview.busy": "Another window is waiting for edit access", - "canvas.workspace.preview.handoff": "Hand off editing to the other window?", - "canvas.workspace.preview.accept": "Save and hand off", - "canvas.workspace.preview.decline": "Keep editing here", - "canvas.workspace.preview.closeEditor": "Save and close the active editor before handing off editing.", "canvas.workspace.help.toggleAssistant": "Toggle AI chat", "canvas.workspace.help.doubleShift": "Press Shift twice", diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index 555adbba4..8763288cf 100644 --- a/src/i18n/messages/zh-CN/canvasWorkspace.ts +++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts @@ -2,12 +2,6 @@ export const canvasWorkspace = { "canvas.workspace.preview.mode": "预览模式", "canvas.workspace.preview.request": "在此编辑", - "canvas.workspace.preview.requested": "已请求编辑权", - "canvas.workspace.preview.busy": "另一窗口正在等待交接", - "canvas.workspace.preview.handoff": "将编辑权交给另一个窗口?", - "canvas.workspace.preview.accept": "保存并交接", - "canvas.workspace.preview.decline": "继续在此编辑", - "canvas.workspace.preview.closeEditor": "请先保存并关闭当前编辑面板,再交接编辑权。", "canvas.workspace.help.toggleAssistant": "打开 / 收起 AI 对话", "canvas.workspace.help.doubleShift": "连按两次 Shift", diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 7cbe7bfc2..1ef98003c 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -441,7 +441,7 @@ "lanes": [ "gate" ], - "note": "Reload after a lost lease release reopens at once. A second window previews live changes, can request editing, and can take over without letting stale writes through." + "note": "Reload retains ownership. A second window previews live changes and takes over immediately. Old writes are rejected even after the original window takes over again." }, { "file": "project_title_enter.mjs", diff --git a/tests/browser/session_lease.mjs b/tests/browser/session_lease.mjs index a9915be67..07efdc342 100644 --- a/tests/browser/session_lease.mjs +++ b/tests/browser/session_lease.mjs @@ -1,5 +1,4 @@ -/** A tab reload after a lost lease release reopens its own project at once, - * while a second live window previews and can take over editing. */ +/** Persistent editing ownership and explicit takeover in two windows. */ import assert from "node:assert/strict"; import { launchBrowser } from "./engine.mjs"; @@ -37,33 +36,21 @@ try { await page.goto(url); await page.getByText(saved[locale], { exact: true }).waitFor({ state: "attached" }); - // A lost pagehide release (crash, killed process): the old page's DELETE - // never leaves it. Only this page's fetch is replaced; the reload is fresh. - const stale = await page.evaluate(() => { - const original = window.fetch; - window.fetch = (input, init) => - String(input).includes("/creation/sessions/") && init?.method === "DELETE" - ? Promise.reject(new TypeError("dropped")) - : original(input, init); - return sessionStorage.getItem("opendirector.session.v1"); - }); - assert.ok(stale, "the tab records its session"); - if (process.env.DEBUG) console.log("--- reload"); + const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")); const started = Date.now(); await page.reload(); - // The old page's lease was still live, so the reload itself released it. - assert.notEqual(await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")), stale); await page.getByText(saved[locale], { exact: true }).waitFor({ state: "attached" }); + assert.equal(await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")), session); const elapsed = Date.now() - started; assert.ok(elapsed < 15000, `reload reopened after ${elapsed} ms`); assert.deepEqual(openStatuses.filter((status) => status === 409), [], `${locale}: reload must not be refused`); const copy = locale === "zh-CN" ? { - open: "在新标签页打开", removed: "打开预览窗口", request: "在此编辑", requested: "已请求编辑权", - accept: "保存并交接", decline: "继续在此编辑", mode: "预览模式", + open: "在新标签页打开", removed: "打开预览窗口", request: "在此编辑", + mode: "预览模式", } : { - open: "Open in new tab", removed: "Open preview window", request: "Edit in this window", requested: "Edit access requested", - accept: "Save and hand off", decline: "Keep editing here", mode: "Preview mode", + open: "Open in new tab", removed: "Open preview window", request: "Edit in this window", + mode: "Preview mode", }; assert.equal(await page.getByText(copy.removed, { exact: true }).count(), 0); @@ -108,10 +95,6 @@ try { await preview.getByText("Renamed in A", { exact: true }).waitFor(); await preview.getByRole("button", { name: copy.request }).click(); - await page.getByRole("button", { name: copy.decline }).click(); - await preview.getByRole("button", { name: copy.request }).click(); - await preview.getByRole("button", { name: copy.requested }).waitFor(); - await page.getByRole("button", { name: copy.accept }).click(); const oldPreview = page.locator('[data-testid="canvas-workspace"][data-edit-mode="preview"]'); await oldPreview.getByText(copy.mode, { exact: true }).waitFor(); const newEditor = other.locator('[data-testid="canvas-workspace"][data-edit-mode="edit"]'); @@ -131,13 +114,18 @@ try { assert.ok(edit.ok && editBody.status === "applied", JSON.stringify(editBody)); await oldPreview.getByText("Synced from B", { exact: true }).waitFor(); - // Explicit release models a successful close without depending on browser - // teardown delivery. The remaining window can acquire with one click. - const released = await fetch(`${api}/api/creation/sessions/${newSession}`, { method: "DELETE", headers }); - assert.ok(released.ok); await oldPreview.getByRole("button", { name: copy.request }).click(); await page.locator('[data-testid="canvas-workspace"][data-edit-mode="edit"]').waitFor(); - console.log(`PASS ${locale}: reload, live preview, decline, handoff, stale write protection and reacquire`); + const reacquired = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")); + assert.notEqual(reacquired, oldSession); + const current = await call(`/api/creation/projects/${id}`); + const currentBasis = [{ objectType: "canvas_item", id: itemId, + revision: current.canvasItems.find((item) => item.id === itemId).revision }]; + const stale = await issue(oldSession, "canvas.update", { itemId, title: "Stale A" }, currentBasis); + assert.equal(stale.status, 409); + assert.equal((await stale.json()).code, "session_expired"); + await fetch(`${api}/api/creation/sessions/${reacquired}`, { method: "DELETE", headers }); + console.log(`PASS ${locale}: reload, live preview, direct takeover and stale write protection`); await context.close(); } } finally { diff --git a/tests/sessionLease.test.ts b/tests/sessionLease.test.ts index 52d9debec..880004f56 100644 --- a/tests/sessionLease.test.ts +++ b/tests/sessionLease.test.ts @@ -1,71 +1,5 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { releaseStaleSession } from "../src/backend/api.ts"; - -function locks(held: string[]) { - const requested: string[] = []; - return { - requested, - request: async (name: string) => { - requested.push(name); - }, - query: async () => ({ held: held.map((name) => ({ name })) }), - }; -} -const noPause = async () => {}; - -test("a reloaded tab releases its previous page's unreleased lease", async () => { - const released: string[] = []; - const browser = locks([]); - assert.equal( - await releaseStaleSession("old", "new", browser, async (id) => released.push(id), noPause), - true, - ); - assert.deepEqual(released, ["old"]); - assert.deepEqual(browser.requested, ["opendirector.session.new"]); -}); - -test("a duplicated tab never releases the lease of a live window", async () => { - const released: string[] = []; - const browser = locks(["opendirector.session.old"]); - assert.equal( - await releaseStaleSession("old", "new", browser, async (id) => released.push(id), noPause), - false, - ); - assert.deepEqual(released, []); -}); - -test("a first load or a browser without Web Locks releases nothing", async () => { - const released: string[] = []; - const release = async (id: string) => released.push(id); - assert.equal(await releaseStaleSession(null, "new", locks([]), release, noPause), false); - assert.equal(await releaseStaleSession("old", "new", undefined, release, noPause), false); - assert.deepEqual(released, []); -}); - -test("a failed release does not block the page", async () => { - assert.equal( - await releaseStaleSession("old", "new", locks([]), async () => { - throw new Error("offline"); - }, noPause), - true, - ); -}); - -test("a previous page that is still unloading is released once its lock is gone", async () => { - const released: string[] = []; - let checks = 0; - const browser = { - request: async () => {}, - query: async () => ({ held: ++checks < 3 ? [{ name: "opendirector.session.old" }] : [] }), - }; - assert.equal( - await releaseStaleSession("old", "new", browser, async (id) => released.push(id), noPause), - true, - ); - 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; diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py index ca873cce3..0500c892b 100644 --- a/tests/test_creation_api.py +++ b/tests/test_creation_api.py @@ -615,3 +615,30 @@ def test_publish_segment_plan_persists_a_read_only_card(api, tmp_path): _layout_command(client, path, project_id, 'canvas.update', dict(itemId=card['id'], locked=False), expected_versions=[dict(objectType='canvas_item', id=card['id'], revision=card['revision'])], status='rejected') + + +def test_canvas_owner_survives_expiry_and_server_restart_until_takeover(api, monkeypatch): + from opendirector.infrastructure import local_projects + + client, local = api + path, command, _ = create(client) + owner = client.headers['x-opendirector-session'] + preview = str(uuid4()) + allow_preview = {'X-OpenDirector-Allow-Preview': 'true'} + opened = client.post(path + '/open-canvas', headers=allow_preview) + assert opened.json()['editing'] == {'mode': 'edit'} + + clock = local_projects.time.time + future = clock() + LocalProjects.LEASE_SECONDS + 1 + monkeypatch.setattr(local_projects.time, 'time', lambda: future) + restarted = LocalProjects(local.repository) + with TestClient(create_app(restarted), headers={'X-OpenDirector-Request': '1'}) as other: + viewer = {'X-OpenDirector-Session': preview} + editor = {'X-OpenDirector-Session': owner} + assert other.post(path + '/open-canvas', headers={**allow_preview, **viewer}).json()['editing'] == {'mode': 'preview'} + assert other.get(path + '/edit-session', headers=editor).json() == {'mode': 'edit'} + assert other.post(path + '/edit-session', headers=viewer).json() == {'mode': 'edit'} + assert other.get(path + '/edit-session', headers=editor).json() == {'mode': 'preview'} + assert other.post(path + '/commands', json=rename(command), headers=editor).status_code == 409 + assert other.delete('/api/creation/sessions/' + preview).is_success + assert other.post(path + '/open-canvas', headers={**allow_preview, **editor}).json()['editing'] == {'mode': 'edit'} From 152942c279e750dfe423b8c8038597171bb0e7f5 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Thu, 26 Nov 2026 20:08:06 +0800 Subject: [PATCH 2/2] [test] canvas: verify editing ownership survives reload Signed-off-by: Weiming Liao --- tests/backendWorkspace.test.ts | 56 ++------------------ tests/browser/capability_discovery.mjs | 2 +- tests/browser/voice_library.mjs | 8 ++- tests/sessionClose.test.ts | 72 +++++--------------------- 4 files changed, 22 insertions(+), 116 deletions(-) diff --git a/tests/backendWorkspace.test.ts b/tests/backendWorkspace.test.ts index b9b729b51..05d7e0396 100644 --- a/tests/backendWorkspace.test.ts +++ b/tests/backendWorkspace.test.ts @@ -602,7 +602,7 @@ test("a stale in-memory revision is reread and the trash retried once", async (t assert.equal(f.projects.size, 0); }); -test("a canvas read that outlives the lease renews it before adopting", async (t) => { +test("a slow canvas read keeps editing ownership without renewal", async (t) => { const f = fixture(t); await initializeWorkspace(); const id = crypto.randomUUID(); @@ -613,7 +613,7 @@ test("a canvas read that outlives the lease renews it before adopting", async (t let now = 1_000_000; Date.now = () => now; CreationProjection.prototype.open = async function (this: CreationProjection) { - // Media hydration streams longer than the server's 60 s lease. + // Media hydration runs past the old lease timeout. now += 61_000; return stub.call(this); }; @@ -624,13 +624,12 @@ test("a canvas read that outlives the lease renews it before adopting", async (t const renewals = f.calls.filter( (call) => call.method === "PUT" && call.path.includes("/sessions/"), ); - assert.equal(renewals.length, 1); - assert.equal(renewals[0]!.body.projectId, id); + assert.equal(renewals.length, 0); assert.equal( f.calls.some((call) => call.method === "DELETE"), false, ); - // The renewed lease is the adopted one, so saving right after works. + // Saving after the slow read still uses the same ownership. await saveWorkspaceDocument({ ...opened, title: "Slow saved" }); assert.equal(f.documents.get(id)?.title, "Slow saved"); } finally { @@ -639,53 +638,6 @@ test("a canvas read that outlives the lease renews it before adopting", async (t } }); -test("a long read that lost its lease fails instead of adopting it", async (t) => { - const f = fixture(t); - const first = await initializeWorkspace(); - const id = crypto.randomUUID(); - f.projects.set(id, { id, name: "Stolen", path: "/projects/Stolen" }); - f.documents.set(id, { ...createDocument("Stolen"), id }); - const stub = CreationProjection.prototype.open; - const realNow = Date.now; - let now = 2_000_000; - Date.now = () => now; - CreationProjection.prototype.open = async function (this: CreationProjection) { - now += 61_000; - return stub.call(this); - }; - const plain = globalThis.fetch; - globalThis.fetch = async (url, options = {}) => { - if ( - String(url).includes("/sessions/") && - (options.method ?? "GET") === "PUT" - ) - return Response.json( - { detail: "工程正在其他窗口中打开", code: "project_open_elsewhere" }, - { status: 409 }, - ); - return plain(url, options); - }; - try { - await assert.rejects(openWorkspaceProject(f.projects.get(id)!)); - // A failed adoption must not point heartbeats at the stolen project. - assert.equal(activeBackendProjectId(), first.id); - // The session moved with the read and the renewal was rejected, so this - // window's lease is put back on the project the canvas is still showing. - assert.equal( - f.calls.filter( - (call) => - call.method === "POST" && - call.path === `/api/creation/projects/${first.id}/open`, - ).length, - 1, - ); - } finally { - globalThis.fetch = plain; - Date.now = realNow; - CreationProjection.prototype.open = stub; - } -}); - test("a read that fails after the lease moves restores the previous project", async (t) => { const f = fixture(t); const first = await initializeWorkspace(); diff --git a/tests/browser/capability_discovery.mjs b/tests/browser/capability_discovery.mjs index 6db4d8f52..3f153e4c6 100644 --- a/tests/browser/capability_discovery.mjs +++ b/tests/browser/capability_discovery.mjs @@ -196,7 +196,7 @@ page.on("requestfailed", (request) => { }); async function reloadAfterRenewal() { // Advancing the capability clock can also start a session heartbeat. Finish - // that request before pagehide releases the session during this reload. + // that request before reloading. await until(() => sessionRenewals.size === 0); assert.deepEqual( renewalFailures, diff --git a/tests/browser/voice_library.mjs b/tests/browser/voice_library.mjs index 103c440d3..783dd4348 100644 --- a/tests/browser/voice_library.mjs +++ b/tests/browser/voice_library.mjs @@ -41,11 +41,7 @@ async function until(check) { } async function reopenAudio(page, assetPath, savedLabel) { await waitForSaved(page, savedLabel); - // Acknowledge this page's lease release before reopening its persisted audio. - const released = page.waitForResponse(response => response.request().method() === "DELETE" && - new URL(response.url()).pathname.startsWith("/api/creation/sessions/")); - await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pagehide"))); - assert.ok((await released).ok()); + const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")); const started = Date.now(); const statuses = []; let receive, timer; @@ -62,6 +58,8 @@ async function reopenAudio(page, assetPath, savedLabel) { // document has not started the project's media read yet. await page.reload({ waitUntil: "domcontentloaded", timeout: reopenTimeout }); await waitForSaved(page, savedLabel); + await page.locator('[data-testid="canvas-workspace"][data-edit-mode="edit"]').waitFor(); + assert.equal(await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")), session); console.log(JSON.stringify({ event: "voice-reopen-ready", assetPath, elapsedMs: Date.now() - started, })); diff --git a/tests/sessionClose.test.ts b/tests/sessionClose.test.ts index 1cebb0647..c8a43993e 100644 --- a/tests/sessionClose.test.ts +++ b/tests/sessionClose.test.ts @@ -13,7 +13,6 @@ import { requireActiveBackendProject, } from "../src/backend/projects.ts"; -const listeners = new Map void>(); let heartbeat: () => void; const draft = (text: string): Conversation => ({ messages: [], @@ -34,8 +33,6 @@ function fixture(t: TestContext, unified = true) { heartbeat = callback; return 1; }, - addEventListener: (name: string, callback: () => void) => - listeners.set(name, callback), }, }); const prefix = unified ? "/api/creation" : "/api"; @@ -43,7 +40,6 @@ function fixture(t: TestContext, unified = true) { path: string; method: string; value: Record; - keepalive?: boolean; }[] = []; let lease: string | null = null; let saved: Conversation | undefined; @@ -54,7 +50,7 @@ function fixture(t: TestContext, unified = true) { const path = String(url), method = options.method ?? "GET"; const value = options.body ? JSON.parse(String(options.body)) : {}; - calls.push({ path, method, value, keepalive: options.keepalive }); + calls.push({ path, method, value }); const response = await intercept?.(path, options); if (response) return response; if (path.endsWith("/open")) { @@ -115,24 +111,6 @@ test("unconnected assistant drafts never write legacy project data", async (t) = assert.ok(f.calls.every((call) => call.path.startsWith("/api/creation/"))); }); -test("page exit releases the unified session with keepalive and tolerates a repeated exit", async (t) => { - const f = fixture(t), - id = crypto.randomUUID(); - await openBackendProject(id, "A"); - rememberChat(id, draft("exit draft")); - listeners.get("pagehide")!(); - await new Promise((resolve) => setImmediate(resolve)); - rememberChat(id, draft("late stale draft")); - listeners.get("pagehide")!(); - await new Promise((resolve) => setImmediate(resolve)); - const close = f.calls.filter((call) => call.method === "DELETE"); - assert.equal(close.length, 2); - assert.ok(close.every((call) => call.method === "DELETE" && call.keepalive)); - assert.equal(f.saved(), undefined); - assert.equal(currentChat(id)?.draft, "late stale draft"); - assert.equal(f.calls.filter((call) => call.path.endsWith("/open")).length, 1); -}); - test("release errors prevent release or switching and preserve the active draft", async (t) => { const f = fixture(t), id = crypto.randomUUID(), @@ -182,37 +160,17 @@ test("a failed target open reacquires the old project without writing chat draft assert.equal(f.calls.at(-1)!.path, `${f.prefix}/projects/${id}/open`); }); -test("pending heartbeat completes before close and cannot reacquire the released lease", async (t) => { +test("browser editing ownership does not need a heartbeat", async (t) => { const f = fixture(t), id = crypto.randomUUID(); await openBackendProject(id, "A"); - rememberChat(id, draft("closed")); - let release!: () => void, entered!: () => void; - const started = new Promise((resolve) => { - entered = resolve; - }); - const blocked = new Promise((resolve) => { - release = resolve; - }); - f.intercept(async (path, options) => { - if (path.includes("/sessions/") && options.method === "PUT") { - entered(); - await blocked; - } - return undefined; - }); heartbeat(); - await started; - const closing = releaseBackendProject(); - await Promise.resolve(); - assert.equal( - f.calls.some((call) => call.method === "DELETE"), - false, - ); - release(); - await closing; + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(f.lease(), id); + assert.equal(f.calls.some((call) => call.method === "PUT"), false); + await releaseBackendProject(); heartbeat(); - await Promise.resolve(); + await new Promise((resolve) => setImmediate(resolve)); assert.equal(f.lease(), null); assert.equal(f.calls.at(-1)!.method, "DELETE"); }); @@ -229,20 +187,18 @@ test("expired close neither reopens the project nor claims to save the stale dra assert.equal(f.calls.filter((call) => call.path.endsWith("/open")).length, 1); }); -test("unified projects retain their own session endpoint for switches and page exit", async (t) => { +test("switching projects releases only the project being left", async (t) => { const f = fixture(t, true), id = crypto.randomUUID(), next = crypto.randomUUID(); await openBackendProject(id, "A"); await openBackendProject(next, "B"); - listeners.get("pagehide")!(); - await new Promise((resolve) => setImmediate(resolve)); const closes = f.calls.filter((call) => call.method === "DELETE"); - assert.equal(closes.length, 2); + assert.equal(closes.length, 1); + assert.equal(f.lease(), next); assert.ok( closes.every((call) => call.path.startsWith("/api/creation/sessions/")), ); - assert.equal(closes.at(-1)!.keepalive, true); assert.equal( f.calls.some((call) => call.path.endsWith("/close")), false, @@ -287,7 +243,7 @@ test("a lapsed-lease recovery waits for a pending switch and never reacquires th ); }); -test("writes rejected together for a lapsed lease share one renewal", async (t) => { +test("rejected writes cannot renew a lost browser editing session", async (t) => { const f = fixture(t), id = crypto.randomUUID(); await openBackendProject(id, "A"); @@ -302,7 +258,7 @@ test("writes rejected together for a lapsed lease share one renewal", async (t) 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); + await Promise.all(saves.map((save) => assert.rejects(save, { code: "session_expired" }))); + assert.equal(f.calls.some((call) => call.method === "PUT"), false); + assert.equal(f.lease(), null); });