Repository navigation
perf(chat): reuse Anthropic context prefixes - #10422
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0430c0f09
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
CI triage update: the cache implementation checks pass, and the two red merge-gate suites are blocked by reproducible
I retried the backend failure once and it reproduced identically. I have not mixed either unrelated repair into this performance PR. |
c0430c0 to
784b356
Compare
784b356 to
a3f1dff
Compare
|
Addressed both review threads from the deterministic monitor pass. P1 — desktop context-snapshot (tombstone dropped turns): P2 — backend chat.py (cap reported over-fetch): Verification:
The Hermetic Backend E2E failure ( |
…over-fetch P1 (desktop context-snapshot): Fall back to a full re-render when the conversation's totalTurnCount decreases since the previous binding delivery. Hard-deleted turns (journal_clear_turns / clearJournalConversation) leave no tombstone in a delta, so the model would believe the cleared content still exists in the binding's history. Normal retention-window aging (turns dropping off as new turns arrive) does not trigger this because totalTurnCount only increases in that case. P2 (backend chat.py): Cap the raw Firestore over-fetch for reported (hidden) rows at CHAT_HISTORY_REPORTED_RAW_SCAN_CAP (50) instead of adding the lifetime reported count. A user with thousands of old reported messages would otherwise stream all of them on every chat send just to return at most 10-17 visible messages. Both fixes include regression tests. Failure-Class: none
a3f1dff to
f5dcfb1
Compare
|
Rebased onto latest This resolved all three previously failing checks:
Both trusted Codex review threads (P1: tombstone dropped turns, P2: cap reported over-fetch) were already addressed in the prior fix commit and remain resolved. |
Classify only the current rendered user instruction, keep personal activity queries on private retrieval, and use the direct-compatible Anthropic web search contract owned by the gateway parser. Verified: cargo test --manifest-path desktop/macos/Backend-Rust/Cargo.toml (398 passed); npm --prefix desktop/macos/agent test; desktop/macos/scripts/agent-logic-harness.sh --cross-surface-smoke; scripts/pr-preflight --pr-body-file /tmp/pr-10422-preflight.md. Failure-Class: none
Keep forced startup refresh for production and Beta, while allowing named non-production bundles to use an unexpired owner-checked token seeded from a signed app. AuthService still refreshes normally on expiry. Verified: xcrun swift test --package-path Desktop --filter AgentRuntimeProcessTests; desktop/macos/scripts/agent-logic-harness.sh --cross-surface-smoke. Failure-Class: none
…#10758) ## Summary Comprehensive fix for the PTT / voice-agent failure class observed live in Omi Beta 0.12.141, plus notch polish. Diagnosed from `/private/tmp/omi-beta.log` and the full git fix history of PTT. **What was broken (from the running Beta's logs):** 1. `RealtimeHub[gemini]: kernel rejected tool ask_higher_model code=tool_not_allowed` on every PTT escalation. The kernel run-tool capability computes its allowlist from the *chat-adapter* projection of the tool manifest, but the realtime-voice surface advertises tools generated from the *surface* projection — so every voice-only tool (`ask_higher_model`, `point_click`) was structurally rejected and Gemini received a 112-byte error as the tool result. This is why voice tool calls fail. 2. Even when the escalation went through, its request body carries no client tools, and the gateway's agentic-turn heuristic (`!client_tools.is_empty()`) therefore never injected the server `web_search` tool — every voice escalation for current facts (weather, prices, scores; all visible in the log) reached Claude with zero web access. This is why PTT can't do web lookups. 3. (Historical, already fixed on main and confirmed shipped in 0.12.141: `tool_choice.name 'web_search'` 400s from the previous build's process were the old forced-caller bug, #10422 lineage.) **Fixes:** - `fix(agent)`: kernel run-tool capability registration now unions the run surface's manifest projection (`toolsForSurface("realtime_voice")`) with the adapter projection for `swift_realtime` runs — still filtered by execution role and spawn-time tool policy. Chat runs cannot inherit voice-only tools (asserted in test). - `fix(desktop)`: the gateway accepts an explicit `omi_web_search: true` opt-in that injects the server `web_search` tool with no client tools present; the private/no-web prompt boundary still wins. The Swift escalation body opts in, the escalation prompt directs grounding in the lookup, and its timeout is raised to 60s for `pause_turn` continuations. **Notch polish (as requested):** - The legend now shows one **Open** row bound to the configured shortcut (matching Settings' "Open Omi Shortcut") instead of Ask + a hardcoded Summon row. The window-summon chord keeps working; it is just no longer listed. - The Omi mark now pulses like a speaker while the assistant answers (two-harmonic breathing, bounded to the 21pt slot), and the listening waveform gains a center-weighted level-meter envelope with a travelling overtone. Reduce Motion suppresses both; the speaking state is announced to accessibility. Driven by the existing reducer-owned `isVoiceResponseGlowActive` projection — no new voice state. **Follow-up commits (same PR):** - `fix(desktop)`: **PTT stuck after a barge-in** (user-reported: PTT didn't stop after asking for the weather; chat appeared to show a duplicate). Root cause: `providerReplacementReady` (the barge-in session replacement) unconditionally rewrote the voice route from `.hubWarmWait` to `.hub`, stealing the captured-audio handoff that only `hubReady` can flush — so the turn had no armed deadline and hung ~2.5 minutes until the provider's idle teardown (log: turn `C6BFD805`, `dropped stale event ... deadline_fired`, terminal only at +150s). Both provider-ready admissions now converge on one `bindProviderReadyHubRoute` helper that never overwrites a manager-owned warm capture (`Failure-Class: FC-split-mutation-authority` — second competing writer for captured-input ownership). Three hermetic reducer tests reproduce the exact stale-drop and fail on the pre-fix reducer (8 failures), pass post-fix. The "duplicate message" was investigated and is NOT an INV-6 violation: kernel `conversation_turns` shows exactly one pair per continuity key; the appearance came from the `kernel_turn_tail` diagnostic returning both revisions of one turn plus two genuinely distinct weather asks. - `feat(desktop)`: **notch animations now react to live audio.** The mic level was 5 Hz-throttled (waveform looked canned); `AudioLevelMonitor` now exposes un-throttled live mic + voice-playback levels polled per frame, `StreamingPCMPlayer` taps the main mixer for the actual audible output RMS, and the mark smooths both with an asymmetric attack/release envelope — the waveform follows the user's voice and the speaking pulse follows the assistant's speech (with a floor so quiet stretches still breathe). **Internet-search findings (live-verified):** - Typed main chat web search was never broken — verified live on the deployed dev backend (completed `web_search` tool call with current market data). - PTT escalation search was broken **purely by deployment**: the `omi_web_search` opt-in exists only on this branch, and deployed gateways silently ignore the unknown field. Side-by-side proof with the identical escalation request: deployed dev backend → `web_search_requests: 0` plus a hallucinated tool-call and an "I don't have web access" answer; this branch's gateway → `web_search_requests: 1` with real source URLs. Three live PTT weather turns against the patched gateway completed with `web_search_exposed=true` and real current conditions. - Real bug found while proving it: `should_record_web_search_fallback` still required client tools, so a voice escalation that asked for web and lost it (haiku route / kill switch) emitted no `chat_retrieval` fallback event — the exact regression the opt-in should surface was telemetry-blind. Fixed with the predicate mirroring `inject_web_search`; two regression tests; `cargo test --locked` 390 pass. - **Rollout consequence:** dev bundles get the gateway fix automatically when this merges (`desktop_backend_auto_dev.yml` is merge-triggered; branch deploys are impossible by design). Omi Beta/stable users need a separate, explicitly-approved `desktop_backend_prod.yml` run after merge. ## Product invariants affected - INV-AGENT-* — run-tool capability allowlist widened for `swift_realtime` runs only; the guard test `agent/tests/run-tool-capability.test.ts` gains behavioral coverage that a swift_realtime run authorizes `ask_higher_model` end-to-end and a plain chat run still cannot. - INV-VOICE-1 — the barge-in fix strengthens this invariant: the reducer remains the single lifecycle owner, and both provider-ready admissions now converge on one route-binding helper so no admission path can overwrite the manager-owned warm-capture claim. Guard: three new reducer tests in `VoiceTurnReducerTests`. - INV-CHAT-1 — path-matched (gateway chat route, floating bar view); no transcript ownership or write-path behavior changes. The single shared `ChatProvider` timeline and kernel journal flow are untouched. ## Failure class (fixes) Failure-Class: new New class registered in this PR: an authority admitting tool invocations must compute its allowlist from the same manifest projection that advertised the tool to the invoking surface. Guard artifact: the behavioral capability test above. The `omi_web_search` starvation fix declares no class of its own (single-instance heuristic gap; the release-boundary web-search probes already guard the deployed behavior). ## Verification - `npx vitest run tests/run-tool-capability.test.ts` — 17/17 pass (new: swift_realtime surface-tool authorization + chat-run exclusion). - `cargo test omi_web_search` — 2/2 pass (opt-in injects `web_search` with no client tools; explicit private/no-web turns stay tool-free). `cargo check` clean. - `./scripts/agent-logic-harness.sh` — all four stages green (Swift lifecycle/state, agent runtime, pi-mono-extension, propagation self-check). - `./scripts/agent-logic-harness.sh --cross-surface-smoke` — green (Swift, agent, Rust retrieval contract). - `xcrun swift test --filter "NotchVoiceMorphMarkTests|OpenOmiShortcutSummonRoutingTests"` — 14/14 pass (new: speaker-pulse bounds/containment, envelope shape, amplitude ceiling, reduce-motion). - `make preflight` — manifest checks pass with this PR body. - Barge-in live check on the rebuilt bundle: a second PTT turn fired during the first turn's playback drain; both turns reached `terminal_success` with `stale_event_count=0` (previously the second turn wedged for 150s). Reducer regression tests cover the exact pre-fix wedge hermetically. - Audio-reactivity tests: `VoiceLevelSmoother` attack/release/clamp/time-gap, speaking-level modulation floor/ceiling, `StreamingPCMPlayer.rmsLevel` on known buffers — 20/20 pass with the containment suite. - QA bundle `omi-ptt-fix` built and launched via `OMI_APP_NAME=omi-ptt-fix ./run.sh --yolo`. **Live voice-path proof** — a natural authenticated PTT turn with real synthesized speech ("What's the weather in New York City right now?") through `ptt_test_turn`: ``` 22:59:28 RealtimeHub[gemini]: tool_call ask_higher_model({"query":"What's the weather in New York City right now?"}) 22:59:34 RealtimeHub: ask_higher_model ← claude-sonnet-4-6 OK in 6304ms (711 chars) 22:59:34 RealtimeHub[gemini]: tool result ask_higher_model raw_bytes=1135 oversized=false 22:59:57 RealtimeHub: reply received chars=423 ``` The identical query in Beta 0.12.141 logged `kernel rejected tool ask_higher_model code=tool_not_allowed` with a 112-byte error result. No rejection occurs on this build; the escalation completes and the reply is spoken. Note: the `omi_web_search` gateway change takes effect in the deployed desktop backend via its normal Cloud Run release lane (whose candidate probes already require a real provider-reported web search); the client sends the opt-in immediately and older backends ignore the unknown field harmlessly. ## Latest UI iterations The notch speaking/listening animation went through several passes after the initial audio-reactivity fix, each refining shape and responsiveness while staying on the same reducer-owned `isVoiceResponseGlowActive` projection (no new voice state added): - `e237326c59` — circular sound-wave speaking ring (replacing the earlier pulse) plus a snappier input waveform response. - `45d9de2a5f` — unidirectional wave propagation and a tail-of-phrase gate hangover so the ring doesn't cut off abruptly at the end of an utterance. - `9773a8a43b` — equalizer-spike input wave and a brisker three-crest speaking ripple for a more percussive, less sluggish feel. - `df2e003808` (current head) — final iteration: uniform fast-spiking ring expansion with a 12ms attack / 90ms release envelope, tuned to track live mic/playback RMS without overshoot. **Verification of the latest state:** - `xcrun swift test --filter NotchVoiceMorphMarkTests` — 16/16 pass on the current head (grew from 14/16 as the ring-expansion iterations added coverage). - Live real-audio check: rebuilt the `com.omi.omi-ptt-fix` bundle and ran `ptt_test_turn` with real synthesized speech end-to-end — reached `terminal_success`, confirming the animation and escalation path both work together on the final build, not just in unit tests. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary - hydrate each live desktop Pi binding with the full canonical retained context once, then deliver only new or changed turns while continuing to refresh dynamic sources and context-plan metadata - replace the backend's moving newest-10 window with a bounded 10–17 message append epoch and enable Anthropic's automatic 1-hour message breakpoint for cross-turn history and agentic tool loops - teach gateway accounting to recognize top-level Anthropic cache controls and document the code audit, measured baseline, candidate decisions, implementation tickets, and savings estimate - restore typed desktop chat by routing on only the current `# User Message`, keeping personal-activity prompts on private Omi retrieval, and using Anthropic's direct-compatible web-search tool version - let non-production named QA bundles reuse a valid owner-checked seeded token at startup while preserving production/Beta's forced Firebase refresh behavior ## Typed chat root cause and fix Local Omi Beta logs showed typed turns failing quickly with Anthropic HTTP 400: the selected `web_search` tool was not callable through the configured direct path. PTT stayed healthy because it uses the separate Gemini Live `RealtimeHub` / `VoiceTurnCoordinator` path. The failure had two coupled causes: 1. Pi's rendered prompt includes retained history plus a final `# User Message`. Retrieval policy classified the entire rendered prompt, so an older turn's web-required instruction could leak into later private or ordinary turns. 2. The gateway emitted `web_search_20260209` for direct named selection. That dynamic-filtering tool version permits the code-execution caller in the live Anthropic contract, while the current parser and routing path expect direct `server_tool_use` / `web_search_tool_result` blocks. The fix isolates classification to the current user section, recognizes “what did I do” as private-context intent in both Rust and Pi, and pins the direct-compatible `web_search_20250305` request shape. Regression coverage exercises stale inherited web policy, personal activity, and the provider request shape. The QA run also exposed a named-bundle-only startup issue: the bundle had a valid seeded Keychain token but attempted a source-app Firebase refresh that cannot exist under a distinct bundle ID. The new credential policy reuses the valid owner-checked token only for non-production named bundles; normal Omi and Omi Beta behavior is unchanged. ## Cache audit and expected impact - Desktop already used explicit 1-hour breakpoints after the stable system policy and on the latest user/tool-result message. A literal midpoint marker inside the repeated snapshot would not be independently reusable because Anthropic hashes cumulative `tools → system → messages` prefixes. - A measured mature 64-turn desktop request used 20,403 uncached plus 29,983 cache-read tokens (59.5% cache-read share). The repeated old-history slice is approximately 13.4K tokens per turn. - Steady-state desktop uncached input is therefore estimated to fall from about 20.4K to 7.0K tokens (66%), with cache-read share rising to roughly 81% while the same live binding remains healthy. - The backend epoch preserves at least the previous 10 visible messages, remains bounded at 17, resets deterministically every eight messages, and is scoped to the active session or app. - No stable-prefix staleness defect was found: the desktop stable identity is constant for its intentional semantic-guidance/capability scope, while profile, memory, tasks, goals, and other live sources are dynamic. Full audit and ticket pack: `docs/superpowers/specs/2026-07-23-context-cache-efficiency-design.md` ## Verification - backend focused cache/gateway tests — 71 passed - desktop Rust suite — 398 passed - Pi adapter policy tests — 36 passed; full agent suite passed - `xcrun swift test --package-path Desktop --filter AgentRuntimeProcessTests` — passed - `./scripts/agent-logic-harness.sh --cross-surface-smoke` — all four stages passed - named bundle `/Applications/omi-context-cache.app` — Swift/Rust/agent build, ad-hoc signing, install, launch, exact bundle identity, automation health, authenticated protocol-v2 runtime, and dev-backend configuration passed - exact named-bundle repros: `hello?` completed with no error/stuck sending state; `What did I do today?` stayed on private Omi context and completed with no error/stuck sending state - `scripts/pr-preflight --pr-body-file /tmp/pr-10422-preflight.md` — passed - bounded pre-push acceptance gate — passed twice, including Swift compile, desktop tool surfaces (53 files / 597 tests), focused backend tests, product invariant checks, formatting, lint, and Rust compile ## Product invariants affected - INV-AGENT-* - INV-CHAT-1 The change preserves canonical kernel ownership, binding replacement/reset boundaries, recent-turn continuity, and additive context delivery. It does not summarize, mutate, or remove canonical turn content. Production Omi/Omi Beta startup auth behavior remains fail-closed and unchanged. Closes BasedHardware#10418 <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/10422?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Failure-Class: none
Summary
# User Message, keeping personal-activity prompts on private Omi retrieval, and using Anthropic's direct-compatible web-search tool versionTyped chat root cause and fix
Local Omi Beta logs showed typed turns failing quickly with Anthropic HTTP 400: the selected
web_searchtool was not callable through the configured direct path. PTT stayed healthy because it uses the separate Gemini LiveRealtimeHub/VoiceTurnCoordinatorpath.The failure had two coupled causes:
# User Message. Retrieval policy classified the entire rendered prompt, so an older turn's web-required instruction could leak into later private or ordinary turns.web_search_20260209for direct named selection. That dynamic-filtering tool version permits the code-execution caller in the live Anthropic contract, while the current parser and routing path expect directserver_tool_use/web_search_tool_resultblocks.The fix isolates classification to the current user section, recognizes “what did I do” as private-context intent in both Rust and Pi, and pins the direct-compatible
web_search_20250305request shape. Regression coverage exercises stale inherited web policy, personal activity, and the provider request shape.The QA run also exposed a named-bundle-only startup issue: the bundle had a valid seeded Keychain token but attempted a source-app Firebase refresh that cannot exist under a distinct bundle ID. The new credential policy reuses the valid owner-checked token only for non-production named bundles; normal Omi and Omi Beta behavior is unchanged.
Cache audit and expected impact
tools → system → messagesprefixes.Full audit and ticket pack:
docs/superpowers/specs/2026-07-23-context-cache-efficiency-design.mdVerification
xcrun swift test --package-path Desktop --filter AgentRuntimeProcessTests— passed./scripts/agent-logic-harness.sh --cross-surface-smoke— all four stages passed/Applications/omi-context-cache.app— Swift/Rust/agent build, ad-hoc signing, install, launch, exact bundle identity, automation health, authenticated protocol-v2 runtime, and dev-backend configuration passedhello?completed with no error/stuck sending state;What did I do today?stayed on private Omi context and completed with no error/stuck sending statescripts/pr-preflight --pr-body-file /tmp/pr-10422-preflight.md— passedProduct invariants affected
The change preserves canonical kernel ownership, binding replacement/reset boundaries, recent-turn continuity, and additive context delivery. It does not summarize, mutate, or remove canonical turn content. Production Omi/Omi Beta startup auth behavior remains fail-closed and unchanged.
Closes #10418
Failure-Class: none