Skip to content

Fix macOS Rewind blank capture, Bee audio crash, ~6 dB system-audio loss, hub timer leak, sync data loss (bug sweep #6) - #9514

Merged
eulicesl merged 7 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm
Jul 12, 2026
Merged

eulicesl merged 7 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm

Conversation

@eulicesl

@eulicesl eulicesl commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Batch 6 of the macOS bug sweep — a second-pass hunt fanned six reviewers across subsystems not deeply swept before (audio pipeline, sync layer, auth/session, realtime voice-turn hub, Rewind capture, Rust backend + notifications). Each finding below was personally re-verified against the source before any code changed. This PR lands the five confirmed crash / data-loss / correctness / leak fixes, each with a pure, hermetic regression test where a testable seam exists.

All five are live on main today.

Fixes

1. Rewind captured no video at all (CRITICAL regression)

VideoChunkEncoder.writeFrame derived the frame presentation timestamp as max(0, frameOffsetInChunk - 1) / frameRate. The - 1 compensated for a pre-increment that the earlier desync fix (02f0b41da) moved to after writeFrame. Post-fix, frame 0 and frame 1 both resolve to PTS 0; AVAssetWriterInputPixelBufferAdaptor.append requires strictly increasing timestamps, so every chunk's second frame was rejected, five failures forced an emergency reset that discarded the in-progress .mp4, no chunk ever finalized, and the Rewind timeline stayed permanently empty. Fixed by mapping frame N → N / frameRate via a testable framePresentationSeconds seam.

2. Crash on malformed Bee ADTS audio frame

AACAudioDecoder.decode formed data.subdata(in: 7..<frameLength) with no guard that frameLength > 7. A corrupted BLE frame decoding to frameLength <= 7 produced an invalid Range and terminated the process. Fixed with a slice-safe adtsRawAACRange(in:) parser that rejects malformed/incomplete frames.

3. System audio captured ~6 dB too quiet

The system-audio converter input format declared the source channel count (stereo) while the fill loop only writes a manually down-mixed channel 0. The converter then averaged the real mix against an unwritten channel 1, attenuating all transcription input ~6 dB. Fixed to declare mono, matching the microphone path.

4. Leaked keepalive timer on every hub reconnect

RawWebSocket's server-close-frame path (opcode 0x8) never cancelled the 20s keepalive DispatchSourceTimer, unlike close()/fail(). Gemini idle-closes the warm hub socket (1008) ~every 2.5 min, so each re-warm orphaned a resumed timer that fired forever. Fixed to cancel in the 0x8 path plus a deinit backstop.

5. Recording started during sync could be dropped (data loss)

syncToCloud snapshotted wals, passed the copy to a reconciler that runs per-job network awaits on the main actor, then reassigned the snapshot back wholesale. WALs appended by the chunk timer / SD / WiFi paths during the awaits were silently dropped and never uploaded. Fixed with a pure id-keyed mergeReconciledUploads that preserves appended WALs and only applies the fields reconcile owns.

Root cause & durable guards

Each fix records its root cause and ships a durable guard:

Testing

  • python3 scripts/check_desktop_test_quality.py — OK (no new source-inspection/wall-clock debt).
  • python3 scripts/check-sources-root-layout.py — OK.
  • python3 scripts/check-e2e-flow-coverage.py --strict — all 6 changed Swift files covered.
  • No Swift toolchain in this environment; the new XCTest cases compile/run on macOS CI (desktop-swift-ci.yml). Opened as a draft so it can be built and verified locally before landing.

Product invariants affected

  • INV-CHAT-1 — path-based match only (FloatingControlBar/RawWebSocket.swift). The change cancels a leaked keepalive DispatchSourceTimer on the socket teardown path; it does not touch the chat write-path, kernel projection, floating viewport, or turn identity, so the invariant's behavior is unchanged and its guard tests are unaffected.

Deferred (lower-severity findings from the same sweep, tracked for follow-up)

Confirmed-but-low or suspected findings not in this PR: StorageSyncService.updateProgress computes elapsed == 0 (SD-card B/s always 0, display-only); WALService totalFrames double-count on repeated failed writes under the same WAL id; audio stop-path converter release ordering (suspected race); NotificationService.notificationMetadata unbounded growth for un-interacted banners; Rust RedisService never invalidates a broken cached connection (rate limiter fails open until restart); BYOK-vs-Firebase-session 401 conflation on the default request path (needs backend 401 semantics confirmation); RealtimeOmniService.pendingAudio uncapped while connecting; RewindIndexer rebuild frame over-count.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q


Generated by Claude Code

Review in cubic

claude added 5 commits July 12, 2026 01:45
…et-desync fix

The frame-offset desync fix (02f0b41) moved `frameOffsetInChunk += 1` from
before `writeFrame()` to after it, but the presentation-timestamp expression
inside `writeFrame` still subtracted 1 from the offset. That `- 1` was only
correct under the old pre-increment ordering. Post-fix, frame 0 and frame 1 both
resolve to PTS 0, and `AVAssetWriterInputPixelBufferAdaptor.append` requires
strictly increasing timestamps — so every chunk's second frame is rejected, five
consecutive failures trigger an emergency reset that discards the in-progress
`.mp4`, no chunk ever finalizes, and the Rewind timeline stays permanently empty.

Fix: derive the PTS from the current (pre-increment) offset directly via a new
`nonisolated static framePresentationSeconds(frameOffset:frameRate:)` seam, so
frame N maps to N / frameRate — strictly increasing.

Root cause: a compensating `- 1` left behind when the increment moved past the
write. Durable guard: the PTS math is now a pure, synchronously testable function
with a regression test asserting strict monotonicity for consecutive offsets
(the exact frame-0/frame-1 collision that broke capture).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
…rash

`AACAudioDecoder.decode` extracted a 13-bit ADTS frame length and, after checking
only `data.count >= frameLength`, formed `data.subdata(in: 7..<frameLength)`. When
a corrupted Bee-device BLE frame decoded to `frameLength <= 7`, that range has
`lowerBound > upperBound`, tripping a Swift `Range` precondition and terminating
the process. The 12-bit ADTS sync-word check is weak enough that radio corruption
can reach this path. Absolute `[0]`/`subdata` indexing would also trap on a `Data`
slice with a non-zero `startIndex`.

Fix: parse and validate the payload range in a new `static adtsRawAACRange(in:)`
seam that requires `frameLength > headerSize`, reads `startIndex`-relative so it
is slice-safe, and returns nil for malformed/incomplete frames instead of
trapping.

Root cause: missing lower-bound guard on an attacker/environment-controlled length
field. Durable guard: pure, converter-free static parser with regression tests
covering frameLength 0...7, incomplete frames, bad sync word, and non-zero
startIndex slices (both the valid and the crash case).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
… dB attenuation

`handleAudioInput` manually down-mixes stereo source frames into a single channel
(channel 0) and never writes channel 1, but the converter input format was built
with the source channel count (e.g. 2). The converter then ran its own stereo→mono
downmix, averaging our real mix against the unwritten channel 1 (silence), so all
system audio fed to transcription was attenuated ~6 dB. The microphone path
(`AudioCaptureService`) already builds its input format with `channels: 1`.

Fix: build the input format via a new `static makeConverterInputFormat(sampleRate:)`
that is always mono, matching what we actually write.

Root cause: input-format channel count disagreed with the single channel the fill
loop populates. Durable guard: the mono contract is now a testable factory with a
regression test asserting `channelCount == 1` across sample rates.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
… close

`close()` and `fail()` both cancel the 20s keepalive `DispatchSourceTimer`, but the
server-close-frame path (opcode 0x8) did not — it set `closed = true`, fired
`onClose`, cancelled the connection, and returned, leaving the timer resumed. The
socket then deallocates (subsequent `close()` is a no-op because `closed` is set),
orphaning a resumed GCD timer that keeps firing its wakeup for the rest of the
process. Gemini idle-closes the warm hub socket with a 1008 close frame roughly
every ~2.5 min and the hub re-warms, so this leaked one zombie timer per re-warm —
unbounded periodic-wakeup accumulation and battery drain on a menubar app.

Fix: cancel `pingTimer` in the 0x8 case exactly like the other two teardown paths,
plus a `deinit { pingTimer?.cancel() }` backstop so no future teardown path can
reintroduce a zombie timer.

Root cause: one of three teardown paths omitted the timer cancel. This is a socket
+ GCD-timer lifecycle fix with no hermetic seam (a live NWConnection receive loop
is required to exercise the 0x8 branch), so it ships with the deinit backstop and
no unit test — stated explicitly per the same constraint as 02f0b41.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
`syncToCloud` snapshotted `wals` into a value-type copy, passed it to
`reconcileUploadedWals` (which runs per-job network `await`s on the main actor),
then reassigned the snapshot back wholesale: `wals = workingWals`. During those
awaits, other main-actor work — the chunk timer's `createWalFromCurrentFrames`,
SD/WiFi `createSdCardWal`, write-completion mutations — can append new WALs to the
live array. The wholesale reassignment silently dropped any WAL appended in that
window, so a recording started while a sync was in flight was lost (its on-disk
`.bin` orphaned, never uploaded), and `saveWals()` made the loss permanent. This
fires on the normal job-completion path, not a rare edge.

Fix: merge reconcile's id-keyed transitions back onto the live array via a new pure
`WALCloudSyncLogic.mergeReconciledUploads(live:snapshot:reconciled:)`. It applies
only the fields reconcile owns (`status`, `jobId`, `uploadedAt`), only when they
actually changed, matched by id — preserving WALs appended during the awaits and
not clobbering concurrent updates to entries reconcile left alone. Passing
`&self.wals` directly was rejected: a long-lived inout across the await risks a
main-actor exclusivity trap on reentrant access.

Root cause: a snapshot-then-overwrite across a suspension point on a mutable
main-actor collection. Durable guard: the merge policy is a pure function with
regression tests for the appended-WAL survival case, the untouched-entry
no-clobber case, and the no-op case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
@eulicesl
eulicesl requested a review from Copilot July 12, 2026 01:55
@eulicesl
eulicesl marked this pull request as ready for review July 12, 2026 01:55
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…Status.memory

The appended-WAL regression test used `status: .memory`, but `.memory` is a
WALStorageType case, not a WALStatus. A freshly created (not-yet-uploaded)
recording is `.inProgress`. Compile-only fix to the new test; no production change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fix-focused macOS “bug sweep” PR addressing multiple correctness, crash, and lifecycle issues in the desktop audio, Rewind capture, realtime hub socket handling, and WAL cloud sync logic, with targeted regression tests added where hermetic seams exist.

Changes:

  • Prevent Rewind video chunks from being discarded by restoring strictly-increasing frame presentation timestamps.
  • Harden Bee AAC decoding against malformed/truncated ADTS frames and fix system-audio converter input to mono to avoid ~6 dB attenuation.
  • Prevent WAL cloud-sync from dropping WALs appended during reconcile awaits, and stop leaking hub keepalive timers on server-initiated websocket close.

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated no comments.

Show a summary per file
File Description
desktop/macos/e2e/flows/ptt-lifecycle.yaml Adds RawWebSocket to e2e flow coverage mapping for the PTT lifecycle.
desktop/macos/e2e/flows/audio-recording.yaml Adds AudioCodecDecoder.swift to e2e flow coverage mapping for audio recording.
desktop/macos/Desktop/Tests/WALCloudSyncLogicTests.swift Adds regression tests validating WAL merge behavior preserves concurrently-appended WALs and avoids clobbering unrelated updates.
desktop/macos/Desktop/Tests/VideoChunkEncoderPresentationTimeTests.swift New tests pin monotonic PTS behavior for VideoChunkEncoder frame presentation time calculation.
desktop/macos/Desktop/Tests/SystemAudioConverterFormatTests.swift New test asserting system-audio converter input format is always mono.
desktop/macos/Desktop/Tests/AACAudioDecoderFrameLengthTests.swift New tests ensuring malformed ADTS frame lengths and non-zero-startIndex Data slices are handled safely (no traps).
desktop/macos/Desktop/Sources/WAL/WALService.swift Uses a pre-await snapshot and merges reconciled status transitions back onto the live WAL array to avoid dropping concurrently-added WALs.
desktop/macos/Desktop/Sources/WAL/WALCloudSyncLogic.swift Introduces id-keyed mergeReconciledUploads that applies only reconcile-owned fields without clobbering live state.
desktop/macos/Desktop/Sources/SystemAudioCaptureService.swift Centralizes converter input format creation to enforce mono input consistent with the downmix path.
desktop/macos/Desktop/Sources/Rewind/Core/VideoChunkEncoder.swift Extracts/test-seams the PTS calculation and fixes the stale “- 1” offset that caused PTS collisions.
desktop/macos/Desktop/Sources/FloatingControlBar/RawWebSocket.swift Cancels keepalive DispatchSourceTimer on server close frames and adds a deinit backstop to prevent timer leaks.
desktop/macos/Desktop/Sources/Audio/AudioCodecDecoder.swift Adds a slice-safe ADTS payload-range parser and uses it in AAC decoding to avoid Range traps on malformed frames.
desktop/macos/changelog/unreleased/20260712-wal-sync-recording-dropped.json Changelog entry for WAL sync data-loss fix.
desktop/macos/changelog/unreleased/20260712-system-audio-transcription-level.json Changelog entry for system-audio level fix.
desktop/macos/changelog/unreleased/20260712-rewind-video-capture-restored.json Changelog entry for Rewind video capture restoration.
desktop/macos/changelog/unreleased/20260712-realtime-hub-timer-leak.json Changelog entry for realtime hub timer leak fix.
desktop/macos/changelog/unreleased/20260712-bee-audio-crash-guard.json Changelog entry for Bee malformed-frame crash guard.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

`SystemAudioCaptureService` is `@available(macOS 14.4, *)`, so the new format
test must carry the same availability annotation (as FailLoudConfigTests does).
Compile-only fix to the new test; no production change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
@eulicesl
eulicesl merged commit 02516d9 into main Jul 12, 2026
21 checks passed
@eulicesl
eulicesl deleted the claude/macos-bug-fixes-testing-i8z7cm branch July 12, 2026 02:23
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.

3 participants