Skip to content

SCA-561: establish single-owner capture coordination - #18946

Merged
Git-on-my-level merged 14 commits into
BasedHardware:mainfrom
Git-on-my-level:sca-561
Sep 26, 2026
Merged

Git-on-my-level merged 14 commits into
BasedHardware:mainfrom
Git-on-my-level:sca-561

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Establish a serialized CaptureCoordinator with explicit capture phases, an immutable state/reducer, ordered effect ports, pendant suspension debt, persisted snapshots, and a committed UI read model.
  • Route ownership-critical CaptureController APIs and callbacks through the coordinator. Keep composite legacy RunStage bodies explicitly staged, with admission guards; the native per-source writer gate remains an interface without a native implementation.
  • Close the reviewed seam defects before asking for review. The Home record button now explains why a Transcribe Later pendant cannot be taken over; an Omi call deliberately mutes that pendant's batch writer for privacy, leaving a gap in its recording during the call. Neither behavior is claimed to be neutral.

Decisions and invariants

  • Exactly one source owns the channel. A phone or call handoff holds at most one pendant suspension; an interim onboarding phone stop explicitly records awaitingPhoneResume and preserves the suspension through call start and call end until an explicit phone start/stop, finish, or disconnect resolves it.
  • Every event executes FIFO. Permission admission runs before a phone takeover or live-phone batch-mode roll can tear down a source or persist a new mode. Effects and changed snapshots are awaited before publication; a failed phone start recovers a connected pendant only if that start newly suspended it, including when snapshot persistence fails. A failed retry over speech-profile debt remains physically idle with the original debt intact and its pre-transition mute restored for explicit retry. A phone start during a call with this hold is refused before effects. A superseded first policy write is adjudicated by its effective policy: when it matches the requested mute, the event continues through its mandatory stages and target commit (including a still-muted mute on stop, disconnect or call start). A mismatched, still-muted unmute keeps the committed paused batch and .bin; only the hypothetical mismatched unmuted mute fails physically closed, remutes after the deny, runs skipped session cleanup, and preserves phone debt or a latched call. Other effect failures fail closed to idle.
  • Phone Live pause releases the mic but retains its socket and recording ID. Phone batch pause leaves the native batch writer in the same file and mutes packet admission; an interruption followed by a user pause stays paused. A repeated identical batch setting is a no-op; a genuine live mode roll stops the old phone session before minting the next ID.
  • An unchanged encoded snapshot skips persistence, so a no-op preferences failure cannot kill a healthy owner. Launch sanitizes persisted hardware ownership to idle and never opens hardware; the existing phone policy-restore marker remains during migration.
  • The shared native gate is a no-op until an iOS/Android per-source gate exists. Phone takeover of a batch pendant remains refused, now with localized feedback. A call suspends a batch pendant by muting shared admission: call audio is intentionally omitted from its Transcribe Later file, a user-visible privacy tradeoff covered by a real-controller test.

GLM/Grok review disposition

