Skip to content

feat(desktop): attribute Gemini proxy traffic by product lane and platform - #20184

Merged
Git-on-my-level merged 20 commits into
mainfrom
lane/gemini-lane-telemetry
Oct 3, 2026
Merged

Git-on-my-level merged 20 commits into
mainfrom
lane/gemini-lane-telemetry

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Attribute desktop Gemini proxy requests to a bounded lane and client_platform on the existing desktop_gemini_proxy_terminal JSON event. Missing/invalid lanes collapse to unknown; platform uses a telemetry-only header, falling back to the existing client-kind resolver (macos, windows, other, unknown).
  • One JSON contract generates Python, Swift, and TypeScript values. macOS GeminiClient requires 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.
  • Create request-state telemetry before FastAPI dependency solving; attribute requested model/action before body reads. Cover plan/trial 402, authorization failures, validation, limiter 429, dispatched requests, and stream cancellation without duplicate terminal events.
  • Telemetry only: no model pins, routing, PT policy, limits, subscription policy, payload inference, or deployment/workflow changes.

Cost / privacy

  • Additional log lines per already-observed request: 0. Enrich the existing single terminal event; previously silent rejection exits now emit that same one terminal event, not a separate rejection/debug line.
  • New per-request I/O: none. Static client headers and generated in-memory server allowlists; no new persistence, HTTP/model calls, analytics, or per-attempt/per-chunk logging. Existing spend-ledger writes gain bounded attribution fields and request correlation; write counts and persistence scheduling are unchanged.
  • Metric series added: none. No counters or metric labels changed.
  • Lane/platform are fixed enums only; no UID, prompt, URL, raw header value, or exception message is added to this event.

Independent Sol review fixes (findings 1, 2, 3, 5)

  • Attempt rows now carry separate bounded product_lane and client_platform fields for both gateway and direct proxy traffic. Keep feature=desktop_proactivity and coarse app_platform=desktop backward 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.
  • Swift and Windows transports send X-Omi-Client-Platform, without X-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 to other.
  • Streaming overflow RoutingFailure propagates as before while still recording exactly one structured terminal event; no SSE error-frame behavior change remains.
  • Reuse the gateway's canonical UUID validator for X-Omi-Request-Id / X-Request-Id, generating an opaque UUID for arbitrary strings before logging or forwarding.
  • Finding 4 remains known, pre-existing and out of scope: Pro soft-limit demotion is bypassed in gateway mode because the original Pro model is dispatched before the downgraded path is reparsed. The affected routing/metering logic is unchanged.
  • Regression tests exercise gateway HTTP authentication/accounting for text, stream and embeddings; direct ledger tags; bounded invalid/missing values; UUID privacy; auth's no-platform-I/O path; streaming propagation and resource cleanup; and both client header transports. The existing embedding rate card is absent, so embedding rows retain cost_status=unpriced with attributable usage; this round does not change pricing.

Lane inventory (client-requested pins, unchanged)

Lane Platforms / caller Requested model
task_extraction macOS TaskAssistant.swift; Windows assistants/tasks/geminiWire.ts macOS Flash (Premium) / Pro (Max), fallback Flash; Windows Flash / Flash
focus Windows assistants/focus/gemini.ts Flash
dictation macOS PushToTalkManager.swift Flash
suggestions macOS SuggestionAssistant.swift Flash-Lite (Premium) / Flash (Max), fallback Flash
live_notes macOS LiveNotesMonitor.swift; Windows renderer liveNotes/liveNotesMonitor.ts macOS Flash-Lite; Windows Flash
screen_synthesis Windows renderer screenSynthesis.ts Flash, existing VITE_GEMINI_MODEL override
memory macOS MemoryAssistant.swift; Windows assistants/memory/gemini.ts Flash-Lite
insight macOS InsightAssistant.swift; Windows assistants/insight/gemini.ts macOS Pro, fallback Flash-Lite; Windows Flash-Lite / Flash-Lite
goals macOS GoalsAIService.swift; Windows assistants/goals/generate.ts Flash-Lite
task_dedup macOS TaskDeduplicationService.swift Flash-Lite
task_prioritization macOS TaskPrioritizationService.swift Flash-Lite
home_suggestions macOS HomeSuggestionsStore.swift Flash-Lite
embedding macOS EmbeddingService.swift; Windows rewind/embeddingClient.ts gemini-embedding-001, single and batch

Flash = 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 to other on 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)

  • macOS dictation polish is not routed to a separate API: PushToTalkManager.runDictationPipeline constructs Flash + interactive; DictationPolisher.polish calls GeminiClient.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.
  • Windows net.fetch / renderer fetch call the Python desktop proxy directly at desktopApiBase / 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.
  • Potential existing billing/routing defect: _meter_server_request returns a Flash-Lite path for over-soft-limit Pro, but _proxy_unobserved passes the original model variable to _proxy_via_gateway before 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-1 preserved: no transcript, journal, context, or session authority changes.
  • INV-VOICE-1 preserved: dictation's model/workload/lifecycle and polish gates are unchanged; only the static lane declaration is added.
  • INV-MEM-1 preserved: extraction/retrieval policies and memory effects are unchanged; only static attribution is added.
  • INV-TASK-2 preserved: 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 through BACKEND_UNIT_TEST_FILE_LIST=/tmp/pr-20184-backend-files.txt bash backend/test.sh: 405 passed across the five original files plus test_desktop_gemini_accounting_attribution.py, test_llm_gateway_auth.py, test_llm_gateway_accounting.py, test_llm_gateway_openai_compatible.py, and test_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 with BACKEND_PYTEST_MARK_EXPR='not integration' through test.sh: all 651 nodes passed (including the 596 source-scan nodes).
  • xcrun swift build --build-tests -c debug --package-path desktop/macos/Desktop passed, including a clean rebuild after restoring removed generated dependencies; xcrun swift test --skip-build --package-path desktop/macos/Desktop --filter GeminiLaneTelemetryTests: 4 passed.
  • Existing gateway streaming-rejection fixture migrated to the required attribution fields; test_desktop_gemini_signature_contract.py through backend/test.sh: 9 passed, including forwarded UUID/lane/platform assertions.
  • npx pnpm@10 typecheck passed; npx pnpm@10 test <11 touched test files>: 76 tests / 11 files passed.
  • make preflight passed all 54 selected checks; review metadata validation passed 4/4. The full bounded pre-push hook passed for final merged head 054f7f2cf7c28a8fe46897002b39cf8b63e8efe4 (full backend Pyright: 0 errors; manifest: 54 passed), then git ls-remote confirmed the exact SHA. The pure JIT launcher contract required removing inherited GOOGLE_APPLICATION_CREDENTIALS from its test environment; the entire hook was rerun, with no bypass.
  • Merged current 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 of origin/main (8fb7dc1ccf) changes no app/desktop/Gemini production sources.
  • Generator --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

  • Terminal head checks: 37 passed, 2 failed, 21 conditionally skipped; no pending or cancelled checks. Desktop Swift Static & Test Contracts and the Xcode 27 advisory both passed. All four backend shards and their aggregate suite passed, including the migrated signature fixture; Windows and Xcode 27 advisory checks passed. The two failures are Dart Analyze & Tests and its downstream Mobile Release Eligibility gate, both from the main-branch defect below.
  • Final merged head 054f7f2cf7c28a8fe46897002b39cf8b63e8efe4 has a pre-existing Dart analyzer failure: app/test/widgets/capturing_finish_swipe_back_test.dart:120 supplies () async => [] where Future<PeopleListResponse?> is required. The test is byte-identical to merged origin/main; its provider and API are identical after canonical formatting. The PR job and main-branch job report the exact same RETURN_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.

Review in cubic

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-03T18:23:44.265656Z 107bb6a New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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 48 files

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

Re-trigger cubic

Git-on-my-level and others added 5 commits October 2, 2026 09:51
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.
@Git-on-my-level
Git-on-my-level force-pushed the lane/gemini-lane-telemetry branch from 98fb34d to 8dc970d Compare October 2, 2026 03:52

@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: 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.

@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: 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".

Comment on lines +342 to +347
except HTTPException as exc:
telemetry.complete(
outcome=_dependency_outcome(exc),
status_code=exc.status_code,
retryable=exc.status_code == 429,
phase='authorization',

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 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 👍 / 👎.

Comment on lines +227 to +231
if 'proxy/gemini' in src and rel not in {
macos_owner,
'ProactiveAssistants/Core/GeminiClient.swift',
'ProactiveAssistants/Services/EmbeddingService.swift',
}:

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 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 👍 / 👎.

Comment on lines +203 to +205
'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,

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 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 👍 / 👎.

@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: 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") ?? "",

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 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 0c00747 into main Oct 3, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/gemini-lane-telemetry branch October 3, 2026 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant