Skip to content

feat: simplify BYOK LLM provider setup - #11454

Merged
undivisible merged 62 commits into
mainfrom
update-byok-llm-providers
Aug 26, 2026
Merged

undivisible merged 62 commits into
mainfrom
update-byok-llm-providers

Conversation

@undivisible

@undivisible undivisible commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Line-Count-Exception: backend/database/users.py | 2178 -> 2194 | existing transactional BYOK fingerprint merge and firestore_client plumbing
Line-Count-Exception: backend/routers/users.py | 2201 -> 2237 | validated LLM BYOK subscription gates plus the snapshot/transcription split
Line-Count-Exception: backend/routers/desktop_proxy.py | 1597 -> 1603 | capability-scoped BYOK header forwarding on desktop proxy routes
Line-Count-Exception: backend/routers/chat.py | 1913 -> 1920 | thread required_llm_provider into /v2/messages quota enforcement
Line-Count-Exception: backend/routers/omni_relay.py | 175 -> 186 | reject unsupported realtime provider before trial cache lookup
Line-Count-Exception: backend/utils/byok.py | 278 -> 341 | clear unvalidated keys on transient middleware failure
Line-Count-Exception: desktop/macos/Desktop/Sources/APIKeyService.swift | 233 -> 384 | owner-bind clear plus reconciliation generation

Summary

  • Add capability-scoped BYOK enrollment and OpenRouter routing with Gemini 2.5 Flash Lite.
  • Replace all-key setup with an LLM provider menu and separate Deepgram transcription key.
  • Keep healthy selected BYOK requests available when unrelated legacy keys are absent or unhealthy.

Product invariants affected

  • INV-AUTH-1
  • INV-CHAT-1
  • INV-VOICE-1
  • INV-MEM-4
  • INV-TASK-2

Verification

  • ./.venv/bin/python -m pytest -q tests/routers/test_users.py tests/unit/test_byok_security.py — 129 passed (includes the LLM-only vs LLM+Deepgram snapshot-split tests).
  • bun test src/shared/byok.test.ts src/main/agentKernel/byokEnroll.test.ts — 25 passed.
  • black --check --line-length 120 --skip-string-normalization backend/utils/byok.py backend/routers/users.py backend/tests/routers/test_users.py backend/tests/unit/test_byok_security.py — passed.
  • make preflight — repository runtime-image source-closure baseline remains incomplete for config.account_cutover; the changed-path gates passed.
  • Bounded pre-push gates passed for backend, OpenAPI, generated outputs, workflow contracts, desktop flow lint, and desktop agent tests. Local Swift compile passed with xcrun swift build -c debug --package-path Desktop.

Failure-Class: none


Note

High Risk
Touches BYOK validation, trial paywall, chat quota, and LLM routing. Incorrect validation or quota bypass would leak paid LLM usage or lock users out.

Overview
Makes BYOK capability-scoped: enroll any LLM provider (OpenAI, Anthropic, Gemini, or OpenRouter) plus optional Deepgram, instead of requiring all four keys.

Entitlements now require validated LLM keys (request_has_llm_byok_key / has_validated_byok_keys). Deepgram-only or raw unvalidated headers no longer unlock unlimited chat, skip quota, or bypass the desktop trial. Paywall cache is provider-aware (e.g. Gemini proxy). Middleware validates fingerprints before the route and still lets recovery paths (/subscription, /byok-active) through with empty keys.

LLM routing uses native ChatAnthropic for Anthropic BYOK, keeps OpenRouter Gemini on OpenRouter (google/…), and falls back to a provider-compatible model when the feature profile key is missing. Gateway lanes are skipped when BYOK switches providers.

Desktop settings replace the four-key form with an LLM picker + optional Deepgram, persist enrolled fingerprints, and attach only the selected keys. Activation is transactional so fingerprints replace rather than merge.

Reviewed by Cursor Bugbot for commit c9e1307. Configure here.

Line-Count-Exception: backend/utils/subscription.py | 1614 -> 1672 | provider-specific paywall cache, desktop-chat Anthropic gate, and required_llm_provider snapshot plumbing
Line-Count-Exception: desktop/macos/Desktop/Sources/AuthService.swift | 2843 -> 2845 | reconcile persisted BYOK activation during auth restore and sign-in

@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_0d4a6b52-9243-4127-b07d-ebd3ebf0ba4e)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

