Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/recording-own-check-message.md
Original file line number Diff line number Diff line change
@@ -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".
8 changes: 4 additions & 4 deletions docs/decisions/design-kit/offline-continuity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/dictation-speech.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 16 additions & 5 deletions packages/ui-react/src/lib/recordings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
const bytes = await new Blob(blobs).arrayBuffer();
Expand Down Expand Up @@ -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<void>> {
// 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<void>> {
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<void>((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<void>((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);
});
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
31 changes: 31 additions & 0 deletions packages/ui-react/tests/association-signout-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading