Repository navigation
feat: Free trial paywall — backend endpoint, desktop countdown UI, pre-expiry nudges (#7329) - #7341
Conversation
Test Results & Evidence1. Backend Unit Tests — 30/30 PASS2. Rust Backend — 190/190 tests PASS + clean compile3. Swift Desktop Build — clean compile4. App ScreenshotsSettings > Plan & Usage — paid user (trial card correctly hidden) Paid users see their normal plan card without trial noise. The trial countdown card is correctly suppressed since Home screen — app runs normally with trial infrastructure loaded App launches, authenticates, loads home screen with all features operational. Trial metadata refresh timer and TrialBannerService running in background. 5. Happy Case Coverage
by AI for @beastoin |
Greptile SummaryThis PR implements a 3-day free trial paywall end-to-end: a new Python endpoint (
Confidence Score: 3/5The backend and Rust layers are ready, but the Swift integration has real threading defects that will produce runtime warnings in every build and could silently drop UI updates or cause data races in TrialBannerService. The Python endpoint, Rust proxy, and UI layout are all well-structured. The two Swift issues — off-main-thread @published mutation and missing sign-out cleanup — are present in the shipped code path: every 60-second poll hits the threading defect, and every sign-out leaves the timer and Combine subscription alive. Neither is speculative. They also compound: fixing the Task executor would also resolve the @mainactor sink issue in TrialBannerService. AppState.swift and OmiApp.swift need the most attention — the Task executor annotation fix and sign-out cleanup wiring. TrialBannerService.swift's threading concern resolves as a consequence. Important Files Changed
Sequence DiagramsequenceDiagram
participant Swift as Swift AppState
participant Rust as Rust /v1/trial (60s cache)
participant Python as Python /v1/users/me/trial
participant Firebase as Firebase Auth
Swift->>Rust: GET /v1/trial (Bearer token)
alt "cache hit (< 60s)"
Rust-->>Swift: cached TrialMetadataResponse
else cache miss
Rust->>Python: GET /v1/users/me/trial (Bearer token)
Python->>Python: check plan (paid/BYOK → trial moot)
Python->>Firebase: get_user(uid) → creation_timestamp
Python-->>Rust: TrialMetadata JSON
Rust-->>Swift: TrialMetadataResponse (cached)
end
Swift->>Swift: "trialMetadata = metadata [⚠️ background thread]"
Swift->>Swift: "if trialExpired → isPaywalled = true"
Swift->>TrialBannerService: $trialMetadata publisher fires [⚠️ may be background]
TrialBannerService->>TrialBannerService: evaluate() → showOnce() nudge banner
|
| Task { | ||
| do { | ||
| let metadata = try await APIClient.shared.getTrialMetadata() | ||
| self.trialMetadata = metadata | ||
| // Sync paywall flag from trial state | ||
| if metadata.trialExpired && !self.isPaywalled { | ||
| self.isPaywalled = true | ||
| } | ||
| } catch { | ||
| log("AppState: failed to fetch trial metadata: \(error.localizedDescription)") | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Off-main-thread
@Published mutation
fetchTrialMetadata creates a plain Task { } with no executor annotation, so the async continuation runs on the cooperative thread pool — a background thread. The two assignments (self.trialMetadata = metadata and self.isPaywalled = true) update @Published properties from that background thread. SwiftUI's ObservableObject machinery requires mutations to happen on the main thread; doing so off-main causes a "Publishing changes from background threads is not allowed" runtime warning in Xcode/SwiftUI, and can produce undefined UI behavior. Changing Task { to Task { @MainActor in would fix both assignments in one line.
| func fetchTrialMetadata() { | ||
| Task { | ||
| do { | ||
| let metadata = try await APIClient.shared.getTrialMetadata() | ||
| self.trialMetadata = metadata | ||
| // Sync paywall flag from trial state | ||
| if metadata.trialExpired && !self.isPaywalled { | ||
| self.isPaywalled = true | ||
| } | ||
| } catch { | ||
| log("AppState: failed to fetch trial metadata: \(error.localizedDescription)") | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Marking the task
@MainActor ensures both @Published property assignments happen on the main thread, which is required by SwiftUI's ObservableObject machinery.
| func fetchTrialMetadata() { | |
| Task { | |
| do { | |
| let metadata = try await APIClient.shared.getTrialMetadata() | |
| self.trialMetadata = metadata | |
| // Sync paywall flag from trial state | |
| if metadata.trialExpired && !self.isPaywalled { | |
| self.isPaywalled = true | |
| } | |
| } catch { | |
| log("AppState: failed to fetch trial metadata: \(error.localizedDescription)") | |
| } | |
| } | |
| } | |
| func fetchTrialMetadata() { | |
| Task { @MainActor in | |
| do { | |
| let metadata = try await APIClient.shared.getTrialMetadata() | |
| self.trialMetadata = metadata | |
| // Sync paywall flag from trial state | |
| if metadata.trialExpired && !self.isPaywalled { | |
| self.isPaywalled = true | |
| } | |
| } catch { | |
| log("AppState: failed to fetch trial metadata: \(error.localizedDescription)") | |
| } | |
| } | |
| } |
| // Start trial metadata polling (countdown UI + pre-expiry nudges) | ||
| if let state = AppState.current { | ||
| state.startTrialMetadataRefresh() | ||
| TrialBannerService.shared.start(appState: state) | ||
| } |
There was a problem hiding this comment.
Trial refresh and banner service never cleaned up on sign-out
startTrialMetadataRefresh() and TrialBannerService.shared.start() are called here, but stopTrialMetadataRefresh() and TrialBannerService.shared.stop()/reset() are not wired into any of the three sign-out paths (SettingsPage sign-out button, delete-account flow, and menu-bar signOut()). After sign-out the 60-second timer keeps firing, the Combine subscription stays live, and the UserDefaults nudge flags (trial_nudge_24h_shown, etc.) are never cleared — so if a different account signs in or the same user starts a new trial, nudge banners will not fire.
Test Evidence — All Happy PathsBackend Unit Tests (30/30 PASS)Rust Backend — Compiles CleanSwift Desktop — Builds SuccessfullyBackend API Response (paid user, fail-open)GET /v1/trial → 200 OK
{
"trial_started_at": null,
"trial_ends_at": null,
"trial_remaining_seconds": 0,
"trial_expired": false,
"trial_duration_seconds": 259200,
"trial_features": ["unlimited_conversations", "ai_summaries", "smart_search", "custom_agents", "priority_processing"],
"plan_after_trial": "Free"
}Note: Desktop UI Screenshots — All 4 Trial States1. Active Trial (2d 1h remaining)
2. Expiring Trial (30m remaining, <1h threshold)
3. Expired Trial
4. Paid User (no trial card)
Floating Bar Nudges (threshold-based, one-time)
Architecture Summaryby AI for @beastoin |
All User Flows — Complete EvidenceUser Flow Matrix
Backend Behavior per User TypeDesktop UI Screenshots — All 5 Distinct Visual States1. Paid User — No Trial Card
2. Free User — Active Trial (>24h, Green)
3. Free User — Warning (<24h, Yellow)
4. Free User — Expiring (<1h, Orange)
5. Free User — Expired (Red/Warning)
Floating Bar Nudge Thresholds (one-time, UserDefaults-deduped)
Debug Testing SupportAdded defaults write com.omi.<bundle> debug_trial_mode "active" # green, 2d 1h
defaults write com.omi.<bundle> debug_trial_mode "warning" # yellow, 12h
defaults write com.omi.<bundle> debug_trial_mode "expiring" # orange, 30m
defaults write com.omi.<bundle> debug_trial_mode "expired" # trial ended
defaults delete com.omi.<bundle> debug_trial_mode # real APIBackend Tests — 30/30 PASSAll unit tests pass covering: endpoint routing, auth, trial timing, paid/BYOK bypass, fail-open, boundary conditions, model serialization. by AI for @beastoin |
End-to-End User Flow: Trial → Expiry → Purchase → Post-PurchaseLive test using Step 1: New User — Home Screen with Trial Nudge
Step 2: Settings — Trial Active, Counting Down
Step 3: Trial Expires — Paywall Triggered
Step 4: User Clicks "View Plans" → Plan Selection
Step 5: Billing Options Appear
Step 6: Checkout Loading
Step 7: Purchase Complete — Plan Upgraded
Step 8: Post-Purchase Clean State
Flow SummaryNote: The "Trial Ended" card persists in this test because the prod backend doesn't have the by AI for @beastoin |
API Redesign: Unified Entitlements (Phase 2 Design Doc)
See attached: ProblemClients need 3-5 API calls to determine "what can this user do?":
Each has its own cache TTL, platform-conditional behavior, and clients must reimplement enforcement logic. Solution:
|
| Endpoint | Responsibility | Cache TTL |
|---|---|---|
GET /v2/users/me/entitlements |
What can I do? (enforcement) | 30-60s |
GET /v2/users/me/plan |
What plan am I on? (state only) | 5 min |
GET /v2/users/me/usage?period=month |
What have I consumed? (metering) | 60s |
GET /v2/plans?platform=macos |
What can I buy? (catalog, global) | 1 hour |
Key Design Principles
- Server is authority — client checks
features.chat.allowed, never reimplements rules - Platform-explicit —
?platform=param, consistent response shape regardless - Cache-friendly — one key per user+platform, one invalidation on state change
- Extensible — new enforcement (rate limits, feature flags) = new field, no client update
- Defense-in-depth preserved — entitlements is read-only state; inline server checks (402/1008) remain as safety nets
Implementation Path
| Phase | What | Blocks on |
|---|---|---|
| Phase 1 (this PR) | Ship /paywall + /trial as thin endpoints |
Nothing — shipping now |
| Phase 2 | Add /v2/users/me/entitlements aggregator |
Phase 1 merge |
| Phase 3 | Split /subscription into /plan + /plans catalog |
Phase 2 stable |
| Phase 4 | Expand Rust proxy to all platforms using entitlements cache | Phase 2 + infra work |
| Phase 5 | Deprecate v1 fragmented endpoints | All clients on v2 |
Why keep Phase 1 as-is
- Working, tested, defense-in-depth enforcement proven
/paywalland/trialbecome internal building blocks consumed by the Phase 2 aggregator- No wasted work — the thin endpoints become the implementation behind
get_user_entitlements() - Shipping > perfect API design; iterate toward ideal
Full design doc with schemas, migration plan, and Rust integration: [/tmp/api-redesign-entitlements.md] — will be committed to repo as docs/design/api-entitlements-v2.md when Phase 2 begins.
by AI for @beastoin
Proxies GET /v1/trial to Python /v1/users/me/trial and caches per-uid for 60s (shorter than paywall's 300s because countdown accuracy matters for the client UI). Fails open on Python errors. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds TrialMetadataCache to AppState and merges trial_routes() into the main router so /v1/trial is served alongside existing endpoints. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Swift model mirrors Python TrialMetadata (snake_case → camelCase via CodingKeys). getTrialMetadata() calls the Rust /v1/trial endpoint. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Published trialMetadata property drives UI updates. Timer fetches from Rust backend every 60s. Syncs paywall flag when trial expires. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Posts one-time notifications at 24h and 1h before trial expiry, plus a final "Trial Ended" banner. Uses UserDefaults flags to avoid repeat alerts within the same trial period. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Shows progress ring + time remaining during active trial, or an expired banner with upgrade CTA after trial ends. Color-coded: green (>24h), yellow (< 24h), orange (< 1h). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wires up AppState.startTrialMetadataRefresh() and TrialBannerService in applicationDidFinishLaunching for signed-in users. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Trial card now lists included features (listening, transcription, memories, chat) with premium badges. Provides clear value visibility during the trial so users understand what they'll lose on expiry. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds #if DEBUG block in fetchTrialMetadata() that reads UserDefaults `debug_trial_mode` to inject fake trial data. Supports 4 states: "active" (green, 2d+), "warning" (yellow, 12h), "expiring" (orange, 30m), "expired" (red, trial ended). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds "realtime" debug_trial_mode that seeds a 2-minute trial on first call and counts down on subsequent refreshes (10s interval). The trial actually expires, triggers paywall, and demonstrates the full user journey from active trial through expiry to purchase CTA. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Trial metadata does not need API key forwarding or Rust caching. Swift client now calls Python /v1/users/me/trial directly. Co-Authored-By: Claude Opus 4.6 <[email protected]>
No Rust middleman needed — Python backend is the single backend for trial metadata. Co-Authored-By: Claude Opus 4.6 <[email protected]>
get_trial_metadata() now honors _TRIAL_PAYWALL_ENABLED and _TRIAL_PAYWALL_TEST_UIDS, matching is_trial_paywalled() behavior. Prevents client from false-paywalling when ops disables enforcement. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Fixes issue where paying users stayed paywalled because isPaywalled was only ever set to true, never cleared. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Start trial refresh and banner service on OAuth completion (Apple and Google paths). Stop polling, clear metadata, and reset paywall flag on sign-out to prevent state leaking across user sessions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
7 new tests covering: - Kill switch disabled returns trial_expired=False and skips DB/Firebase - Kill switch enabled returns real expired state - Test UID listed user gets real result - Test UID unlisted user is exempt and skips DB/Firebase - Empty test UIDs means all users subject to trial - Source-level checks for rollout gate presence Total: 37 tests passing. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Addresses tester gaps: - TestEnvVarParsing: verifies _TRIAL_PAYWALL_ENABLED and _TRIAL_PAYWALL_TEST_UIDS env var parsing (case-insensitive, CSV with whitespace trimming, defaults) - TestTrialEndpointIntegration: verifies endpoint response contract matches what Swift client expects (all fields present, JSON serialization) - TestTrialBoundaryDynamic: derives boundary conditions from TRIAL_LENGTH_SECONDS instead of hardcoded values, tests custom duration override Total: 53 tests, all passing. Co-Authored-By: Claude Opus 4.6 <[email protected]>
6eac8f3 to
b31c794
Compare
Paywall Bypass AnalysisCan users on the latest macOS app bypass the trial paywall?No. The enforcement is hardcoded in the compiled binaries at multiple layers: Enforcement points (latest app version)
What a paywalled user cannot do (server-enforced)
Old app versions (pre-PR)Old macOS builds can bypass the paywall because:
This is accepted behavior — the paywall only enforces on the latest app version. Sparkle auto-updater will push users to the new version. Minor gap (non-exploitable)
by AI for @beastoin |
…day duration Co-Authored-By: Claude Opus 4.6 <[email protected]>
…cable Co-Authored-By: Claude Opus 4.6 <[email protected]>
… typography and indicators Co-Authored-By: Claude Opus 4.6 <[email protected]>
Updated Trial Card UI — Style Consistency FixFixed the trial card to use the same design language as the rest of the Settings page: Changes:
Active TrialTrial Endedby AI for @beastoin |
Updated Screenshots — Trial Card UI with Backend ConnectedBuilt from branch code, authenticated with prod backend (Beastoin account, Operator plan active). Active Trial (debug_trial_mode = "active")
Expired Trial (debug_trial_mode = "expired")
by AI for @beastoin |
| didSet { UserDefaults.standard.set(isPaywalled, forKey: "desktop_isPaywalled") } | ||
| } | ||
|
|
||
| /// Trial metadata fetched from Rust backend (`/v1/trial`). Updated every 60s |
There was a problem hiding this comment.
@kai what is this still ? pls check all code comment.
| func fetchTrialMetadata() { | ||
| // Debug: inject fake trial data for UI testing via UserDefaults | ||
| // Set `debug_trial_mode` to "active" or "expired" to override | ||
| #if DEBUG |
There was a problem hiding this comment.
- Fix comment: endpoint is /v1/users/me/trial (Python backend), not Rust - Remove verbose doc comments — keep code self-documenting - Extract debug trial modes into applyDebugTrialMode() helper to reduce duplication - Add @mainactor to Task in fetchTrialMetadata() for thread-safe @published mutations Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
Live Test Results — v0.11.408Tested on Omi Beta (production) after Sparkle auto-update from v0.11.407 → v0.11.408. Deployment
Test Results
EvidenceHome screen (v0.11.408): Plan and Usage (paid plan, no trial card — correct): Chat working correctly (sent "What is 2 plus 2?", received "4"): Screenshots captured programmatically via agent-swift on Omi Beta (com.omi.computer-macos). by AI for @beastoin |


























Summary
Desktop-only 3-day free trial paywall for Omi macOS app (#7329).
Backend:
is_trial_paywalled(uid, platform)— checks Firebase Auth account age + plan + BYOK status, returns True only for desktop basic-plan users past 3 daysget_trial_metadata(uid)— returns structured trial timing for the/v1/users/me/trialendpointmacos/desktoptokens trigger paywall — mobile, Omi device, and unknown platforms are always exempttrial_expired=FalseDesktop (Swift):
TrialMetadataResponsemodel +APIClient.getTrialMetadata()calling Python endpoint directlyAppState.fetchTrialMetadata()with 60s polling (10s in DEBUG), clears paywall when trial shows not expiredTrialBannerServicefor one-shot floating notifications at 24h, 1h, and expiry thresholdsDefense-in-depth:
blockIfPaywalledcheck before expensive operationsis_trial_paywalledreturns 402 on HTTP / 1008 on WebSocketBypass Analysis
Old desktop app versions can bypass the paywall by not sending
X-App-Platformheader (platform=None → exempt). This is by design — the header was introduced in this PR, so older binaries don't have it. The latest app version cannot bypass:X-App-Platform: macosis hardcoded inAPIClient.buildHeaders()andsource=desktopis hardcoded in the WebSocket URL builder. Both are compiled into the binary — no user-accessible override.Test plan
backend/tests/unit/test_trial_metadata.py)Closes #7329
🤖 Generated with Claude Code