result = get_or_create_omi_gateway_llm_for_byok(
feature_auto_lane_id(feature),
provider=_effective_byok_provider(model, provider),
api_key=byok_key,

P1 Badge Route capability-selected BYOK through a matching gateway lane

When feature gateway mode is enabled, the selected provider does not alter feature_auto_lane_id(feature); it only chooses the forwarded credential header. For the new default OpenRouter path, the forced Gemini model also makes _effective_byok_provider label the OpenRouter key as Gemini, so OpenAI-backed lanes report a missing key while Gemini-backed lanes send that OpenRouter credential to Google and fail authentication. Use a lane whose route matches the selected BYOK provider, and forward the key under that actual provider identity.

ℹ️ 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".

Comment on lines +248 to +251
let requested =
BYOKLLMProvider(rawValue: UserDefaults.standard.string(forKey: .byokLLMProvider) ?? "openrouter")
?? .openrouter
return byokKey(requested.provider) == nil ? nil : requested.provider

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Migrate existing BYOK installs before defaulting to OpenRouter

For an existing macOS BYOK user, the four legacy keys are present but dev_byok_llm_provider does not exist; this defaults the selection to OpenRouter and then returns nil unless the user also happens to have a new OpenRouter key. The install therefore stops attaching BYOK headers, can be deactivated by settings reconciliation, and becomes paywalled after upgrading despite its previously valid keys. Infer a provider from the stored legacy keys or persist a migration before making the new selection authoritative.

AGENTS.md reference: AGENTS.md:L121-L121

Useful? React with 👍 / 👎.

Comment thread backend/utils/llm/clients.py Outdated
byok_provider = _effective_byok_provider(model, provider)
byok_key = get_byok_key(byok_provider)
if not byok_key:
for candidate in ('openrouter', 'openai', 'gemini'):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Route Anthropic selections through the user's key

When Anthropic is the only configured LLM provider, this candidate list never finds its key. Every ordinary get_llm() feature—including memory, insights, extraction, and non-agent chat—therefore continues with Omi's managed provider even though the new quota check treats the Anthropic header as BYOK and grants the free plan; only the separate anthropic_client chat-agent path uses the user's key. Either support Anthropic in this routing path or do not offer it as a provider for all LLM capabilities.

Useful? React with 👍 / 👎.

Comment thread backend/utils/llm/clients.py Outdated
Comment on lines +514 to +518
provider = candidate
byok_provider = candidate
byok_key = candidate_key
if candidate == 'gemini' and not model.startswith('gemini'):
model = 'gemini-2.5-flash-lite'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remap non-OpenAI models before using an OpenAI key

With only an OpenAI BYOK key, any feature whose configured route is Gemini or OpenRouter enters this fallback with that provider's model name, changes provider to openai, but leaves model unchanged. In direct-routing environments, _create_byok_client then sends values such as gemini-2.5-flash-lite or gemini-3-flash-preview to OpenAI's endpoint, so affected flows such as onboarding, translation, trends, and wrapped analysis fail with an unknown-model error. Select an OpenAI-supported model whenever this fallback changes the provider to OpenAI.

Useful? React with 👍 / 👎.

Comment thread backend/utils/llm/clients.py Outdated
Comment on lines +511 to +515
for candidate in ('openrouter', 'openai', 'gemini'):
candidate_key = get_byok_key(candidate)
if candidate_key:
provider = candidate
byok_provider = candidate

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Record provider-switch fallback telemetry

Whenever the feature's configured provider key is absent but another BYOK key is present, this branch silently changes the provider and potentially the model without calling the shared fallback recorder. That leaves incompatible-model failures and unexpected provider spend indistinguishable from normal routing in production; emit record_fallback with the original and selected providers and the resulting outcome.

AGENTS.md reference: AGENTS.md:L91-L91

Useful? React with 👍 / 👎.

Comment thread backend/utils/subscription.py Outdated
Comment on lines 225 to 226
# cache TTL is 5 min and Firestore's BYOK `is_active` heartbeat is 24 h,
# so even a perfectly-configured BYOK user can transiently look stale to

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update the partial-key paywall regression contract

The new request-level check makes any nonempty LLM key bypass the trial paywall, but backend/tests/unit/test_paywall_reconnect_gate.py::TestByokRequestEscapeHatch::test_partial_byok_headers_still_paywall still supplies OpenAI, Anthropic, and Gemini headers and asserts that the user remains paywalled. The full backend unit suite will deterministically fail that unchanged regression test; update it to cover the new capability-scoped escape hatch and retain a Deepgram-only negative case.

AGENTS.md reference: AGENTS.md:L117-L117

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

20 issues found across 27 files

Confidence score: 2/5

  • backend/utils/llm/clients.py has multiple provider/model resolution regressions: OpenRouter BYOK can be misrouted as Gemini, get_llm('followup') can lose its direct-Gemini path, and legacy OpenAI keys can be paired with incompatible Gemini models, leading to wrong-route requests and model-not-found failures — preserve explicit provider intent first, resolve feature profile before preference overrides, and enforce provider/model compatibility in fallback selection.
  • backend/utils/subscription.py and backend/utils/byok.py together leave a concrete access-control gap where a non-empty BYOK header (or an enrolled provider entry with null/empty fingerprint) can bypass expected trial/paywall validation paths — require validated enrollment/fingerprint checks before allowing the BYOK escape path and treat missing fingerprints as non-eligible.
  • desktop/macos/Desktop/Sources/APIKeyService.swift risks breaking upgraded legacy BYOK users by defaulting an unset provider preference to OpenRouter, which can silently drop their free-plan routing until settings are manually revisited — preserve existing legacy provider configuration during migration when preference is unset.
  • desktop/windows/src/main/agentKernel/byokValidator.ts, desktop/windows/src/shared/byok.ts, and related settings UI files can now produce ambiguous/misaligned validation states (missing explicit empty results, partial config accepted despite all-or-nothing contract, stale or contradictory errors), increasing user confusion and bad key payload injection into subprocesses — align validator contract and messaging across platforms and clear stale provider-specific UI errors on state changes.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+DeveloperKeys.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+DeveloperKeys.swift:215">
P2: Changing from a rejected provider to an empty provider leaves the previous provider's rejection banner visible because this early-return path never clears `byokActivationError` or `byokKeyStatuses`; clearing that UI state before returning would keep the settings screen consistent with the inactive BYOK state.</violation>
</file>

<file name="desktop/macos/pi-mono-extension/index.ts">

<violation number="1" location="desktop/macos/pi-mono-extension/index.ts:834">
P3: Capability-scoped BYOK activation now produces misleading diagnostics and stale documentation: a single configured key is logged as five attached headers, while the comments still describe all-four-only behavior. Logging `Object.keys(byokHeaders).length` and updating the all-four comments would keep partial BYOK routing diagnosable.</violation>
</file>

<file name="desktop/windows/src/main/codingAgent/pi-mono-extension/index.ts">

<violation number="1" location="desktop/windows/src/main/codingAgent/pi-mono-extension/index.ts:1051">
P3: Partial BYOK enrollment now activates headers, but diagnostics still claim that all 5 BYOK headers were attached and the surrounding comment documents all-key behavior. Reporting `Object.keys(byokHeaders).length` and updating the comment to describe capability-scoped keys would keep support output and implementation aligned.</violation>
</file>

<file name="desktop/windows/src/main/agentKernel/byokValidator.ts">

<violation number="1" location="desktop/windows/src/main/agentKernel/byokValidator.ts:112">
P2: Callers can no longer distinguish an unconfigured provider from a missing validation result: blank keys are omitted instead of returned as `{ ok: false, kind: 'empty', detail: 'Empty' }`. Either preserve the complete result contract or update `ByokValidationResults` and every consumer to explicitly handle absent entries.</violation>
</file>

<file name="desktop/windows/src/renderer/src/components/settings/tabs/DeveloperKeysSection.tsx">

<violation number="1" location="desktop/windows/src/renderer/src/components/settings/tabs/DeveloperKeysSection.tsx:97">
P3: The `hasAll` binding now returns true whenever any single LLM key is present (because `isByokActive` switched from `every` to `some`), but the name implies all providers are configured. This drives both the free-plan messaging and the live-validation gate, so the misleading name can cause a future maintainer to misread the activation condition. Consider renaming to something like `hasActiveLlByok` / `hasAnyLlKey` and updating the messaging to match the new partial-set semantics.</violation>

<violation number="2" location="desktop/windows/src/renderer/src/components/settings/tabs/DeveloperKeysSection.tsx:107">
P2: An invalid single LLM key now triggers validation but the error still tells users that all four keys are required, contradicting the new capability-scoped setup and optional Deepgram behavior. Updating the rejection message to describe the active LLM requirement and only the rejected providers would avoid sending users down the wrong setup path.</violation>
</file>

<file name="desktop/windows/src/shared/byok.ts">

<violation number="1" location="desktop/windows/src/shared/byok.ts:114">
P2: Partial LLM configurations now pass the active gate and can be injected into the subprocess, while this module still promises an all-or-nothing BYOK contract. The capability-scoped change should update the surrounding contract/docs and the backend assumption together, or retain the all-provider gate; otherwise partial sets can be rejected or silently fall through to managed billing.</violation>

<violation number="2" location="desktop/windows/src/shared/byok.ts:130">
P3: The comment above the loop ("isByokActive guarantees a non-empty trimmed value for every provider") is now stale. `isByokActive` was changed from `.every(...)` to `BYOK_LLM_PROVIDERS.some(...)`, so it no longer guarantees a value for every provider — which is exactly why the new per-iteration `if (value)` guard was needed. The code is correct, but the comment now contradicts the new semantics and can mislead the next reader into thinking the guard is redundant. Suggest updating the comment to reflect that isByokActive only guarantees at least one LLM key is present.</violation>
</file>

<file name="backend/tests/unit/test_byok_security.py">

<violation number="1" location="backend/tests/unit/test_byok_security.py:697">
P3: Test name `test_openrouter_gemini_byok_routes_to_gemini_direct` and its docstring ('Must use Gemini base URL, not OpenRouter', 'Must use the bare model name for Gemini direct API') contradict the new assertions, which now require the OpenRouter base URL and the 'google/' prefixed model name. Rename the test/docstring to describe OpenRouter routing (or drop the stale direct-Gemini wording).</violation>

<violation number="2" location="backend/tests/unit/test_byok_security.py:706">
P3: Test `test_non_gemini_openrouter_returns_none` is named for and documented as a 'returns None' case, but the changed assertion is `assert result is not None`. Name/docstring and assertion are mutually contradictory; rename to reflect that non-Gemini OpenRouter models now do create a client.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/BYOKPaywallTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/BYOKPaywallTests.swift:39">
P3: The changed assertion (XCTAssertTrue) now contradicts the function name 'RequiresAllFourKeys' and the comment 'Three of four → still not active'. Rename the test to reflect the new capability-scoped semantics (e.g. selected-provider active without all four keys) and update the comment, so the test name/comment don't mislead future readers.</violation>

<violation number="2" location="desktop/macos/Desktop/Tests/BYOKPaywallTests.swift:133">
P3: The changed assertion (XCTAssertFalse) now checks that removing the deepgram key does NOT re-apply the paywall, contradicting the test name 'ReappliesPaywall' and the comment 'paywall returns'. Rename the test and update the comment to describe the new intent (removing transcription key leaves LLM BYOK active, still not paywalled).</violation>
</file>

<file name="desktop/macos/Desktop/Tests/AgentRuntimeProcessTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/AgentRuntimeProcessTests.swift:1109">
P3: Under the new single-provider BYOK design, usableBYOKEnvironment() should forward only the selected LLM provider plus Deepgram. This test drops the old openai/anthropic/gemini assertions and only checks positive presence of .openrouter/.deepgram, so a regression that forwards all legacy keys again (or forwards the wrong selected provider) would still pass. Add absence assertions for the non-selected providers to pin the intended filtering.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/APIKeyService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/APIKeyService.swift:249">
P1: Existing BYOK users with the legacy provider keys lose the free-plan route after upgrading unless they revisit settings, because an unset provider preference is forced to OpenRouter. Preserve an already-configured legacy LLM provider (or migrate the preference) before applying the OpenRouter default for new users.</violation>
</file>

<file name="backend/utils/subscription.py">

<violation number="1" location="backend/utils/subscription.py:228">
P1: An expired desktop user can bypass the trial paywall by presenting any non-empty LLM BYOK header unless shared fingerprint/enrollment validation has already run for every caller. The escape hatch would be safer if it required a validated, provider-specific enrollment rather than raw request-header presence; the same validation should gate the quota bypass below.</violation>
</file>

<file name="backend/utils/byok.py">

<violation number="1" location="backend/utils/byok.py:248">
P2: A supplied key can bypass fingerprint validation when its enrolled provider entry has an empty or null fingerprint, because the loop skips that entry while this filter checks only provider membership. Filtering on a non-empty stored fingerprint (or dropping invalid state entries) keeps unverified keys out of provider clients.</violation>
</file>

<file name="backend/utils/llm/clients.py">

<violation number="1" location="backend/utils/llm/clients.py:502">
P1: `get_llm('followup')` can lose its explicit direct-Gemini BYOK route because the OpenRouter preference is applied before the feature profile is resolved. Resolve the Gemini BYOK profile first, then apply OpenRouter only when no profile route is selected.

(Based on your team's feedback about preserving the Followup Gemini BYOK route.) .</violation>

<violation number="2" location="backend/utils/llm/clients.py:504">
P1: Gateway-routed OpenRouter BYOK requests are classified as Gemini and can send an OpenRouter key to the Gemini route. Preserve `provider='openrouter'` when this key is used, while applying the Gemini mapping only for an actual direct-Gemini credential.</violation>

<violation number="3" location="backend/utils/llm/clients.py:511">
P3: The 'openrouter' entry at the head of the fallback candidate tuple is redundant: the loop only runs when get_byok_key('openrouter') was already falsy in the first branch, so candidate 'openrouter' can never match there. Iterating ('openai', 'gemini') would express the intent just as well and avoid implying a re-check that can never succeed.</violation>

<violation number="4" location="backend/utils/llm/clients.py:514">
P1: A legacy OpenAI key can now be paired with a Gemini-resolved model and produce a model-not-found request at OpenAI. Restrict fallback candidates to compatible model/provider pairs or select an OpenAI model when choosing the OpenAI key.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic


nonisolated static var selectedBYOKLLMProvider: BYOKProvider? {
let requested =
BYOKLLMProvider(rawValue: UserDefaults.standard.string(forKey: .byokLLMProvider) ?? "openrouter")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: Existing BYOK users with the legacy provider keys lose the free-plan route after upgrading unless they revisit settings, because an unset provider preference is forced to OpenRouter. Preserve an already-configured legacy LLM provider (or migrate the preference) before applying the OpenRouter default for new users.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/APIKeyService.swift, line 249:

<comment>Existing BYOK users with the legacy provider keys lose the free-plan route after upgrading unless they revisit settings, because an unset provider preference is forced to OpenRouter. Preserve an already-configured legacy LLM provider (or migrate the preference) before applying the OpenRouter default for new users.</comment>

<file context>
@@ -210,7 +241,14 @@ final class APIKeyService: ObservableObject {
+
+  nonisolated static var selectedBYOKLLMProvider: BYOKProvider? {
+    let requested =
+      BYOKLLMProvider(rawValue: UserDefaults.standard.string(forKey: .byokLLMProvider) ?? "openrouter")
+      ?? .openrouter
+    return byokKey(requested.provider) == nil ? nil : requested.provider
</file context>

Comment thread backend/utils/subscription.py Resolved
Comment thread backend/utils/llm/clients.py Outdated

byok_provider = _effective_byok_provider(model, provider)
byok_key = get_byok_key(byok_provider)
byok_key = get_byok_key('openrouter')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: get_llm('followup') can lose its explicit direct-Gemini BYOK route because the OpenRouter preference is applied before the feature profile is resolved. Resolve the Gemini BYOK profile first, then apply OpenRouter only when no profile route is selected.

(Based on your team's feedback about preserving the Followup Gemini BYOK route.) .

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/llm/clients.py, line 502:

<comment>`get_llm('followup')` can lose its explicit direct-Gemini BYOK route because the OpenRouter preference is applied before the feature profile is resolved. Resolve the Gemini BYOK profile first, then apply OpenRouter only when no profile route is selected.

(Based on your team's feedback about preserving the Followup Gemini BYOK route.) .</comment>

<file context>
@@ -496,8 +499,24 @@ def get_llm(
 
-    byok_provider = _effective_byok_provider(model, provider)
-    byok_key = get_byok_key(byok_provider)
+    byok_key = get_byok_key('openrouter')
+    if byok_key:
+        provider = 'openrouter'
</file context>

Comment thread backend/utils/llm/clients.py Resolved
Comment thread backend/utils/llm/clients.py Outdated
byok_key = get_byok_key(byok_provider)
byok_key = get_byok_key('openrouter')
if byok_key:
provider = 'openrouter'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: Gateway-routed OpenRouter BYOK requests are classified as Gemini and can send an OpenRouter key to the Gemini route. Preserve provider='openrouter' when this key is used, while applying the Gemini mapping only for an actual direct-Gemini credential.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/llm/clients.py, line 504:

<comment>Gateway-routed OpenRouter BYOK requests are classified as Gemini and can send an OpenRouter key to the Gemini route. Preserve `provider='openrouter'` when this key is used, while applying the Gemini mapping only for an actual direct-Gemini credential.</comment>

<file context>
@@ -496,8 +499,24 @@ def get_llm(
-    byok_key = get_byok_key(byok_provider)
+    byok_key = get_byok_key('openrouter')
+    if byok_key:
+        provider = 'openrouter'
+        byok_provider = 'openrouter'
+        model = 'gemini-2.5-flash-lite'
</file context>

}, [])

const hasAll = BYOK_PROVIDERS.every((p) => keys[p].trim().length > 0)
const hasAll = isByokActive(keys)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The hasAll binding now returns true whenever any single LLM key is present (because isByokActive switched from every to some), but the name implies all providers are configured. This drives both the free-plan messaging and the live-validation gate, so the misleading name can cause a future maintainer to misread the activation condition. Consider renaming to something like hasActiveLlByok / hasAnyLlKey and updating the messaging to match the new partial-set semantics.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/windows/src/renderer/src/components/settings/tabs/DeveloperKeysSection.tsx, line 97:

<comment>The `hasAll` binding now returns true whenever any single LLM key is present (because `isByokActive` switched from `every` to `some`), but the name implies all providers are configured. This drives both the free-plan messaging and the live-validation gate, so the misleading name can cause a future maintainer to misread the activation condition. Consider renaming to something like `hasActiveLlByok` / `hasAnyLlKey` and updating the messaging to match the new partial-set semantics.</comment>

<file context>
@@ -75,7 +94,7 @@ export function DeveloperKeysSection(): React.JSX.Element {
   }, [])
 
-  const hasAll = BYOK_PROVIDERS.every((p) => keys[p].trim().length > 0)
+  const hasAll = isByokActive(keys)
   const hasAnyKey = BYOK_PROVIDERS.some((p) => keys[p].trim().length > 0)
 
</file context>

Comment thread desktop/windows/src/shared/byok.ts Resolved
Comment thread backend/utils/llm/clients.py Outdated
byok_provider = _effective_byok_provider(model, provider)
byok_key = get_byok_key(byok_provider)
if not byok_key:
for candidate in ('openrouter', 'openai', 'gemini'):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The 'openrouter' entry at the head of the fallback candidate tuple is redundant: the loop only runs when get_byok_key('openrouter') was already falsy in the first branch, so candidate 'openrouter' can never match there. Iterating ('openai', 'gemini') would express the intent just as well and avoid implying a re-check that can never succeed.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/llm/clients.py, line 511:

<comment>The 'openrouter' entry at the head of the fallback candidate tuple is redundant: the loop only runs when get_byok_key('openrouter') was already falsy in the first branch, so candidate 'openrouter' can never match there. Iterating ('openai', 'gemini') would express the intent just as well and avoid implying a re-check that can never succeed.</comment>

<file context>
@@ -496,8 +499,24 @@ def get_llm(
+        byok_provider = _effective_byok_provider(model, provider)
+        byok_key = get_byok_key(byok_provider)
+    if not byok_key:
+        for candidate in ('openrouter', 'openai', 'gemini'):
+            candidate_key = get_byok_key(candidate)
+            if candidate_key:
</file context>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 27 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/utils/subscription.py Resolved
Comment thread backend/utils/llm/clients.py Resolved
Comment thread backend/utils/llm/clients.py Resolved
Comment thread backend/utils/llm/clients.py Resolved
Comment thread desktop/windows/src/shared/byok.ts Resolved
Comment thread backend/utils/llm/clients.py Resolved
@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge desktop labels Aug 12, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for continuing to simplify the BYOK setup. I agree with the product direction of capability-scoped keys, but I found several blocking issues in the current implementation that should be fixed before merge:

  • backend/utils/llm/clients.py: the OpenRouter preference is applied before the feature/profile route is resolved. That can override feature-specific direct Gemini BYOK paths such as followup, and the fallback loop can pair a legacy OpenAI key with the already-resolved Gemini model, producing incompatible model/provider requests. Please preserve explicit route intent first and only substitute OpenRouter/direct provider choices when the selected credential is compatible with the resolved model.
  • backend/utils/byok.py: _check_byok_validity() now skips stored providers with missing/empty fingerprints, but then keeps request keys for any provider present in stored_fingerprints. That lets an enrolled-but-invalid fingerprint entry pass an unverified key into _byok_ctx. Filter on a valid stored fingerprint, not just provider membership.
  • backend/utils/subscription.py: _request_has_llm_byok_key() checks only raw request header presence before bypassing trial/paywall and chat-quota gates. Because these are billing/security-adjacent paths, the bypass should be tied to a validated provider-specific enrollment/fingerprint rather than any non-empty LLM header.
  • desktop/macos/Desktop/Sources/APIKeyService.swift: defaulting an unset dev_byok_llm_provider preference to OpenRouter means upgraded users who already have legacy OpenAI/Gemini/Anthropic keys can lose BYOK/free-plan routing until they revisit settings. Please preserve or migrate an existing legacy LLM provider before applying the OpenRouter default for new setups.
  • desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+DeveloperKeys.swift: the empty-selected-provider early return in refreshBYOKActivation() deactivates when any key exists, but it does not clear byokActivationError/byokKeyStatuses, so a stale rejection banner can remain after the user changes provider/key state.
  • desktop/windows/src/main/agentKernel/byokValidator.ts and desktop/windows/src/renderer/src/components/settings/tabs/DeveloperKeysSection.tsx: blank providers are now omitted from validation results, while the renderer and error wording still read like an all-four-provider contract. Please either keep a complete validation-result contract or update the consumers/messages so partial capability-scoped setup is explicit.
  • desktop/macos/pi-mono-extension/index.ts, desktop/windows/src/main/codingAgent/pi-mono-extension/index.ts, desktop/windows/src/shared/byok.ts, backend/tests/unit/test_byok_security.py, desktop/macos/Desktop/Tests/BYOKPaywallTests.swift, and desktop/macos/Desktop/Tests/AgentRuntimeProcessTests.swift: several comments/test names/diagnostics still describe the old all-four-key behavior or no longer assert absence of non-selected provider keys. These are lower severity than the routing/paywall issues, but should be cleaned up so future maintainers do not misread the new BYOK contract.

I’m requesting changes because this touches BYOK credential handling, billing/paywall bypasses, and LLM provider routing. Once the validated-enrollment gate, provider/model compatibility, migration behavior, and failing checks are addressed, this should be ready for human maintainer product/security sign-off.


Automated maintainer review; final merge decision remains with the Omi maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_59812a52-7866-42e0-b8a1-4861b5d15e72)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

if byok_key and gateway_feature_mode:
result = get_or_create_omi_gateway_llm_for_byok(
feature_auto_lane_id(feature),
provider=_effective_byok_provider(model, provider),
api_key=byok_key,

P1 Badge Route fallback BYOK providers through matching gateway lanes

In the checked production configuration, OMI_LLM_GATEWAY_FEATURE_MODE is gateway, but this call still addresses the feature's fixed auto lane; the provider argument only forwards a credential header and does not change that lane's configured provider. For example, an OpenRouter-only user requesting memories selects the OpenRouter fallback here, then calls the OpenAI-backed omi:auto:memories lane with only an OpenRouter key, which the gateway rejects as missing_byok_key rather than running the selected fallback. Use a route matching the fallback provider or bypass the fixed feature lane for provider-switched BYOK calls.

ℹ️ 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".

Comment thread backend/utils/subscription.py Outdated
Comment on lines +174 to +175
def _request_has_llm_byok_key() -> bool:
return has_validated_byok_keys()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Require a validated LLM key before bypassing quota

When an enrolled user sends only a matching Deepgram header, request validation retains that key and marks the context validated, so this helper returns true even though no LLM credential is present. Both the trial-paywall escape hatch and enforce_chat_quota then allow the request, while get_llm() falls back to an Omi-managed credential, allowing managed inference without quota; check the validated key set for an actual LLM provider rather than accepting any validated BYOK key.

Useful? React with 👍 / 👎.

@AppStorage("dev_openai_api_key") var devOpenAIKey: String = ""
@AppStorage("dev_openrouter_api_key") var devOpenRouterKey: String = ""
@AppStorage("dev_deepgram_api_key") var devDeepgramKey: String = ""
@AppStorage(DefaultsKey.byokLLMProvider.rawValue) var devBYOKLLMProvider: String = "openrouter"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Migrate legacy selection before reconciling Settings

For an upgraded macOS install with legacy provider keys but no dev_byok_llm_provider, this independent @AppStorage default selects OpenRouter in the Settings view even though APIKeyService now infers a legacy provider. Opening the pane runs its .task, sees an empty selected OpenRouter key alongside existing keys, and calls deactivateBYOK(), taking the previously working install off the free plan. Fresh evidence after the earlier inference fix is that Settings still obtains its selection from this unmigrated default; initialize or persist the inferred legacy provider before reconciliation.

AGENTS.md reference: desktop/macos/AGENTS.md:L352-L352

Useful? React with 👍 / 👎.

Comment thread backend/utils/byok.py Resolved
Comment thread backend/utils/llm/clients.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 243cbfc4e9

ℹ️ 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".

Comment thread backend/utils/subscription.py Outdated
Comment on lines 887 to 888
if users_db.is_byok_active(uid) and _request_has_llm_byok_key():
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep quota enforcement unless the BYOK key serves chat

For Gemini- or OpenRouter-only enrollment, this bypasses the chat quota even though /v2/chat/completions only switches away from Omi-managed inference when an Anthropic key is present (desktop_chat.py:1243-1288). Because activation accepts a client-supplied fingerprint and request validation merely checks that the header matches it, any authenticated user can enroll an arbitrary OpenRouter fingerprint, send the matching fake header, and receive managed gateway/direct-Anthropic chat without the monthly quota. Only bypass when the selected route actually forwards the validated key, or route these providers through their BYOK credentials first.

AGENTS.md reference: backend/AGENTS.md:L28-L28

Useful? React with 👍 / 👎.

Comment thread backend/utils/llm/clients.py Resolved
@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_bad49e4e-2638-41ba-9838-6713c66fdc11)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d0b5d26d37

ℹ️ 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".

Comment thread backend/routers/omni_relay.py Resolved
Comment thread backend/routers/omni_relay.py Resolved
Comment thread backend/routers/users.py Resolved
Comment on lines +329 to +334
class TestChatQuotaBYOKBypass:
@patch('utils.subscription.get_byok_key')
@patch('utils.subscription.has_validated_byok_keys', return_value=True)
@patch('utils.subscription.users_db')
def test_enforce_chat_quota_bypasses_for_byok_with_openai_key(self, mock_users_db, mock_get_key):
@patch('utils.subscription.is_trial_paywalled', return_value=False)
def test_enforce_chat_quota_bypasses_for_validated_openai_key(
self, _mock_paywalled, mock_users_db, _mock_validated

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Install provider keys in the quota bypass tests

These rewritten tests patch has_validated_byok_keys() to true but never put an OpenAI key into get_byok_keys(), even though _request_has_llm_byok_key() now requires both conditions. The module's earlier ContextVar tests leave keys behind, so this case can pass only because of test ordering (and the Anthropic-only case can actually exercise a leaked OpenAI key); run each case with an explicitly installed and subsequently reset provider key so it proves the intended capability-specific bypass.

AGENTS.md reference: AGENTS.md:L119-L119

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8e72cfbeb2

ℹ️ 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".

Comment thread desktop/windows/src/shared/byok.ts Resolved
Comment thread backend/routers/users.py Resolved
@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_f7a6196c-3452-4dde-a49e-33c46e1f45bd)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a1890e609b

ℹ️ 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".

Comment thread backend/database/users.py Resolved
Comment thread desktop/windows/src/shared/byok.ts Resolved
@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_ad7ab0d8-91ce-4a50-aad1-5def94ba0cfa)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e5be47ed98

ℹ️ 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".

Comment thread backend/utils/llm/clients.py Resolved
Comment thread backend/routers/users.py Outdated
unlimited_phone_quota = PhoneCallQuota(has_access=True, is_paid=True)

if users_db.is_byok_active(uid) and has_byok_keys():
if users_db.is_byok_active(uid) and get_byok_key('deepgram'):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate Deepgram before advertising unlimited transcription

The new Deepgram condition still runs behind get_current_user_uid_no_byok_validation, so get_byok_key('deepgram') reads the raw middleware header rather than an enrolled, fingerprint-validated capability. Fresh evidence after the earlier entitlement fix is that any LLM-enrolled account can now attach an arbitrary X-BYOK-Deepgram value and receive the unlimited subscription response with transcription limits and subscription controls hidden, even though listen validation drops that key and still enforces the real transcription credits. Base this response on a validated Deepgram capability while retaining a separate recovery path for fingerprint drift.

Useful? React with 👍 / 👎.

Comment thread backend/utils/byok.py Resolved
@cursor

cursor Bot commented Aug 13, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_a6829eab-b0e3-45f1-a073-550be8244fe2)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 68e1fce535

ℹ️ 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".

Comment thread desktop/windows/src/shared/byok.ts Resolved
@cursor

cursor Bot commented Aug 13, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_ffea9cc2-e9ee-4a31-b1ad-ad7ad86258c4)

@cursor

cursor Bot commented Aug 14, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_139874c4-8d78-4275-9b61-cc471e862486)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2632e71223

ℹ️ 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".

)


def get_basic_plan_limits() -> PlanLimits:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P0 Badge Restore the desktop quota wrappers

Removing enforce_desktop_chat_quota and is_desktop_trial_paywalled makes the backend entrypoint fail during import: main.py eagerly imports routers such as desktop_chat.py and desktop_agent_vm.py, which still import those names from this module. Restore the wrappers (including their customer-Firestore routing) or migrate every importer in the same change; otherwise no backend process can start.

AGENTS.md reference: backend/AGENTS.md:L26-L26

Useful? React with 👍 / 👎.

@cursor

cursor Bot commented Aug 14, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_48bc07f5-6911-4d37-b7da-01ae14eca78d)

@undivisible
undivisible force-pushed the update-byok-llm-providers branch from a209299 to 984af53 Compare August 14, 2026 09:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 984af536ca

ℹ️ 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".

Comment thread backend/utils/subscription.py Resolved
@undivisible

Copy link
Copy Markdown
Collaborator Author

All blocking items from this review are addressed on the current head:

  • clients.py routing — feature/profile route is resolved first, OpenRouter substitutes only when no profile key exists; fallback selects a compatible model per provider (_byok_fallback_model); provider-switched BYOK bypasses the pinned gateway lane; record_fallback emitted on provider switch.
  • byok.py — validated keys are filtered on a stored non-empty fingerprint, not provider membership.
  • subscription.py — trial-paywall and chat-quota escape hatches now require a validated LLM BYOK key (has_validated_byok_keys), and main's firestore_client/provision plumbing plus enforce_desktop_chat_quota/is_desktop_trial_paywalled are retained.
  • APIKeyService.swift — legacy provider preference is inferred from stored keys before the OpenRouter default applies.
  • DeveloperKeys settings — empty-selected-provider early return clears byokActivationError/byokKeyStatuses.
  • Windows validator/UI — capability-scoped result contract and messaging updated; OpenRouter validation now hits the auth-gated /auth/key endpoint.
  • Stale comments/tests — all-four-key comments, test names, and pi-extension diagnostics updated to capability-scoped semantics; runtime test adds absence assertions for non-selected providers.

@cursor

cursor Bot commented Aug 14, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_097aa171-3f1c-4cfe-b58b-4b76ca572ed7)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ab69c46521

ℹ️ 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".

The Settings banner derived "Free plan active" from key presence, so an
invalid key or a failed activate POST kept claiming the subscription charge
was skipped while the adjacent error said the free plan stayed off.

Track the enrollment outcome separately from field presence: initialize from
byokValidatedProviders (last successful enrollment), flip on result.active,
keep prior state when the enroll POST fails (server state unknown), and clear
on validation-failure deactivate and Clear All.

Verification: typecheck:web clean; shared/lib behavior covered by the
validated-capability vitest suites in the previous commit.
Accept firestore_client on the usage-quota snapshot mock, expect the
provider-scoped paywall cache keys, stub byokValidatedProviders in the
Windows AdvancedTab suite, and re-indent the Swift MainActor block.

Failure-Class: none
…re shape

Mark Codex migration complete even when no legacy OpenAI key exists, route Gemini BYOK around the rejecting gateway lane, require the matching provider for trial/TTS exemptions, and gate local BYOK plus Windows enrollment on the validated snapshot.
@undivisible
undivisible force-pushed the update-byok-llm-providers branch from 034175d to 7ff0691 Compare August 25, 2026 15:40

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ff06917be

ℹ️ 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".

Comment thread backend/utils/subscription.py Resolved
Comment thread backend/routers/desktop_tts_updates.py Resolved
{hasActiveLLMByok
? "You're paying your own providers. Omi skips the subscription charge. Keys stay on this PC."
: 'Provide all four keys (OpenAI, Anthropic, Gemini, Deepgram) to switch to the free plan. Keys stay on this PC — we never store them on our servers.'}
: 'Add an LLM key to switch to the free plan. OpenRouter is preferred when configured; Deepgram is optional and only powers transcription. Keys stay on this PC — we never store them on our servers.'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make OpenRouter actually preferred on Windows

When an upgraded Windows installation already has an OpenAI key and the user adds OpenRouter based on this new promise, the client enrolls and forwards both credentials, while get_llm() selects the BYOK profile's OpenAI key at backend/utils/llm/clients.py:542-549 before it considers OpenRouter at :553-559. Requests therefore continue charging the old OpenAI account rather than the advertised preferred OpenRouter account. Persist an explicit selected LLM provider and forward only that capability, as the macOS implementation does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving leftover. Making OpenRouter actually preferred on Windows needs an explicit selected-LLM-provider field and header forwarding to match macOS — larger than this pass. Not inventing a half-wired Windows selector here.

Add required_llm_provider to get_chat_quota_snapshot so quota reads no
longer NameError, require Anthropic on the direct agent route, clear
unowned pre-upgrade keys on first bind, and reject unsupported omni
providers before the trial cache.

Failure-Class: none

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a6988be309

ℹ️ 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".

Comment on lines +354 to +355
guard let selectedProvider = Self.selectedBYOKLLMProvider, Self.byokKey(selectedProvider) != nil else { return }
let generation = Self.nextReconciliationGeneration()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Serialize Settings and startup BYOK reconciliation

When startup validation is in flight and the user changes or deletes the selected key in Settings, refreshBYOKActivation() can enroll/deactivate the newer state without advancing this counter, so the old startup task still passes isCurrentReconciliation() and overwrites the backend and persisted fingerprints with its stale snapshot. Fresh evidence after the stale-reconciliation fix is that the new generation is private to reconcileBYOKActivation() and therefore does not coordinate with the Settings enrollment path; both paths need to participate in the same generation or serialization mechanism.

Useful? React with 👍 / 👎.

Comment on lines +56 to +58
const keys = await window.omi?.byokGetAll?.()
if (keys && isByokActive(keys)) {
await window.omi?.byokEnroll?.(token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Run startup enrollment after the account-switch wipe

When the light-401 flow signs out account A without wiping local data and the user reauthenticates as account B, this module-level auth callback races the awaited reconcileAccountForSignIn() guard in useAuth: it can read A's encrypted BYOK keys and invoke enrollment with B's token before the guard clears them. The activation handler captures that old key set, so completing the later local wipe does not prevent A's provider fingerprints from being enrolled for B, exposing A's provider billing and credentials across the account switch; startup reconciliation must run only after the account-owner guard has completed.

Useful? React with 👍 / 👎.

Comment on lines 100 to +102
if (!isByokActive(keys)) {
await deleteActivate(apiBase, token, backendFetch)
return { active: false, results: {} }
return { active: false, results: {}, enrolledFingerprints: {} }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Treat failed deactivation as unknown server state

When removing the last LLM key or rejecting every configured LLM key, deleteActivate() ignores both non-2xx responses and network errors, yet this result claims the backend is known to have no enrolled fingerprints. The IPC handler consequently clears the prior local enrollment evidence even if the server still enforces the old fingerprint; if a rejected replacement key remains stored, every subsequent request attaches it and receives a fingerprint-mismatch 403 until another successful reconciliation or the 24-hour heartbeat expiry. Propagate DELETE failure like POST failure and omit enrolledFingerprints while server state is unknown.

Useful? React with 👍 / 👎.

…client

Gemini and Anthropic have direct BYOK clients. When feature resolves to
either, OpenRouter preference must not override. Wrap the preference block
so it only fires for providers without a native BYOK path.
_validated_byok_keys iterated request_keys, silently skipping providers
enrolled in Firestore but not sent in request headers. Change to iterate
stored_fingerprints and fail when an enrolled provider's key is missing.
Return validated dict directly instead of filtering via fingerprint
lookup.
…llm_byok_key

request_has_llm_byok_key checked validated flag + raw keys present but
never consulted Firestore fingerprints. Add uid check and fingerprint
lookup so a validated-but-not-enrolled provider is not considered
active. Fall back to raw key check on cache failure.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d0e3a4eb3a

ℹ️ 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".

Comment thread backend/routers/users.py
Comment on lines +1125 to +1129
providers = set(data.fingerprints.keys())
if not providers - {'deepgram'}:
raise HTTPException(
status_code=400,
detail=f"Missing fingerprints for providers: {sorted(missing)}",
detail='At least one LLM provider fingerprint is required',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep non-OpenAI BYOK from using managed embeddings

When a user activates with only OpenRouter, Gemini, or Anthropic, this accepts the enrollment and grants unlimited BYOK enrichment, but memory and conversation vector writes still use _OpenAIEmbeddingsProxy, which consults only get_byok_key('openai') and otherwise calls Omi's managed OpenAI client (backend/utils/llm/clients.py:253-262; consumers include backend/database/vector_db.py:407,451). These supposedly self-funded users can therefore generate unmetered managed embedding spend. Require a compatible embedding credential, route embeddings through the selected provider, or keep these operations metered.

Useful? React with 👍 / 👎.

Comment thread backend/routers/chat.py
Comment on lines +362 to +365
def _required_chat_quota_provider() -> str | None:
# Direct agent chat consumes managed Anthropic unless an Anthropic BYOK key
# is on the request. Other BYOK providers must stay metered on this path.
return 'anthropic' if get_chat_agent_route() == CHAT_AGENT_ROUTE_DIRECT else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Meter incompatible BYOK on the gateway agent route

Fresh evidence after the direct-route fix is that the gateway branch still returns no provider requirement here. With CHAT_AGENT_ROUTE=gateway, agentic.py:1263-1264 sends every non-Anthropic request to the managed OpenAI/Luna runner, yet an OpenRouter-, OpenAI-, or Gemini-only header satisfies the generic exemption and grants unlimited /v2/messages and voice-message use while Omi pays the gateway bill. Require Anthropic for this route too, or actually forward a compatible selected credential into the gateway lane.

AGENTS.md reference: backend/AGENTS.md:L28-L28

Useful? React with 👍 / 👎.

Comment on lines 1090 to +1091
APIKeyService.shared.startFetchingKeys()
Task { await APIKeyService.shared.reconcileBYOKActivation() }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bind BYOK ownership before starting sign-in requests

Fresh evidence after the owner-binding fix is that the browser sign-in path starts fetchApiKeys() here—and schedules loadNameFromBackendIfNeeded() earlier—before the reconciliation task invokes bindBYOKOwner. After account A signs out and account B signs in, A's persisted keys and enrolled fingerprints can therefore be attached to B's profile/config requests before they are cleared; direct realtime work can also consume A's credential during this window, while an already-enrolled B can instead receive fingerprint-mismatch failures. Bind or clear BYOK synchronously inside the authenticated owner transition, before launching any post-sign-in request.

Useful? React with 👍 / 👎.

@undivisible
undivisible dismissed Git-on-my-level’s stale review August 26, 2026 18:15

All 3 blocking items fixed in d0e3a4e: OpenRouter gated on direct-BYOK providers, fingerprint validation iterates enrolled providers, trial bypass checks enrollment

@undivisible
undivisible merged commit fb67ca9 into main Aug 26, 2026
34 of 38 checks passed
@undivisible
undivisible deleted the update-byok-llm-providers branch August 26, 2026 18:22
Git-on-my-level added a commit that referenced this pull request Aug 26, 2026
PR #11454 moved macOS BYOK activation to enrollment-verified
fingerprints (isByokActive and usableBYOKEnvironment gate on
persistEnrolledFingerprints), and its own test lanes shipped red: the
tests store raw keys but never enroll them, so every key reads as
inactive. Their teardowns already clear enrollment — the setups now
enroll what they store, matching the production activation path. All 8
previously-failing cases (BYOKPaywallTests + the two
AgentRuntimeProcessTests BYOK-environment cases) pass locally.

Co-Authored-By: Claude Fable 5 <[email protected]>
undivisible added a commit that referenced this pull request Aug 27, 2026
Unused import introduced by BYOK refactor (#11454). Causes pyright error
in CI.\n\nFailure-Class: none
Git-on-my-level added a commit that referenced this pull request Aug 27, 2026
…11454's contract (#12277)

* chore(desktop): unbreak the local Swift build and formatter gate on Xcode 26

Two pre-existing blockers on `main` that fail the pre-push gate for any
desktop PR when the local toolchain is newer than the pinned Xcode 16.4:

- `AppState+Permissions.swift` has swift-format drift, and
  `desktop-swift-format-lint` runs `lint-scope` over every first-party
  Swift file. Formatter output only.
- `AppState+Transcription.swift:848` captures `alertPresenter` implicitly
  in an escaping closure. Swift 6.2 (Xcode 26.x) rejects this; Xcode 16.4
  accepts it. Writing `self.` is what the diagnostic asks for and is the
  same strong capture the implicit form already produced, so behavior is
  unchanged on both toolchains.

Failure-Class: none

* chore(desktop): dodge the Xcode 16.4 SILGen segfault on alertPresenter

Every desktop CI lane (Static & Test Contracts, Release Compile, Build &
Tests aggregate) has been red since main's d49f978 landed
`var alertPresenter: any DesktopAlertPresenting = AppKitSheetAlertPresenter()`:
the pinned Xcode 16.4 toolchain segfaults (signal 11) in silgen
emitStoredPropertyInitialization while lowering that existential-erasure
default initializer. Reproduced on main itself (d49f978, fb67ca9,
50cf064 all failed; d06e220 passed only because its desktop jobs were
path-filter skipped) and on unrelated PRs (#12269, #12272), so this is not
specific to this branch.

Move the initializer from the stored-property default position into
init(). Identical semantics on both toolchains - AppState is @mainactor
with a single designated init, and the alert tests overwrite the presenter
immediately after construction. Xcode 26.6 parses, swift-format lint
passes, changelog gate passes.

Failure-Class: none

* test(desktop): enroll BYOK fingerprints so paywall/agent tests match #11454's contract

#11454 replaced the old "all keys present in UserDefaults" check for
isByokActive with a stricter one: the selected provider's *current* key
must match a fingerprint already persisted via
APIKeyService.persistEnrolledFingerprints (set by activateBYOK
reconciliation after BYOKValidator confirms the key). Seven tests across
BYOKPaywallTests and AgentRuntimeProcessTests still set up state the old
way — raw UserDefaults keys, no enrollment — and started failing the
moment CI could actually reach them (#12276): main's own contract job
caught this on #11454 before merge, but a compiler crash landed 8
minutes earlier (tracked separately in #12275) blocked every real
desktop Swift test run afterward, so it went unnoticed.

This is a test-only fix that transcribes #11454's already-stated and
already-tested enrollment contract into the tests that never learned
about it; no Sources change.

- BYOKPaywallTests: add `enroll(_:)`, calling
  `persistEnrolledFingerprints` with the SHA-256 fingerprint of the
  provider's current key, exactly as `activateBYOK` reconciliation would
  after successful validation. Five tests were asserting on raw key
  presence: testByokActiveRequiresSelectedLLMKey (needs a *second*
  enrollment after setAllBYOKKeys() rewrites openrouter's key and
  invalidates the first fingerprint), testBuildHeadersAttachSelectedLLMByokKey,
  testBuildHeadersSuppressesOnlyInvalidByokHeader,
  testPaywallFlagSuppressedWhenByokActive, and
  testRemovingDeepgramKeyLeavesSelectedLLMByokActive (both of the last
  two now select the provider explicitly rather than relying on legacy
  first-match inference, since every provider's key is set and the test
  must enroll the same provider it selects).
- AgentRuntimeProcessTests: enroll the selected provider in
  testUsableByokEnvironmentIncludesAllKeysWhenAllProvidersAreUsable and
  testUsableByokEnvironmentSuppressesAllKeysWhenOneProviderIsKnownBad —
  usableBYOKEnvironment() gates on isByokActive before the
  CredentialHealthManager suppression these tests exercise. Both
  existing `defer` blocks now also save/restore the enrollment map.

Not touched: testBuildHeadersCanExplicitlyExcludeByokKeys and
testLowLevelTransportDefaultsToExcludingByokKeys currently pass
vacuously — neither enrolls a provider, so isByokActive is false and
headers come back nil regardless of includeBYOK. Flagging for whoever
owns BYOK rather than fixing here, since giving them real coverage
means deciding what "excluded despite being active" should assert, and
that's a product call, not a mechanical transcription of #11454.

No assertions were weakened or removed — every fix completes test setup
to match the stated contract. testPaywallFlagSuppressedWhenByokActive is
the only coverage that an enrolled BYOK user is never paywalled; it was
made to pass by enrolling correctly, not by loosening what it checks.

Fixes: #12276
Failure-Class: none

---------

Co-authored-by: David Zhang <[email protected]>
Git-on-my-level added a commit that referenced this pull request Aug 27, 2026
* feat: add JIT knowledge ledger foundation

* chore: refresh integration OpenAPI contract

* fix: make trigger evaluation release-safe

Failure-Class: none

* fix: preserve lifecycle semantics in ledger apply

Failure-Class: none

* feat: adopt guarded JIT knowledge surfaces

Route the agent preference writer through the intent-backed ledger, register a privacy-filtered entity timeline tool, render optional evidence on Windows, and add a base-ref-protected Gate F legacy-surface ratchet.

Failure-Class: none

* feat: add progressive JIT knowledge reads

Register owner-scoped current-ledger search and explicit playbook hydration, with pre-limit semantic filtering and bounded outputs. Add a content-free planner/resume migration fixture without claiming canonical transaction completion.\n\nValidation: 141 focused backend tests passed; backend typecheck reported 0 errors; repository preflight passed 120 checks.

* feat: render chat evidence on web

Render bounded, fail-soft conversation evidence after authoritative answers in both web chat entry points. Unsupported, future, duplicate, and raw failure details remain inert.\n\nValidation: 337 web tests passed; web typecheck, oxlint, and Prettier passed; repository preflight passed 120 checks.

* feat: require intent-backed ledger search results

Apply the intent-backed requirement at the final merged canonical/history filter, with a passive historical-row regression case.\n\nValidation: 54 focused backend tests passed.

* test: keep agent tool isolation stubs current

* feat: gate JIT conversation retrieval

* fix: make entity timeline scans deterministic

Failure-Class: none

* fix: honor rejected ledger projections

Failure-Class: none

* feat: render inert screen evidence on web

* fix: reuse canonical review projection

Failure-Class: none

* fix(web): await recap context effect

Failure-Class: none

* test: amortize preference tool isolation load

Failure-Class: none

* feat(app): add knowledge ledger review surface

Failure-Class: none

* feat(macos): use canonical ledger prompt projection

Failure-Class: none

* test(memory): classify legacy surface inventory roles

Failure-Class: none

* fix(app): preserve ledger history completeness state

Failure-Class: none

* feat(macos): preserve canonical ledger mirror metadata

Failure-Class: none

* fix(app): match canonical ledger ordering

Failure-Class: none

* test(api): prove ledger client schema parity

Failure-Class: none

* feat(memory): expose bounded ledger history

Failure-Class: none

* chore(api): generate ledger history clients

Failure-Class: none

* feat(retrieval): add bounded card participants

Failure-Class: none

* feat(macos): project ledger trigger watchlist

Failure-Class: none

* fix(clients): fail closed on ledger authority

Failure-Class: none

* feat(macos): expose bounded trigger snapshot

Failure-Class: none

* fix(memory): keep closed history read only

Failure-Class: none

* feat(app): disclose partial ledger history

Failure-Class: none

* test(macos): cover ledger trigger bridge

Failure-Class: none

* fix(app): use neutral ledger accents

Failure-Class: none

* chore(api): declare ledger history route policy

Failure-Class: none

* test(macos): remove unsafe JSON fixture unwraps

Failure-Class: none

* fix(memory): satisfy typed history boundary

Failure-Class: none

* fix(macos): require prompt snapshot authority

Failure-Class: none

* test(memory): prove ledger migration on emulator

Failure-Class: none

* feat(retrieval): emit bounded screen evidence

Failure-Class: none

* test(memory): classify maintenance retirement readiness

Failure-Class: none

* feat(macos): adapt Rewind metadata for triggers

Failure-Class: none

* test(retrieval): align screen timestamp contract

Failure-Class: none

* feat(memory): correct ledger facts by amendment

Failure-Class: none

* test(memory): prove ledger correction on emulator

Failure-Class: none

* feat(macos): harden local trigger observations

Failure-Class: none

* feat(agent): search bounded historical facts

Failure-Class: none

* test(macos): cover trigger observation adapter

* fix(memory): gate historical fact retrieval

* feat(memory): add gated JIT retrieval strategy

* test(memory): prove mixed-version JIT runtime parity

* chore(memory): keep JIT gate exports type-safe

* refactor(memory): isolate JIT prompt contract

* fix(conversations): round-trip owner-scoped references

Accept the conversation:<id> references emitted by JIT result cards while retaining strict UUID-only bare IDs and share links. Restrict machine IDs to a bounded safe alphabet so evidence suffixes and path-like values fail closed.

Failure-Class: none

* test(memory): join JIT citations to evidence envelope

* fix(retrieval): enforce JIT conversation search budget

Cap JIT summary searches per request and bound database hydration to the projection limit before reads. Preserve the legacy path when JIT is disabled.

Failure-Class: FC-unbounded-user-collection-in-prompt

* fix(memory): keep JIT retrieval request scoped

* test(macos): prove future JIT evidence stays inert

* fix(memory): keep JIT card citations request-global

Failure-Class: new

* fix(retrieval): separate JIT hydration from search

Treat gated owner-scoped references as exact hydration without searching transcript text for the reference. Charge every JIT candidate search to the shared four-search request budget, including snippet-bearing requests, while keeping exact hydration free and preserving released JIT-off UUID/share-link behavior.\n\nVerified:\n- cd backend && ./.venv/bin/python -m pytest tests/unit/test_conversation_jit_processing.py tests/unit/test_conversation_exact_reference_search.py -q (58 passed)\n- cd backend && uvx --from pyright==1.1.403 pyright -p pyrightconfig.json --pythonpath .venv/bin/python (0 errors)\n- git diff --check\n\nFailure-Class: FC-unbounded-user-collection-in-prompt

* fix(memory): keep repeated JIT cards index-safe

* fix(retrieval): satisfy JIT card type contract

* fix(retrieval): hydrate collected JIT cards

* test(app): preserve answers during delayed evidence requests

* test(app): exercise production evidence composition

* feat(memories): restore superseded ledger facts

* fix(memories): reconcile reverted ledger facts

* feat(memories): append reverted ledger facts

* feat(memories): synchronize revert client contract

* fix(memory): name ledger revert identity

* fix(memories): type and enlarge revert controls

* fix(memories): fence revert retries and refreshes

* fix(memories): fence ledger revert authority

* test(memory): count ledger revert rate limit

* feat: expose agent-controlled historical facts

* feat: reopen standalone ledger facts

* feat: add fail-closed JIT QA bundle routing

* feat: add safe local JIT QA backend stack

* fix: harden isolated JIT QA stack

* feat: add explicit multi-source entity timeline

* feat(backend): add JIT rollout authority

* feat(backend): fence every proactive paid boundary

* fix(backend): release proactive quota on cancellation

Release the reserved proactive quota exactly once when cancellation interrupts paid-boundary refresh or a provider retry, then re-raise cancellation without emitting retry telemetry. Add deterministic regression coverage for both cancellation points.

Failure-Class: FC-proactive-quota-cancellation | new

* fix(backend): make proactive quota cancellation safe

Detach in-flight Redis reservations on request cancellation and release only admitted slots once they settle. Move direct-provider fallback telemetry behind the fresh paid-boundary rollout check so late kill or unknown decisions cannot report false recovery.\n\nFailure-Class: FC-proactive-quota-cancellation | new

* fix(backend): preserve quota compensation during shutdown

Keep late Redis reservation compensators outside the ordinary cancellable background-task drain. Desktop and main application shutdown paths now wait for these critical compensators before cancelling ordinary work, with deterministic blocked-thread and lifecycle-order regressions.\n\nFailure-Class: FC-proactive-quota-cancellation | new

* fix(backend): use expiring proactive quota leases

* fix(backend): make quota finalization clock-safe

* fix(backend): isolate jit rollout control plane

* fix(backend): close jit control plane safely

* fix(backend): emit retry recovery after quota commit

* test(backend): keep rollout app contract fast

* feat(jit): add guarded proactivity and first-open policies

* chore(desktop): mark jit policy as internal

* test(desktop): cover jit proactivity policy flow

* feat(backend): wire durable JIT first-open processing

* feat(desktop): fence JIT proactivity runtime admission

* feat: activate authoritative JIT proactivity runtime

* fix: harden JIT proactivity authority

* fix: close proactive runtime authority gaps

* fix(jit): make first-open effects resumable

* fix(jit): fence outstanding first-open work

* fix(jit): resume app usage receipts

* fix(jit): make app usage retries no-op

Failure-Class: none

* fix(jit): allow completed usage after app deletion

Failure-Class: none

* fix(jit): register first-open folder query

Failure-Class: none

* Fix first-open import isolation

* feat(memory): govern ledger slots and prompt winners

* feat(macos): stage guarded ledger prompt adoption

* feat(jit): adopt authoritative ledger prompts on macOS

* fix(jit): close ledger adoption authority leaks

* fix(jit): reauthorize every ledger migration write

* fix(jit): fence ledger cutover publication

* fix: keep ledger prompt rollback reversible

* feat(jit): add guarded frame request retention contracts

* fix(jit): close frame retention authority and evidence lifecycle

* fix(jit): make frame retention retries and cleanup durable

* fix(jit): make frame evidence recovery and retention complete

* fix(jit): close frame retention recovery gaps

* Harden temporary frame retention and deployment

* fix: harden JIT frame retention and consumption

* fix: close JIT frame lifecycle recovery gaps

* fix: unify JIT frame authority and retention

Failure-Class: FC-split-mutation-authority

* docs: keep frame retention guidance lean

* fix: retire duplicate frame flag bindings

Failure-Class: FC-split-mutation-authority

* fix: register frame keyframe queries

Failure-Class: FC-split-mutation-authority

* fix: serialize frame retention deploys

Failure-Class: FC-split-mutation-authority

* test: cover frame pixel deletion ordering

* style: format cumulative Dart changes

* fix(app): retain permanent conversation photo fetches

* fix: bound frame vision retention and authority

* fix: drain terminal frame request metadata

* chore: record internal ledger adoption change

* feat(memory): add dark daily sweep authority

* feat(memory): harden daily sweep fences and runtime seam

* feat(memory): reconcile existing standing triggers in sweep adapter

* fix(memory): harden daily sweep recovery and source fences

* fix(memory): close daily sweep source producers

* fix(memory): close daily sweep review findings

* Add dark daily memory sweep authority and recovery

* fix(memory): harden daily sweep rejection repairs

* test(listen): stub onboarding admission in bootstrap regression

The daily sweep PR fences onboarding mode behind the server-owned
backend admission (get_backend_onboarding_admission), so the bootstrap
regression test now simulates an admitted session instead of failing
closed on a real Firestore read.

Verification: focused test passes in 1.64s (previously failed after a
4m27s Firestore timeout); full test_listen_runtime_regressions.py +
test_onboarding_question_start.py: 26 passed; black --check clean.

* fix(memory): close daily sweep rollout and retry cursors

* fix(memory): isolate daily sweep lifecycle and retry fairness

* Harden daily sweep admission and completed-day staging

* fix daily memory sweep reliability boundaries

* preserve daily sweep invocation tombstones

* close daily sweep invocation lifecycle fences

* fix: keep daily sweep lifecycle cleanup active

* fix: acquire ledger snapshot client off event loop

* fix(memory): preserve migration tier fence without legacy growth

* test(memory): prove legacy adjudication race fences

* fix(dev): allow bounded ADC readiness refresh

* test: keep ledger prepush deterministic

* test(memory): register prompt receipt control path

* fix(memory): fence ledger writer transitions

* feat(backend): preserve closed ledger history in export

* feat(memory): define ledger query semantics

* fix(backend): fence trigger snapshots on final authority

* fix(backend): bypass stale coalesced JIT refreshes

* feat(macos): mirror bounded memory evidence

Decode generated v3 evidence into a domain mirror, persist canonical bounded JSON through the memory cache, and preserve it across compatibility sync and older-local conflicts. Invalid, future-shaped, oversized, and over-count payloads fail closed without hiding memory text or granting prompt authority.

Tests: xcrun swift test --package-path Desktop --filter ServerMemoryV17DecodingTests

Tests: xcrun swift test --package-path Desktop --filter MemoryLedgerMirrorTests

Tests: python3 scripts/check_desktop_test_quality.py

Failure-Class: none

* fix(macos): fence and classify memory evidence

Keep generated memory fields independent from malformed evidence, distinguish absent valid and invalid evidence states, preserve prior evidence on invalid payloads, and gate replacements on a monotonic server timestamp so stale active evidence cannot resurrect redacted rows. Cover populated-table migration upgrades.

Tests: xcrun swift test --package-path Desktop --filter ServerMemoryV17DecodingTests

Tests: xcrun swift test --package-path Desktop --filter MemoryLedgerMirrorTests

Tests: python3 scripts/check_desktop_test_quality.py

Failure-Class: none

* fix(macos): preserve evidence fences and scrub redactions

Advance evidence revisions for identical valid payloads, fence stale active responses after a local edit, and remove artifact/device pointers from redacted evidence before canonical persistence.

Tests: xcrun swift test --package-path Desktop --filter ServerMemoryV17DecodingTests

Tests: xcrun swift test --package-path Desktop --filter MemoryLedgerMirrorTests

Tests: python3 scripts/check_desktop_test_quality.py

Failure-Class: none

* chore(macos): record ledger evidence mirror

* feat(macos): deep-link local evidence cards to Rewind

* fix(macos): fence Rewind frame evidence version

* fix(macos): validate Rewind evidence card availability

* fix(macos): bind task detail Rewind navigation to local leases

* fix(macos): fence Rewind citation owner handoff

* chore(macos): register Rewind evidence deep links

* test(macos): cover Rewind evidence navigation

* feat(desktop): evaluate JIT trigger watchlists locally

* feat(desktop): wire authoritative JIT trigger runtime

* feat(desktop): bind JIT claims to snapshot authority

* fix(desktop): revalidate trigger authority at execution

* fix(desktop): keep JIT execution leases live

* test(memory): bind standalone reopen to direct-user writer

* fix: make JIT QA sign-in self-contained

Failure-Class: new

Verification: bash desktop/macos/tests/test-jit-qa-target.sh; bash desktop/macos/tests/test-yolo-dev-backend.sh; repaired named-bundle Google sign-in reached authenticated onboarding.

* feat(memory): complete JIT policy and native Windows parity

* docs(backend): keep service map within context budget

* test(macos): cover JIT client and staging flows

* chore(backend): declare JIT mirror route policy

* fix(backend): use strict Firestore boundary for JIT admission

Failure-Class: FC-malformed-doc-read

* chore(quality): register malformed-document guard surface

* fix(backend): fail closed on malformed JIT authority

Failure-Class: FC-malformed-doc-read

* refactor(backend): name JIT workflow boundary results

* test: repair JIT CI contracts

* fix(backend): preserve ledger query exports

Retain the explicit same-name re-exports consumed by tests and downstream callers while satisfying the enforced Pyright unused-import boundary after the main rebase.

Failure-Class: none

* test(backend): isolate gateway setup timing

Failure-Class: none

* style(memory): format direct-user evidence path

Failure-Class: none

* test(agent): isolate ACP process-group fallback

Failure-Class: none

* fix(dev-harness): preserve ownership markers in narrow CI

* test(jit): refresh emulator fixtures for current contracts

* test(jit): orchestrate local rollout dogfood

* test(jit): harden local dogfood authority

* fix(dev-harness): install PostHog for CI tests

* fix(chat): project server JIT rollout into retrieval

Resolve the backend-owned PostHog decision inside the bounded agent setup path and pass only its boolean result to prompt/tool configuration. Unknown or failed authority remains on the released legacy path, while callers cannot self-enroll through configurable input.\n\nVerification: backend/.venv/bin/python -m pytest -q backend/tests/unit/test_chat_async_offload.py backend/tests/unit/test_atomicity_lifecycle_regressions.py (41 passed)\n\nFailure-Class: new

* fix(memory): preserve preference writer compatibility

Select the agent preference write path from the canonical per-user writer control. Default compatibility mode retains the released MemoryService payload and receipt behavior; ledger mode keeps the retry-stable ledger write, and transition states fail closed.\n\nVerification: backend/.venv/bin/python -m pytest -q backend/tests/unit/test_chat_async_offload.py backend/tests/unit/test_atomicity_lifecycle_regressions.py (41 passed)\n\nFailure-Class: FC-split-mutation-authority

* fix(jit): separate migration rollout authority

Keep staged JIT chat and proactive exposure independent from legacy-row migration and writer cutover. Migration now requires its own default-off PostHog flag and still rechecks the shared kill switch at every mutation and publication boundary. Repair the isolated conversation-JIT fixture for main's chat-scope import.

Verification: 217 focused JIT, chat-scope, migration, and lifecycle tests passed; 28 conversation-JIT fixture tests passed; independent Sol review accepted the split for QA-only dev rollout.

Failure-Class: FC-split-mutation-authority

* fix(photos): preserve retained image retrieval

Treat an empty legacy inline marker as absent when permanent storage is authoritative, while malformed non-empty inline payloads still fail closed. Route live and retained thumbnails through the storage-aware image loader and preserve the conversation identity through the full-screen viewer.\n\nVerification: backend data-export tests 32 passed; Flutter photo-viewer tests 5 passed; focused Dart analysis clean; independent Sol review found and verified the viewer identity repair.\n\nFailure-Class: none

* fix(memory): keep disabled daily sweep dark

Resolve the backend-owned authority before inventory and require its literal true decision before any UID discovery, registry, cleanup, scheduler, model, or commit work. Missing, malformed, throwing, disabled, and kill-switched authority now exits without touching user data; enabled behavior is preserved.\n\nVerification: 60 focused daily-sweep job, scheduler, and inventory tests passed; independent Sol review accepted the fail-closed gate.\n\nFailure-Class: FC-split-mutation-authority

* fix(jit): satisfy fail-closed type contracts

* test(backend): admit full runtime contract checks

* style(backend): format conversation bound test

* test(backend): keep conversation router isolation current

* test(backend): admit export boundary duration

* fix(macos): persist failed chat turn notice

Failure-Class: none

* fix(macos): repair JIT rollout admission contracts

Failure-Class: none

* fix(windows): treat JIT screen evidence as untrusted

Failure-Class: none

* fix(backend): preserve explicit app failure contract

Failure-Class: none

* fix(app): finish photo viewer consolidation

* fix(backend): make provider writes lock-free against the deletion gate

The account-wide legal-hold deletion gate wrapped every GCS upload and
Pinecone/Typesense upsert in an exclusive per-uid Firestore mutex with no
lease: concurrent same-account writes hard-failed (dropped audio, lost
vectors) and a crash between acquire and finish blocked the account's
gated operations forever, with no janitor. Provider writes now use a
lock-free fence that refuses only during account deletion or a live
destructive operation; destructive kinds keep exclusive ownership, an
abandoned gate self-expires after six hours, and releasing a gate on the
failure path can no longer mask the original error.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): issue onboarding admission at socket connect

The completed-onboarding early exit returned False from an Optional[str]
function; the listen runtime derives admission via 'is not None', so
users who had already completed onboarding were admitted with a
fabricated session id — the exact provenance forgery the admission
exists to prevent. Separately, the 20-minute admission TTL was anchored
to the app-launch state read, so a user reaching the speech-profile step
late (or any client that never calls the state endpoint) silently lost
onboarding questions and is_user tagging. The bootstrap now issues or
refreshes the admission from the durable account state at connect time;
completed accounts still can never re-enter, and issuing stays
best-effort with the read failing closed.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): keep the released proactivity lane open for legacy clients

Gating /v1/desktop/proactivity/completions on the JIT cohort returned
403 to every non-admitted user — which is the entire deployed desktop
fleet on deploy day, since shipped clients poll this route continuously
and treat 403 as a plain error. Context-bucket extraction and the
director would have died fleet-wide, dark cohort or not, and any
environment without a PostHog key (local, self-host) would have lost
the lane entirely. The route returns to merge-base admission semantics
(tier quotas only); JIT admission remains enforced on the JIT
reservation routes, and retiring this lane stays a later explicit
operation after clients migrate.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): withhold JIT tools and history reads outside the rollout

Five new tools (search_knowledge, search_historical_facts, read_playbook,
get_entity_timeline, look_at_frame) sat unconditionally in CORE_TOOLS, so
every legacy chat request carried their schemas and the model burned tool
budget on 'no entries found' answers. They are now filtered per request
off the same resolved rollout boolean that gates the JIT prompt appendix.
The memories-tab ledger-history endpoint likewise answered every user
with a bounded 501-row provider scan that can only ever be empty outside
the rollout; it now returns empty without the scan for non-admitted
(and unknown/error) states.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): bound rollout control-plane cost and confine sync resolution

Synchronous callers resolved rollout flags via per-call asyncio.run
against the shared provider singleton, crossing event loops: awaiting a
Task attached to another loop raises, a timed-out asyncio.run strands a
coalescer entry that then serves stale UNKNOWN forever, and the LRU cache
was mutated from multiple threads. Sync resolution now runs on one
long-lived control-loop thread with its own authority instance. Unknown
snapshots gain a 5-second negative cache — UNKNOWN can never authorize
work, and without it a fleet whose flags are simply absent pays one
uncached PostHog call per conversation finalization. The screen-sync
loop drops its force_refresh (one uncached decide per device per minute
fleet-wide) and moves to its own rate bucket so two Macs' background
sync can no longer starve conversation photo reads out of the shared
120/hour frame-requests bucket. The first-open policy's kill-switch
telemetry label also reported str(Enum) instead of the value and could
never match.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): skip eager extraction under a non-compatibility writer mode

A ledger-cutover user still ran the full L1 extraction model call at
finalization, after which writer admission refused the compatibility
write — the conflict retried, exhausted, and failed the entire
finalization for every conversation, with the model spend already paid.
Extraction now checks the canonical writer mode first and skips when the
daily sweep owns memory formation; only a positively-read
non-compatibility mode skips, so any control-state read failure
preserves the legacy eager path.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): export tolerates byte-less legacy photo rows

A conversation photo row carrying the legacy empty inline marker and no
storage reference failed the whole portability export forever, though it
holds no durable image anywhere — there is nothing to omit. Such rows now
export as metadata with a content-free gap reason. Frame requests in a
retained state keep the fail-closed contract via an explicit
require_bytes parameter.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(windows): harden JIT delivery, admission, and bootstrap boundaries

Five verified defects: (1) the exclusive notification delivery slot
leaked on any throw between reservation and commit — one SQLite hiccup
during a JIT turn permanently silenced every proactive lane; the span is
now try/finally-guarded and stale slots expire after ten minutes.
(2) The ambient lane interpolated the raw window title into a
tool-capable agent prompt; the turn now carries only the opaque context
handle plus a sanitized executable name, framed as untrusted data like
the nano-triage lane. (3) Google Calendar was fetched every ~60s before
admission, so non-cohort users with Google connected paid ~1,440 reads a
day for a refused feature; observation now gates calendar evidence on
the cached authority. (4) Rollout-authority errors reset the cache and
retried every frame (~1 req/s offline, forever); failures now back off
from 30s to 10 minutes. (5) An unguarded JIT schema exec inside the
shared database open could abort local storage for all features; the
mirror bootstrap is now isolated, keeps the host-facing tables alive,
and JIT stays inert when unavailable. Also re-checks the control-plane
owner before committing the toast so an account switch mid-turn cannot
show the previous owner's advice.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(macos): restore screen provenance, guard migrations, fence chat turns

Four verified defects: (1) every pre-existing screen-derived task lost
its 'Screen context / Open Rewind' source row because the new evidence
policy dropped any provenance that is not rewind_frame.v1; the merge-base
fallback row is restored for capture.v2/legacy refs (a test flipped to
match the regression is restored to its merge-base assertions).
(2) RewindDatabase published its pool before migrating, latching a failed
migration into a permanent false-initialized state, and three unguarded
ALTER TABLE memories migrations died with duplicate-column on machines
that ran earlier builds of this branch; migration now precedes
publication and the ALTERs/CREATEs are existence-guarded. (3) EventKit
was queried on every context visit before the flags check; non-admitted
owners now build no observation inputs. (4) A failed chat turn's
reconstructed notice could be appended into a different conversation's
transcript when the user switched sessions or cleared chat mid-flight;
both transcript resets now revoke the active turn like selectApp already
did. The pre-terminalized discard class (user Stop/watchdog) still drops
the durable notice on relaunch — pinned by a characterization test in
agent/tests/conversation-journal.test.ts with the least-invasive fix
described there.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(testing): resolve firebase-tools from the checked-in dependency

npx --prefix resolves the package bin against the current directory on
some npm versions, and the admission runner deliberately launches from an
isolated temp dir (firebase writes debug logs to cwd) — surfacing as
'sh: firebase: command not found' on hosts without brew node@22. Prefer
the vendored node_modules binary when it matches the pin; npx remains
the fallback.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(backend): keep one eager-extraction call site for the surface ratchet

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(backend): gate eager extraction at the public boundary

The writer-mode skip moves from _extract_memories_inner to
extract_memories: the replace-policy contract test pins the inner helper
to exactly the canonical replacement path, and the public boundary is
the better seam anyway — a sweep-owned user now skips parity capture and
usage tracking along with the model call.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(listen): stub onboarding admission issuance in bootstrap regression

The connect-time ensure call landed in a harness that only stubbed the
read, so the bootstrap test paid an extra real-module exception path and
grazed the 0.30s fast-unit CPU budget under fanout load. Stub the
issuance like the read.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(listen): allowlist the bootstrap regression's CPU budget

The full listen-runtime bootstrap test measures exactly at the 0.30s
fast-unit CPU budget under a saturated pre-push fanout (CPU inflates
~2x there per the guard's own notes) while passing comfortably alone.
It exercises deliberately heavyweight machinery; record it as an
intentional exception rather than trimming the coverage.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(backend): keep list(CORE_TOOLS) literal through JIT tool gating

The JIT-only tool filter replaced the list(CORE_TOOLS) assignment with an
inline comprehension, which broke the prompt-cache structural invariant
(test_prompt_cache_optimization.py::test_core_tools_used_in_both_functions).
Restore the list(CORE_TOOLS) copy and apply the JIT-only filter as a
conditional pass, preserving rollout semantics and tool order.

* feat(jit): drop automatic goal updates from the JIT featureset

Product decision (David, 2026-08-26): goals change only through explicit
user action for JIT-admitted conversations. Goal progress is no longer a
first-open obligation — the effect is removed from FIRST_OPEN_EFFECTS and
the worker, and the policy plan can no longer express deferring it.
Legacy obligations carrying a pending goal_progress row are normalized
away and complete on the remaining two effects. Non-JIT (legacy eager)
conversations keep today's automatic goal updates unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(sweep): one summary-spine agent pass per day, with folder backstop

Replaces the per-conversation transcript extractor in the completed-day
producer with a single two-phase agent run: the whole day's conversation
summaries go in as one bounded spine (200 conversations / 120k chars —
effectively unreachable, so heavy days no longer stall the cursor), and
the agent may request up to 8 raw transcript excerpts (8k chars each) to
verify specifics before finalizing. At most two provider calls per user
per day, both inside the existing at-most-once invocation fence; the
staged page carries the memory candidates AND folder assignments for the
day's unopened, unfiled conversations, applied idempotently (first-open
or user assignment always wins). Memories must cite their source
conversations; uncited output is dropped. The cost gate becomes a
worst-case ceiling checked before any call. The onboarding cold-start
channel keeps per-conversation transcript extraction unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(sweep): harden the daily agent prompts from a real-data lab pass

Iterated on one real heavy day (26 conversations) with strong- and
weak-model stand-ins, an adversarial judge, and hand-verified transcript
ground truths. Rules added, each pinned to an observed failure: actor
binding in active voice with a personal-attribute gate (a discussed or
recommended topic is never someone's attribute; judgments about named
people are stored as assessments); decision-state basis labels binding
the verb (decided/proposed/observed, discussed-no-outcome dropped);
salience ordering (money, metrics, named-party intent, identity, and
durable decisions before any operational fact; one fact per memory);
never guessing the direction of an invitation/offer/commitment (verify
or drop); and no deferring the whole answer to verification. The agent
output schema gains a 'basis' field. The memories QoS call-site
inventories now count the daily-sweep agent's call site (3 -> 4).

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(sweep): tune the daily agent prompts against the real memories model

Ran the assembled prompts against gpt-5.6-luna (the real 'memories'
route model) on the same real day. Three refinements from observed
behavior: the basis label no longer leaks into memory text (metrics
read as metrics, not 'David observed that…'); the never-guess-direction
trigger is mechanical (passive/verbless summary phrasing or 'Speaker'
as the actor forces a transcript_request — luna confidently inverted
'Tim: Invited to New York' until this; with it, phase B verifies and
corrects to the true direction), hedging is itself a request signal,
and nothing high-salience may be silently dropped; and a rich-day yield
anchor (8-16 memories for 15+ conversations) counters the model's
over-pruning without inviting padding. Final real-model run: 11 true
memories + 2 legitimate verification requests, zero fabrications,
~22k tokens (~2 calls) for a 26-conversation day.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(sweep): profile-maintaining slots, ledger lookups, cache-ready prompts

The daily agent now sees the user's current profile (the same
get_prompt_memories seam chat uses — the ledger render for migrated
users), may run up to 4 owner-scoped prior-memory keyword lookups
(provider fail-soft; hits re-read through the canonical store before
disclosure) to dedup and supersede, and may name a slot for standing
attributes — an occupied slot becomes an amend through the existing
canonical occupancy check, so the daily run maintains the rendered
profile with no second write path. Both phase prompts share a
byte-identical prefix (pinned by a test) and pass a per-user
prompt_cache_key through get_llm; measured against gpt-5.6-luna the
provider cache is exact-match rather than prefix-based today, so this
is future-proofing rather than present savings.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(sweep): type the memory-searcher seam for the pyright contract

CI's authoritative typecheck rejected the untyped lookup seam
(memories.py: list(Any or [])). The searcher is now
Optional[Callable[[str], Sequence[str]]] and results are built through
a typed comprehension; behavior unchanged (absent or failing searcher
still degrades to an empty result block).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: repair four main-inherited CI breakages after sync

origin/main is currently red on its own tip; syncing it into this PR
inherits the breakage, so the fixes ride here:
- subscription.py: drop the unused get_byok_keys import (pyright
  reportUnusedImport fails the Backend unit suite).
- AppState+Transcription.swift: explicit self for alertPresenter inside
  the escaping showAlert completion (strict-concurrency compile error in
  all three Desktop Swift lanes, shipped red on main by d49f978).
- AppState+Permissions.swift: pinned swift-format drift from the same
  main commit (desktop-swift-format-lint).
- web/app/bun.lock: add the prettier + prettier-plugin-tailwindcss
  entries 64db30c pinned in package.json without updating the
  lockfile (frozen install fails web-app-checks).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(sweep): close the second review round's findings

Three parallel adversarial reviews over the post-takeover additions:
- Clamp every model-controlled phase-B input (draft memories, request
  reasons, lookup queries/results) and add the clamped worst case to the
  pre-call cost ceiling, which previously under-estimated phase B.
- Attest an empty consumed day when the staged page carries an older
  stage schema version instead of stalling the cursor forever on every
  deploy-boundary schema bump.
- Make the folder backstop's unfiled check and write share one
  transaction so a concurrent first-open/user assignment always wins.
- Let equal-rank sweep candidates amend sweep-authored slot occupants:
  the profile-maintenance path froze after a slot's first write. User
  statements still always win; slotless subject matches still dedup.
- Neutralize ``` fences in summaries/excerpts/lookup results, and mark
  raw-transcript fallback rows '(unstructured transcript excerpt)' with
  a prompt rule refusing slots/personal attributes from them without
  transcript verification (test pins the marker to the rule).
- Remove the dead first-open goal-authority threading left by the goals
  removal, and update the stale jit-first-open-runtime doc.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: repair three more main-inherited breakages

All shipped red on main and only surfaced once earlier failures were
cleared:
- AppState.swift: move the alertPresenter default out of the stored
  property initializer — Xcode 16.4's SILGen segfaults (signal 11)
  emitting it, which failed all three Desktop Swift lanes even after
  the explicit-self fix.
- test_byok_security.py: main's BYOK rewrite (d0e3a4e, 1da8880)
  changed request_has_llm_byok_key to per-provider enrollment checks and
  made partial headers fail closed, but left the tests targeting the old
  get_byok_keys()-based lenient contract (masked on main because pyright
  failed before pytest ran). The tests now assert the shipped strict
  contract their own docstrings already describe.
- subscription.py: pinned-black formatting for the BYOK fallback
  expression (the Formatting lane rejects the file as main wrote it).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(tests): stub the chat-agent gateway route pin in the chat router harness

Main's a6988be made routers.chat import CHAT_AGENT_ROUTE_DIRECT /
get_chat_agent_route from utils.llm.gateway_client, but the chat-router
test harness (and test_chat_file_upload_unsupported's local override)
stub utils.llm.gateway_client without those symbols, so every suite that
loads the real router failed at import — masked on main because pyright
fails its Backend unit suite before pytest runs. Ninth main-inherited
repair in this sync.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(tests): teach test_chat_quota's utils.byok stub the rewritten import surface

utils/subscription.py now imports get_byok_uid and get_cached_byok_state
(main's BYOK rewrite); the module-scoped utils.byok fake predates them, so
reloading subscription under the fake raised ImportError at setup — and the
polluted process took test_chat_openapi_operation_ids and
test_desktop_screen_crisp down with it in CI's batched run (all three pass
standalone). Tenth main-inherited repair, same pyright-masked pattern.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(tests): update three more suites for main's BYOK/gateway import surface

Same pyright-masked pattern as the harness and test_chat_quota repairs:
- test_desktop_transcribe stubbed utils.llm as a non-package, so
  routers.chat's new utils.llm.gateway_client import could not resolve
  (50 failures); the submodule is now in its stub list.
- test_paywall_reconnect_gate's BYOK escape-hatch tests never set the
  request uid context that the enrollment-verifying rewrite requires
  (middleware sets it in production); they now do, and teardown clears it.
- test_chat_session_app_identity's enforce_chat_quota stub rejected the
  new required_llm_provider keyword.

All three suites pass locally (69 + 35 + 6).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(tests): enroll fingerprints in the desktop BYOK tests

PR #11454 moved macOS BYOK activation to enrollment-verified
fingerprints (isByokActive and usableBYOKEnvironment gate on
persistEnrolledFingerprints), and its own test lanes shipped red: the
tests store raw keys but never enroll them, so every key reads as
inactive. Their teardowns already clear enrollment — the setups now
enroll what they store, matching the production activation path. All 8
previously-failing cases (BYOKPaywallTests + the two
AgentRuntimeProcessTests BYOK-environment cases) pass locally.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(deploy): enable the daily memory sweep on development

The sweep's five deployment inputs were pinned off in every environment, so
cohort enrolment alone could never start it -- turning it on for a dogfood
account required a second PR. Development now carries the live values:

- ENABLED/MODEL_ENABLED on, so the job stops exiting at its first authority
  gate and the model authority can budget a route.
- MODEL_NAME pinned to gpt-5.6-luna, which is the declaration interlock the
  runner checks against get_model('memories') before any provider call.
- MAX_MODEL_COST_USD 0.80, the worst-case pre-call ceiling for a maximal day
  including phase B's clamped draft/reason/lookup overhead.
- COHORT_ENABLED on with COHORT_FLAG daily-memory-sweep-v1, so enrolment is a
  per-uid PostHog boolean and an unnamed cohort stays a closed rollout.

Production is deliberately untouched and stays fully pinned off. The job still
cannot form a memory for anyone until that flag exists and resolves true for a
uid, which remains a control-plane action rather than a deployment one.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(firestore): terminate the daily-sweep occupant indexes with __name__

The six daily-sweep occupant lookups were the only declarations in the
manifest without a trailing __name__ field -- 63 of 69 entries carry one,
and main had none missing it. Firestore appends the terminator itself and
reports the index back that way, so these six could never match the live
inventory.

The failure mode is not a missing index; the indexes build fine. It is that
reconciliation never converges: every run reports the same six as missing,
tries to create them, and fails on ALREADY_EXISTS. That takes down the
Firestore schema workflow on both environments permanently, and with it the
development backend deploy's readiness gate -- the same class of outage the
workflow's own header records from the hourly_usage index in PR #11979.

The derived specs previously appended their extra predicates to the base
spec's index_fields, which would have placed them after the terminator, so
the shared prefixes are now named explicitly and each spec ends with
__name__. Verified against real Firestore: reconciliation reports zero
missing indexes in both based-hardware and based-hardware-dev.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: close final JIT rollout and CI gaps

Fence direct JIT tools and frame pixels, keep Windows account wipes safe after optional schema failures, and repair inherited CI regressions.

Failure-Class: none

---------

Co-authored-by: David Zhang <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
## What changed and why

Make backend Python formatting converge automatically through one pinned
wrapper used by pre-commit, pre-push, and CI. PR #11454 reached its
final CI run with two Python files that local checks had allowed
through; the exact failure is visible in [Repo Checks run
32996234890](https://github.com/BasedHardware/omi/actions/runs/32996234890/job/98266511125).

The wrapper uses an already-installed Black 26.5.1 when available and
otherwise resolves that exact version through cached `uvx`. This does
not add a status check, approval, checklist, or deploy step; it replaces
three disagreeing formatter paths in the existing workflow.

## Product invariants affected

none

## How it was verified

- `bash scripts/test-backend-python-format.sh` — exact, stale, and
missing formatter paths passed.
- `bash scripts/test-pre-commit-pinned-toolchains.sh` — existing hook
toolchain contracts passed.
- `bash scripts/test-pre-push-backend-test-cap.sh` — existing bounded
pre-push behavior passed.
- `python3 .github/scripts/test_run_checks.py` — 47 manifest contract
tests passed.
- `python3 .github/scripts/check_agents_md_lean.py` — all nine agent
guides stayed within budget.
- `actionlint -shellcheck '' .github/workflows/repo-checks.yml` —
workflow syntax passed.
- `OMI_PR_BODY_FILE=/tmp/omi-backend-formatter-pr-body.md make
preflight` — all 110 repository checks passed after rebasing onto
current `origin/main`.
- Bounded pre-push checks passed for formatter contracts, backend type
checking (0 errors), runtime-image closure, 28 focused backend tests,
OpenAPI compatibility/generation, workflow contracts, and desktop-flow
lint. The unrelated desktop Swift compile was retried with
`PRE_PUSH_SKIP_DESKTOP_SWIFT=1` after SwiftPM's FluidAudio cache lacked
commit `19600a485baa4998812e4654b70d2bab8f2c9949`; this PR changes no
desktop source.

## Tests

`scripts/test-backend-python-format.sh` is the regression test: it
proves all three callers delegate to the shared pin, exact local Black
avoids a download, stale Black self-corrects through `uvx`, and a
machine missing both gets the canonical uv install path.

## Failure class (fixes)

Failure-Class: none

## New guards (only when adding a check or ratchet)

The guard would have caught PR #11454 / run 32996234890 before its late
CI formatting failure. It is a shared primitive rather than a parallel
policy check: the contract test protects the single formatter executable
that every existing local and CI caller now invokes.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12448?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. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

desktop needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants