Skip to content

[Desktop][PTT] Refactor voice turns into explicit state machines #9264

Closed

Description

@Git-on-my-level

Oracle prescription captured from omi-ptt-long-term-prescripti on 2026-07-08. Current PR #9248 adds the first voice-output lease slice; this issue tracks the larger follow-up refactor.

[Desktop][PTT] Long-term refactor: single voice-turn state machine, reducer, and effect boundaries

Background

The current desktop PTT / realtime voice path works, but it has grown into a set of overlapping implicit state machines spread across several objects:

  • PushToTalkManager owns shortcut UX, mic capture, warm-wait buffering, silence gating, omni/deepgram fallback, transcript routing, context capture, hints, automation hooks, and direct bar state mutation. It exposes only five public PTT states (idle, listening, pendingLockDecision, lockedListening, finalizing), but the real state space is much larger because it also tracks flags like isHubMode, isWaitingForHub, isOmniSTT, followUpPill, micCaptureGeneration, batchAudioBuffer, activeTracer, etc. See PushToTalkManager.swift:48-54, PushToTalkManager.swift:73-95, PushToTalkManager.swift:681-943, and PushToTalkManager.swift:1140-1552.

  • RealtimeHubController owns warm session lifecycle, session failover, PTT turn state, barge-in, local language ID, provider audio/text, selected-voice fallback, deterministic agent acks, tool execution, agent delegation, kernel persistence, response glow, and direct playback calls. Its per-turn state bag spans transcript, assistant text, screenshot, output suppression, language ID tasks, pending tool calls, reconnect state, playback state, and idempotency. See RealtimeHubController.swift:171-268, RealtimeHubController.swift:1013-1277, RealtimeHubController.swift:1340-1380, RealtimeHubController.swift:1405-1823, and RealtimeHubController.swift:1825-1907.

  • RealtimeHubSession is nominally a provider transport adapter, but it also embeds provider turn lifecycle details: OpenAI response-active state, Gemini activity windows, pending audio/video/commit, provider-specific tool call tracking, and finish-turn decisions. See RealtimeHubSession.swift:80-120, RealtimeHubSession.swift:325-389, RealtimeHubSession.swift:752-838, and RealtimeHubSession.swift:842-914.

  • FloatingBarVoicePlaybackService owns streaming TTS chunking, synthesis queueing, filler, one-shots, background-agent kickoff audio, playback generations, isSpeaking, and it directly mutates floating-bar glow state. See FloatingBarVoicePlaybackService.swift:47-86, FloatingBarVoicePlaybackService.swift:354-422, and FloatingBarVoicePlaybackService.swift:550-560.

The current PR introduces a useful first slice: PTTVoiceOutputCoordinator, which makes native realtime PCM, selected-voice fallback, and deterministic agent ack compete for a turn-scoped voice lease. That should remain, but it is still local to the hub controller and does not yet make PTT state ownership globally explicit. See PTTVoiceOutputCoordinator.swift:28-33.

The long-term problem to solve is not one more guard. It is that several objects can currently believe they own the same turn, the same output lane, or the same UI phase. That makes silent turns, no-response hangs, stale callbacks, and voice overlap too easy to reintroduce. The stress taxonomy already names the kinds of regressions we need to make structurally impossible: response_already_running, voice_output_overlap, realtime_no_response_timeout, deferred_commit_timeout, barge_in_replacement_timeout, and stale_provider_audio_after_interrupt. See DesktopStressDiagnostics.swift:21-35.

Goal

Build a single authoritative PTT / voice-turn state model with explicit events, explicit effects, turn-scoped IDs, and a derived UI projection.

The desired end state:

  1. PushToTalkManager becomes an input adapter, not the owner of capture, route, hub, fallback, playback, and UI state.
  2. RealtimeHubController becomes a realtime session runtime, not the owner of the whole PTT turn.
  3. RealtimeHubSession remains a provider transport normalizer, not a policy engine.
  4. FloatingBarVoicePlaybackService becomes a playback engine, not a PTT state participant or bar-state mutator.
  5. One reducer owns the voice-turn lifecycle.
  6. Every async callback carries a turnID, captureID, sessionID, responseID, toolCallID, or leaseID sufficient to reject stale work deterministically.
  7. Every PTT turn terminates exactly once with a typed terminal reason.
  8. Only one audible PTT output lane can be active at a time, across native provider audio, selected-voice fallback, deterministic agent ack, filler, and one-shot playback.

This is a long-term refactor issue, not work to include in the current PR.

Proposed architecture

