Repository navigation
Description
Summary
Finish the macOS chat/PTT/agent migration as one atomic convergence refactor. The system now has the right canonical nouns—kernel sessions/runs/attempts, a shared chat timeline, a typed voice turn, generated tool capabilities, and projection-only UI stores—but several legacy components can still perform the canonical verbs independently: route intent, transition a voice turn, authorize tools, persist turns, assemble context, and choose providers.
This issue removes those parallel authorities instead of adding another compatibility layer.
The implementation should land as one reviewed PR with small internal commits and feature-complete tests. Intermediate commits may preserve buildability, but the merged result must contain the new owners and delete the superseded paths in the same PR. Do not land preparatory abstractions, dual-write stages, dormant fallbacks, or “temporary” compatibility shims separately.
High-level observation
Omi has largely centralized its domain objects without fully centralizing mutations of those objects.
That produces an architecture that looks canonical in diagrams while remaining plural at runtime:
- the kernel owns an agent run, but Swift foreground request lifetime can still decide whether its tool call is trusted;
VoiceTurnCoordinatormodels the voice turn, whilePushToTalkManagerandRealtimeHubControllerretain overlapping logical turn state;ChatProvider.messagesis the shared visible timeline, while kernel recording, optimistic staging, backend saves/polling, and pill completion still participate in turn durability;- generated capabilities exist, while individual surfaces still carry semantic routing and tool-use instructions;
- sessions have adapter bindings, while UI preferences and bridge modes still participate in provider selection.
Most of these paths had good short-term reasons: incremental migration, low-latency UI, process-driver differences, and incident recovery. The failure was not preserving them initially; it was preserving them without an enforced exit. Locally safe fixes accumulated into globally fragile protocols.
The governing rule for this refactor is:
For every canonical model, define one exclusive mutation API, migrate every caller, and delete every alternative mutation path before merge.
Derived projections, physical drivers, and caches may remain. They must not authorize, transition, route, or durably persist canonical state.
Why now
A voice-created background agent can currently be known to the kernel, associated with a live run, correctly correlated through the adapter, and still have get_memories rejected by Swift as unrouted_tool_call. The July 10 direct-worker relay fix retained run correlation inside the Node control plane, but Swift continues to authorize tool calls only through AgentRuntimeProcess.activeRequests, which is populated by foreground query() calls—not direct-control-created child runs.
This is representative rather than isolated: the same authority split appears in voice lifecycle, delegation routing, context freshness, persistence, and provider selection. Patching the individual memory edge case would perpetuate the pattern.
Locked target architecture
Surfaces (main chat / floating chat / PTT / pills)
|
| user intent + presentation events
v
omi-agentd kernel
- owns session/run/attempt identity and lifecycle
- owns intent/delegation decision
- owns tool authorization by run capability
- owns the canonical turn journal + sync outbox
- owns immutable session execution profile
- publishes ordered events and versioned context snapshots
|
+--> adapter drivers (pi-mono / ACP / Hermes / OpenClaw)
+--> capability executors (Swift-local tools where required)
+--> backend turn sync
|
v
Swift projections and physical drivers
- ChatProvider renders journal projection
- VoiceTurnCoordinator is the sole voice-turn reducer
- PushToTalkManager owns microphone capture only
- RealtimeHubController owns provider socket/audio transport only
- Floating UI owns presentation only
Scope and required end state
1. Make VoiceTurnCoordinator the sole logical voice-turn owner
The typed reducer already models turn ID, capture ID, session/response/tool IDs, phase, route, deadlines, output lease, terminal reason, and UI projection. Complete that migration.
Required changes:
- Move all logical turn transitions into
VoiceTurnReducerevents/effects. - Make
PushToTalkManageran input driver: start/stop capture, emit capture/transcription facts, execute reducer effects. - Make
RealtimeHubControllera provider driver: maintain socket/provider physical state, emit provider/tool/playback facts, execute reducer effects. - Represent reconnect, deferred commit, barge-in replacement, pending tools, playback drain, and turn-recorded status in the canonical turn model when they affect logical completion.
- Render floating-bar voice UI exclusively from
VoiceTurnUIProjection. - Keep physical driver state only where it describes hardware/socket reality and cannot claim logical turn ownership.
Delete before merge:
PushToTalkManager.PTTStateand equivalent logical busy/listening authority.- controller-local logical turn booleans such as
turnRecorded,pendingInputTurnInterrupting, and independent pending-turn structures once represented by reducer state. - controller paths that directly clear or mutate floating voice presentation outside the presenter.
- duplicate timers/deadlines outside
VoiceTurnCoordinatorfor canonical turn transitions.
2. Collapse semantic routing into one kernel decision
Introduce one typed kernel route contract:
routeIntent({
intent,
surface,
activeSessionId,
activeRunId,
providerAvailability,
allowedCapabilities
}) ->
| answer_inline
| spawn_agent
| continue_run
| clarify
| rejectRequired changes:
- Use the same route contract for main chat, typed floating chat, and realtime/PTT.
- Surface models may propose a route/tool call; the kernel validates and resolves it through this contract before side effects.
- Keep only deterministic parsing at the surface: explicit provider name, explicit agent count, direct references/handles, and syntactic negation.
- Keep provider availability and leaf/coordinator policy in the kernel, not prompt-specific surface branches.
- Preserve voice-specific acknowledgement wording as presentation policy after the route decision.
Delete before merge:
- semantic model routing in
AgentPillsManager.classify. - the parallel semantic decision in
AgentDelegationResolverif its behavior is subsumed by kernelrouteIntent. - duplicated spawn/clarify semantic rules in realtime instructions and chat prompts; prompts should describe capabilities, not implement policy.
- surface-local exceptions that can disagree about whether to spawn, continue, clarify, or answer inline.
3. Authorize and execute tools by active kernel run
Replace foreground-request-derived trust with a run-scoped capability contract:
invokeTool(runId, attemptId, toolName, arguments)
Required changes:
- The kernel validates that the run/attempt is current and non-terminal.
- The kernel validates execution role, owner, grants, and tool manifest policy.
- Swift registers a bounded run capability for Swift-local tools and executes through one canonical executor entry point.
- Capability registration/revocation is explicit and tied to run/attempt lifecycle events.
- Request/client IDs remain tracing and transport correlation fields; they are not authorization.
- Unknown, superseded, cancelled, terminal, wrong-owner, and disallowed-role calls fail closed.
- Tool results return through the same run/attempt channel for foreground and background work.
Delete before merge:
activeRequestsas a tool-authorization source.- direct-worker request-lifetime preservation and inferred external request authority.
- authorization based on “exactly one active adapter request.”
- mutable context-file fields whose sole purpose was to impersonate a foreground request. If a context file remains necessary for MCP transport, it carries the run capability reference only.
- separate foreground versus direct-control tool-execution policies.
4. Make the kernel turn journal the single durable chat write path
Every main-chat-visible turn must first be a canonical kernel turn with one stable ID and typed content blocks.
Required changes:
- Record human, assistant, tool, notification, voice, agent-spawn, and agent-completion turns through one journal API.
- Journal insertion immediately publishes a pending projection for low latency.
- A kernel outbox synchronizes journal turns to the backend and records delivery state/remote ID.
- Backend reconciliation imports only genuinely remote turns and deduplicates by canonical turn ID.
ChatProviderbecomes a projection/cache of journal state, not a parallel persistence orchestrator.- Agent completion is an ordinary typed content block on the producing turn.
- Preserve resources on the producing message and all existing INV-6 continuity requirements.
Delete before merge:
- direct surface calls to
APIClient.saveMessagefor chat turns. - save-versus-poll suppression machinery that exists only because two writers race.
- special
pill_completionpersistence/projection branches and free-text reconstruction as a write path. Legacy bracket formats may remain read-only only if existing persisted data requires them. pendingSurfaceTurnsonce journal pending state replaces it.- independent cross-surface writes; surfaces project the same journal event.
5. Build one versioned context snapshot and render it per adapter/surface
Introduce a structured snapshot:
ContextSnapshot {
version,
owner,
recentTurns,
memories,
tasks,
screenContext,
activeAgentRuns,
capabilities
}
Required changes:
- One service determines content selection and freshness.
- Main chat, floating chat, voice, and leaf workers consume the same snapshot version.
- Small renderers apply surface/adapter presentation policy: voice brevity, leaf boundary, tool syntax, model format.
- Realtime warm-session refresh compares snapshot version/capability version, not assembled prompt strings.
- Context availability and omission reasons are observable without logging raw content.
Delete before merge:
- independent content-selection paths for main, floating, realtime seed, and worker contexts.
- string-based freshness inference.
- duplicated semantic capability instructions whose policy is enforced by the manifest/router.
- reconnect logic whose only trigger is opaque prompt-string drift.
6. Make provider/model selection an immutable session execution profile
Define:
SessionExecutionProfile {
adapterId,
credentialScope,
modelProfile,
executionRole
}
Required changes:
- Persist the profile on session creation and use it for every run unless an explicit, audited migration creates a new binding generation.
- UI preferences select the profile for the next session; they do not silently mutate an active session.
- Background children receive an explicit profile derived under kernel policy.
- Realtime provider selection remains separate only where it describes the voice transport itself; delegated agent provider selection still flows through the kernel profile.
Delete before merge:
- mutable bridge/harness mode as independent runtime authority.
- provider overrides whose semantics differ by surface.
- repeated
BridgeMode -> harnessMode -> adapterIddecisions after session creation. - fallback provider selection outside the canonical policy boundary.
Canonical ownership matrix after the refactor
| Concern | Exclusive owner | Allowed projections/drivers |
|---|---|---|
| Agent session/run/attempt lifecycle | AgentRuntimeKernel |
status stores, pills, chat cards |
| Intent/delegation resolution | kernel route service | surface syntax extraction and wording |
| Tool authorization | kernel run capability broker | Swift/Node tool executors |
| Chat turn durability | kernel turn journal/outbox | ChatProvider, floating viewport, backend mirror |
| Voice logical lifecycle | VoiceTurnCoordinator reducer |
capture, realtime, playback drivers |
| Context contents/freshness | context snapshot service | surface/adapter renderers |
| Provider/model binding | session execution profile | UI preference for future sessions |
Any mutable state outside this table must be documented as physical driver state, a derived projection, or a bounded cache with a deterministic rebuild source.
Execution strategy: one atomic convergence PR
Use one feature branch and one PR. Internal commits should be independently reviewable but are not intended to merge separately:
- Characterization tests and observability
- Add end-to-end behavioral tests for current supported flows and the known direct-spawn memory failure.
- Add counters/traces for legacy-path use so the PR can demonstrate zero use before deletion.
- Introduce canonical APIs behind existing behavior
- Add route contract, run tool broker, turn journal/outbox, context snapshot, and execution profile.
- Do not add long-lived fallback branches; adapters may exist only inside this PR while callers migrate.
- Migrate every caller by domain
- Typed chat, floating chat, PTT, direct voice spawn, agent follow-up, notifications, task chat, cancellation, restart, provider selection.
- Delete old authorities
- Remove the inventory above, not merely disable it.
- Delete obsolete tests and replace them with behavioral contract tests.
- Run the full named-bundle gauntlet and inspect zero-legacy telemetry.
- Merge only when deletion and behavioral gates are green.
If the work becomes too large for one reviewable PR, reduce scope by removing an entire domain from both implementation and issue—not by landing half of a domain with dual authorities. The six domains are coupled, but tool routing + routing + voice ownership are the minimum coherent set; turn journal/context/provider collapse may be split only through an explicitly revised architecture issue with no new compatibility seam left behind.
Required behavioral acceptance matrix
All tests must exercise production behavior through controllable seams. Source-string assertions may enforce forbidden patterns, but do not count as behavioral coverage.
Chat and continuity
- Main typed turn appears once immediately and once after backend acknowledgement—same message identity, no duplicate.
- Floating typed turn appears in main and floating projections from one journal entry.
- Backend-imported remote turn appears once.
- Agent spawn and completion retain structured identity across restart.
- Artifacts remain attached to the producing message.
- Polling/reconciliation cannot duplicate a locally originated turn.
PTT/realtime
- Cold start, warm start, deferred commit, reconnect, and playback drain reach exactly one terminal reason.
- Barge-in cancels/supersedes the correct response and cannot terminate the replacement turn.
- Stale capture/provider/tool/playback callbacks are ignored by turn ID.
- Direct memory read answers inline when policy permits.
- Explicit voice delegation creates exactly one child and records exactly one acknowledgement/completion.
- UI projection returns to idle after success, cancellation, provider failure, and timeout.
Agents and tools
- Typed-chat spawn -> leaf
get_memoriessucceeds. - Realtime direct-control spawn -> leaf calls
get_memoriestwice -> both succeed. - Follow-up run in the same child session can call tools.
- Terminal/cancelled/superseded attempt replay is rejected.
- Wrong-owner and leaf-restricted control calls are rejected.
- Runtime restart restores durable sessions but does not revive terminal capabilities.
- Hermes/OpenClaw/local provider profiles remain pinned and do not silently fall back to managed/default routing.
Context
- Main chat, realtime, and spawned leaf receive the same snapshot version for the same logical moment.
- Surface renderers differ only by declared policy.
- Snapshot version changes trigger one controlled realtime refresh; unchanged versions do not reconnect.
- Missing memory/screen/task sources are explicit metadata outcomes, not silent prompt omissions.
Mechanical deletion/guard tests
Add CI checks that fail if the merged tree reintroduces:
- tool authorization through
activeRequests; - semantic use of
AgentPillsManager.classifyor a second delegation resolver; - logical
PTTStateoutside the reducer; - direct chat-turn
saveMessagecalls outside the journal sync adapter; - new
pill_completionwrite branches or free-text agent identity formats; - active-session provider mutation through UI bridge mode;
- context freshness based on full prompt-string comparison;
- compatibility code without
owner,removal_condition, andremove_bymetadata.
Ratchet counts to zero; do not establish a nonzero baseline.
Verification requirements
cd desktop/macos && ./scripts/agent-logic-harness.sh- Focused Swift tests for voice reducer/coordinator, continuity, runtime routing, provider profiles, and context snapshots.
- Full
desktop/macos/agentNode suite, including real JSONL/MCP-to-Swift relay integration tests. - Clean debug build and clean release compile where cross-file signatures change.
- Named bundle only, never production:
cd desktop/macos
OMI_APP_NAME=omi-chat-ptt-convergence OMI_SKIP_TUNNEL=1 ./run.sh
./scripts/agent-continuity-gauntlet.sh --suite all --bundle-id com.omi.omi-chat-ptt-convergence
./scripts/check-gauntlet-evidence-at-head.sh- Exercise the exact voice request: “Have an agent look through my memories today and surface one surprising insight.” Verify successful memory tool results, one child run, one completion, and no
unrouted_tool_call. - Inspect logs/telemetry for zero legacy-path invocations and zero malformed JSONL frames.
- Run
scripts/pr-preflight --pr-body-file ...with every matched invariant ID.
Definition of done
- Each concern in the ownership matrix has exactly one mutation owner.
- All acceptance-matrix flows pass behaviorally.
- Named-bundle all-suite gauntlet passes at the PR HEAD.
- Known direct-spawn memory reproduction succeeds twice in the same worker.
- Legacy-path telemetry is zero during the full gauntlet.
- Every listed obsolete path is deleted, not deprecated or bypassed.
- Forbidden-pattern ratchets are zero.
- No new compatibility flag, dual write, fallback router, second store, or parallel lifecycle authority remains.
- Docs and locked invariants describe the final architecture, not migration phases.
- PR body records root cause, recurrence evidence, durable guard, real-path evidence, and rollback plan.
- Independent architecture review confirms the implementation removed more routing/state concepts than it introduced.
Non-goals
- Rewriting
omi-agentdin Rust. - Replacing provider adapters that already fit beneath the kernel.
- Removing optimistic UI; pending journal projection remains immediate.
- Moving every local Swift capability into Node. Swift may remain the executor while the kernel owns authorization.
- Combining long-term Omi memory with agent-session history.
- Redesigning chat or floating-bar visuals.
- Changing production provider/model policy beyond making existing policy canonical and session-bound.
Rollback strategy
Keep the refactor atomic at merge, but make rollback operationally simple:
- preserve schema forward/backward readability for one release window;
- do not destructively migrate existing chat or agent data;
- journal/outbox migration must be idempotent and restart-safe;
- rollback is a revert of the complete PR, not runtime switching between old and new authorities;
- do not ship a production feature flag that keeps both architectures live.
Relevant source areas
desktop/macos/Desktop/Sources/FloatingControlBar/VoiceTurnStateMachine.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/VoiceTurnCoordinator.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/PushToTalkManager.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/AgentPill.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/AgentDelegationResolver.swiftdesktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarWindow.swiftdesktop/macos/Desktop/Sources/Providers/ChatProvider.swiftdesktop/macos/Desktop/Sources/Providers/ChatToolExecutor.swiftdesktop/macos/Desktop/Sources/Chat/AgentRuntimeProcess.swiftdesktop/macos/Desktop/Sources/Chat/KernelTurnProjection.swiftdesktop/macos/Desktop/Sources/Chat/DesktopCoordinatorService.swiftdesktop/macos/agent/src/runtime/**desktop/macos/agent/src/index.tsdesktop/macos/pi-mono-extension/**docs/doc/developer/agent-control-plane.mdxdocs/product/invariants/agent-control-plane.md
Invariants likely affected
INV-AGENT-*agent identity, authority, lifecycle, provider boundary, and leaf-worker rules.INV-6shared chat continuity and single-write projection rules.- Any path-matched auth or brand invariants reported by
scripts/pr-preflight --suggest.
This issue should remain the canonical tracker for the convergence. Follow-up issues are for genuinely new product behavior, not deferred removal of architecture superseded here.
Activity
Git-on-my-level commentedon Jul 12, 2026
Two amendments to bake in before implementation starts. The atomic one-PR strategy stands; these make it survivable.
1. Ownership-matrix addition: task-chat turn persistence
Rewind/Core/TaskChatMessageStorage.swift:165has its ownsaveMessage— a third chat persistence path (SQLite task threads), parallel to bothChatProvider's backend saves and the kernel journal this issue introduces. If left undecided, it becomes the nextunrouted_tool_call-style seam the moment task chat and main chat interact.Decision required in domain 4, before the journal API is finalized — one of:
TaskChatMessageStoragebecomes a projection/cache.Task-thread turn durability | TaskChatMessageStorage | task chat UI), with a guard that main-chat turns can never be written there and vice versa.Either is acceptable; an undocumented third writer is not. The mechanical deletion/guard list should then also forbid new chat-turn writers outside the declared owners (not just
saveMessagecall sites).Note: #9519 (Rewind repository base refactor) touches the same file — coordinate so it doesn't churn
TaskChatMessageStoragewhile this decision is pending.2. Execution-strategy amendments (de-risking the atomic PR)
main. Step 1 of the execution strategy (behavioral tests + legacy-path telemetry counters) is not a compatibility seam — it's the safety net, and landing it before the branch means every concurrent fix onmainruns against it too, and shrinks the long-lived branch's drift surface. The convergence branch then starts from a tested baseline. (Same sequencing rule adopted by the backend sibling refactor(backend): converge conversation lifecycle onto a single mutation owner #9516.)Related
This issue's governing rule is now being applied elsewhere in the codebase; siblings for broader context: #9516 (backend conversation lifecycle), #9517 (LLM gateway migration exit criteria — cross-stack
SessionExecutionProfilealignment opportunity with domain 6), #9518 (notification dispatch), #9519 (Rewind storage plumbing), #9520 (ProactiveAssistants audit).Converge desktop agent, voice, and journal ownership (#9597)