Repository navigation
feat(desktop): attribute Gemini proxy traffic by product lane and platform - #20184
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
All reported issues were addressed across 48 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…afe attribution - _stream_provider now handles RoutingFailure raised while the overflow fallback resolves its next route mid-body: the terminal event keeps the structured routing outcome (503, exc.phase) instead of degrading to a generic 500 stream_iterator_error via the terminal stream guard. - validate_attribution rejects lane keys / workload / platform values that are not non-keyword lowerCamelCase identifiers, matching what render_swift emits unquoted as case names and render_typescript interpolates; --check now fails before only the desktop compilers would. - Regression tests for both; desktop source-scan ratchets are slow-marked and the file joins tests/slow_guardrail_manifest.txt so the fast unit lane keeps its CPU budget. Verified: pytest tests/unit/test_desktop_gemini_attribution.py (55 fast + 594 slow) and tests/unit/test_desktop_proxy.py (117) all pass; generator --check clean.
… assertions - geminiProxyFetch selects /v1/proxy/gemini-stream for streamGenerateContent; the plain route loses the streaming route's handling and cancellation telemetry. - geminiClientPlatform maps Linux to 'other' (was 'linux'), matching the generated Python/Swift attribution contract's bounded platform set. - The transport-ownership ratchet normalizes path separators so the forward-slash owner literals compare correctly on Windows. - Per-owner tests assert the exact X-App-Platform value via geminiClientPlatform(process.platform) instead of set-membership (and the insight/geminiWire tests gain the previously missing assertion), so a hardcoded or detached platform header now fails. - The macOS QA probe's echoed attribution keys are renamed gemini_helper_sample_* to reflect that they verify the shared header helper contract with a fixed sample, not each lane's live wiring; the e2e flow expectations follow. Verified: vitest run over the 8 touched test files (59 tests) passes; npm run typecheck passes; swiftc -parse on the QA source passes.
98fb34d to
8dc970d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8dc970d18f
ℹ️ 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 terminal event's client_platform enum ({macos, windows, other, unknown})
is server-side; the X-App-Platform header carries client identities that
journey_metrics_contract._PLATFORM_CLIENT_KIND resolves. That resolver
recognizes 'linux' (→ desktop_linux → event 'other') but not 'other', so
sending 'other' from the Linux build would record client_platform: unknown
for every request. Restore 'linux' on the wire, document the two-level
contract on the resolver, and pin it with a test.
Verified: vitest over geminiProxy.test.ts + geminiClient.test.ts (14 tests)
and npm run typecheck pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4050f10c22
ℹ️ 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".
| except HTTPException as exc: | ||
| telemetry.complete( | ||
| outcome=_dependency_outcome(exc), | ||
| status_code=exc.status_code, | ||
| retryable=exc.status_code == 429, | ||
| phase='authorization', |
There was a problem hiding this comment.
Preserve screen-task rejection outcomes in route telemetry
When a flagged screen-task request is rejected before _proxy—either because SCREEN_TASK_STOP is enabled or an identified macOS build is below the floor—enforce_flagged_screen_task_proxy raises a typed 409 (screen_task_stopped or screen_task_build_below_floor), but this catch-all records it as authorization_rejected in the authorization phase. The response remains correct, while the new terminal event misleadingly attributes an operational/build-policy rejection to auth; inspect the exception detail here (or complete telemetry at the screen-task check) so those requests retain their actual outcome and phase.
Useful? React with 👍 / 👎.
| if 'proxy/gemini' in src and rel not in { | ||
| macos_owner, | ||
| 'ProactiveAssistants/Core/GeminiClient.swift', | ||
| 'ProactiveAssistants/Services/EmbeddingService.swift', | ||
| }: |
There was a problem hiding this comment.
Include the existing screen-task transport in the migration
When the newly manifested slow guard runs, this ownership check always fails: ProactiveAssistants/Assistants/TaskExtraction/ScreenTaskTransport.swift still constructs v1/proxy/gemini/... at line 45 and sets X-Omi-Workload at line 48, so this loop adds that file to offenders for both conditions before asserting the list is empty. Migrate that production request through the shared header transport (which also prevents its lane from remaining unknown) before enforcing this ratchet, or deliberately account for the transport in the ownership contract.
Useful? React with 👍 / 👎.
| 'lane': self.lane if self.lane in GEMINI_LANES else 'unknown', | ||
| 'client_platform': self.client_platform if self.client_platform in GEMINI_CLIENT_PLATFORMS else 'unknown', | ||
| 'workload_class': self.workload_class, |
There was a problem hiding this comment.
Retain the screen-task gate fields in terminal events
For every flagged screen-task proxy request, the refactored terminal event now drops the existing bounded gate_outcome and audit_sample dimensions. Before this extraction, ProxyTelemetry.__init__ captured direct_attempt.gate_fields(request.headers) and complete() spread those fields into the event; the new helper adds lane/platform here but omits both operations. This removes the backend correlation needed to distinguish passed, rejected, fail-open, and audited-reject Gemini calls, so preserve those fields alongside the new attribution dimensions.
Useful? React with 👍 / 👎.
…metry # Conflicts: # app/lib/pages/conversation_detail/page.dart # app/lib/pages/conversation_detail/widgets/transcript_tab.dart # app/lib/widgets/transcript.dart
…metry # Conflicts: # app/lib/services/wals/local_wal_sync.dart # app/test/services/capture/capture_transcript_coverage_test.dart
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f1ec4f4920
ℹ️ 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".
| "proactivity_base_url": ProactiveLaneClient.backendBaseURL, | ||
| "gemini_helper_sample_lane": geminiRequest.value(forHTTPHeaderField: "X-Omi-Lane") ?? "", | ||
| "gemini_helper_sample_workload": geminiRequest.value(forHTTPHeaderField: "X-Omi-Workload") ?? "", | ||
| "gemini_helper_sample_client_platform": geminiRequest.value(forHTTPHeaderField: "X-App-Platform") ?? "", |
There was a problem hiding this comment.
Read the platform header emitted by the helper
When the proactive-assistant-proxy-routing named-bundle flow runs, applyGeminiProxyHeaders sets X-Omi-Client-Platform and explicitly leaves X-App-Platform unset, so this action returns an empty gemini_helper_sample_client_platform while the updated flow expects macos. Read X-Omi-Client-Platform here so the bridge assertion can pass and actually verify the production helper contract.
AGENTS.md reference: desktop/macos/AGENTS.md:L365-L365
Useful? React with 👍 / 👎.
Summary
laneandclient_platformon the existingdesktop_gemini_proxy_terminalJSON event. Missing/invalid lanes collapse tounknown; platform uses a telemetry-only header, falling back to the existing client-kind resolver (macos,windows,other,unknown).GeminiClientrequires a lane, including all four completion transports; single/batch embeddings use the same header primitive. Windows main/renderer transports converge on one helper requiring lane and workload.Cost / privacy
Independent Sol review fixes (findings 1, 2, 3, 5)
product_laneandclient_platformfields for both gateway and direct proxy traffic. Keepfeature=desktop_proactivityand coarseapp_platform=desktopbackward compatible. Gateway text, streaming, and single-embedding requests forward the proxy UUID so terminal events join to every provider attempt. The existing generated lane vocabulary is unchanged for proactivity-v2 per-user budgets.X-Omi-Client-Platform, withoutX-App-Platform; the proxy reads this telemetry-only header without activating auth's Redis/Firestore platform persistence. Older clients retain the existing resolver fallback; Linux maps toother.RoutingFailurepropagates as before while still recording exactly one structured terminal event; no SSE error-frame behavior change remains.X-Omi-Request-Id/X-Request-Id, generating an opaque UUID for arbitrary strings before logging or forwarding.cost_status=unpricedwith attributable usage; this round does not change pricing.Lane inventory (client-requested pins, unchanged)
task_extractionTaskAssistant.swift; Windowsassistants/tasks/geminiWire.tsfocusassistants/focus/gemini.tsdictationPushToTalkManager.swiftsuggestionsSuggestionAssistant.swiftlive_notesLiveNotesMonitor.swift; Windows rendererliveNotes/liveNotesMonitor.tsscreen_synthesisscreenSynthesis.tsVITE_GEMINI_MODELoverridememoryMemoryAssistant.swift; Windowsassistants/memory/gemini.tsinsightInsightAssistant.swift; Windowsassistants/insight/gemini.tsgoalsGoalsAIService.swift; Windowsassistants/goals/generate.tstask_dedupTaskDeduplicationService.swifttask_prioritizationTaskPrioritizationService.swifthome_suggestionsHomeSuggestionsStore.swiftembeddingEmbeddingService.swift; Windowsrewind/embeddingClient.tsgemini-embedding-001, single and batchFlash =
gemini-2.5-flash, Flash-Lite =gemini-2.5-flash-lite, Pro =gemini-2.5-pro. Windows sources also ship Linux: explicit Linux platform is normalized tootheron the server. There are no invented macOS Focus/screen-synthesis Gemini callers. Existing backend model remapping/overflow remains unchanged; this table is requested pins, not a claim that Pro is served directly.Findings (not fixed)
PushToTalkManager.runDictationPipelineconstructs Flash + interactive;DictationPolisher.polishcallsGeminiClient.sendTextRequest, which uses the identity-bound desktop proxy base plus/v1/proxy/gemini/models/...:generateContent. It only runs when text is nonempty, policy is.required, network is allowed/online. The client-side managed-proactivity gate rejects identified Basic non-BYOK users before HTTP, and server plan/trial 402 previously happened before terminal telemetry existed. These are code-proven reasons requests may be absent; no production access was used to explain the specific zero-count window.net.fetch/ rendererfetchcall the Python desktop proxy directly atdesktopApiBase/VITE_OMI_DESKTOP_API_BASE. The in-tree Rust package contains old model policy, not a Gemini HTTP relay; there is no intermediary custom-header forwarder to fix._meter_server_requestreturns a Flash-Lite path for over-soft-limit Pro, but_proxy_unobservedpasses the originalmodelvariable to_proxy_via_gatewaybefore reparsing that path. In gateway mode, this appears to defeat quota demotion and select the Pro gateway lane instead (which remaps to the costlier target Flash-Lite family). Left unchanged; this is code-path evidence, not a live billing measurement.Why isn't this just a guard?
It is a shared primitive: generated enum values plus required Swift/TypeScript interfaces and centralized header/transport ownership. Narrow source tripwires supplement behavioral request/event tests to catch future bypasses. Triggering evidence is the operator's 2026-09-30 14:00–20:00Z observation: 42% unknown Flash workload, no lane/platform attribution, and invisible plan-gated requests. No live query was repeated for this PR.
Product invariants affected
INV-CHAT-1preserved: no transcript, journal, context, or session authority changes.INV-VOICE-1preserved: dictation's model/workload/lifecycle and polish gates are unchanged; only the static lane declaration is added.INV-MEM-1preserved: extraction/retrieval policies and memory effects are unchanged; only static attribution is added.INV-TASK-2preserved: candidate/extraction/deduplication/prioritization policies and effect gates are unchanged; only required lane declarations are added.Failure-Class: none
Review-round validation (2026-10-03)
BACKEND_UNIT_TEST_FILE_LIST=/tmp/pr-20184-backend-files.txt bash backend/test.sh: 405 passed across the five original files plustest_desktop_gemini_accounting_attribution.py,test_llm_gateway_auth.py,test_llm_gateway_accounting.py,test_llm_gateway_openai_compatible.py, andtest_llm_gateway_embeddings_route.py. Original files:test_desktop_gemini_attribution.py,test_desktop_proxy.py,test_desktop_gemini_gateway.py,test_managed_spend_ledger.py,test_fallback_observability.py. Attribution repeated withBACKEND_PYTEST_MARK_EXPR='not integration'throughtest.sh: all 651 nodes passed (including the 596 source-scan nodes).xcrun swift build --build-tests -c debug --package-path desktop/macos/Desktoppassed, including a clean rebuild after restoring removed generated dependencies;xcrun swift test --skip-build --package-path desktop/macos/Desktop --filter GeminiLaneTelemetryTests: 4 passed.test_desktop_gemini_signature_contract.pythroughbackend/test.sh: 9 passed, including forwarded UUID/lane/platform assertions.npx pnpm@10 typecheckpassed;npx pnpm@10 test <11 touched test files>: 76 tests / 11 files passed.make preflightpassed all 54 selected checks; review metadata validation passed 4/4. The full bounded pre-push hook passed for final merged head054f7f2cf7c28a8fe46897002b39cf8b63e8efe4(full backend Pyright: 0 errors; manifest: 54 passed), thengit ls-remoteconfirmed the exact SHA. The pure JIT launcher contract required removing inheritedGOOGLE_APPLICATION_CREDENTIALSfrom its test environment; the entire hook was rerun, with no bypass.origin/main(8bfac915d9) after it advanced during the hook. Both Dart conflicts were proven formatting-only against the former merge base; resolutions preserve current main content. Six affected Flutter suites passed all 170 tests. The later clean merge oforigin/main(8fb7dc1ccf) changes no app/desktop/Gemini production sources.--check,git diff --check, pinned Pyright on six changed gateway/accounting/telemetry modules (0 errors), and PR metadata validation passed. One-minute load was below 30 at heavy-suite admission. No CPU limits, allowlists, or hooks bypassed.CI follow-up
054f7f2cf7c28a8fe46897002b39cf8b63e8efe4has a pre-existing Dart analyzer failure:app/test/widgets/capturing_finish_swipe_back_test.dart:120supplies() async => []whereFuture<PeopleListResponse?>is required. The test is byte-identical to mergedorigin/main; its provider and API are identical after canonical formatting. The PR job and main-branch job report the exact sameRETURN_OF_INVALID_TYPE_FROM_CLOSURE. Left unchanged because only branch-caused CI failures are authorized for this fix round.Validation limits
Live services, model inference, deployed telemetry, app installation/launch and named-bundle E2E were not run. Regression coverage uses local fake providers and request/ledger capture. The named-bundle E2E flow includes a pure header snapshot for future QA.
🤖 Generated with Claude Code