1. Add a single PTTOrchestrator

Introduce a new owner for voice-turn state:

@MainActor
final class PTTOrchestrator {
  private var model: PTTModel
  private let reducer: PTTReducer
  private let effects: PTTEffectRunner

  func send(_ event: PTTEvent) {
    let result = reducer.reduce(model, event)
    model = result.model
    effects.run(result.effects, snapshot: model.snapshot)
  }
}

The orchestrator is the only object allowed to decide:

  • whether a turn exists;
  • which route owns the turn;
  • whether the turn is recording, finalizing, awaiting provider response, awaiting tool results, playing, cancelled, or terminal;
  • whether a hub commit is legal;
  • whether fallback should happen;
  • whether output can start;
  • whether the bar should display listening, thinking, hint, response glow, transcript, or idle.

2. Use a pure reducer for state transitions

The reducer should be pure and testable. It should not call singletons, mutate FloatingControlBarState, start audio capture, send websocket messages, play audio, or write diagnostics directly.

Shape:

struct PTTModel: Equatable {
  var phase: PTTPhase
  var hub: HubRuntimeSnapshot
  var capture: CaptureSnapshot
  var playback: VoiceOutputSnapshot
  var ui: PTTUIProjection
  var diagnostics: TurnDiagnostics?
}

enum PTTEvent: Equatable {
  case shortcutDown(timestamp: TimeInterval)
  case shortcutUp(timestamp: TimeInterval)
  case lockDecisionExpired(turnID: TurnID)

  case permissionResolved(granted: Bool)
  case captureStarted(turnID: TurnID, captureID: CaptureID, device: String)
  case captureFailed(turnID: TurnID, captureID: CaptureID, error: String)
  case audioChunkBuffered(turnID: TurnID, captureID: CaptureID, stats: AudioStats)
  case silentMicDetected(turnID: TurnID, captureID: CaptureID, detection: SilentMicDetection)

  case contextCaptured(turnID: TurnID, snapshot: PTTContextSnapshot)
  case hubWarmStateChanged(HubRuntimeSnapshot)
  case hubTurnBegan(turnID: TurnID, sessionID: SessionID)
  case hubCommitAccepted(turnID: TurnID, sessionID: SessionID)
  case hubCommitDeferred(turnID: TurnID, reason: DeferredCommitReason)
  case hubCommitRejected(turnID: TurnID, reason: HubRejectReason)

  case transcriptionPartial(turnID: TurnID, text: String)
  case transcriptionFinal(turnID: TurnID, text: String)
  case transcriptionFailed(turnID: TurnID, error: String)

  case providerInputTranscript(turnID: TurnID, sessionID: SessionID, text: String, final: Bool)
  case providerAudio(turnID: TurnID, sessionID: SessionID, pcm24k: Data)
  case providerText(turnID: TurnID, sessionID: SessionID, text: String, final: Bool)
  case providerToolCall(turnID: TurnID, sessionID: SessionID, call: RealtimeToolCall)
  case providerTurnDone(turnID: TurnID, sessionID: SessionID)
  case providerError(turnID: TurnID?, sessionID: SessionID, error: ProviderError)

  case toolResult(turnID: TurnID, callID: ToolCallID, result: String)
  case playbackStarted(turnID: TurnID, leaseID: LeaseID)
  case playbackDrained(turnID: TurnID, leaseID: LeaseID)
  case playbackFailed(turnID: TurnID, leaseID: LeaseID, error: String)

  case timerFired(turnID: TurnID, timer: PTTTimer)
  case cancel(reason: CancelReason)
  case cleanup
}

Reducer output:

struct PTTReduction {
  var model: PTTModel
  var effects: [PTTEffect]
}

enum PTTEffect: Equatable {
  case requestMicPermission
  case startCapture(turnID: TurnID, captureID: CaptureID, mode: CaptureMode)
  case stopCapture(captureID: CaptureID)
  case rebuildCapture(reason: String)

  case prefetchContext(turnID: TurnID)
  case warmHub
  case beginHubTurn(turnID: TurnID, interrupting: Bool)
  case feedHubAudio(turnID: TurnID, sessionID: SessionID?, audioRef: AudioBufferRef)
  case commitHubTurn(turnID: TurnID, sessionID: SessionID)
  case cancelHubTurn(turnID: TurnID)

  case startOmniSTT(turnID: TurnID)
  case transcribeBatch(turnID: TurnID, audioRef: AudioBufferRef, reason: BatchReason)
  case sendFloatingBarQuery(turnID: TurnID, text: String, followUp: Bool)
  case sendAgentFollowUp(turnID: TurnID, pillID: UUID, text: String)

  case executeTool(turnID: TurnID, call: RealtimeToolCall)
  case recordKernelTurn(turnID: TurnID, userText: String, assistantText: String, interrupted: Bool, idempotencyKey: String)

  case acquireVoiceLease(turnID: TurnID, lane: VoiceOutputLane, reason: String)
  case playNativePCM(turnID: TurnID, leaseID: LeaseID, pcm24k: Data)
  case playSelectedVoice(turnID: TurnID, leaseID: LeaseID, text: String)
  case playDeterministicAck(turnID: TurnID, leaseID: LeaseID, ack: DeterministicAck)
  case stopPlayback(scope: PlaybackStopScope)

  case scheduleTimer(turnID: TurnID, timer: PTTTimer, deadline: Deadline)
  case cancelTimer(turnID: TurnID, timer: PTTTimer)
  case updateUIPresentation(PTTUIProjection)
  case emitDiagnostic(PTTDiagnosticEvent)
}

3. Represent the real state space, not just five top-level states

The current five-state PushToTalkManager.PTTState is too small for the actual behavior. Replace it with typed phases that encode route, ownership, and legal next events.

Suggested model:

enum PTTPhase: Equatable {
  case idle

  case pendingLockDecision(PendingLockTurn)
  case recording(RecordingTurn)

  case finalizing(FinalizingTurn)

  case awaitingResponse(AwaitingResponseTurn)
  case awaitingTools(AwaitingToolsTurn)
  case playing(PlayingTurn)

  case terminal(TerminalTurn)
}

enum PTTRoute: Equatable {
  case hub(sessionID: SessionID)
  case hubWarmWait(deadline: Deadline)
  case omniSTT
  case deepgramBatch(reason: BatchReason)
  case deepgramLive
  case agentFollowUp(pillID: UUID)
}

enum VoiceOutputLane: Equatable {
  case nativeRealtime
  case selectedVoiceFallback
  case deterministicAgentAck
  case filler
  case none
}

Important: audio buffers should not be copied through the reducer on every chunk. Use a sidecar TurnAudioStore keyed by turnID / captureID, and let the reducer receive throttled stats and milestones. The hot CoreAudio path should remain fast.

4. Split long-lived hub session state from per-turn state

The warm realtime session is not the PTT turn. Model them separately.

enum HubSessionPhase: Equatable {
  case unavailable(reason: HubUnavailableReason?)
  case warming(provider: RealtimeHubProvider, authMode: CredentialAuthMode, attempt: Int)
  case warm(sessionID: SessionID, provider: RealtimeHubProvider)
  case replacingForBargeIn(oldSessionID: SessionID, pendingTurnID: TurnID)
  case failed(provider: RealtimeHubProvider, reason: ProviderFailureClass)
}

Rules:

  • HubSessionPhase.warm means the session is connected and authenticated.
  • PTT may select .hub only when the hub is warm or within an explicit warm-wait grace window.
  • A warm session can reconnect while idle.
  • A warm session cannot be torn down by settings changes or system wake while it owns an active turn.
  • Barge-in replacement is a first-class hub phase, not a loose combination of pendingBargeInReplacement, pendingBargeInProvider, pendingBargeInAuth, bargeInContinuityTask, responding, and realtimePlaybackActive.

5. Promote voice output leasing to a shared service

PTTVoiceOutputCoordinator is the right idea. Promote it from a controller-local helper into the authoritative VoiceOutputCoordinator for all PTT audible paths.

Current lanes:

  • native realtime PCM;
  • selected app voice fallback;
  • deterministic agent ack.

Add long-term lanes / scopes:

  • filler;
  • voice sample;
  • non-PTT chat response;
  • PTT selected-voice fallback;
  • PTT deterministic one-shot.

Required behavior:

actor VoiceOutputCoordinator {
  func beginTurn(_ turnID: TurnID)
  func acquire(_ lane: VoiceOutputLane, turnID: TurnID, policy: VoiceLeasePolicy) -> VoiceLeaseDecision
  func release(_ leaseID: LeaseID)
  func suppressProviderOutput(turnID: TurnID, reason: String)
  func endTurn(_ turnID: TurnID)
}

The playback service should accept commands with a lease:

struct VoicePlaybackCommand {
  let turnID: TurnID?
  let leaseID: LeaseID?
  let payload: VoicePlaybackPayload
  let onDrain: PlaybackDrainPolicy
}

