From 092157eb2306668fa98858f3eac241582ecfaaf9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:57:45 +0100 Subject: [PATCH 1/2] fix(ui-react): keep uncertain-save and pending-bind draft states in the device-local snapshot (#3446) The stored draft record now carries `uncertain` (only when true) and a pending `bind`, and `parseDraft` reads them back, ignoring a malformed bind without rejecting the draft. An emptied, host-null draft stays in the snapshot while it is uncertain, and `restoreLocal` brings both states back, so the draft client's existing uncertain-save and bind paths run after a reload. A host refresh no longer overwrites an emptied uncertain draft before that path settles it. Records written before this change restore as before (`v: 1`). Tombstones, device branches and cross-tab adoption do not inherit the new fields, and a settled uncertain record is deleted rather than kept as a tombstone. Citations into local-work.ts move with the shifted lines. Refs #1214 Co-authored-by: Claude Opus 5.5 --- .../draft-reconciliation-across-reload.md | 4 + docs/plans/chat-history-deletion.md | 2 +- docs/process/test-waits.md | 10 +- packages/ui-react/src/lib/local-work.ts | 29 ++-- packages/ui-react/src/stores/draft-state.ts | 23 ++- packages/ui-react/tests/draft-client.test.ts | 78 +++++++++++ packages/ui-react/tests/draft-store.test.ts | 45 ++++++ .../tests/fixtures/local-work-client.ts | 15 ++ .../ui-react/tests/local-work-runtime.test.ts | 132 ++++++++++++++++++ 9 files changed, 319 insertions(+), 19 deletions(-) create mode 100644 .changeset/draft-reconciliation-across-reload.md diff --git a/.changeset/draft-reconciliation-across-reload.md b/.changeset/draft-reconciliation-across-reload.md new file mode 100644 index 0000000000..69f51f2793 --- /dev/null +++ b/.changeset/draft-reconciliation-across-reload.md @@ -0,0 +1,4 @@ +--- +"@schlessera/brain-ui-react": patch +--- +Fix two draft states being lost when the page reloads. If a draft's first save got no answer and the reader then emptied the draft, the host refresh after a reload brought the cleared text back. Now the emptied draft is kept on this device, and after the reload the client deletes the copy the host may hold. If a new chat's first message was accepted while a newer save was still out, the bind to its session was dropped, so the host kept an unbound draft. Now the bind survives the reload and completes. Records written by older versions restore as before. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 78ff9c5144..97c0d117c5 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -228,7 +228,7 @@ and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:1 `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave belongs to `createDraftClient` (`createDraftClient`, `packages/ui-react/src/lib/draft-client.ts:45-57`); browser reloadable work belongs -to `createLocalWork` (`createLocalWork`, `packages/ui-react/src/lib/local-work.ts:227-245`). +to `createLocalWork` (`createLocalWork`, `packages/ui-react/src/lib/local-work.ts:236-254`). The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`; gating its resume case alone would leave HTTP, background readers and provider startup open. diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index f2d6159c34..0a4037af1c 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -224,13 +224,13 @@ per-site `sites` counters distinguish attribution from helper-definition counts. change, upload abort/resume or host draft reconciliation can schedule a separate device-context write. That write reads native browser state and enters browser locks/IndexedDB before adopting retained draft records back into the mounted -stores (`context`, `packages/ui-react/src/lib/local-work.ts:296-310`; -`flush`, `packages/ui-react/src/lib/local-work.ts:313-324`; -`adoptDeviceRecord`, `packages/ui-react/src/lib/local-work.ts:502-508`). The real +stores (`context`, `packages/ui-react/src/lib/local-work.ts:305-319`; +`flush`, `packages/ui-react/src/lib/local-work.ts:322-333`; +`adoptDeviceRecord`, `packages/ui-react/src/lib/local-work.ts:513-519`). The real scroll listener schedules that work (`handleScroll`, `packages/ui-react/src/components/chat/chat-page.tsx:318-328`), as do draft, track, selection and focus subscriptions (`stores.drafts.subscribe`, -`packages/ui-react/src/lib/local-work.ts:632-643`). A protocol receipt or the +`packages/ui-react/src/lib/local-work.ts:643-654`). A protocol receipt or the first moved wheel frame can precede this native write and its React reaction; late adoption can blur the field, change scroll/selection, replace an answer or restore a consumed pill. A disconnected upload can similarly be misclassified @@ -242,7 +242,7 @@ acknowledgements remain separate positive conditions. **Duration and margin.** In the quiet scenes, `changed` registers the real 250 ms device debounce (`LOCAL_WRITE_DELAY_MS`, `packages/ui-react/src/lib/local-work.ts:88-90`; `changed`, -`packages/ui-react/src/lib/local-work.ts:518-531`). The five non-IME boundaries +`packages/ui-react/src/lib/local-work.ts:529-542`). The five non-IME boundaries retain 500 ms: one 250 ms scheduled opportunity plus 250 ms (100%) headroom for native dispatch, storage/lock continuations and React work, followed by the original two native animation frames. This is a bounded opportunity to diff --git a/packages/ui-react/src/lib/local-work.ts b/packages/ui-react/src/lib/local-work.ts index c42cfb9a16..e179c6bdd2 100644 --- a/packages/ui-react/src/lib/local-work.ts +++ b/packages/ui-react/src/lib/local-work.ts @@ -118,7 +118,7 @@ export function findByFocusId(id: string): HTMLElement | null { } type StoredAttachment = { data: string; mediaType: string; bytes: number; name: string }; -type StoredDraft = Omit & { v: 1; deviceRevision?: number; attachments: StoredAttachment[] }; +export type StoredDraft = Omit & { v: 1; deviceRevision?: number; attachments: StoredAttachment[] }; const draftVersion = (value: unknown): number => (value as StoredDraft | undefined)?.deviceRevision ?? 0; function serializedDraft(value: unknown): string | undefined { if (value === undefined) return undefined; @@ -132,8 +132,8 @@ const isStr = (v: unknown): v is string => typeof v === "string"; const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); const isStrOrNull = (v: unknown): v is string | null => v === null || isStr(v); -/** A kept draft, if it is well formed: what comes out of storage is not trusted. */ -function parseDraft(raw: unknown): LocalDraft | null { +/** @internal A kept draft, if it is well formed: what comes out of storage is not trusted. */ +export function parseDraft(raw: unknown): LocalDraft | null { const r = raw as Partial | null; if (!r || r.v !== 1 || !isStr(r.draftId) || !isStrOrNull(r.sessionId ?? null) || !isStr(r.text) || !isNum(r.editedAt) || !Array.isArray(r.attachments)) return null; const attachments: PendingAttachment[] = []; @@ -144,7 +144,12 @@ function parseDraft(raw: unknown): LocalDraft | null { const h = r.host; const host = h && isNum(h.revision) && isStrOrNull(h.sessionId ?? null) && isNum(h.updatedAt) && typeof h.clean === "boolean" ? { revision: h.revision, sessionId: h.sessionId ?? null, updatedAt: h.updatedAt, clean: h.clean } : null; - return { draftId: r.draftId, sessionId: r.sessionId ?? null, text: r.text, attachments, editedAt: r.editedAt, host, deviceOnly: r.deviceOnly === true, ...(r.deviceConflict && isStr(r.deviceConflict.otherId) && isStrOrNull(r.deviceConflict.sessionId) ? { deviceConflict: r.deviceConflict } : {}) }; + // A record written before #1214 has neither: it restores as it always did. + // A malformed bind is dropped on its own, never the whole draft. + const b = r.bind; + const bind = b && isStr(b.sessionId) && isStr(b.requestId) ? { sessionId: b.sessionId, requestId: b.requestId } : null; + return { draftId: r.draftId, sessionId: r.sessionId ?? null, text: r.text, attachments, editedAt: r.editedAt, host, deviceOnly: r.deviceOnly === true, ...(r.deviceConflict && isStr(r.deviceConflict.otherId) && isStrOrNull(r.deviceConflict.sessionId) ? { deviceConflict: r.deviceConflict } : {}), + ...(r.uncertain === true ? { uncertain: true } : {}), ...(bind ? { bind } : {}) }; } function parseContext(raw: unknown): WorkContext | null { @@ -166,7 +171,8 @@ function parseContext(raw: unknown): WorkContext | null { }; } -function storeDraft(d: ComposerDraft): StoredDraft { +/** @internal The record a draft is kept on this device as. */ +export function storeDraft(d: ComposerDraft): StoredDraft { return { v: 1, draftId: d.draftId, @@ -177,6 +183,9 @@ function storeDraft(d: ComposerDraft): StoredDraft { deviceOnly: d.deviceOnly === true, ...(d.deviceConflict ? { deviceConflict: d.deviceConflict } : {}), host: d.host ? { revision: d.host.revision, sessionId: d.host.sessionId, updatedAt: d.host.updatedAt, clean: d.host.edit === d.edit } : null, + // Reconciliation the draft client still owes the host (#1214). + ...(d.uncertain ? { uncertain: true } : {}), + ...(d.bind ? { bind: { sessionId: d.bind.sessionId, requestId: d.bind.requestId } } : {}), }; } @@ -344,7 +353,8 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork { const nextCommitted = new Map(); for (const d of Object.values(drafts)) { // An emptied draft the host still holds is kept too: its deletion is still owed. - if (!hasContent(d) && d.host === null && !d.deviceConflict) continue; + // So is one whose first save got no answer: the host may hold it (#1214). + if (!hasContent(d) && d.host === null && !d.deviceConflict && !d.uncertain) continue; next.set(d.draftId, d); const value = storeDraft(d); const serialized = JSON.stringify(value); @@ -358,7 +368,8 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork { for (const id of written.keys()) if (!next.has(id)) { const baseline = committed.get(id); const saved = baseline ? parseDraft(JSON.parse(baseline)) : null; - if (saved && !saved.text && !saved.attachments.length && !saved.host) { next.set(id, null); nextCommitted.set(id, baseline!); } + // An empty tombstone stays; an emptied uncertain record is not one and is deleted once settled. + if (saved && !saved.text && !saved.attachments.length && !saved.host && !saved.uncertain) { next.set(id, null); nextCommitted.set(id, baseline!); } else changes.push({ delete: draftKey(id) }); } const ctx = context(); @@ -421,7 +432,7 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork { const branch = mintDraftId(); const source = incoming ?? { v: 1 as const, draftId: id, sessionId: drafts[id]?.sessionId ?? parseDraft(saved)?.sessionId ?? null, text: "", attachments: [], editedAt: Date.now(), host: null }; const viewSession = source.sessionId ?? predecessor?.saved.sessionId ?? null; - const value: StoredDraft = { ...source, draftId: branch, sessionId: null, host: null, deviceRevision: 1, deviceConflict: { otherId: other?.draftId ?? id, sessionId: viewSession } }; + const value: StoredDraft = { ...source, draftId: branch, sessionId: null, host: null, uncertain: undefined, bind: undefined, deviceRevision: 1, deviceConflict: { otherId: other?.draftId ?? id, sessionId: viewSession } }; planned.push({ put: draftKey(branch), value }); result.push({ source: id, branch, sessionId: viewSession, other: other ? parseDraft(other) : null, kept }); next.delete(id); nextCommitted.delete(id); nextVersions.delete(id); @@ -441,7 +452,7 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork { // Keep an empty revision tombstone. A stale write after deletion // must branch rather than reuse the deleted identity's revision. if (saved) { - const value: StoredDraft = { ...saved, text: "", attachments: [], host: null, deviceConflict: undefined, deviceRevision: draftVersion(saved) + 1 }; + const value: StoredDraft = { ...saved, text: "", attachments: [], host: null, deviceConflict: undefined, uncertain: undefined, bind: undefined, deviceRevision: draftVersion(saved) + 1 }; planned.push({ put: key, value }); actual.set(key, value); next.set(id, null); nextCommitted.set(id, serializedDraft(value)!); nextVersions.set(id, value.deviceRevision!); } diff --git a/packages/ui-react/src/stores/draft-state.ts b/packages/ui-react/src/stores/draft-state.ts index 31940587db..223de2047a 100644 --- a/packages/ui-react/src/stores/draft-state.ts +++ b/packages/ui-react/src/stores/draft-state.ts @@ -127,6 +127,10 @@ export interface LocalDraft { /** @internal A device-local keep-both branch; its other version stays reachable. */ deviceConflict?: { otherId: string; sessionId: string | null }; host: { revision: number; sessionId: string | null; updatedAt: number; clean: boolean } | null; + /** A first save got no answer: the host may hold it, and a reconciliation is owed (#1214). */ + uncertain?: boolean; + /** An accepted first message's session, still to be bound on the host (#1214). */ + bind?: { sessionId: string; requestId: string } | null; } export interface DraftStoreState { @@ -497,8 +501,9 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s for (const k of kept) { const state = get(); if (state.drafts[k.draftId] || successors.has(k.draftId) || retired.has(k.draftId)) continue; - // An emptied draft comes back only while its deletion is owed to the host. - if (k.text.length === 0 && k.attachments.length === 0 && !(k.host && !k.host.clean) && !k.deviceConflict) continue; + // An emptied draft comes back only while its deletion is owed to the + // host, or while a lost first save may have left a copy there (#1214). + if (k.text.length === 0 && k.attachments.length === 0 && !(k.host && !k.host.clean) && !k.deviceConflict && !(k.uncertain && !k.host)) continue; // A session whose draft this page already holds keeps that one. if (k.sessionId !== null && Object.values(state.drafts).some((d) => d.sessionId === k.sessionId && (hasContent(d) || d.host))) continue; // An id handed to the session before this arrived goes to it, as in @@ -515,6 +520,9 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s edit, // Its images upload again before the next save: the ids they had are not kept. host: k.host ? { revision: k.host.revision, edit: k.host.clean ? edit : edit - 1, sessionId: k.host.sessionId, attachmentIds: [], updatedAt: k.host.updatedAt } : null, + // The draft client's uncertain-save and bind paths pick these up again (#1214). + uncertain: k.uncertain === true && k.host === null, + bind: k.bind ?? null, }); } }, @@ -551,7 +559,8 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s // The caller keeps its prior expectation until those edits save. if (other && (!preserveOther || !drafts[other.draftId])) { const edit = 1; - drafts[other.draftId] = { ...blank(other.draftId, other.sessionId, other.editedAt), ...other, edit, + const { uncertain: _uncertain, bind: _bind, ...content } = other; + drafts[other.draftId] = { ...blank(other.draftId, other.sessionId, other.editedAt), ...content, edit, host: other.host ? { ...other.host, edit: other.host.clean ? edit : -1, attachmentIds: [] } : null }; } return { drafts, fresh: s.fresh === sourceId || s.fresh === liveId ? branchId : s.fresh }; @@ -561,7 +570,9 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s const current = get().drafts[kept.draftId]; if (current) release(current.attachments, []); const edit = 1; - const d = { ...blank(kept.draftId, kept.sessionId, kept.editedAt), ...kept, edit, deviceEpoch: (current?.deviceEpoch ?? 0) + 1, + // Another tab's pending reconciliation stays that tab's to finish. + const { uncertain: _uncertain, bind: _bind, ...content } = kept; + const d = { ...blank(kept.draftId, kept.sessionId, kept.editedAt), ...content, edit, deviceEpoch: (current?.deviceEpoch ?? 0) + 1, host: kept.host ? { ...kept.host, edit: kept.host.clean ? edit : -1, attachmentIds: [] } : null }; set(s => ({ drafts: { ...s.drafts, [kept.draftId]: d } })); }, @@ -814,6 +825,10 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s return; } if (local.host && local.host.revision >= draft.revision) return; + // Emptied after a first save that got no answer: the draft client + // settles that copy itself (deleting it, or a conflict on a newer + // revision), so a host refresh never brings the cleared text back. + if (!local.host && local.uncertain && !hasContent(local)) return; if (local.conflict?.sameId && local.conflict.other.revision >= draft.revision) return; // The host holds exactly what is here (a save whose answer was lost): // that is an acknowledgement, not another device's version. diff --git a/packages/ui-react/tests/draft-client.test.ts b/packages/ui-react/tests/draft-client.test.ts index 790a4a275c..70550b92a0 100644 --- a/packages/ui-react/tests/draft-client.test.ts +++ b/packages/ui-react/tests/draft-client.test.ts @@ -3,6 +3,8 @@ import type { Draft } from "@schlessera/brain-ui-sdk/protocol"; import { createBrainUiRoot, type BrainUiRoot } from "../src/root.ts"; import { tracksFor, trackKey, stagedTrackViews } from "../src/lib/draft-tracks.ts"; import type { PendingAttachment } from "../src/lib/image-attachments.ts"; +import { parseDraft, storeDraft } from "../src/lib/local-work.ts"; +import type { LocalDraft } from "../src/stores/draft-state.ts"; // The draft client (#951, D52 §5) against a small in-memory host that keeps // #979's revision rules: If-Match, conflicts carrying the host's version, @@ -101,6 +103,7 @@ function fakeHost() { let down = false; let full = false; let losePut = false; + let bindDown = false; let deleteHold: ReturnType | null = null; let deleteFailure = 0; let maxText = Infinity; @@ -166,6 +169,14 @@ function fakeHost() { images.set(attachmentId, { draftId: id, mime: headers.get("content-type")!, bytes, name: null }); return json({ attachmentId }); } + if (sub === "/bind") { + if (bindDown) throw new TypeError("fetch failed"); + const body = JSON.parse(String(init.body)) as { sessionId: string; requestId: string }; + if (!row || row.deleted) return json({ error: "DRAFT_NOT_FOUND", message: "" }, 404); + const revision = row.revision + 1; + rows.set(id, { ...row, sessionId: body.sessionId, revision, updatedAt: 9_000 + revision }); + return json({ revision }); + } if (method === "GET") { // The answer is what the host held when the read arrived, however late it lands. const now = rows.get(id); @@ -208,6 +219,8 @@ function fakeHost() { setDown: (value: boolean) => { down = value; }, setFull: (value: boolean) => { full = value; }, loseNextPut: () => { losePut = true; }, + /** Every bind gets no answer while set. */ + setBindDown: (value: boolean) => { bindDown = value; }, failNextDelete: (status: number) => { deleteFailure = status; }, holdDeletes: () => { const gate = deferred(); deleteHold = gate; gates.add(gate); return async () => { deleteHold = null; gates.delete(gate); gate.resolve(); await clock.advance(0); }; }, setMaxText: (value: number) => { maxText = value; }, @@ -621,6 +634,71 @@ describe("uncertain answers", () => { }); }); +/** + * A reload (#1214): this page's drafts go through the record the device keeps + * them as, and a fresh root on the same host restores them before its first + * host list, as `refresh` waits for `localWork.restoring()`. + */ +function reload(host: ReturnType, before: ReturnType) { + const kept = Object.values(before.drafts().drafts) + .map((d) => parseDraft(JSON.parse(JSON.stringify(storeDraft(d))))) + .filter((d): d is LocalDraft => d !== null); + roots.splice(roots.indexOf(before.ui), 1); + before.ui.dispose(); + const after = boot(host); + after.drafts().restoreLocal(kept); + return after; +} + +describe("reconciliation owed across a reload (#1214)", () => { + test("an emptied draft whose first save got no answer is reconciled after a reload, not brought back", async () => { + const host = fakeHost(); + const before = boot(host); + const id = before.drafts().idFor(ITHACA); + host.loseNextPut(); + before.drafts().edit(id, ITHACA, { text: "Ask Aeolus" }); + await until(() => before.drafts().drafts[id]?.uncertain === true); + expect(host.rows.get(id)?.revision, "the host stored the save whose answer was lost").toBe(1); + // Offline now: the reconciliation cannot run before the reload. + host.setDown(true); + before.drafts().edit(id, ITHACA, { text: "" }); + await clock.advance(SAVE_PAUSE + 1); + expect(host.rows.get(id)?.deleted, "nothing reached the host before the reload").toBeUndefined(); + host.setDown(false); + const after = reload(host, before); + await clock.advance(SAVE_PAUSE + FIRST_RETRY); + expect(Object.values(after.drafts().drafts).map((d) => d.text), "the cleared text is not restored from the host").not.toContain("Ask Aeolus"); + expect(host.rows.get(id)?.deleted, "the host's copy of the lost save is deleted").toBe(true); + expect(after.drafts().drafts[id]).toBeUndefined(); + }); + + test("a pending bind survives a reload and completes", async () => { + const host = fakeHost(); + const before = boot(host); + const first = before.drafts().fresh; + before.drafts().edit(first, null, { text: "Which harbour?" }); + await until(() => before.drafts().drafts[first]?.host?.revision === 1); + before.drafts().beginSend({ requestId: "req-harbour", draftId: first, sessionId: null, text: "Which harbour?", attachments: [], + message: { type: "chat_message", requestId: "req-harbour", text: "Which harbour?", source: "typed" } }, "Which harbour?"); + const release = host.hold(); + before.drafts().edit(first, null, { text: "And the harbour fees" }); + await until(() => host.calls.includes(`PUT /drafts/${first}`) && before.drafts().drafts[first]?.savingSince !== null, 5_000, true); + // Accepted while the newer unbound save is out: its answer decides, and the bind is owed. + before.drafts().accepted("req-harbour", ITHACA); + expect(before.drafts().drafts[first]?.bind).toEqual({ sessionId: ITHACA, requestId: "req-harbour" }); + host.setBindDown(true); + await release(); + await until(() => host.calls.includes(`POST /drafts/${first}/bind`)); + expect(host.rows.get(first), "the newer save is on the host, still unbound").toMatchObject({ revision: 2, sessionId: null }); + expect(before.drafts().drafts[first]?.bind, "the bind is still owed at the reload").toEqual({ sessionId: ITHACA, requestId: "req-harbour" }); + host.setBindDown(false); + const after = reload(host, before); + await clock.advance(SAVE_PAUSE + FIRST_RETRY); + expect(host.rows.get(first)?.sessionId, "the pending bind completes after the reload").toBe(ITHACA); + expect(after.drafts().drafts[first]).toMatchObject({ sessionId: ITHACA, bind: null, text: "And the harbour fees", host: { revision: 3, sessionId: ITHACA } }); + }); +}); + describe("orphans, continued", () => { test("a read begun before the reader's choice deleted the other draft does not raise the conflict again", async () => { const host = fakeHost(); diff --git a/packages/ui-react/tests/draft-store.test.ts b/packages/ui-react/tests/draft-store.test.ts index 89b060858f..847bb0ae2e 100644 --- a/packages/ui-react/tests/draft-store.test.ts +++ b/packages/ui-react/tests/draft-store.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import type { Draft } from "@schlessera/brain-ui-sdk/protocol"; import { createDraftStore, holdsUnsaved, type DraftSend, type LocalDraft } from "../src/stores/draft-state.ts"; import { draftSaveView, draftTitle, unboundDrafts } from "../src/lib/drafts.ts"; +import { parseDraft } from "../src/lib/local-work.ts"; import type { PendingAttachment } from "../src/lib/image-attachments.ts"; // Per-session drafts (#951, D52 §5): the root's draft store on its own, @@ -588,6 +589,50 @@ describe("drafts kept on this device (#1014)", () => { expect(state().drafts.gone).toBeUndefined(); }); + test("a record written before #1214 restores exactly as before: not uncertain, nothing to bind", () => { + const { state } = store(); + state().setSupport(true); + const legacy = parseDraft({ v: 1, draftId: "legacy", sessionId: ITHACA, text: "Ask Aeolus", attachments: [], editedAt: 900, deviceOnly: false, + host: { revision: 2, sessionId: null, updatedAt: 1, clean: true } }); + expect(legacy, "a record without the new fields is well formed").not.toBeNull(); + expect(legacy).not.toHaveProperty("uncertain"); + expect(legacy).not.toHaveProperty("bind"); + // Emptied with no host copy: dropped, as it always was. + const emptied = parseDraft({ v: 1, draftId: "legacy-empty", sessionId: RAFT, text: "", attachments: [], editedAt: 900, host: null }); + state().restoreLocal([legacy!, emptied!]); + expect(state().drafts.legacy).toMatchObject({ text: "Ask Aeolus", uncertain: false, bind: null, host: { revision: 2 } }); + expect(state().drafts["legacy-empty"]).toBeUndefined(); + }); + + test("a malformed bind is ignored, never the whole draft; the owed states restore", () => { + const { state } = store(); + state().setSupport(true); + const host = { revision: 2, sessionId: null, updatedAt: 1, clean: true }; + const base = { v: 1, sessionId: ITHACA, text: "Which harbour?", attachments: [], editedAt: 900, host }; + const malformed = [{ sessionId: ITHACA }, { sessionId: 7, requestId: "req-1" }, "req-1", []].map((bind, i) => parseDraft({ ...base, draftId: `bad-${i}`, bind })); + for (const d of malformed) { + expect(d, "the draft itself is kept").not.toBeNull(); + expect(d).not.toHaveProperty("bind"); + } + const bound = parseDraft({ ...base, draftId: "bound", bind: { sessionId: ITHACA, requestId: "req-1", extra: true } }); + expect(bound?.bind, "only the two known fields are taken").toEqual({ sessionId: ITHACA, requestId: "req-1" }); + // `uncertain` is taken only as a literal true. + expect(parseDraft({ ...base, draftId: "odd", uncertain: "yes" })).not.toHaveProperty("uncertain"); + const uncertain = parseDraft({ v: 1, draftId: "lost", sessionId: RAFT, text: "", attachments: [], editedAt: 900, host: null, uncertain: true }); + state().restoreLocal([bound!, uncertain!]); + expect(state().drafts.bound).toMatchObject({ bind: { sessionId: ITHACA, requestId: "req-1" }, uncertain: false }); + // An emptied draft whose lost save is still owed a reconciliation comes back. + expect(state().drafts.lost).toMatchObject({ text: "", host: null, uncertain: true, bind: null }); + }); + + test("a host refresh never brings back text the reader cleared after a lost first save", () => { + const { state } = store(); + state().setSupport(true); + state().restoreLocal([{ draftId: "lost", sessionId: RAFT, text: "", attachments: [], editedAt: 900, host: null, uncertain: true }]); + state().restore(hostDraft({ draftId: "lost", sessionId: RAFT, revision: 1, text: "Ask Aeolus" })); + expect(state().drafts.lost).toMatchObject({ text: "", host: null, uncertain: true, conflict: null }); + }); + test("a failed device write takes `kept on this device` off the line", () => { const { state } = store(); const id = state().idFor(ITHACA); diff --git a/packages/ui-react/tests/fixtures/local-work-client.ts b/packages/ui-react/tests/fixtures/local-work-client.ts index 0c98c9da7e..a1e3225ee7 100644 --- a/packages/ui-react/tests/fixtures/local-work-client.ts +++ b/packages/ui-react/tests/fixtures/local-work-client.ts @@ -49,6 +49,21 @@ Object.assign(window, { return outcome(root.localWork!.snapshotNow()); }, restoring: () => root.localWork!.restoring(), + /** Whether the host keeps drafts (#951), and the view's draft id. */ + draftsSupported: () => root.stores.drafts.getState().supported, + draftId: () => root.stores.drafts.getState().idFor(root.stores.chat.getState().activeSessionId), + /** One draft's reconciliation state, by id (#1214). */ + draft: (draftId: string) => { + const d = root.stores.drafts.getState().drafts[draftId]; + return d ? { text: d.text, sessionId: d.sessionId, revision: d.host?.revision ?? null, uncertain: d.uncertain, bind: d.bind } : null; + }, + texts: () => Object.values(root.stores.drafts.getState().drafts).map((d) => d.text), + /** What the host keeps, read with this page's session cookie. */ + hostDrafts: async () => ((await (await fetch("/api/drafts")).json()) as { drafts: Array<{ draftId: string; sessionId: string | null; revision: number; preview: string }> }).drafts, + clearHostDrafts: async () => { + const { drafts } = (await (await fetch("/api/drafts")).json()) as { drafts: Array<{ draftId: string; revision: number }> }; + for (const d of drafts) await fetch(`/api/drafts/${encodeURIComponent(d.draftId)}`, { method: "DELETE", headers: { "if-match": String(d.revision) } }); + }, snapshotNow: () => outcome(root.localWork ? root.localWork.snapshotNow() : Promise.resolve()), /** The partition module itself, past any UI. */ read: (accountKey: string, key: string) => outcome(root.partitions!.open(`account:${accountKey}`).get(key)), diff --git a/packages/ui-react/tests/local-work-runtime.test.ts b/packages/ui-react/tests/local-work-runtime.test.ts index a33ce59e80..413c72d542 100644 --- a/packages/ui-react/tests/local-work-runtime.test.ts +++ b/packages/ui-react/tests/local-work-runtime.test.ts @@ -163,6 +163,12 @@ type Fixture = { write(accountKey: string, key: string): Promise; firstVisible(): { anchor: string; offset: number; scrollTop: number } | null; scrollTo(top: number): void; + draftsSupported(): boolean | null; + draftId(): string; + draft(draftId: string): { text: string; sessionId: string | null; revision: number | null; uncertain: boolean; bind: { sessionId: string; requestId: string } | null } | null; + texts(): string[]; + hostDrafts(): Promise>; + clearHostDrafts(): Promise; }; const fixture = (page: Page, fn: (f: Fixture) => T) => page.evaluate(`(${fn.toString()})(window.__local)`) as Promise>; async function until(page: Page, predicate: string, timeout = 15_000) { @@ -703,3 +709,129 @@ describe.skipIf(!executablePath)("device-local work context (#1014)", () => { } }, 30_000); }); + +// Reconciliation owed across a reload (#1214): the snapshot keeps an uncertain +// first save and a pending bind through real IndexedDB, and the reloaded page +// settles each against the real host's #979 draft routes instead of losing it. +describe.skipIf(!executablePath)("draft reconciliation kept on this device (#1214)", () => { + // One matcher reference: `unroute` removes only a handler registered with the same one. + const draftPath = (url: URL) => url.origin === origin && url.pathname.startsWith("/api/drafts/"); + const draftOf = (page: Page, id: string) => page.evaluate((draftId) => (window as unknown as { __local: Fixture }).__local.draft(draftId), id); + const hostDrafts = (page: Page) => fixture(page, (f) => f.hostDrafts()); + async function newChat(page: Page) { + await signIn(page); + await page.goto(origin); + await until(page, "f.connected() && f.accountKey() !== null && f.draftsSupported() === true"); + await fixture(page, (f) => f.restoring()); + await fixture(page, (f) => f.clearHostDrafts()); + expect(await fixture(page, (f) => f.activeSessionId()), "a fresh device opens the new chat").toBeNull(); + } + /** Polls until `done`, for at most `ms`: the assertions after it say what happened. */ + async function settle(done: () => Promise, ms = 20_000) { + const end = Date.now() + ms; + while (Date.now() < end && !(await done())) await Bun.sleep(100); + } + + test("an emptied draft whose first save got no answer is deleted on the host after a reload, not brought back", async () => { + const context = await browser!.newContext({ viewport: { width: 900, height: 700 } }); + const page = await context.newPage(); + try { + await newChat(page); + const text = "Ask Aeolus for the west wind"; + // The host stores the first save; its answer never arrives. Offline after that. + let stored = false; + await context.route(draftPath, async (route) => { + if (!stored && route.request().method() === "PUT") { stored = true; await route.fetch(); } + await route.abort(); + }); + await field(page).fill(text); + const id = await fixture(page, (f) => f.draftId()); + await until(page, `f.draft(${JSON.stringify(id)})?.uncertain === true`, 20_000); + expect((await hostDrafts(page)).find((d) => d.draftId === id), "the host stored the save whose answer was lost").toMatchObject({ revision: 1, preview: text }); + await field(page).fill(""); + await until(page, `f.draft(${JSON.stringify(id)})?.text === ""`); + await committed(page); + expect((await hostDrafts(page)).some((d) => d.draftId === id), "the host still holds it at the reload").toBe(true); + await context.unroute(draftPath); + await page.reload(); + await until(page, "f.connected() && f.accountKey() !== null && f.draftsSupported() === true"); + await fixture(page, (f) => f.restoring()); + // Settled one way or the other: the host's copy deleted, or the cleared text back. + await settle(async () => !(await hostDrafts(page)).some((d) => d.draftId === id) || (await fixture(page, (f) => f.texts())).includes(text)); + expect(await fixture(page, (f) => f.texts()), "the cleared text is not restored from the host").not.toContain(text); + expect((await hostDrafts(page)).some((d) => d.draftId === id), "the host's copy of the lost save is deleted").toBe(false); + expect(await field(page).inputValue()).toBe(""); + // Settled: the device no longer keeps it as owed, so a later reload asks nothing again. + await committed(page); + const records = await fixture(page, (f) => f.list(f.accountKey()!)); + const kept = records.ok ? records.value.find((r) => r.key === `root:odysseus-local/draft/${id}`)?.value : undefined; + expect(kept === undefined || !(kept as { uncertain?: boolean }).uncertain, "the settled draft's record is no longer uncertain").toBe(true); + } finally { + await fixture(page, (f) => f.clearHostDrafts()).catch(() => {}); + await context.close(); + } + }, 120_000); + + test("a pending bind survives a reload and the host binds the newer save to its session", async () => { + const context = await browser!.newContext({ viewport: { width: 900, height: 700 } }); + // The first message is held on its way out until the newer save is on the host. + let releaseMessage: (() => void) | null = null; + await context.routeWebSocket(() => true, (socket) => { + const server = socket.connectToServer(); + socket.onMessage((frame) => { + const message = JSON.parse(String(frame)) as { type: string }; + if (message.type === "chat_message" && !releaseMessage) releaseMessage = () => server.send(frame); + else server.send(frame); + }); + }); + const page = await context.newPage(); + try { + await newChat(page); + const first = "Which harbour shelters the fleet?"; + await field(page).fill(first); + const id = await fixture(page, (f) => f.draftId()); + await until(page, `f.draft(${JSON.stringify(id)})?.revision === 1`); + await field(page).press("Enter"); + await settle(async () => releaseMessage !== null, 5_000); + expect(releaseMessage, "the first message is held before the host sees it").not.toBeNull(); + // The newer edit's save reaches the host; its answer is held. + let answerSave: (() => Promise) | null = null; + let bindsOffline = false; + await context.route(draftPath, async (route) => { + const request = route.request(); + if (request.method() === "PUT" && !answerSave) { + const response = await route.fetch(); + answerSave = () => route.fulfill({ response }); + return; + } + if (bindsOffline && new URL(request.url()).pathname.endsWith("/bind")) { await route.abort(); return; } + await route.continue(); + }); + const newer = "And the harbour fees"; + await field(page).fill(newer); + await settle(async () => (await hostDrafts(page)).some((d) => d.draftId === id && d.revision === 2), 10_000); + expect((await hostDrafts(page)).find((d) => d.draftId === id), "the newer save is on the host, unbound").toMatchObject({ revision: 2, sessionId: null, preview: newer }); + expect((await draftOf(page, id))?.revision, "this page has not heard that save's answer").toBe(1); + // Accepted while that save is out: the host kept revision 2, and the bind is owed. + releaseMessage!(); + await until(page, `f.draft(${JSON.stringify(id)})?.bind != null`); + const session = (await draftOf(page, id))!.bind!.sessionId; + bindsOffline = true; + await answerSave!(); + await until(page, `f.draft(${JSON.stringify(id)})?.revision === 2`); + await committed(page); + expect(await draftOf(page, id), "the bind is still owed at the reload").toMatchObject({ text: newer, revision: 2, bind: { sessionId: session } }); + expect((await hostDrafts(page)).find((d) => d.draftId === id)?.sessionId, "the host's newer save is still unbound").toBeNull(); + await context.unroute(draftPath); + await page.reload(); + await until(page, "f.connected() && f.accountKey() !== null && f.draftsSupported() === true"); + await fixture(page, (f) => f.restoring()); + await settle(async () => (await hostDrafts(page)).find((d) => d.draftId === id)?.sessionId === session); + expect((await hostDrafts(page)).find((d) => d.draftId === id)?.sessionId, "the pending bind completes after the reload").toBe(session); + expect(await draftOf(page, id)).toMatchObject({ text: newer, sessionId: session, bind: null }); + } finally { + await fixture(page, (f) => f.clearHostDrafts()).catch(() => {}); + await context.close(); + } + }, 120_000); +}); From 1826620d0105864d3cbc8c78179a7cc751269c8e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 16:18:40 +0100 Subject: [PATCH 2/2] fix(ui-react): name this store's own recording check instead of another tab (#3470) A recording mutation refused while this store holds brain-ui:recording for its own recovery, sync or another mutation now rejects with "Recordings are still being checked. Try again in a moment." (#3326, ruling A). Capture holds and every holder outside this store keep "Recording in another Brain tab". The lock stays ifAvailable; no wait path is added. Refs #3326 Co-authored-by: Claude Opus 5.5 --- .changeset/recording-own-check-message.md | 5 +++ .../design-kit/offline-continuity.md | 8 ++--- docs/decisions/dictation-speech.md | 2 +- packages/ui-react/src/lib/recordings.ts | 21 ++++++++++--- .../tests/association-signout-runtime.test.ts | 31 +++++++++++++++++++ .../browser/saved-transcription.offline.tsx | 3 +- 6 files changed, 59 insertions(+), 11 deletions(-) create mode 100644 .changeset/recording-own-check-message.md diff --git a/.changeset/recording-own-check-message.md b/.changeset/recording-own-check-message.md new file mode 100644 index 0000000000..c5d4191c7d --- /dev/null +++ b/.changeset/recording-own-check-message.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": patch +--- + +A recording action refused because this page is still checking its own saved recordings now says "Recordings are still being checked. Try again in a moment." instead of "Recording in another Brain tab". The refusal is still immediate; locking and timing are unchanged. Another tab, another root's recordings store on the same page, and a recording in progress in any tab keep "Recording in another Brain tab". diff --git a/docs/decisions/design-kit/offline-continuity.md b/docs/decisions/design-kit/offline-continuity.md index e4aeeb7de6..202819a2cf 100644 --- a/docs/decisions/design-kit/offline-continuity.md +++ b/docs/decisions/design-kit/offline-continuity.md @@ -91,7 +91,7 @@ transcript-ready audio. Playback and review remain local. Transcribe requires its explicit upload confirmation and the server capability. Add to draft persists the chosen draft and its receipt before accepted metadata/deletion; failure keeps the recording. It never sends a message or answers an approval -(`async accept`, `packages/ui-react/src/lib/recordings.ts:688-716`). +(`async accept`, `packages/ui-react/src/lib/recordings.ts:699-727`). The [tray runtime proof](https://github.com/schlessera/brain-kit/pull/1241) measures focus, reading-anchor preservation, playback, failed writes and native transaction ordering. Surviving transcript text remains reviewable even if its @@ -103,7 +103,7 @@ origin/device, across account and unassigned partitions**, with no age expiry and no eviction to admit a new recording (`RECORDING_MAX_MS`, `packages/ui-react/src/lib/recordings.ts:9-16`). The lower browser capacity wins. Estimates are advisory; write success determines what exists -(`async function budget`, `packages/ui-react/src/lib/recordings.ts:195-205`). +(`async function budget`, `packages/ui-react/src/lib/recordings.ts:196-206`). Limits stop capture and keep a contiguous playable prefix, rather than cutting an encoded chunk or deleting older work. Both quota and blob I/O errors stop writes. The [store runtime proof](https://github.com/schlessera/brain-kit/pull/1230) @@ -112,7 +112,7 @@ chunks and crash recovery. **Saved up to** is the last chunk end whose chunk/index transaction completed, not elapsed UI time or the requested MediaRecorder interval -(`const next =`, `packages/ui-react/src/lib/recordings.ts:326-343`). Requested +(`const next =`, `packages/ui-react/src/lib/recordings.ts:337-354`). Requested intervals and warning/minimum-budget defaults are tuning, never promises. [#1250's measured fixture correction](https://github.com/schlessera/brain-kit/pull/1253) further demonstrates why a visible recording sheet or a timeslice deadline is @@ -265,7 +265,7 @@ can do with surviving data; they do not measure when a real browser evicts it: | Neither index nor chunks (and no other surviving record) | Nothing can be listed or reported; no loss notice can be promised | Recovery uses the surviving index and ordered chunks -(`async recover(partition)`, `packages/ui-react/src/lib/recordings.ts:553-617`). +(`async recover(partition)`, `packages/ui-react/src/lib/recordings.ts:564-628`). The store tests force missing-chunk states, including a full origin that cannot repair metadata. Requesting `navigator.storage.persist()` is best effort; no copy calls it a guarantee. No unload callback can save data after a crash, and diff --git a/docs/decisions/dictation-speech.md b/docs/decisions/dictation-speech.md index 15e0601201..1decf9d9e0 100644 --- a/docs/decisions/dictation-speech.md +++ b/docs/decisions/dictation-speech.md @@ -146,7 +146,7 @@ Reconnection, reload and sign-in do not upload or retry audio. Status recovery uses read-only queries; an explicit earlier accept/discard may also flush its queued receipt deletion. Missing status after a lost reply is not proof that nothing was sent (`async syncTranscriptions`, -`packages/ui-react/src/lib/recordings.ts:795-843`). The transcript commits locally +`packages/ui-react/src/lib/recordings.ts:806-854`). The transcript commits locally before review. Add to draft commits a hash-bound draft receipt before deleting the audio; acceptance stays device-local and resumes ordinary host draft workflow only after a subsequent user edit or explicit Send diff --git a/packages/ui-react/src/lib/recordings.ts b/packages/ui-react/src/lib/recordings.ts index f313bcb8b2..422763ee70 100644 --- a/packages/ui-react/src/lib/recordings.ts +++ b/packages/ui-react/src/lib/recordings.ts @@ -102,6 +102,7 @@ export function recordingTime(ms: number): string { } export const RECORDING_UNAVAILABLE = "This recording is no longer available on this device."; export const TRANSCRIPT_CHANGED = "Transcript changed in another tab. Review it before adding it to your draft."; +const STILL_CHECKING = "Recordings are still being checked. Try again in a moment."; const notEnough = "Not enough space on this device to record. Free space by transcribing or discarding recordings."; async function hash(blobs: Blob[]): Promise { const bytes = await new Blob(blobs).arrayBuffer(); @@ -203,12 +204,22 @@ export function createRecordingStore(options: RecordingStoreOptions): RecordingS bytes = Math.max(0, bytes); return { bytes, canRecord: bytes >= MIN_BYTES, message: bytes >= MIN_BYTES ? null : notEnough }; } - async function acquire(): Promise<() => Promise> { + // Holds of the exclusive lock by this store for anything but capture: its + // own recovery, sync and mutations (#3326). While one is held, a refusal + // names this store's own check instead of another tab. A capture hold, and + // any holder outside this store, keeps the cross-tab message. + let maintaining = 0; + async function acquire(capture = false): Promise<() => Promise> { if (!navigator.locks) throw new DOMException("This browser cannot coordinate recording tabs.", "NotSupportedError"); return new Promise((resolve, reject) => { const requested = navigator.locks.request(LOCK, { ifAvailable: true }, async (lock) => { - if (!lock) { reject(new Error("Recording in another Brain tab")); return; } - await new Promise((unlock) => resolve(async () => { unlock(); await requested; })); + if (!lock) { reject(new Error(maintaining > 0 ? STILL_CHECKING : "Recording in another Brain tab")); return; } + if (!capture) maintaining++; + await new Promise((unlock) => resolve(async () => { + unlock(); + // Count the hold until the native lock is actually released. + try { await requested; } finally { if (!capture) maintaining--; } + })); }); void requested.catch(reject); }); @@ -279,7 +290,7 @@ export function createRecordingStore(options: RecordingStoreOptions): RecordingS if (!sameGeneration(partition, pending.generation)) throw new PartitionRefusedError(partition); }; try { - release = preflight?.release ?? await acquire(); + release = preflight?.release ?? await acquire(true); checkStart(); const free = await budget(); checkStart(); @@ -488,7 +499,7 @@ export function createRecordingStore(options: RecordingStoreOptions): RecordingS const partition = heldPartition(); const generation = partitions.writerGeneration(partition); openingGeneration = generation; - release = await acquire(); + release = await acquire(true); const free = await budget(); if (!free.canRecord) { emit("refused", notEnough); throw new Error(notEnough); } signal.throwIfAborted(); diff --git a/packages/ui-react/tests/association-signout-runtime.test.ts b/packages/ui-react/tests/association-signout-runtime.test.ts index f39f4daa58..cc3ea75c8f 100644 --- a/packages/ui-react/tests/association-signout-runtime.test.ts +++ b/packages/ui-react/tests/association-signout-runtime.test.ts @@ -832,6 +832,37 @@ for (const action of ["Keep working", "Escape", "uncheck"] as const) runtimeTest }finally{await context.close();} },30_000); +runtimeTest("a tray mutation refused by this store's own recovery says the recordings are still being checked, not another tab",async()=>{ + const {page,context}=await boot();let other:Page|undefined; + const tray=page.locator("[data-recordings-tray]"); + // The tray item's own error line; it shows the store's refusal message as is. + const refusal=async(after:string|null)=>{const alert=tray.getByRole("alert").filter(after===null?{}:{hasNotText:after});await alert.waitFor({timeout:5000});return await alert.textContent();}; + const kept=async()=>(await work(page,w=>w.read("unassigned"))).filter(r=>r.key==="recording:index:sirens"||r.key.startsWith("recording:chunk:sirens:")).length; + try {await work(page,w=>w.seed("unassigned","sirens"));await signIn(page);await associationShown(page);await click(page,"Not now"); + await act(page,page.getByRole("button",{name:/On this device/})); + // This page's own recovery holds the native recording lock (#3326); the mounted tray item stays actionable. + await work(page,w=>w.holdInventoryRecovery()); + expect((await work(page,w=>w.recoveryEvents())).some(event=>event.root==="primary"&&event.partition==="unassigned"&&event.state==="pending"),"a real primary recovery owns the recording lock").toBe(true); + await act(page,page.getByRole("button",{name:/^Discard recording from /}));await act(page,page.getByRole("button",{name:/^Delete recording from /})); + expect(await refusal(null),"this store's own recovery is not another tab").toBe("Recordings are still being checked. Try again in a moment."); + expect(await kept(),"a refused discard keeps the recording metadata and audio").toBe(2); + await work(page,w=>w.releaseInventoryRecovery()); + // A real recording in another tab still reads as another tab. + other=await context.newPage();await other.goto(origin);await other.waitForFunction(()=>!!window.__work?.key());await work(other,w=>w.captureUnassigned()); + expect((await work(other,w=>w.captureActive()))?.partition,"the second tab really records").toBe("unassigned"); + await act(page,page.getByRole("button",{name:/^Delete recording from /})); + expect(await refusal("Recordings are still being checked. Try again in a moment."),"another tab's real recording keeps the cross-tab refusal").toBe("Recording in another Brain tab"); + expect(await kept(),"a discard refused by another tab's recording keeps the recording").toBe(2); + await work(other,w=>w.stopCapture()); + // So does a real recording held by this same store. + await work(page,w=>w.captureUnassigned()); + expect((await work(page,w=>w.captureActive()))?.partition,"this page really records").toBe("unassigned"); + const refused=await work(page,w=>w.fullDiscard("sirens")); + expect(refused.startsWith("Error: Recording in another Brain tab "),`this store's own live recording keeps the recording refusal: ${refused}`).toBe(true); + expect(await kept(),"a discard refused by a live recording keeps the recording").toBe(2); + }finally{await work(page,w=>w.releaseInventoryRecovery()).catch(()=>{});await work(page,w=>w.stopCapture()).catch(()=>{});if(other)await work(other,w=>w.stopCapture()).catch(()=>{});await context.close();} +},30_000); + for (const generation of ["initial", "reopened"] as const) runtimeTest(`a full origin permits explicit unassigned discard in its ${generation} admitted generation`,async()=>{ const {page,context}=await boot(); try {await signIn(page);if(generation==="reopened") await work(page,w=>w.reopenUnassigned());await work(page,w=>w.seed("unassigned","sirens")); diff --git a/packages/ui-react/tests/browser/saved-transcription.offline.tsx b/packages/ui-react/tests/browser/saved-transcription.offline.tsx index be23ac5d03..bf7695129a 100644 --- a/packages/ui-react/tests/browser/saved-transcription.offline.tsx +++ b/packages/ui-react/tests/browser/saved-transcription.offline.tsx @@ -258,7 +258,8 @@ test("fixture cleanup drains account-switch recovery before the next real seed", try { await ready; expect((await navigator.locks.query()).held?.filter(lock => lock.name === "brain-ui:recording")).toHaveLength(1); - await expect(c.root.recordings!.sink().begin!({ mimeType: "audio/webm;codecs=opus" })).rejects.toThrow("Recording in another Brain tab"); + // The holder is this store's own recovery, not another tab (#3326). + await expect(c.root.recordings!.sink().begin!({ mimeType: "audio/webm;codecs=opus" })).rejects.toThrow("Recordings are still being checked. Try again in a moment."); let completed = false; cleanup = c.cleanup().then(() => { completed = true; }); await navigator.locks.query(); // A native round trip, while the known owner remains held.