Skip to content

fix(desktop): eliminate ghost-session auth for AI chat - #9324

Merged
Git-on-my-level merged 12 commits into
mainfrom
fix/desktop-auth-re-login
Jul 9, 2026
Merged

Git-on-my-level merged 12 commits into
mainfrom
fix/desktop-auth-re-login

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add AuthSessionCoordinator with light invalidateSession (distinct from nuclear signOut), definitive-death classifier, and single-flight refresh.
  • Fix launch restore + Firebase listener to force-refresh REST tokens and invalidate only on definitive death; route post-refresh HTTP 401 through the coordinator and remove AuthBackoffTracker.
  • Unify chat auth recovery UX: ChatErrorCard on Chat/Dashboard/floating bar, draft preserved on auth send failure, OAuth auto-retry once.
  • Add debounced proactive ensureValidSession on app become-active, INV-AUTH-1 invariant + CI ratchet.

Product invariants affected

  • INV-AUTH-1 (new): desktop Firebase session truth and 401 invalidation
  • INV-CHAT-1: shared chat error/recovery surfaces across Chat, Dashboard, floating bar

Commits

  1. 8392e9d AuthSessionCoordinator foundation
  2. 90d1239 Restore/listener forced refresh
  3. d1b771f APIClient 401 + remove backoff
  4. 249368a Chat auth UX unification
  5. 02addcf Proactive check + INV-AUTH-1

Test plan

  • xcrun swift test --filter 'AuthSessionCoordinator|AuthDefinitiveDeath' (7 passed)
  • xcrun swift test --filter ChatErrorStateTests restore/auth UX tests (26 passed)
  • xcrun swift test --filter APIClientAuthRecovery (3 passed)
  • python3 .github/scripts/check_desktop_auth_session.py (INV-AUTH-1 ratchet passed)
  • python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict --base origin/main
  • CI green on desktop + repo checks

@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: 02addcf139

ℹ️ 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 +133 to +137
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("docs/product/invariants/auth-session.md")

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 Walk up to the repo root before checking invariant docs

With #filePath under desktop/macos/Desktop/Tests, four deletingLastPathComponent() calls stop at /workspace/omi/desktop, so this builds /workspace/omi/desktop/docs/product/invariants/auth-session.md. The invariant doc added by this commit is at /workspace/omi/docs/product/invariants/auth-session.md, so testInvAuthInvariantDocExists fails in the focused auth suite unless this walks up one more level or uses a shared repo-root helper.

Useful? React with 👍 / 👎.

@mintlify

mintlify Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
omi 🟢 Ready View Preview Jul 9, 2026, 8:07 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

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

Confidence score: 5/5

  • Safe to merge after the addressed issues were fixed.

You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

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

Re-trigger cubic

Git-on-my-level and others added 8 commits July 9, 2026 17:51
…ession

Introduce session phases, definitive-death classifier, single-flight refresh
scaffolding, and sessionDidInvalidate bridge teardown separate from nuclear signOut.

Verified: xcrun swift test --filter 'AuthSessionCoordinator|AuthDefinitiveDeath' (7 passed)
Co-authored-by: Cursor <[email protected]>
Stop deferring on expired cached tokens, use refreshSingleFlight on restore
and Firebase-nil listener, route definitive refresh death through invalidateSession,
and drop blanket HTTP 400 from refreshIdToken.

Verified: xcrun swift test --filter AuthSessionCoordinator|ChatErrorState restore tests (9 passed)
Co-authored-by: Cursor <[email protected]>
Centralize refresh-and-retry in APIClient with signOutOn401 opt-out, unify
delete/streaming/upload paths, and remove AuthBackoffTracker.

Verified: xcrun swift test --filter APIClientAuthRecovery (3 passed)
Co-authored-by: Cursor <[email protected]>
Map bridge auth failures to ChatErrorCard, preserve draft on auth send failures,
auto-retry after OAuth recovery, and show recovery on Dashboard and floating bar.

Verified: xcrun swift test --filter ChatErrorStateTests (26 passed)
Co-authored-by: Cursor <[email protected]>
Debounce ensureValidSession on app become-active, document INV-AUTH-1 with
BYOK vs session 401 table, and add CI ratchet for APIClient 401 handlers.

Verified: python3 .github/scripts/check_desktop_auth_session.py; xcrun swift test --filter AuthSessionCoordinator|APIClientAuthRecovery
Co-authored-by: Cursor <[email protected]>
Map AuthSessionCoordinator and related polling paths to existing harness
flows so strict desktop e2e coverage CI passes.

Verified: python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict --base origin/main
Co-authored-by: Cursor <[email protected]>
Correct repo-root path for INV-AUTH-1 doc guard and update credential-health
source scans for authorizedRetryRequest + invalidateSessionAfterUnauthorized.

Co-authored-by: Cursor <[email protected]>
…H-1 CI

Map definitive AuthError.notSignedIn during 401 refresh to session
invalidation (voice mint no longer looks transient), and run the auth
session ratchet from Hygiene when APIClient/Auth paths change.

