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
4 changes: 4 additions & 0 deletions .changeset/draft-reconciliation-across-reload.md
Original file line number Diff line number Diff line change
@@ -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.
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
2 changes: 1 addition & 1 deletion docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,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.

Expand Down
10 changes: 5 additions & 5 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
29 changes: 20 additions & 9 deletions packages/ui-react/src/lib/local-work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export function findByFocusId(id: string): HTMLElement | null {
}

type StoredAttachment = { data: string; mediaType: string; bytes: number; name: string };
type StoredDraft = Omit<LocalDraft, "attachments"> & { v: 1; deviceRevision?: number; attachments: StoredAttachment[] };
export type StoredDraft = Omit<LocalDraft, "attachments"> & { 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;
Expand All @@ -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<StoredDraft> | 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[] = [];
Expand All @@ -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 {
Expand All @@ -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,
Expand All @@ -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 } } : {}),
};
}

Expand Down Expand Up @@ -344,7 +353,8 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork {
const nextCommitted = new Map<string, string>();
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);
Expand All @@ -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();
Expand Down Expand Up @@ -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);
Expand All @@ -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!);
}
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
Loading
Loading