Skip to content

feat(backend): Add trial metadata endpoint for desktop paywall UX - #7330

Merged
beastoin merged 7 commits into
mainfrom
worktree-free-trial-paywall-rework
May 16, 2026
Merged

beastoin merged 7 commits into
mainfrom
worktree-free-trial-paywall-rework

Conversation

@beastoin

@beastoin beastoin commented May 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds GET /v1/users/me/trial endpoint that returns structured trial metadata for desktop clients to render countdown banners and pre-expiry upgrade nudges. This is Phase 1 (backend) of the free trial paywall rework (#7329).

Changes

  1. models/users.py — New TrialMetadata Pydantic model with fields: trial_started_at, trial_ends_at, trial_remaining_seconds, trial_expired, trial_duration_seconds, trial_features, plan_after_trial

  2. utils/subscription.py —

    • TRIAL_LENGTH_SECONDS now env-configurable (default 3 days, same as before)
    • TRIAL_FEATURES constant listing features available during trial
    • get_trial_metadata(uid) function: computes trial timing from Firebase Auth creation timestamp, handles paid/BYOK bypass, fails open on errors
  3. routers/users.py — New GET /v1/users/me/trial endpoint returning TrialMetadata

  4. tests/unit/test_trial_metadata.py — 30 tests (source-level + behavioral + auth + boundary) covering active trial, expired trial, paid/BYOK bypass, Firebase failure, boundary edge cases, model serialization

Design decisions

  • Fail-open: Firebase lookup errors → trial_expired=False (never false-paywall)
  • Paid/BYOK users: get trial_expired=False with zeroed timing (trial is irrelevant)
  • No cache added: reuses existing Firebase Auth lookup (already cached 5 min in Redis via _is_trial_expired_cached)
  • Backward compatible: existing /v1/users/me/paywall endpoint unchanged

Response shape

{
  "trial_started_at": 1747123456,
  "trial_ends_at": 1747382656,
  "trial_remaining_seconds": 172800,
  "trial_expired": false,
  "trial_duration_seconds": 259200,
  "trial_features": ["unlimited_listening", "unlimited_transcription", "unlimited_memories", "unlimited_insights", "30_chat_questions_per_month"],
  "plan_after_trial": "Free"
}

Test plan

  • 30 unit tests pass (source-level + behavioral + auth + boundary)
  • Existing paywall tests pass (60 total, no regression)
  • Black formatting applied
  • Live test: backend boots, curl /v1/users/me/trial returns 200 with correct JSON
  • Unauthenticated request returns 401
  • Existing /v1/users/me/paywall endpoint unaffected

Live test evidence

# Authenticated request
$ curl -s http://localhost:18080/v1/users/me/trial -H "Authorization: Bearer $TOKEN"
{
  "trial_started_at": null,
  "trial_ends_at": null,
  "trial_remaining_seconds": 0,
  "trial_expired": false,
  "trial_duration_seconds": 259200,
  "trial_features": ["unlimited_listening", "unlimited_transcription", ...],
  "plan_after_trial": "Free"
}

# Unauthenticated request
$ curl -s http://localhost:18080/v1/users/me/trial
{"detail":"Authorization header not found"}  (HTTP 401)

# Existing endpoint unchanged
$ curl -s http://localhost:18080/v1/users/me/paywall -H "Authorization: Bearer $TOKEN" -H "X-App-Platform: macos"
{"paywalled": false}

Risks

  • Low risk: additive endpoint, no change to existing paywall enforcement
  • No database schema changes
  • No new external dependencies

Closes #7329 (Phase 1)

by AI for @beastoin

beastoin and others added 6 commits May 16, 2026 09:46
Part of #7329: rework free trial paywall for macOS desktop app.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds structured trial metadata computation for desktop clients:
- trial_started_at, trial_ends_at, trial_remaining_seconds
- Fail-open on Firebase errors (never false-paywall)
- Paid/BYOK users get trial_expired=False (trial is moot)
- TRIAL_LENGTH_SECONDS now configurable via env var (default 3 days)

Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Returns trial timing (start, end, remaining), features list, and
post-trial plan name. Used by desktop clients for countdown UI and
pre-expiry upgrade nudges.

Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Source-level tests verify wiring, behavioral tests validate:
- Active trial timing, expired trial, paid/BYOK bypass
- Firebase failure fail-open, model serialization

Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Verifies endpoint uses Depends(auth.get_current_user_uid), is a GET
method, and returns get_trial_metadata(uid) result.

Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@greptile-apps

greptile-apps Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds a new GET /v1/users/me/trial endpoint that returns structured trial timing metadata for desktop clients to render countdown banners and upgrade nudges. The implementation is additive and does not touch existing paywall enforcement logic.

  • utils/subscription.py: get_trial_metadata() computes trial timing from Firebase Auth creation timestamp with paid/BYOK bypass and fail-open error handling; TRIAL_FEATURES constant and env-configurable TRIAL_LENGTH_SECONDS are also added.
  • models/users.py / routers/users.py: TrialMetadata Pydantic model and the new endpoint are wired correctly with proper auth dependency and response_model.
  • tests/unit/test_trial_metadata.py: 25 tests added covering all major code paths; the exec-based behavioral test helper is intentionally designed to avoid full module import but is brittle to source-layout changes.

Confidence Score: 4/5

Safe to merge; the change is purely additive and does not alter existing paywall enforcement.

The endpoint and model are correctly implemented and the fail-open design is sound. The docstring inside get_trial_metadata incorrectly states the function benefits from the existing Redis cache when it actually calls Firebase Auth directly on every invocation. Separately, the exception handler references names defined much later in the file, which could silently break the fail-open guarantee after future refactoring.

backend/utils/subscription.py — the uncached Firebase call and the forward-reference in the exception handler both live here.

Important Files Changed

Filename Overview
backend/utils/subscription.py Adds get_trial_metadata() and TRIAL_FEATURES constant; function docstring incorrectly claims Redis caching and forward-declares TRIAL_FEATURES ~280 lines below its first use in the exception handler
backend/models/users.py Adds TrialMetadata Pydantic model with correct fields and safe defaults; no issues found
backend/routers/users.py Adds GET /v1/users/me/trial endpoint; correct response_model, auth dependency, and import wiring
backend/tests/unit/test_trial_metadata.py 25 tests covering active/expired trial, paid/BYOK bypass, Firebase failure, and model serialization; exec-based behavioral test helper is fragile but intentional to avoid full module import
backend/test.sh Adds test_trial_metadata.py to the CI test script; no issues

Sequence Diagram

sequenceDiagram
    participant Client as Desktop Client
    participant Router as GET /v1/users/me/trial
    participant Sub as get_trial_metadata()
    participant UsersDB as users_db
    participant Firebase as firebase_auth (uncached)
    participant Redis as Redis Cache

    Client->>Router: GET /v1/users/me/trial (Bearer token)
    Router->>Sub: get_trial_metadata(uid)
    Sub->>UsersDB: get_user_valid_subscription(uid)
    UsersDB-->>Sub: subscription (plan)
    alt Paid plan or BYOK
        Sub->>UsersDB: is_byok_active(uid)
        UsersDB-->>Sub: True/False
        Sub-->>Router: "TrialMetadata(trial_expired=False, zeroed timing)"
    else Basic plan, no BYOK
        Sub->>Firebase: get_user(uid) [NO Redis cache]
        Firebase-->>Sub: user_record.creation_timestamp
        Note over Sub,Redis: Redis cache NOT consulted here
        Sub->>Sub: "compute remaining = max(0, ends_at - now)"
        Sub-->>Router: TrialMetadata(full timing)
    end
    alt Exception at any step
        Sub-->>Router: "TrialMetadata(trial_expired=False) [fail-open]"
    end
    Router-->>Client: TrialMetadata JSON
Loading

Reviews (1): Last reviewed commit: "Add auth dependency verification tests p..." | Re-trigger Greptile

Comment on lines +120 to +121
This reuses the same Firebase Auth lookup path as `_is_trial_expired_uncached`
and benefits from the same Redis cache for the expensive bits.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 The docstring says the function "benefits from the same Redis cache for the expensive bits," but get_trial_metadata never consults the Redis cache — it calls firebase_auth.get_user(uid) directly at line 136. The existing cache in _is_trial_expired_cached stores only a boolean expired flag (not the creation timestamp), so it can't be reused here anyway. For a countdown-banner endpoint that desktop clients will poll regularly, every call triggers an uncached Firebase Auth network round-trip. The comment should be corrected to avoid misleading future callers into thinking this path is cached.

Suggested change
This reuses the same Firebase Auth lookup path as `_is_trial_expired_uncached`
and benefits from the same Redis cache for the expensive bits.
This uses the same Firebase Auth lookup path as `_is_trial_expired_uncached`
but does NOT benefit from the Redis cache in `_is_trial_expired_cached` (which
stores only a boolean flag, not the creation timestamp). Each call makes a
direct, uncached Firebase Auth request. Consider caching the creation timestamp
separately if this endpoint is polled frequently by desktop clients.

Comment on lines +162 to +170
except Exception as e:
logger.warning("get_trial_metadata failed for uid=%s: %s", uid, e)
# Fail-open: report as active trial so UI doesn't flash paywall.
return TrialMetadata(
trial_expired=False,
trial_duration_seconds=TRIAL_LENGTH_SECONDS,
trial_features=TRIAL_FEATURES,
plan_after_trial=get_plan_display_name(PlanType.basic),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Fragile fail-open: exception handler references forward-declared names

The except handler at line 162 references TRIAL_FEATURES (defined at line 399) and get_plan_display_name (defined at line 416). Python resolves names at call time, so this works while the module loads normally. However, if either name is undefined when this handler fires — for example, after a refactoring that moves or conditionally guards TRIAL_FEATURES — the handler itself raises an uncaught NameError, silently defeating the documented fail-open guarantee. Moving TRIAL_FEATURES to before get_trial_metadata in the file would make the dependency explicit and safe.

Addresses tester coverage gap: verifies behavior at the exact 3-day
boundary (1 second before and after expiry).

Part of #7329.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin
beastoin merged commit fdd3b2e into main May 16, 2026
2 checks passed
@beastoin
beastoin deleted the worktree-free-trial-paywall-rework branch May 16, 2026 10:32
@beastoin

Copy link
Copy Markdown
Collaborator Author

Phase 2+3 (desktop UI) consolidated into #7341 which contains all 3 phases of #7329.

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.

Rework free trial paywall for macOS desktop app (3-day premium trial)

1 participant