Co-authored-by: Cursor <[email protected]>
Pre-existing upstream formatting issue in web/frontend/src/app/apps/[id]/page.tsx
(commit 5aae506 / #9185) that blocked Frontend Lint CI. Prettier v2 (used by CI)
formats nested ternaries differently from v3 (installed locally).
…idation, atomic signOut, cancellation guard

- performLightSessionInvalidation now clears Auth.auth().currentUser so
  restoreAuthState/listener don't re-create the ghost session on next launch
  (Codex P1 #3549953865, Cubic P1 #3549981982)
- signOut() moves sessionCoordinator.resetAfterNuclearSignOut() after
  try Auth.auth().signOut() so the state transition is atomic (Cubic P2 #3549981991)
- .signIn recovery catches AuthError.cancelled separately so user cancellation
  doesn't auto-pivot to Apple sign-in (Cubic P2 #3549981985)
- Remove fragile .prefix(900) from ChatErrorStateTests (Cubic P3 #3549981992)
- Simplify whitespace-specific negative assertion in APIClientAuthRecoveryTests
  (Cubic P3 #3549981996)

Verification:
- xcrun swiftc -parse passes on all 4 modified files
- python3 .github/scripts/check_desktop_auth_session.py (INV-AUTH-1 ratchet passed)
- python3 .github/scripts/check-desktop-changelog.py (changelog fragment found)
…ry block

The cancellation guard added to .signIn recovery pushed ensureBridgeStarted()
beyond the .prefix(1200) window in testSignInRecoveryRetriesAfterOAuth.
Removing the prefix limit (same fix pattern as Thread 7 review feedback).

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

3 issues found across 4 files (changes from recent commits).

You’re at about 99% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

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/AuthService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/AuthService.swift:626">
P1: The new `try? Auth.auth().signOut()` in `performLightSessionInvalidation()` is missing a `DesktopLocalProfile.isEnabled` guard. In local harness mode `FirebaseApp.configure()` is skipped, and `Auth.auth()` traps fatally when called — the codebase already documents this exact concern and guards it elsewhere (`if !DesktopLocalProfile.isEnabled` in `getIdToken()`). Because `invalidateSession` is now called automatically by the coordinator on definitive refresh failures, a local/emulator session that fails to re-bootstrap will crash the process instead of clearing state safely. Consider wrapping the call with `if !DesktopLocalProfile.isEnabled { try? Auth.auth().signOut() }`.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Providers/ChatProvider.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Providers/ChatProvider.swift:5024">
P2: When the user cancels Google sign-in in the `ChatErrorCard` recovery flow, the cancelled branch restores `currentError` but forgets to restore `lastFailedPrompt`. Since the function clears that field on entry, a subsequent card tap will have nothing to retry, and a successful Apple fallback sign-in will not auto-retry the original failed prompt. Also prefer setting `errorMessage = nil` when `currentError` is restored, since the codebase keeps the structured card and legacy banner mutually exclusive.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/ChatErrorStateTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/ChatErrorStateTests.swift:251">
P2: The `testSignInRecoveryRetriesAfterOAuth` test lost its `.prefix(1200)` scoping, which reduces the specificity of the `ensureBridgeStarted()` check. That method also appears in the unrelated `automationSwapTestOwner` and `automationRestoreTestOwner` methods later in the file, so the assertion could pass even if the sign-in recovery block omits that call. Consider scoping the snippet to a tighter range — for example, up to the next `case` or `}` boundary — so the test validates the recovery block's own code, not incidental matches from other methods.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

…astFailedPrompt on cancel, scope test snippet

- Guard try? Auth.auth().signOut() with DesktopLocalProfile.isEnabled check
  to prevent fatal trap in local harness mode where Firebase isn't configured
  (Cubic P1 review-run b4671a81)
- Restore lastFailedPrompt in cancellation branch so retry card still works
  after user cancels Google sign-in (Cubic P2 review-run b4671a81)
- Set errorMessage = nil when currentError is restored (structured/legacy
  banner mutual exclusivity)
- Scope testSignInRecoveryRetriesAfterOAuth snippet to .signIn case block
  (stop at next case) to prevent incidental matches from unrelated methods
  (Cubic P2 review-run b4671a81)
@Git-on-my-level

Copy link
Copy Markdown
Member Author

The test already uses 5 deletingLastPathComponent() calls, which resolves correctly from desktop/macos/Desktop/Tests/ to the repo root where docs/product/invariants/auth-session.md lives. CI's Desktop Swift Build & Tests passes testInvAuthInvariantDocExists. This appears to be based on a miscount of the deletions.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor summary — review feedback addressed

Addressed all actionable Codex/Cubic review feedback across two bot review rounds.

Code fixes

  • Firebase SDK sign-out during light invalidation (Codex P1, Cubic P1): performLightSessionInvalidation() now clears Auth.auth().currentUser via try? Auth.auth().signOut() so restoreAuthState() and the auth-state listener do not re-create the ghost session on next launch. Guarded with !DesktopLocalProfile.isEnabled to prevent fatal trap in local harness mode.
  • Atomic nuclear sign-out (Cubic P2): Moved sessionCoordinator.resetAfterNuclearSignOut() after try Auth.auth().signOut() succeeds so the coordinator phase doesn't falsely report .signedOut if Firebase sign-out throws.
  • Google sign-in cancellation guard (Cubic P2): .signIn recovery now catches AuthError.cancelled separately so user cancellation doesn't auto-pivot to Apple sign-in. Restores lastFailedPrompt so the error card's retry action still works.
  • Test robustness (Cubic P3 x2): Removed fragile .prefix(900) truncation in testRestoredSessionValidationForceRefreshesOnLaunch. Simplified whitespace-specific negative assertion in testDeleteUsesShared401RecoveryPath. Scoped testSignInRecoveryRetriesAfterOAuth snippet to the .signIn case block boundary.
  • Pre-existing lint fix: Fixed prettier v2 formatting on web/frontend/src/app/apps/[id]/page.tsx (pre-existing upstream issue from fix(web): guard app-detail image + capabilities on h.omi.me frontend (#7237) #9185 blocking Frontend Lint CI).

Not addressed (with rationale)

  • Codex P2 "Walk up to repo root": False positive — the test already uses 5 deletingLastPathComponent() calls, resolving correctly to the repo root. CI's Desktop Swift Build & Tests passes testInvAuthInvariantDocExists.

Verification

  • xcrun swiftc -parse passes on all modified Swift files
  • python3 .github/scripts/check_desktop_auth_session.py — INV-AUTH-1 ratchet passed
  • python3 .github/scripts/check-desktop-changelog.py — changelog fragment found
  • CI: all checks green (Desktop Swift Build & Tests, Frontend Lint, Cubic AI code reviewer, and all others)

@Git-on-my-level
Git-on-my-level merged commit 9937c7a into main Jul 9, 2026
20 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/desktop-auth-re-login branch July 9, 2026 17:18
cursor Bot pushed a commit that referenced this pull request Jul 9, 2026
- Keep both listen_ws_session and canonical_memory_pipeline workflow contracts
- Union fast-unit duration allowlist entries from both branches
- Reconcile APIClient: retain OmiHTTPTransport for headers/codec/session while
  preserving main's RequestAuthPolicy 401 recovery (ghost-session fix #9324)

Co-authored-by: David Zhang <[email protected]>
Git-on-my-level added a commit that referenced this pull request Jul 10, 2026
## Summary

Single-branch thermo-nuclear quality repayment across backend and macOS
desktop (waves 1–8):

- **W1** — Extract task integration ops to
`utils/task_integrations_ops.py`; fix `utils→routers` import violation
in `task_sync.py`; import-boundary ratchet + Todoist characterization
tests
- **W2** — Atomic memory re-extract (extract-first, then delete/save)
for legacy + canonical paths; cascade delete cleans
memories/action-items before conversation doc
- **W3** — Listen connect bootstrap (`listen_session_bootstrap.py`)
offloads Firestore reads; register `listen_ws_session` workflow contract
(#9239)
- **W4** — Extract sync pipeline to `utils/sync/pipeline.py`; thin
`routers/sync.py`
- **W5** — Share `TaskChatCoordinator` with `RecurringTaskScheduler`;
INV-6 tripwire for shadow `ChatProvider()`
- **W6** — Pure `STTSessionState` + transition tests; replace five STT
booleans in AppState
- **W7** — `RewindStorageTestIsolation` harness + migrate three leaky
memory suites (#9029)
- **W8** — Extract `OmiHTTPTransport` from `APIClient.swift` (#8844);
line-count ratchet

Related: #8844, #9029, #9239

## Product invariants affected

- INV-AUTH-1: merge retained APIClient session-scoped 401 recovery /
RequestAuthPolicy from #9324 while keeping OmiHTTPTransport extract
- INV-6: TaskChatCoordinator shared with RecurringTaskScheduler (shadow
ChatProvider tripwire)

## Characterization / coverage additions

- `test_utils_import_boundary.py`, `test_task_integrations_ops.py`
- `test_memory_replace_policy.py`
- `test_listen_session_bootstrap.py`
- `STTSessionStateTests`, combined-memory script
- Existing sync/listen/APIClient suites updated as move anchors

## Verification (local)

```bash
cd backend && python3 scripts/check_workflow_contracts.py
cd backend && ./test.sh tests/unit/test_utils_import_boundary.py tests/unit/test_task_integrations_ops.py \
  tests/unit/test_memory_replace_policy.py tests/unit/test_listen_session_bootstrap.py \
  tests/unit/test_sync_v2.py tests/unit/test_workflow_contracts.py
cd desktop/macos && xcrun swift test --package-path Desktop --filter 'STTSessionStateTests|APIClient|MemoryAuthoritativeTierSyncTests'
bash desktop/macos/scripts/swift-test-combined-memory.sh
```

## Out of scope (deferred Wave 9+)

- `MemoryWritePolicy` / `ListenReceiveLoop` peel / sync v1/v2 unify /
Chat models extract / ConversationsRepository
- Mega-UI (FloatingControlBar, TasksPage, Dashboard dual-home)
- Full AppState god split, production DI for all singletons


Made with [Cursor](https://cursor.com)

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/9327?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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