Reviewed finding Disposition / evidence
Must 1: stall/reconnect reopen after pause Fixed: restart stages await native start; committed phase is checked before restart and after async boundaries. Scripted real-controller held-start stall → queued pause asserts the native mic stays stopped.
Must 2: old/duplicate recording ID on batch toggle Fixed: mint completes old telemetry, creates a fresh ID; stage stop precedes mint/start; identical toggle returns success without effects. Real controller asserts changing ID and unchanged repeat-start count.
Must 3: permission/start failure strands pendant Fixed: permission preflight precedes suspend and leaves existing pendant untouched on denial or request error; a later start-stage failure physically closes then synchronously reopens the connected pendant under a fresh recording ID. Fake-port and real-controller denial/start-failure cases cover both.
Must 4: onboarding PhoneStop(false) loses pendant Fixed: serialized awaitingPhoneResume debt, named [device-start, phone-start, interim-stop, phone-start, phone-stop] → pendantLive regression. A call starting over the hold only flags callActive — the debt survives call start and call end, and device starts refresh identity without resuming; only an explicit phone start/stop (or a phone stop during the call, which still converts it to call debt) resolves it (20k-soak counterexample seed=6080350 fixed).
Must 5: muted pendant id vs telemetry Fixed: intentionally paused start marks telemetry started rather than failed; actual failed starts fail closed. Real paused-connect/resume test retains its ID.
Must 6: interruption user pause lost Fixed: interruption pause settles in phone paused (mode-correct), and interruption end cannot reopen it; reducer effect test checks mute/mic stop on Live. Batch keeps the same muted native file.
Must 7: eager device roll/settings open during call Fixed: session generation rolls inside queued device-update stage; eager display identity is retained for legacy provider reads. Device settings/reconnect socket and BLE opens require staged pendant ownership and device identity after awaits; a monotonic eager identity-only revision fences in-flight same-ID BLE ABA while the session roll waits in the queue. Established stream frames check policy admission and actual device ID, not this open-only revision. Real-controller packet test confirms frames still reach the socket after same-ID and capability-normalized refresh; real call/settings/reconnect and C1 ABA tests assert no stale socket.
Must 8: public getters leak staged owner Fixed: public source, interruption, phone-pause/batch and pendant-batch getters derive from committed readModel; only staged internals read stagedReadModel. A held real native start asserts public getters remain idle until commit.
Must 9: silent batch-pendant Home button Fixed: Home shows localized OmiFeedback.info instead of starting/navigating; widget test asserts feedback and zero phone starts.
Must 10: stress false confidence Fixed: 2,000 pure-model sequences and 128 effect-port sequences include the full scripted event alphabet, RNG-driven snapshot/socket/policy/native-start faults, held effects with queued socket/BLE signals, kill/reconstruction, stack/reason and physical/telemetry/snapshot invariants, seeded shrinking. Each named episode compares the reducer against a dispatched fake-port replay, checking emitted effects, snapshot, session keys and telemetry IDs; real-controller scripts separately cover stall/pause, call/reconnect, mode roll, denied permission, muted connect, kill/pause and continued BLE frames after device refresh. The prior 20,000-sequence soak passed; the current-head soak is part of this round's verification. Random fake stages are not claimed to exercise every production I/O path.
GLM 6: idle resume opens an unowned pendant Fixed: idle unmute is policy-only and cannot execute ResumeDeviceTailStage or open BLE/socket.
GLM 7: call mutes batch pendant Kept intentionally as a privacy protection; the batch writer stays in its file but drops call-duration packets. Documented above and covered by a real-controller call/resume/ID test.
Grok 9 / GLM 8: no-op persist, superseded pause and un-emitted ports Fixed snapshot no-op skip and deferred recordingState=pause until policy write is confirmed unsuperseded. BleStreamStart, WalFinalize, WalSessionRoll are defined but never emitted; architecture doc names their real staged owners.
GLM 11: lazy getter after dispose Fixed: access after dispose throws rather than constructing a new coordinator; existing disposal tests remain unchanged.
GLM 13: testing keepalive coalescing Documented: simultaneous KeepAliveTick(testingProbe:true) requests join the first probe's future; the second caller observes that first request's outcome. Production keepalive is not coalesced this way.
Grok migration table / GLM 12 omissions Documented in CAPTURE_ARCHITECTURE.md: native mic state callbacks, _setCaptureMuted, profile changes, manual offline cut, dispose, system-audio keepalive, background mode, recordingState reads, remaining onClosed sync flags and stage-internal socket/BLE/WAL. OnConnected's direct state write moved into the queued stage.

Verification-round disposition (GLM N1–N5 / Grok 1–5)

Item Resolution
1. Installed BLE audio starved after same-ID/normalized refresh Fixed: revision gates in-flight opens and subscriptions at installation; installed frames instead check policy admission and actual device ID. The real-controller connect-order replay asserts the socket receives 1, then 2, then 3 packets across same-ID and normalized refresh; pre-fix it failed after packet 1. The C1 same-ID ABA test remains green.
2. Call ends speech-profile hold early Fixed: call start/end preserve the phone debt and awaitingPhoneResume; identity refresh during the hold does not open BLE. An explicit later phone start/stop resumes exactly one pendant. Named fake-port and real-controller denied-retry episodes assert no early stream.
3. Snapshot failure after takeover strands pendant Fixed: post-effect snapshot persistence failure passes the newly appended suspension into the same serialized fail-closed recovery. Fake ports assert a fresh pendant ID, physical BLE restored, mic off, snapshot equal to committed state, and the original failure reported.
4. Denied phone start reported as success Fixed: a successful phone-start transition reports true; streamRecording throws on refused/denied/absorbed failure. Home handles failure with localized feedback and logs/navigates only after the committed phone source exists; speech-profile disposal handles the rejected resume without an unhandled Future.
5. Recovery for pre-existing hold Fixed: only suspensions added by this start can trigger pendant restart; failed retry over onboarding debt stays idle, leaves BLE closed, preserves its one phone debt, and can be retried.
6. Batch-mode roll permission gap Fixed: CheckPhonePermission precedes BatchModeStage; denial leaves the old recording, flag, ID and physical mic untouched.
7. Unowned non-user stop with resume intent Fixed: connected pendant resumes through the same fresh-ID path as a user stop; disconnected case restores policy without opening hardware.
8. Fuzzer/named episode false confidence Fixed: seeded native phone-start faults with positive recovery coverage, mode-correct failed-state checks (idle, recovered live or recovered paused), and every named episode checks effect calls, snapshot and telemetry identity as well as phase. The stronger fuzzer found an exposed paused batch writer on a superseded first policy write; the recovery now compares effective policy with the requested value. A matching mute continues through required cleanup, a mismatched still-muted unmute leaves the paused writer untouched, and hypothetical mismatched open admission fails physically closed. Named regressions cover all three outcomes.
9. Prefetched permission leak Fixed: optional permission-grant cleanup port runs in _run's finally, including denied and abandoned transitions; its fake-port regression asserts a denied grant is cleared before the next start.

Second verification-round disposition (Grok 1–3 / GLM 1–3)

Item Resolution
1. Failed phone restart over onboarding debt unmutes Fixed: after physical deny, re-write pre-transition mute before the idle+debt snapshot; port regression verifies true → false → true, mic/BLE closed and debt retained.
2. Superseded paused phone-batch stop drops pendant debt Fixed: a still-muted superseded stop now completes its StopPhoneBatchStage and target snapshot, retaining pendant debt or converting it into a latched call's suspension. Hypothetical unmuted admission triggers physical deny, remute and stage cleanup, preserving debt for explicit retry. The batch-card Stop awaits and handles rejection with localized feedback.
3. Superseded paused pendant-batch resume admits writer Fixed: a superseded unmute that stays muted keeps pendantBatchPaused, recording ID and .bin untouched. A matching unmuted policy continues the resume; a still-muted superseded mute on call start/disconnect executes SuspendPendantStage or StopDeviceSessionStage plus telemetry before committing.
4. Speech-profile dispose swallows failure silently Fixed: log error and stack trace with Logger.error before returning from the asynchronous dispose resume.
5. Phone start during in-call onboarding hold wipes debt on failure Fixed: reject this specific start without effects (result: false); preserve the existing call-suspension takeover behavior outside a hold. Port regression checks call flag, mute and debt through call end.
6. Prior device subscription lingers after mid-open identity change Documented residual: installed frame guards reject old-device bytes; the old characteristic subscription is cancelled at the next _closeBleStream. No new-socket traffic leaks.

Targeted verification disposition (paused-batch policy supersede)

Item Resolution
Superseded resume whose policy stays muted Fixed: a lost unmute keeps the committed paused session, .bin, identity, debt and call unchanged; no physical deny, remute, stage or snapshot. A thrown post-write environment read reports the error without tearing down the safe pause.
Superseded mute whose policy stays muted Fixed: the requested policy has taken effect, so the event continues through remaining effects and target commit. Named tests assert phone-batch stop (including during a call), pendant-batch disconnect with telemetry, call-start suspend, and phone finish; no mandatory stage is skipped.
Simulated open admission after a mute Defensive branch physically denies, remutes, runs skipped cleanup, and retains phone debt or latched call suspension; this specific result is unreachable for a superseded mute under current production policy publication. A matching unmuted superseded resume simply commits its live target without closing the batch file, making a fail-close resume cleanup stage inapplicable.
Harness and UI The fake defaults a superseded policy write to production's effective mute; simulateOpenAdmissionOnSupersede explicitly labels the hypothetical open fault. Effect-port fault injection includes paused-batch stop, disconnect and call start; both live pause controls log phone-mic resume only after the effective policy is unmuted.

Migration plan

Now: phone/pendant start, stop, pause, finish and handoff; Omi call suspend/resume; native interruption/stall; socket listeners/keepalive; batch/settings/onboarding; launch marker recovery. Next: extract device/phone stage bodies into primitive effects (BLE open, WAL finalize/roll, socket open), migrate remaining native-callback mirrors and reconnect inputs, implement the native per-source writer gate, retire the restore marker after verified snapshot migration, then finish UI read-model adoption. The current direct exceptions and rationale are enumerated in app/lib/services/capture/CAPTURE_ARCHITECTURE.md; the staged bodies are not represented as already-migrated ports.

File-size review exceptions

Line-Count-Exception: app/lib/services/capture/capture_controller.dart | 3509 -> 3753 | Migration temporarily retains legacy composite stage bodies beside the coordinator adapter and adds a monotonic display-identity revision fence and stale-attempt teardown for same-ID BLE ABA during awaited codec/socket opens; the next extraction removes bodies rather than hiding behavior.
Line-Count-Exception: app/lib/services/capture/capture_coordinator.dart | 0 -> 2828 | Explicit event/state/effect types, pure reducer, serialized executor and snapshot are together during the compatibility and stress gate; split at proved port seams after migration.

Failure classes

Failure-Class: FC-unowned-session-mutation-tears-down-live-capture

Addresses FC-split-mutation-authority, FC-concurrent-capture-contention, and FC-unowned-session-mutation-tears-down-live-capture. This is a staged foundation, not a claim that native writers, every legacy mirror, or every RunStage is already under primitive port control.

