Repository navigation
fix(app): durable live-capture safety copies, chat draft persistence, startup WAL re-arm - #23961
Conversation
… startup WAL re-arm Live phone-mic audio now keeps a durable local safety copy until the server confirms it, matching the Apple Watch safety-copy contract: chunks whose frames were transport-marked synced at socket send are stored instead of dropped (a transport send never starts the retention clock), the lifecycle pause seals and flushes the in-memory tail like the Watch checkpoint, and the conversation stamp binds transport-only synced copies so the end-of-session confirmation can release covered copies into synced retention and reclassify uncovered ones for repair upload. The chat composer draft is persisted and restored on open, and cleared only after a send is accepted, so an interrupted or refused send stays restorable. A cold start re-arms the transient WAL retry budget the same way a connectivity restore does; durable HTTP refusals keep their persisted clock.
…ersistence, startup re-arm
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 21233cc500
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| void _persistDraft() { | ||
| if (!mounted) return; | ||
| prefs.chatMessageDraft = textController.text; |
There was a problem hiding this comment.
Preserve the pending draft when the composer is cleared
When a send starts, _sendMessageUtil clears textController, which triggers this listener and persists an empty draft after 300 ms, before the send is acknowledged. Killing the app during a slower request therefore loses the supposedly protected draft. A failed send only temporarily repairs this: it saves text, but leaving chat subsequently calls _persistDraft() from dispose() and overwrites that saved text with the still-empty controller. Track the unacknowledged message separately so programmatic composer clearing and disposal cannot erase its recovery copy.
Useful? React with 👍 / 👎.
| _draftSaveTimer?.cancel(); | ||
| prefs.chatMessageDraft = accepted ? '' : text; |
There was a problem hiding this comment.
Preserve newer composer text when an earlier send finishes
The text field remains enabled while a reply streams, so the user can type their next question and have it persisted before the current reply finishes. This unconditional completion write then replaces that newer draft with either an empty string on success or the previous message on failure, and cancels any pending save of the newer text. If the app is killed afterward, reopening loses the next question or restores the wrong one. Only clear the draft belonging to the completed send, preserving any newer composer edits.
Useful? React with 👍 / 👎.
| // recordings that spent their transient retry budget: without this they | ||
| // strand on disk until the next network flap. Refused (4xx) WALs keep | ||
| // their persisted refusal clock and are untouched by the reset. | ||
| await phone.resetExhaustedAutoRetries(); |
There was a problem hiding this comment.
Recheck provider lifetime after resetting persisted retries
If the provider is disposed while resetExhaustedAutoRetries() awaits its WAL-index disk write, initialization now resumes past the preceding _isCurrent(generation) check and configures the global transfer coordinator with the disposed provider's callbacks. It also creates a periodic-sync owner after dispose() has already performed its cleanup. In particular, a replacement provider that configured the singleton during that wait can have its callbacks overwritten; the stale provider's drain then returns contended because _isDisposed is true, preventing background recovery through that coordinator. Recheck _isCurrent(generation) immediately after this new await before configuring or starting anything.
Useful? React with 👍 / 👎.
| String get chatMessageDraft => getString('chatMessageDraft', defaultValue: ''); | ||
|
|
||
| set chatMessageDraft(String value) => saveString('chatMessageDraft', value); |
There was a problem hiding this comment.
Scope persisted chat drafts to their owning account
After an authentication session expires, signing into a different account on the same phone can restore the previous account's private composer text. The new preference uses a device-global key, while AuthService.expireSession() calls clearUserDisplayCache(), which clears cached messages and identity but does not remove this draft; the expiration listener in AuthenticationProvider only clears provider state, not the preferences store. Unlike explicit Settings sign-out, this path never calls clearPreferencesForSignOut(), and ChatPage.initState() subsequently restores the global draft without checking its owner. Store drafts under the originating UID and fence writes to that owner, or clear them across every authentication boundary.
Useful? React with 👍 / 👎.
P1: the safety copy only became durable when the 75s chunk timer ran, so a process death inside that window still lost the buffered frames. The phone-mic buffer now drains on the pendant's 10-second cadence (finalize + flush, the same shape as the Watch checkpoint), so at most one drain interval of live frames is ever un-stored; the lifecycle pause reuses the same drain. P2: an accepted reply cleared the persisted draft unconditionally, which erased a newer draft typed while the reply streamed. The persisted copy is now only replaced when it still holds this send's text (accepted: clear; failed: keep), and a newer draft is never clobbered in either direction.
…compare P2a: cancelling the debounce could discard the only save of a failed send sent inside the 300ms window, leaving a stale draft persisted. The composer draft is now flushed synchronously at send start, so the persisted copy provably holds this send's text before the request runs. P2b: the post-send comparison used the context-prefixed prompt while the draft stores only composer text, so a context send's prompt could reappear as a draft. The comparison now uses the pre-wrap composer text.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dfce965615
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // retain the session. A transport send is not transcript confirmation. | ||
| bool shouldStored = | ||
| _bufferDeviceType == DeviceType.appleWatch || SharedPreferencesUtil().unlimitedLocalStorageEnabled; | ||
| bool shouldStored = _keepsLiveSafetyCopy || SharedPreferencesUtil().unlimitedLocalStorageEnabled; |
There was a problem hiding this comment.
Re-arm transport-only copies after an interrupted session
If the process dies after a phone-mic drain but before conversation stamping/transcript confirmation, these newly retained copies remain persisted as status == synced with syncedAt == 0. The startup loader preserves that state, while isAutoUploadEligible() and getOrphanedWals() exclude synced records; repository-wide inspection found no startup path that confirms or reclassifies them. Consequently, audio missing from the server never enters automatic repair after reopening, and these files also remain outside the retention sweep indefinitely. Reclassify recovered, unconfirmed phone-mic copies for repair (or reconcile their server coverage) before treating them as synced history.
Useful? React with 👍 / 👎.
| if (!_isCurrent(generation) || _deviceId != 'phone-mic' || _frames.isEmpty) return; | ||
| await _finalizeCurrentSession(generation); |
There was a problem hiding this comment.
Make periodic phone drains compatible with transcript coverage
With the default transcript-based custody release, this wall-clock drain can seal a non-integral number of audio seconds—for example, 999 PCM frames—because native audio callbacks and the timer are not synchronized. However, walCoveredByTranscript() in wal_policy.dart rejects every WAL whose totalFrames % framesPerSecond != 0, regardless of how completely the saved transcript covers it. Consequently, ordinary successful live recordings can repeatedly reclassify their new safety-copy chunks as missing and upload them again for repair, unnecessarily consuming bandwidth and backend work. Drain whole-second prefixes while retaining the remainder, or make coverage safely support fractional-duration copies; the new tests only exercise integral frame counts.
Useful? React with 👍 / 👎.
…ce (#23962) ## What changed and why The web chat composers kept their draft in React component state only and cleared it before the send was acknowledged, so a failed or interrupted send left the typed text with no restorable copy after a refresh. The mobile app got the same fix in #23961; this is the web half, per-surface: - **`chatDraft.ts` (new):** one storage key per composer scope (`omi.chat.draft.panel`, `omi.chat.draft.home`), with SSR- and quota-safe read/write/clear helpers. - **`ChatPanel.tsx` / `ChatComposer.tsx`:** the draft is restored on mount, persisted as it changes, and cleared only after the send is accepted. The post-send write only replaces the persisted copy when it still holds this send's text — a newer draft typed while a send is running is never clobbered (the guard the #23961 review asked for is applied here from the start), and an already-cleared copy of a failed send is restored. - **`useChat.ts`:** `sendMessage` now resolves `false` when the stream reported an error chunk or the transport failed (and for a superseded send whose catch path returns early), so callers can distinguish accepted sends. Existing behavior is unchanged otherwise. ## Review round (this push) Two round-1 findings, each fixed with a test: 1. **P1 — cross-account draft exposure.** The storage keys were shared across accounts and never cleared on sign-out, so one account's unsent prompt could restore — and be sent — from another account's composer on the same browser. Drafts are now scoped to the signed-in uid (`setChatDraftOwner` registered by the auth provider), and an account switch or sign-out clears the previous owner's drafts. 2. **P2 — reopening the panel did not restore a failed send's draft.** The panel stays mounted while closed, so the mount-time initializer never reran. The panel now restores an empty composer from the persisted draft on each open transition. Round 2 (delta) found one further P1 in that scoping, fixed: 3. **P1 — a send that outlives its account could write under the new owner's key.** A pending `handleSend` continuation (send started under account A, account switched before the stream failed) could persist A's prompt under B's draft key. Both composers capture the draft owner at send start (`chatDraftOwner()`) and drop the post-send draft write when the owner changed mid-send. Covered by the new outlives-its-account test. ## How it was verified - `bunx vitest run` on the touched suites: 3 new `useChat.sendMessage` acceptance tests (done-chunk true; error-chunk and transport-failure false; nothing-to-send false) and 7 chat-draft tests (restore on open, persist-as-typed + clear on accepted send, keep restorable on failed send, newer draft during a running send is never clobbered, reopen-without-refresh restores a failed draft, one account's draft never restores into another account's, a send that outlives its account writes nothing under the new owner) — all green; the existing `ChatPanel.evidence`, `ChatComposer`, `HomePage` and `AuthProvider` suites stay green (36 tests across six files). ## Failure class (fixes) Failure-Class: new ## Failure-class transition narrative **Violated contract:** a composer that clears its input before the send is acknowledged holds no restorable copy of what the user typed. The same contract covers the send verdict: a caller that cannot observe whether the stream failed cannot keep restorable state for a retry. **Canonical guard:** `chatDraft.ts` persists each composer scope's draft on change and restores it on mount; `useChat.sendMessage` resolves false on an error chunk or transport failure; both composers clear the persisted copy only on acceptance and only when it still holds this send's text (synchronous read/write pair, no debounce race). Guard artifacts: `web/app/src/components/chat/chatDraft.ts`, `ChatPanel.tsx`, `ChatComposer.tsx`, `web/app/src/hooks/useChat.ts`, `.github/failure-classes/FC-web-draft-cleared-before-acknowledgement.json` and the tests above. **Evidence:** this PR is the evidence; `evidence_prs` is `[]`. ## UI evidence UI-Evidence: none -- reason: no visual surface changes; both composers render identically and only draft persistence changes.
What changed and why
Three small custody fixes on the app side, all following contracts that already exist on main:
_keepsLiveSafetyCopy): the copy is written withsyncedAt = 0(a transport send never starts the retention clock), the lifecycle pause seals and flushes the in-memory tail the same way the Watch checkpoint does, and the conversation stamp now binds transport-only synced copies (status == synced && syncedAt == 0) soconfirmSessionTranscriptioncan release covered copies into synced retention and reclassify uncovered ones for repair upload — the eligibility check in that confirmation already accepted this row shape, the rows just never existed before.TextEditingControllerand was cleared before the send was acknowledged. The draft is now persisted (0.3s coalesced) and restored when chat opens, and cleared only after a send is accepted: a reply that arrived and did not fail. A failed reply, a quota refusal (no reply at all) or an interrupted send keeps the draft restorable.retryCount >= walMaxAutoRetries,status == miss) was only re-armed on a connectivity restore — a cold start with steady connectivity left it stranded until the next network flap. The transfer coordinator's startup attach now re-arms it the same way; durable HTTP refusals (400/413,uploadRejected) keep their persisted refusal clock and are untouched, exactly as the refusal policy requires.Product invariants affected
INV-CAP-1 (pendant audio retention) —
app/lib/services/wals/**changed. The change strengthens custody: live phone-mic frames now follow the same durable-copy rule the Watch safety copy and pendant ring already follow (a send is not server confirmation; the copy stays recoverable until the transcript or an upload confirms it). No path deletes sampled audio; the retention sweep continues to never removesyncedAt == 0copies.How it was verified
flutter teston the touched suites: 4 new live-safety-copy tests (10s-tail drain stores + flushes the copy instead of dropping it; pause seal flushes to disk; stamp → covered release vs uncovered repair reclassification), 5 new chat-draft tests (restore on open, no stale resurrection, failed send keeps the draft, accepted send clears it, a newer draft typed while a reply streams is never clobbered), 1 new cold-start re-arm test (spent budget reset, refusal clock preserved) — all green.local_wal_sync_test,session_wal_sync_test,local_wal_live_custody_test,local_wal_sync_session_generation_test,l5_capture_committed_test,wal_stale_missing_test,pendant_custody_main_red_test,chat_duplicate_failed_reply_test,chat_stop_reply_test): 204/204 green.bash app/scripts/analyze_ratchet.sh— passed, no new analyzer issues.Review round (this push)
Two round-1 findings, each fixed with a test:
_drainPhoneTail: finalize + flush, the same shape as the Watch checkpoint), so at most one drain interval of live frames is ever un-stored; the lifecycle pause reuses the same drain.Round 2 (delta) found two further P2s in that draft guard, both fixed:
_draftSaveTimercancelled, then an immediate write), so the persisted copy provably holds this send's text before the request runs; the post-send decision compares against that exact value. Covered by the new in-window send test.draftText), captured before the context prefix is prepended.Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2669 -> 2692 | safety-copy storage gate, 10s live-tail drain + pause seal, generalized transport-synced conversation stamp (+23 net; three
shouldStoredsites share one_keepsLiveSafetyCopygetter)Line-Count-Exception: app/lib/backend/preferences.dart | 1635 -> 1641 | one persisted property pair (
chatMessageDraft) beside the neighboring chat prefs, following the file's existing getter/setter idiomFailure class (fixes)
Failure-Class: new
Failure-class transition narrative
Violated contract: a transport send is not server confirmation. A live capture surface that marks frames synced at socket-send time and skips durable storage for all-synced chunks holds no local copy of the audio it already handed off, so the end-of-session transcript confirmation has no stamped copy to judge or repair, and the retry budget of the transient failure class ends with the process instead of the network epoch. The same contract covers composer input: a draft cleared before the send is acknowledged has no restorable copy.
Canonical guard:
_keepsLiveSafetyCopystores phone-mic live chunks like the Watch safety copy withsyncedAt = 0(the retention sweep never removes them); the lifecycle pause seals and flushes the tail (_finalizeCurrentSession+_flush, the Watch checkpoint's shape);stampConversationIdbinds transport-only synced copies soconfirmSessionTranscriptionreleases covered copies into synced retention and reclassifies uncovered ones tomissfor repair upload;SyncProvider's startup attach re-arms the transient retry budget exactly likeonConnectivityRestoredwhile refusals keep their persisted clock; the composer draft persists and clears only after acceptance. Guard artifacts:app/lib/services/wals/local_wal_sync.dart,app/lib/pages/chat/page.dart,app/lib/providers/sync_provider.dart,.github/failure-classes/FC-live-frame-synced-without-durable-copy.jsonand the three test files above.Evidence: this PR is the evidence;
evidence_prsis[].UI evidence
UI-Evidence: none -- reason: no visual surface changes; the composer renders identically and no layout or copy changed.