No playback path should be able to start audible PTT output without a lease. This includes fallback text in hubDidEmitText, deterministic setup-needed messages, background-agent kickoff phrases, filler, and AVSpeech fallback after cloud TTS failure.

6. Make UI a projection, not shared mutable state

Create a PTTBarPresenter that is the only layer allowed to write to FloatingControlBarState.

Current direct mutations are spread across PushToTalkManager, RealtimeHubController, and FloatingBarVoicePlaybackService. Examples include listening state, locked state, hints, thinking, voice transcript, response glow, and resize behavior.

Desired flow:

PTTModel + PlaybackSnapshot
  → PTTUIProjection
  → PTTBarPresenter.apply(projection)
  → FloatingControlBarState / FloatingControlBarManager

Projection fields:

struct PTTUIProjection: Equatable {
  var isVoiceListening: Bool
  var isVoiceLocked: Bool
  var isVoiceFollowUp: Bool
  var voiceTranscript: String
  var pttHintText: String
  var isThinking: Bool
  var isVoiceResponseActive: Bool
  var shouldExpandForVoice: Bool
  var shouldCollapseAfterVoice: Bool
}

The presenter owns resize policy. The reducer owns semantic UI state. Playback engines and provider sessions do not mutate bar state directly.

Ownership after refactor

Component Owns Does not own
PushToTalkManager Keyboard shortcut events, automation entrypoints, setup/cleanup wiring Capture route, hub fallback, transcription decisions, playback, bar mutations
PTTOrchestrator Turn lifecycle, reducer, route selection, terminal reason, effects, UI projection Provider protocol parsing, actual audio IO, actual websocket IO
AudioCaptureRuntime Starting/stopping CoreAudio capture, device override, silent-mic callback, audio-level callback PTT route selection, finalization, UI
TurnAudioStore Bounded per-turn audio buffers and stats State transitions
RealtimeHubRuntime Warm session pool, token minting, reconnect/failover, provider availability snapshot PTT UI, tool execution policy, selected-voice playback
RealtimeHubSession Provider websocket send/receive normalization App tools, kernel persistence, bar state, playback
RealtimeToolExecutor Execute hub tool calls and return typed results Turn lifecycle, provider session lifecycle, playback arbitration
VoiceOutputCoordinator Turn-scoped audible-output ownership Actual audio playback
FloatingBarVoicePlaybackService TTS synthesis, AVAudioPlayer, AVSpeechSynthesizer, playback drain events PTT ownership, response glow, bar resize
PTTBarPresenter Applying PTTUIProjection to existing UI objects Business logic

Invariants to make impossible to violate

Turn ownership

  • There is at most one active PTT turn.
  • Every active turn has a stable TurnID.
  • Every async callback that can mutate PTT state carries TurnID and, when applicable, CaptureID, SessionID, ResponseID, ToolCallID, or LeaseID.
  • Stale callbacks are ignored by construction and emit a low-cardinality diagnostic.
  • A turn reaches exactly one terminal reason: success, silent rejected, too short, cancelled, provider fallback, provider error, transcription error, no-response timeout, deferred-commit timeout, barge-in replacement timeout, or cleanup.

Capture

  • Capture cannot be active while the turn is idle or terminal.
  • stopCapture is idempotent and keyed by CaptureID.
  • A capture-start completion for an old CaptureID cannot resurrect an ended turn.
  • Silent-mic recovery cannot leave both old and new captures running.
  • System audio mute is restored on every terminal path.

Route selection

  • A turn is owned by exactly one route: hub, hub warm-wait, omni STT, Deepgram batch/live fallback, or agent follow-up.
  • Hub warm-wait either transitions to hub commit or to transcription fallback by a deadline.
  • A hub commit cannot happen before the provider’s input/activity window is ready.
  • A deferred barge-in replacement commit either commits on the replacement session or terminates/falls back by a deadline.
  • Realtime hub unavailability never loses already captured audio.

Silence gating

  • Silent or too-short buffered turns are rejected before model commit or STT submission.
  • Silent hub turns call provider abandon/clear, not commit.
  • Silent turns produce visible user feedback when the turn was too short to capture usable audio.
  • Dead-mic recovery is driven by explicit diagnostics and cannot silently clear the user’s next real turn.

Provider/session

  • Provider events from detached or replaced sessions cannot affect the active turn.
  • OpenAI response events must match the current response ID.
  • Gemini audio/tool/turn-complete events must match a committed pending turn.
  • Settings changes and system wake can replace idle warm sessions, but cannot tear down an active turn without producing a terminal event.
  • Provider error handling cannot both fail over and continue using the failed session.

Tools

  • A provider turn cannot finish while tool results are pending.
  • Tool results are sent only for the turn epoch that requested them.
  • Stale tool results are dropped before side effects where possible, and always before provider send.
  • Deterministic agent ack audio is requested only after successful spawn.
  • Agent handoff persistence uses final user transcript, not a partial interim transcript.

Playback

  • At most one audible PTT lane owns output at a time.
  • Native realtime audio, selected voice fallback, deterministic agent ack, filler, and AVSpeech fallback all obey the same lease system.
  • Provider output suppressed by deterministic ack cannot later leak through as stale native audio or stale text fallback.
  • Playback drain releases exactly the active lease.
  • Barge-in stops prior local playback and prevents old playback-drain callbacks from clearing the new turn’s UI.

UI

  • The floating bar is a projection of state.
  • UI cannot be in impossible combinations like idle + isVoiceListening, terminal + isThinking, or provider output active + no active turn.
  • Bar resize happens in one presenter, not from both PTT and hub code.
  • Response glow is driven by playback / provider state events, not directly by arbitrary services.

Migration plan

Phase 0 — Baseline diagnostics and stress fixtures

No behavior changes.

Add a thin event logger around the current path:

  • turn_id
  • capture_id
  • session_id
  • response_id
  • lease_id
  • route
  • provider
  • terminal reason
  • commit result
  • fallback reason
  • playback lane
  • pending tool count
  • barge-in strategy
  • stale callback count

Extend desktop stress diagnostics to include structured details for:

  • no response after commit;
  • deferred commit timeout;
  • voice output overlap;
  • stale provider audio after interrupt;
  • response already running;
  • silent rejected;
  • too-short tap;
  • hub fallback.

Acceptance for Phase 0:

  • Existing behavior unchanged.
  • Stress output can reconstruct a full turn timeline.
  • Known failure families have explicit terminal reasons, not generic errors.
  • Current PTTVoiceOutputCoordinator decisions are logged with turn ID, lane, and active lane.

Phase 1 — Introduce typed IDs and protocol seams

Still minimal behavior change.

Add:

struct TurnID: Hashable, Sendable { let rawValue: UUID }
struct CaptureID: Hashable, Sendable { let rawValue: UInt64 }
struct SessionID: Hashable, Sendable { let rawValue: UUID }
struct LeaseID: Hashable, Sendable { let rawValue: UUID }
struct ToolCallID: Hashable, Sendable { let rawValue: String }

Wrap current singletons behind protocols:

  • AudioCaptureClient
  • RealtimeHubClient
  • TranscriptionClient
  • VoicePlaybackClient
  • VoiceOutputLeasing
  • RealtimeToolExecuting
  • PTTBarPresenting
  • PTTDiagnosticsSink
  • PTTClock

Acceptance for Phase 1:

  • Current code still orchestrates the turn, but every async callback is tagged.
  • Unit tests can fake capture, hub, transcription, playback, timers, and diagnostics.
  • No untagged callback can directly mutate PTT turn state.

Phase 2 — Extract audio buffer and silence-gate services

Move bounded buffering, audio stats, speech-like/VAD gates, and dead-mic policy out of PushToTalkManager.

Create:

final class TurnAudioStore {
  func begin(turnID: TurnID, captureID: CaptureID)
  func append(turnID: TurnID, captureID: CaptureID, pcm16k: Data) -> AudioAppendResult
  func snapshot(turnID: TurnID) -> TurnAudioSnapshot
  func clear(turnID: TurnID)
}

struct PTTSilenceGate {
  func evaluate(_ audio: TurnAudioSnapshot, route: PTTRoute) -> SilenceGateDecision
}

Acceptance for Phase 2:

  • Existing hub, omni, batch, and warm-wait fallback gates call one shared gate.
  • Too-short and silent decisions are table-tested.
  • Buffer cap warning remains once-per-turn and is keyed by turnID.
  • Dead-mic recovery tests cover repeated zero buffers, successful turn reset, and rebuild reset.

Phase 3 — Shadow reducer

Add PTTReducer and run it in shadow mode next to the existing implementation.

The reducer receives mirrored events but does not drive effects yet. Log divergence between current ad hoc state and reducer state.

Acceptance for Phase 3:

  • Reducer unit tests cover hold, quick tap, double-tap lock, locked finalize, cancel, cleanup, permission denied, too-short tap, voiced turn, silent turn, warm-wait ready, warm-wait timeout, hub commit rejected, omni fallback, and agent follow-up.
  • Shadow reducer reaches the same terminal classification as current code on stress runs.
  • No user-visible behavior changes.

Phase 4 — Move PushToTalkManager decisions into reducer-driven effects

Start letting PTTOrchestrator drive the existing services.

PushToTalkManager should only translate:

  • shortcut down/up;
  • automation begin/end;
  • pill follow-up begin/end/cancel;
  • setup/cleanup.

Into PTTEvents.

The orchestrator emits effects for:

  • mute/restore;
  • start/stop capture;
  • context capture;
  • hub warm wait;
  • transcription fallback;
  • send query;
  • show hint;
  • diagnostics.

Acceptance for Phase 4:

  • PushToTalkManager no longer has route flags like isHubMode, isWaitingForHub, isOmniSTT, or omniTurnSent.
  • PushToTalkManager no longer owns batchAudioBuffer.
  • PTT hold/lock/follow-up/automation behavior is preserved.
  • Silent and too-short behavior is preserved.
  • Warm hub unavailable path falls back without losing captured audio.

Phase 5 — Split realtime hub runtime from voice turn ownership

Refactor RealtimeHubController into smaller pieces:

  • RealtimeHubRuntime: warm sessions, auth/mint, reconnect/failover, provider availability.
  • RealtimeTurnAdapter: begin/feed/commit/cancel for a specific turnID and sessionID.
  • RealtimeProviderEventAdapter: converts session delegate callbacks into PTTEvents.
  • RealtimeToolExecutor: executes app tools and returns typed tool results.

RealtimeHubController may remain as a facade during migration, but it should stop owning PTT phases such as responding, audioReceivedThisTurn, turnRecorded, pendingVoiceAgentHandoff, pendingRealtimeToolCallIds, and playback state.

Acceptance for Phase 5:

  • Hub session lifecycle can be tested without PTT UI.
  • PTT turn lifecycle can be tested without real websocket sessions.
  • Barge-in replacement is explicit and deadline-bound.
  • OpenAI in-session cancel and Gemini fresh-session replacement are both tested.
  • Provider errors from detached sessions cannot affect the active turn.
  • response_already_running, deferred_commit_timeout, and barge_in_replacement_timeout are covered by deterministic tests.

Phase 6 — Promote voice output coordinator and refactor playback

Move from PTTVoiceOutputCoordinator to a shared VoiceOutputCoordinator.

Update all PTT audible paths to acquire a lease before playback:

  • native provider PCM;
  • selected voice fallback when provider produces text but no audio;
  • deterministic background-agent ack;
  • directed-provider setup-needed one-shot;
  • filler;
  • AVSpeech fallback after cloud TTS or AVAudioPlayer failure.

FloatingBarVoicePlaybackService should no longer mutate FloatingControlBarState or infer PTT state from isSpeaking. It should emit playback events:

enum VoicePlaybackEvent {
  case started(turnID: TurnID?, leaseID: LeaseID?)
  case drained(turnID: TurnID?, leaseID: LeaseID?)
  case failed(turnID: TurnID?, leaseID: LeaseID?, error: String)
}

Acceptance for Phase 6:

  • No PTT path can start audible output without a lease.
  • Stale playback-drain events cannot clear a newer turn’s glow.
  • Forced TTS playback failure still speaks fallback text, but under the same lease.
  • Stress runs report zero voice_output_overlap.
  • Existing non-PTT voice samples still work under a separate non-PTT scope.

Phase 7 — Move bar state to projection/presenter

Add PTTBarPresenter.

Remove direct bar mutations from:

  • PushToTalkManager;
  • RealtimeHubController;
  • FloatingBarVoicePlaybackService.

The reducer produces PTTUIProjection; the presenter applies it to the current FloatingControlBarState.

Acceptance for Phase 7:

  • Snapshot tests cover UI projections for idle, listening, locked, pending lock hint, too-short hint, transcribing, thinking, awaiting provider audio, native audio playing, selected fallback playing, deterministic ack playing, barge-in, error, and terminal.
  • Resize behavior is centralized.
  • FloatingBarVoicePlaybackService no longer calls clearVoiceResponseState() or writes isVoiceResponseActive.
  • The bar cannot remain expanded after a silent/cancel/error terminal unless the projection says it should.

Phase 8 — Flip from shadow to primary orchestrator

Use the orchestrator as the primary PTT implementation behind a feature flag.

Suggested gates:

  • internal dev flag;
  • canary / TestFlight flag;
  • per-route flag: hub first, fallback cascade second, agent follow-up third;
  • kill switch to current path until parity.