Verification

  • Why four legacy fixture files changed: the protected C1 spine c1_composition_test.dart remains unchanged and its pre-coordinator idle + manually attested deviceRecord ABA fixture is supported only by KeepAliveTick(testingProbe:true); while that explicit probe is in flight under idle, generation retirement is eager solely to preserve the spine's isCurrent(before)==false assertion. Production keepalive and actual owners never use the exception. capture_socket_generation_test.dart now starts a real pendant session through the production public API and preserves the stale-open and positive-control assertions; the same-ID ABA race it found is fenced by a synchronous, non-ownership identity revision while its generation roll stays queued. capture_provider_test.dart's reconnect assertion now starts a real phone session and awaits pendingSourceSwitch instead of expecting a synchronous socket callback. transcription_paused_warning_test.dart isolates the widget's source projection behind a view fixture; real controller mute/recording-ID coverage remains in coordinator tests. The visual-audit capture fake supplies the new pendant-batch getter. No assertion or protected check was skipped to turn red into green.
  • Existing one-source suite, coordinator seeded/effect fuzz and named real-controller regressions, Home feedback widget test, focused Dart analyzer and python3 scripts/l10n.py check: passed locally after review fixes.
  • Pure-model CI budget: 2,000 sequences of 50–200 events from 0x5ca561. Effect-port budget: 128 sequences of 50–119 events with seeded holds and snapshot/socket/policy/native-start faults, now including production-reachable still-muted supersession on paused phone stop, pendant disconnect and call start. The simulated open-admission stop is a named defensive regression, not a claim about a production-reachable superseded mute. Earlier soaks found seed=6080350 and the exposed batch writer at seed=6071672; this round's OMI_CAPTURE_SOAK_SEQUENCES=20000 flutter test --no-pub test/services/capture/capture_coordinator_test.dart passed 74/74 coordinator tests with the 20,000-sequence pure-model soak and 128-sequence effect fuzz.
  • Current-head focused coordinator and one-source tests passed 91/91; targeted Home widget tests passed 25/25. Full bash app/test.sh passed 138 spine and 3,246 main tests (five skipped). Analyzer ratchet, localization (49 locales, 3,389 keys), scripts/pr-preflight --pr-body-file pr-body-capture-coordinator.md (22 checks) and make preflight (22 checks) passed. Final head 6127506ccb5c5331e39744105ce0dc021c956d87: all seven expected workflows passed. Mobile App Checks includes Dart Analyze & Tests, Pacific/Kiritimati Dart tests, Seeded Journeys, Android JVM Unit Tests, Android Compile Smoke, Generated Files and Mobile Release Eligibility. Repo Checks, Backend Checks, Backend Hermetic E2E, Web Checks, Desktop Checks, and Desktop Swift CI succeeded (unaffected jobs intentionally skipped).
  • Earlier head 6b34d423ec exposed a test-harness timing assumption in the Pacific/Kiritimati shard: the held native-start regression inspected startCalls before async WAL setup reached the fake host. The fake host now signals entry; both held-start regressions await it instead of a fixed event-loop pump. On prior head c4f8b88869, targeted TZ=Pacific/Kiritimati and TZ=Pacific/Pago_Pago coordinator tests each passed 65/65. This was a fixture timing issue, not a capture behavior failure. The PR remains open and unmerged pending targeted review and David's decision.

Generated with Devin

Git-on-my-level and others added 10 commits September 26, 2026 00:43
Route ownership-changing capture events through a single coordinator so competing sources cannot independently claim the microphone. Save a draft checkpoint while stress and conformance gates are still in progress.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The ownership migration is intended to preserve user-visible capture behavior and therefore carries no release-note copy.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Bring the foundation onto the newest capture wedge and socket recovery contracts while retaining both injectable monitors and coordinator ports.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… owners

Prevent a phone finish during a call from restarting the pendant, mint recording IDs only once, and fail closed when a transition cannot safely activate hardware. Add seeded and real-controller regression coverage.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Keep synchronous device and socket observations for existing callers while routing capture effects through the coordinator, and restore explicit phone restart and global mute admission semantics.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Keep batch handoff, suspended resume intent, unowned stop and deferred batch behavior explicit alongside the seeded coordinator gate.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Preserve pending pendant intent through onboarding and calls, fence stale
BLE/socket completions, and make failure recovery and recording IDs agree
with the coordinator's committed source. Exercise the real controller and
seeded faulty ports before advancing the architecture for review.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Restore the reviewed C1 spine contract without allowing its legacy fixture
to reopen hardware or roll sessions synchronously in production.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Preserve upstream capture UI copy and generated localization changes alongside
the ownership review fixes so the PR can pass its synthetic-merge gate.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The Pacific/Kiritimati shard exposed a fixture race: an event-loop pump
could finish before WAL setup reached the held fake native start. Synchronize
on the fake host's actual entry point instead of test-runner scheduling.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review September 25, 2026 23:21
Git-on-my-level and others added 4 commits September 26, 2026 07:16
…ff failures

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Git-on-my-level
Git-on-my-level merged commit d2c7519 into BasedHardware:main Sep 26, 2026
34 checks passed
Itaxh1 added a commit to Itaxh1/omi that referenced this pull request Sep 26, 2026
Brings in BasedHardware#18946 (capture coordinator); the 01:00 work carried onto it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant