Skip to content

S13: desktop .planGated at Gemini and pixel lane clients - #12863

Merged
Git-on-my-level merged 7 commits into
mainfrom
feat/free-tier-s13-plan-gated
Sep 6, 2026
Merged

Git-on-my-level merged 7 commits into
mainfrom
feat/free-tier-s13-plan-gated

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

S13 — desktop .planGated at the two clients

Shard S13 of the ratified local-models free-tier program (omi-knowledge-base/projects/local-models-free-tier/implementation/60-shards.md S13; spec 30-desktop-proactivity.md §3.1). S14 already 402s Gen-1 Gemini generate/stream. This PR stops the desktop from retrying that refusal and builds the cached entitlement service S11 will consume.

What changed

  • New SubscriptionEntitlementService caches GET /v1/users/me/subscription. Authority is that snapshot, not TierManager and not the trial-paywall UserDefaults gate.
  • Identified basic + non-BYOK → typed non-retryable .planGated. Unknown / fetch-failed plan fails open (server decides). This overrides SubscriptionPlanType.hasPaidCapability, which treats .unknown as unpaid.
  • GeminiClient gates every public send before the retry loop, and maps HTTP 402 + error=plan_gated (including FastAPI {detail:{error}}) to .planGated. Chat-quota 402 (trial_expired) stays .apiError.
  • ProactiveLaneClient pre-gates pixels only (imageData != nil). Text-only JIT nano triage stays open (S14 remaining half / S24 narrowing). HTTP 402 plan_gated still maps to .planGated so a later server gate is not retried as http_error / network.
  • Thin OMI_LOCAL_PROACTIVITY flag read at the .planGated throw sites. No local-lane implementation.
  • S15 desktop follow-ups: hub /v2/realtime/usage now sends turn_id when the session has one; mid-session provider-quota 1008 presents the usage-limit UI. Gemini idle 1008 (expectedIdleTeardown) does not.

Automatic-or-dead check

  • GeminiClient.GeminiClientError.planGated.shouldAutoRetry == false and GeminiClient.shouldAutoRetry(.planGated) == false.
  • GeminiClient.httpError on 402 + plan_gated body → .planGated even when X-Omi-Retryable: true.
  • Pixel complete(imageData:) with a gated decision throws .planGated and issues no network request.
  • Text-only complete with the same gated decision still hits the lane (JIT survives).
  • ProactiveLaneFailureClassification.classify(.planGated) is plan_gated, not network / http_error.
  • Entitlement: basic+non-BYOK gated; paid allowed; unknown allowed; BYOK basic allowed.

Red-proof: drop the try await Self.enforceManagedProactivity() at the start of sendTextRequest and the 402 mapper in httpError, and the new tests fail.

Proof

Hermetic desktop unit tests in this PR (SubscriptionEntitlementServiceTests, AIBackendErrorNormalizationTests, ProactiveLaneClientTests, RealtimeHubCloseClassifierTests). Local Xcode 16.4 is not installed on this Mac; GitHub macos-15 Desktop Swift jobs are the compile+test proof.

Dest: desktop-only. Merging does not deploy Cloud Run. Hourly desktop beta train may pick the merge up; FREE_PROACTIVITY_GATE / FREE_TIER_LOCAL_PROCESSING stay off.

Line-count ratchet

Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubSession.swift | 1819 -> 1821 | S15 follow-up: pass existing turn_id into hub usage reports
Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+SessionDelegate.swift | 1572 -> 1578 | S15 follow-up: present usage-limit UI only after quota 1008 failover exhausts

Cut list

  • Server gate on desktop_proactivity completions (JIT lane; do not take).
  • Pixel-vs-text discrimination inside Gemini generateContent (S24).
  • Local-lane implementation behind OMI_LOCAL_PROACTIVITY (S9/S24).
  • S11 finalization wiring (consumes this entitlement service).
  • Pusher-hardening decision 4; prod memory-maintenance-job create.

Product invariants affected

  • INV-AUTH-1
  • INV-CHAT-1

Path overlap only: APIClient.swift gained an optional turn_id on hub usage reports. Session death and transcript ownership are unchanged.

How it was verified

  • python3 desktop/macos/scripts/check_desktop_test_quality.py — OK
  • New/updated XCTest cases listed under Automatic-or-dead
  • Did not run run-swift-ci.sh locally (requires Xcode 16.4; this host is 26.6)

Tests

  • SubscriptionEntitlementServiceTests — decision matrix, cache + live BYOK, fetch fail-open, auth invalidate, usage turn_id, 402 body parse
  • AIBackendErrorNormalizationTests — .planGated not retried; 402 plan_gated vs trial_expired
  • ProactiveLaneClientTests — pixel pre-gate, text-only open, 402 map, classify ≠ network
  • RealtimeHubCloseClassifierTests — usage-limit UI only after quota failover exhausts
  • SuggestionAssistantTelemetryTests — .planGated maps to .other

Failure-Class: none

Review in cubic

Git-on-my-level and others added 4 commits September 6, 2026 08:25
Stop retrying S14's 402 plan_gated on managed Gemini, and pre-gate only
pixel ProactiveLane calls so text-only JIT triage stays open. Fold the
S15 hub turn_id and quota-1008 usage-limit follow-ups into the same client.

Co-authored-by: Cursor <[email protected]>
Desktop source changes require an in-repo fragment so Release Eligibility stays green after merge.

Co-authored-by: Cursor <[email protected]>
The new cached subscription service is consulted by Gemini/lane clients and the plan-usage settings path.

Co-authored-by: Cursor <[email protected]>
Keep the flag-read branch; the deferred-work ratchet requires a GitHub issue on new TODO comments.

Co-authored-by: Cursor <[email protected]>

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

6 issues found across 15 files

Confidence score: 3/5

  • ProactiveLaneClient.swift performs the entitlement lookup before the owner guard when authorizationSnapshot is stale, so an old delivery can be terminalized as plan-gated for the current user's plan — restore the owner check before entitlement evaluation.
  • SubscriptionEntitlementService.swift can repopulate its cache with the previous owner's subscription after sign-out or an owner switch, potentially applying the wrong proactivity gating to the new user — discard canceled refresh results when ownership changes.
  • The covers: claims in proactive-assistant-proxy-routing.yaml and plan-usage.yaml are not backed by calls through SubscriptionEntitlementService, reducing confidence that entitlement behavior is exercised — remove the claims or route the flows through the service.
  • SubscriptionEntitlementService.swift may misclassify a plan_gated marker beyond the first 512 bytes as a retryable API error; separately, 20260906-plan-gated-proactivity.json exposes internal retry and “plan gate” terminology to users — make marker detection complete and rewrite the changelog around the user-visible outcome.
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/ProactiveAssistants/Core/ProactiveLaneClient.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/ProactiveAssistants/Core/ProactiveLaneClient.swift:454">
P2: When `authorizationSnapshot` is already stale, this entitlement lookup runs before the existing owner guard and can throw `.planGated` for the current user's plan. The caller then terminalizes the old delivery as a plan gate instead of dropping it as `.ownerChanged`; check owner freshness before invoking `managedPixelDecision()`.</violation>
</file>

<file name="desktop/macos/changelog/unreleased/20260906-plan-gated-proactivity.json">

<violation number="1" location="desktop/macos/changelog/unreleased/20260906-plan-gated-proactivity.json:2">
P3: The changelog entry describes the implementation instead of the user-visible outcome: "instead of retrying paid Gemini calls" names the internal retry flow and service, and "plan gate" is internal terminology. State only what the user sees, matching the style of existing entries in releases/.</violation>
</file>

<file name="desktop/macos/e2e/flows/plan-usage.yaml">

<violation number="1" location="desktop/macos/e2e/flows/plan-usage.yaml:7">
P2: The `covers:` entry for SubscriptionEntitlementService.swift is not actually exercised by this flow. S2's `subscription_snapshot` action calls `APIClient.shared.getUserSubscription()` directly, bypassing SubscriptionEntitlementService entirely, and opening the Settings Account page does not invoke the service (it gates Gemini/ProactiveLane proactivity, not billing UI). So the flow passes regardless of the service's behavior. List the source in `covers:` only once the flow drives and verifies its gating/caching logic, or remove the entry.</violation>
</file>

<file name="desktop/macos/e2e/flows/proactive-assistant-proxy-routing.yaml">

<violation number="1" location="desktop/macos/e2e/flows/proactive-assistant-proxy-routing.yaml:10">
P2: This flow does not exercise SubscriptionEntitlementService, so listing it in `covers:` is a false coverage claim. The two bridge actions here only resolve Gemini/embedding/proactivity proxy URLs (S1) and run knowledge-ledger prompt/trigger projections (S2); neither touches entitlement gating, 402 plan_gated mapping, or entitlement caching. Remove this entry, or extend the flow with a step that actually drives the entitlement service's behavior (e.g., gating decision / fetch-fail fail-open) before claiming it as covered.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.swift:97">
P2: When sign-out or an owner switch occurs during a refresh, the canceled task can still return the previous owner's subscription and repopulate this service's cache. That can gate the new user's proactivity incorrectly for the TTL; associate refreshes with an invalidation generation/owner and discard results from obsolete tasks.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.swift:191">
P3: `isPlanGated` only searches the first 512 bytes of the 402 body for `plan_gated`, so a marker beyond that offset is missed and the error is treated as retryable `.apiError`. Drop the `prefix(512)` truncation (or guard it so the search runs over the full body) on this fallback path.</violation>
</file>

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

Re-trigger cubic

Comment on lines +454 to +461
if await managedPixelDecision() == .planGated {
// S24 local-lane seam: when OMI_LOCAL_PROACTIVITY flips, route pixels to
// LocalInferenceRuntime. Text-only completions stay ungated here.
if ProcessInfo.processInfo.environment["OMI_LOCAL_PROACTIVITY"] == "1" {
// Local lane not shipped — still fail closed to `.planGated`.
}
throw ProactiveLaneClientError.planGated
}

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: When authorizationSnapshot is already stale, this entitlement lookup runs before the existing owner guard and can throw .planGated for the current user's plan. The caller then terminalizes the old delivery as a plan gate instead of dropping it as .ownerChanged; check owner freshness before invoking managedPixelDecision().

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

<comment>When `authorizationSnapshot` is already stale, this entitlement lookup runs before the existing owner guard and can throw `.planGated` for the current user's plan. The caller then terminalizes the old delivery as a plan gate instead of dropping it as `.ownerChanged`; check owner freshness before invoking `managedPixelDecision()`.</comment>

<file context>
@@ -434,6 +450,16 @@ actor ProactiveLaneClient {
     clearCooldownsIfOwnerChanged(currentOwner)
     try checkQuotaCooldown(operation: operation)
+    if imageData != nil {
+      if await managedPixelDecision() == .planGated {
+        // S24 local-lane seam: when OMI_LOCAL_PROACTIVITY flips, route pixels to
+        // LocalInferenceRuntime. Text-only completions stay ungated here.
</file context>
Suggested change
if await managedPixelDecision() == .planGated {
// S24 local-lane seam: when OMI_LOCAL_PROACTIVITY flips, route pixels to
// LocalInferenceRuntime. Text-only completions stay ungated here.
if ProcessInfo.processInfo.environment["OMI_LOCAL_PROACTIVITY"] == "1" {
// Local lane not shipped — still fail closed to `.planGated`.
}
throw ProactiveLaneClientError.planGated
}
if let authorizationSnapshot,
!RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot)
{
throw ProactiveLaneClientError.ownerChanged
}
if await managedPixelDecision() == .planGated {
// S24 local-lane seam: when OMI_LOCAL_PROACTIVITY flips, route pixels to
// LocalInferenceRuntime. Text-only completions stay ungated here.
if ProcessInfo.processInfo.environment["OMI_LOCAL_PROACTIVITY"] == "1" {
// Local lane not shipped — still fail closed to `.planGated`.
}
throw ProactiveLaneClientError.planGated
}

description: Hermetic Settings billing subscription snapshot on offline stack
app: non-prod
covers:
- desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.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.

P2: The covers: entry for SubscriptionEntitlementService.swift is not actually exercised by this flow. S2's subscription_snapshot action calls APIClient.shared.getUserSubscription() directly, bypassing SubscriptionEntitlementService entirely, and opening the Settings Account page does not invoke the service (it gates Gemini/ProactiveLane proactivity, not billing UI). So the flow passes regardless of the service's behavior. List the source in covers: only once the flow drives and verifies its gating/caching logic, or remove the entry.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/e2e/flows/plan-usage.yaml, line 7:

<comment>The `covers:` entry for SubscriptionEntitlementService.swift is not actually exercised by this flow. S2's `subscription_snapshot` action calls `APIClient.shared.getUserSubscription()` directly, bypassing SubscriptionEntitlementService entirely, and opening the Settings Account page does not invoke the service (it gates Gemini/ProactiveLane proactivity, not billing UI). So the flow passes regardless of the service's behavior. List the source in `covers:` only once the flow drives and verifies its gating/caching logic, or remove the entry.</comment>

<file context>
@@ -4,6 +4,7 @@ tier: 2
 description: Hermetic Settings billing subscription snapshot on offline stack
 app: non-prod
 covers:
+  - desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.swift
   - desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+AccountBilling.swift
   - desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Components/SettingsContentView+BillingHelpers.swift
</file context>

- desktop/macos/Desktop/Sources/ProactiveAssistants/Core/JITProactivityPolicy.swift
- desktop/macos/Desktop/Sources/Chat/KnowledgeLedgerPromptProjection.swift
- desktop/macos/Desktop/Sources/ProactiveAssistants/Core/GeminiClient.swift
- desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.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.

P2: This flow does not exercise SubscriptionEntitlementService, so listing it in covers: is a false coverage claim. The two bridge actions here only resolve Gemini/embedding/proactivity proxy URLs (S1) and run knowledge-ledger prompt/trigger projections (S2); neither touches entitlement gating, 402 plan_gated mapping, or entitlement caching. Remove this entry, or extend the flow with a step that actually drives the entitlement service's behavior (e.g., gating decision / fetch-fail fail-open) before claiming it as covered.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/e2e/flows/proactive-assistant-proxy-routing.yaml, line 10:

<comment>This flow does not exercise SubscriptionEntitlementService, so listing it in `covers:` is a false coverage claim. The two bridge actions here only resolve Gemini/embedding/proactivity proxy URLs (S1) and run knowledge-ledger prompt/trigger projections (S2); neither touches entitlement gating, 402 plan_gated mapping, or entitlement caching. Remove this entry, or extend the flow with a step that actually drives the entitlement service's behavior (e.g., gating decision / fetch-fail fail-open) before claiming it as covered.</comment>

<file context>
@@ -7,6 +7,7 @@ covers:
   - desktop/macos/Desktop/Sources/ProactiveAssistants/Core/JITProactivityPolicy.swift
   - desktop/macos/Desktop/Sources/Chat/KnowledgeLedgerPromptProjection.swift
   - desktop/macos/Desktop/Sources/ProactiveAssistants/Core/GeminiClient.swift
+  - desktop/macos/Desktop/Sources/Services/SubscriptionEntitlementService.swift
   - desktop/macos/Desktop/Sources/ProactiveAssistants/Core/KnowledgeLedgerTriggerObservationAdapters.swift
   - desktop/macos/Desktop/Sources/ProactiveAssistants/Core/KnowledgeLedgerTriggerProjection.swift
</file context>

func invalidate() {
lock.lock()
cached = nil
inflight?.cancel()

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: When sign-out or an owner switch occurs during a refresh, the canceled task can still return the previous owner's subscription and repopulate this service's cache. That can gate the new user's proactivity incorrectly for the TTL; associate refreshes with an invalidation generation/owner and discard results from obsolete tasks.

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

<comment>When sign-out or an owner switch occurs during a refresh, the canceled task can still return the previous owner's subscription and repopulate this service's cache. That can gate the new user's proactivity incorrectly for the TTL; associate refreshes with an invalidation generation/owner and discard results from obsolete tasks.</comment>

<file context>
@@ -0,0 +1,206 @@
+  func invalidate() {
+    lock.lock()
+    cached = nil
+    inflight?.cancel()
+    inflight = nil
+    lock.unlock()
</file context>

@@ -0,0 +1,3 @@
{
"change": "Free-plan screen proactivity now stops on the plan gate instead of retrying paid Gemini calls, and a mid-session voice quota close shows the usage-limit prompt."

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 changelog entry describes the implementation instead of the user-visible outcome: "instead of retrying paid Gemini calls" names the internal retry flow and service, and "plan gate" is internal terminology. State only what the user sees, matching the style of existing entries in releases/.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/changelog/unreleased/20260906-plan-gated-proactivity.json, line 2:

<comment>The changelog entry describes the implementation instead of the user-visible outcome: "instead of retrying paid Gemini calls" names the internal retry flow and service, and "plan gate" is internal terminology. State only what the user sees, matching the style of existing entries in releases/.</comment>

<file context>
@@ -0,0 +1,3 @@
+{
+  "change": "Free-plan screen proactivity now stops on the plan gate instead of retrying paid Gemini calls, and a mid-session voice quota close shows the usage-limit prompt."
+}
</file context>
Suggested change
"change": "Free-plan screen proactivity now stops on the plan gate instead of retrying paid Gemini calls, and a mid-session voice quota close shows the usage-limit prompt."
"change": "Free-plan proactivity now stops instead of making further paid requests, and a mid-session voice quota close now shows the usage-limit prompt."

}
}
}
let body = String(data: data.prefix(512), encoding: .utf8)?.lowercased() ?? ""

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: isPlanGated only searches the first 512 bytes of the 402 body for plan_gated, so a marker beyond that offset is missed and the error is treated as retryable .apiError. Drop the prefix(512) truncation (or guard it so the search runs over the full body) on this fallback path.

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

<comment>`isPlanGated` only searches the first 512 bytes of the 402 body for `plan_gated`, so a marker beyond that offset is missed and the error is treated as retryable `.apiError`. Drop the `prefix(512)` truncation (or guard it so the search runs over the full body) on this fallback path.</comment>

<file context>
@@ -0,0 +1,206 @@
+        }
+      }
+    }
+    let body = String(data: data.prefix(512), encoding: .utf8)?.lowercased() ?? ""
+    return body.contains("plan_gated")
+  }
</file context>
Suggested change
let body = String(data: data.prefix(512), encoding: .utf8)?.lowercased() ?? ""
let body = String(data: data, encoding: .utf8)?.lowercased() ?? ""

Git-on-my-level and others added 3 commits September 6, 2026 08:41
Xcode 16.4 rejects NSLock from async functions. The cache and the test
decision seam are now actors so release compile can lock without that API.

Co-authored-by: Cursor <[email protected]>
Xcode 16.4 rejects NSLock inside async functions and also rejects actor
stored properties in a nonisolated init. Scope the lock to synchronous
helpers so the cache stays Sendable without becoming an actor.

Co-authored-by: Cursor <[email protected]>
Xcode 16.4 treats await inside XCTAssertEqual as an autoclosure and rejects it.

Co-authored-by: Cursor <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 63bbcec into main Sep 6, 2026
27 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/free-tier-s13-plan-gated branch September 6, 2026 13:58
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