Acceptance for Phase 8:

  • All existing PTT behaviors work with the orchestrator enabled:

    • hold-to-talk;
    • double-tap lock;
    • locked finalize;
    • too-short hint;
    • silent rejection;
    • hub active path;
    • hub warm-wait path;
    • hub rejected commit fallback;
    • omni STT fallback;
    • Deepgram batch/live fallback;
    • agent pill voice follow-up;
    • automation beginPushToTalkForAutomation / endPushToTalkForAutomation;
    • barge-in;
    • background-agent spawn;
    • selected voice fallback;
    • provider audio playback.

Phase 9 — Delete legacy flags and collapse facades

After parity, remove old duplicated state fields and no-op shims.

Acceptance for Phase 9:

  • PushToTalkManager is mostly event translation.
  • RealtimeHubController no longer contains the giant mixed state bag for PTT turn, playback, tools, language ID, bar state, and persistence.
  • FloatingBarVoicePlaybackService is playback-only.
  • The issue can be closed when the acceptance criteria below pass.

Required tests

Reducer unit tests

Use a fake clock and deterministic effect runner.

Required cases:

  • idle → shortcutDown → recording;
  • recording → shortcutUp → finalizing;
  • quick tap → pending lock → timeout → finalizing;
  • quick tap → second tap → locked recording;
  • locked recording → tap → finalizing;
  • permission denied → terminal;
  • capture start completes after cancel → ignored;
  • audio arrives after finalize snapshot → ignored or only stats-safe;
  • too-short turn → hint → idle;
  • silent turn → reject → provider abandon/clear;
  • voiced hub turn → commit → awaiting response;
  • hub warm-wait ready before release;
  • hub warm-wait ready after release;
  • hub warm-wait timeout while still holding;
  • hub warm-wait timeout after release;
  • hub commit rejected → batch fallback;
  • omni error before release → keep capturing and fallback at finalize;
  • omni error after release → batch fallback now;
  • transcription final after timeout → stale ignored;
  • cleanup from every phase returns to idle and emits stop effects.

Audio/silence tests

  • Empty buffer.
  • Too-short non-empty buffer.
  • Quiet room noise.
  • Loud non-speech click/keyboard noise.
  • Sustained voiced speech.
  • Quiet speech caught by VAD fallback.
  • Dead mic consecutive zero turns triggers rebuild.
  • Successful voiced turn resets dead-mic counter.
  • Buffer cap produces one warning and bounded memory.

Hub runtime tests

  • Warm session success.
  • Token mint failure falls back without active turn loss.
  • Provider auth failure failover.
  • Provider quota failure failover.
  • Expected idle close rewarms without Sentry-class error.
  • System wake replaces idle warm session only.
  • Settings change does not tear down active turn.
  • OpenAI response-active guard prevents duplicate response creation.
  • Gemini activityStart/activityEnd ordering is valid.
  • Gemini abandoned turn cannot fire tools.
  • Session replacement for barge-in buffers audio and commit.
  • Replacement timeout terminates with typed reason.

Provider event tests

  • Stale session audio ignored.
  • Stale OpenAI response ID ignored.
  • Gemini turnComplete before pending tool results defers finish.
  • Tool result arrives after turn epoch changes → ignored.
  • Provider text final with no audio triggers selected-voice fallback only if lease acquired.
  • Provider audio after deterministic ack suppression is dropped.
  • Provider error during active response produces terminal reason and UI clears.

Playback tests

  • Lease acquire/release idempotency.
  • Same lane reacquire returns same lease or idempotent success.
  • Competing lane denied.
  • Stale turn lease denied.
  • Playback drain releases only matching lease.
  • Forced AVAudioPlayer failure falls back to system voice under same lease.
  • Barge-in stops old playback and prevents old drain callback from clearing new output.
  • Non-PTT voice sample does not steal PTT lease.

Tool / agent tests

  • spawn_agent ack plays only after successful spawn.
  • Spawn failure does not play kickoff.
  • Directed provider unavailable speaks setup-needed message only if lease acquired.
  • Pending tool calls keep turn open.
  • Tool result is not sent to stale session.
  • Agent handoff kernel record uses final transcript.
  • Interrupted turn is recorded once with idempotency key.

UI projection tests

Snapshot-test projections for:

  • idle;
  • listening hold;
  • pending lock decision;
  • locked listening;
  • too-short hint;
  • recording-too-long hint;
  • transcribing;
  • thinking after commit;
  • awaiting provider response;
  • native realtime playing;
  • selected voice fallback playing;
  • deterministic ack playing;
  • barge-in;
  • silent rejected;
  • provider error;
  • cleanup.

Stress / headless tests

Extend the existing desktop stress taxonomy.

Required release-gate scenarios:

  • ptt_voiced: repeated voiced turns complete.
  • ptt_silent: silent turns reject and return to idle.
  • chat_bridge: existing chat bridge still works.
  • subagent_launch: spawn success produces one acknowledgement and one pill.
  • Barge-in loop: user interrupts while native PCM is still draining.
  • Hub warm-wait loop: cold start, release before warm, warm timeout fallback.
  • Provider no-response loop: committed turn with no provider completion.
  • Deferred commit loop: Gemini replacement delayed beyond deadline.
  • Playback failure loop: force TTS playback failure and verify fallback is leased.
  • Wake/reconnect loop: idle close and system wake do not create a silent first turn.

Release gate should fail on any nonzero count of:

  • response_already_running
  • voice_output_overlap
  • realtime_no_response_timeout
  • deferred_commit_timeout
  • barge_in_replacement_timeout
  • stale_provider_audio_after_interrupt

Acceptance criteria for closing this issue

  • There is one authoritative PTT turn owner: PTTOrchestrator / reducer.

  • Every active turn has a TurnID.

  • Every terminal path emits exactly one terminal reason.

  • PushToTalkManager no longer owns route-selection flags or audio buffers.

  • RealtimeHubController / replacement runtime no longer owns selected-voice fallback, deterministic ack playback, bar UI state, or PTT terminal decisions.

  • RealtimeHubSession is a provider transport adapter with normalized events and no app-level tool/persistence/playback logic.

  • FloatingBarVoicePlaybackService does not mutate floating-bar PTT UI state directly.

  • All PTT audible output paths require a VoiceOutputCoordinator lease.

  • Stale provider, capture, transcription, tool, timer, and playback callbacks are rejected by ID.

  • Hub warm-wait, deferred commit, provider no-response, and barge-in replacement have explicit deadlines and typed terminal/fallback paths.

  • UI projection snapshot tests cover all common and failure phases.

  • Stress release gate passes with zero forbidden terminal reasons.

  • Latency remains comparable to the current implementation:

    • no new synchronous work on PTT key-down beyond event dispatch;
    • audio capture hot path does not route every chunk through heavy main-actor reducer work;
    • warm hub path remains snappy;
    • fallback path does not add avoidable waits.
  • Existing user-visible behavior is preserved unless separately approved:

    • hold/lock PTT;
    • too-short hint;
    • silent rejection;
    • hub realtime answer;
    • selected voice fallback;
    • voice follow-up to agent pills;
    • background-agent kickoff;
    • barge-in;
    • automation hooks.

Non-goals

  • Do not change provider models, provider selection, or BYOK / managed-token policy.
  • Do not remove the fallback cascade until the reducer-driven path has full parity.
  • Do not redesign the floating bar UI.
  • Do not tune VAD thresholds or speech recognition quality as part of this issue, except to preserve current behavior through extracted services.
  • Do not rewrite RawWebSocket or provider transport internals unless required for ID tagging.
  • Do not change tool semantics or agent delegation policy beyond extracting execution boundaries.
  • Do not add new product behavior such as new voice modes, new tools, or new agent providers.
  • Do not include this refactor in the current PR; the current PR’s lease coordinator is a stepping stone.

Risks / unknowns

  • The audio hot path cannot afford a naive reducer event per PCM chunk. Use a sidecar TurnAudioStore, aggregate stats, and keep provider feed on a fast path with turn/capture IDs.
  • Swift actor isolation may expose existing main-actor assumptions. The migration should add protocol seams before moving ownership.
  • Gemini and OpenAI have genuinely different turn contracts. The new model must preserve OpenAI in-session cancel and Gemini fresh-session replacement as explicit strategies, not abstract them away prematurely.
  • Provider no-response detection is subtle: server turn-done, local playback drain, pending tools, and selected fallback are different clocks.
  • Moving UI to projection may reveal implicit dependencies in the floating bar resize/glow code.
  • Tool side effects are high risk because some execute before provider result send. Stale-turn guards must happen before side effects wherever possible.
  • Kernel turn persistence and barge-in idempotency need careful migration to avoid duplicate or missing history.
  • Feature flags and shadow-mode diagnostics are necessary; a big-bang rewrite would be too risky.
  • Test fakes must model provider timing realistically enough to catch races, not just happy paths.

Activity

  1. added a commit that references this issue on Jul 10, 2026
    7572bcf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions