Repository navigation
feat(desktop): let users choose which Gmail account to read - #10963
Conversation
There was a problem hiding this comment.
1 issue found across 11 files
Confidence score: 2/5
- In
desktop/macos/Desktop/Sources/Onboarding/OnboardingDataSourcesStepView.swift, there’s a race where a user account selection during the Gmail probe can be overwritten, leaving onboarding stuck on “Scanning your data sources…” indefinitely and blocking completion. Re-checkGmailSelectionStore.hasMadeChoiceafter the probe finishes and before installing the probe result to avoid applying stale state.
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/Onboarding/OnboardingDataSourcesStepView.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/Onboarding/OnboardingDataSourcesStepView.swift:116">
P1: Selecting an account while the background Gmail probe is still running can leave onboarding on “Scanning your data sources…” forever. Re-check `GmailSelectionStore.hasMadeChoice` after the probe/before installing the continuation, or otherwise make a pre-wait selection resume the gate.</violation>
</file>
Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.
Re-trigger cubic
| actionTitle: "Choose account", | ||
| action: { | ||
| Task { | ||
| await coordinator.loadGmailAccounts() |
There was a problem hiding this comment.
P1: Selecting an account while the background Gmail probe is still running can leave onboarding on “Scanning your data sources…” forever. Re-check GmailSelectionStore.hasMadeChoice after the probe/before installing the continuation, or otherwise make a pre-wait selection resume the gate.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/Onboarding/OnboardingDataSourcesStepView.swift, line 116:
<comment>Selecting an account while the background Gmail probe is still running can leave onboarding on “Scanning your data sources…” forever. Re-check `GmailSelectionStore.hasMadeChoice` after the probe/before installing the continuation, or otherwise make a pre-wait selection resume the gate.</comment>
<file context>
@@ -99,7 +109,14 @@ struct OnboardingDataSourcesStepView: View {
+ actionTitle: "Choose account",
+ action: {
+ Task {
+ await coordinator.loadGmailAccounts()
+ coordinator.showingGmailAccountPicker = true
+ }
</file context>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: baaaaed0ba
ℹ️ 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".
| private static let selectedPathKey = "gmailSelectedCookiePath" | ||
| private static let selectedLabelKey = "gmailSelectedAccountLabel" |
There was a problem hiding this comment.
Scope the Gmail selection to the signed-in owner
When account A selects a Gmail profile and then signs out, these process-wide UserDefaults keys survive because AuthService.signOut() only clears keys registered with OnboardingFlow.clearPersistedState(), and neither new key is registered there. Account B therefore sees hasMadeChoice == true, skips onboarding selection, and can import account A's selected Gmail into account B's memories. Key the selection by the authenticated owner or clear both values at the owner/sign-out boundary.
Useful? React with 👍 / 👎.
| guard !GmailSelectionStore.hasMadeChoice else { return } | ||
| let accounts = (try? await GmailAccountProbe.availableAccounts()) ?? [] |
There was a problem hiding this comment.
Recheck the Gmail choice after probing accounts
If the user opens the manual picker and selects an account while this potentially long account probe is in flight, the initial guard has already passed and selectGmailAccount finds no installed waiter to resume. After the probe returns, this method installs a continuation despite the now-persisted choice and suspends Gmail indefinitely, preventing gmailInsightsFinished and therefore onboarding completion. Recheck hasMadeChoice after the probe before creating the waiter.
Useful? React with 👍 / 👎.
| static func filter(_ configs: [[String: String]]) -> [[String: String]] { | ||
| guard let selected = selectedCookiePath, !selected.isEmpty else { return configs } | ||
| let narrowed = configs.filter { $0["db_path"] == selected } | ||
| return narrowed.isEmpty ? configs : narrowed |
There was a problem hiding this comment.
Record the stale-profile fail-open
When the persisted cookie database disappears or its path changes, this branch silently widens an explicit account selection back to every browser profile, so the reader can ingest a different inbox while Settings still displays the old account label. Because this is a fail-open correctness-mode switch, emit DesktopDiagnosticsManager.recordFallback(...) when it occurs (and preferably surface or clear the stale selection) rather than making the fallback invisible.
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
| let browserConfigs = GmailSelectionStore.filter( | ||
| BrowserGoogleSession.configsForPython(logPrefix: "GmailReaderService")) |
There was a problem hiding this comment.
Snapshot the selected profile for the entire Gmail read
During the onboarding newer_than:365d read, readRecentEmails invokes this method once for the query and repeatedly for label feeds, and every invocation rereads the mutable global selection here. If the user changes the picker while those Python requests are running, early feeds can come from the old profile and later feeds from the new one; the service then merges and saves both accounts' emails as one import. Capture the selected configuration once at readRecentEmails entry or serialize selection changes with the complete read.
Useful? React with 👍 / 👎.
| func selectGmailAccount(_ cookiePath: String?, label: String) { | ||
| GmailSelectionStore.persist(cookiePath: cookiePath, label: label) | ||
| showingGmailAccountPicker = false |
There was a problem hiding this comment.
Clear stale Gmail results when switching accounts
After a Settings read has populated gmailEmails, gmailLastFetched, and gmailMemoriesSaved, selecting another account only updates the persisted profile and dismisses the sheet. The page consequently labels the new account while continuing to display the previous account's email subjects, senders, and last-read status until another read succeeds. Reset the account-specific result state when the selection changes.
Useful? React with 👍 / 👎.
| .foregroundColor(OmiColors.textTertiary) | ||
| } | ||
| Spacer() | ||
| if selectedCookiePath == nil { |
There was a problem hiding this comment.
Distinguish no choice from an explicit Automatic choice
On fresh onboarding, selectedCookiePath is nil both before any choice and after the user explicitly chooses Automatic, so this renders Automatic with a checkmark even while the coordinator is suspended waiting for an explicit selection. A user can reasonably dismiss the apparently already-selected option, leaving the Gmail waiter and onboarding completion blocked. Pass the choice state into the picker or model selection as an enum so the unchecked state is visually distinct.
Useful? React with 👍 / 👎.
| guard let accounts = try? await GmailAccountProbe.availableAccounts(), !accounts.isEmpty else { | ||
| return |
There was a problem hiding this comment.
Surface failures from the Settings account probe
When profile discovery cannot read Safe Storage, Python is unavailable, the helper times out, or no account payload can be parsed, the probe resolves to an empty list and this guard silently returns. Pressing Choose therefore only shows and then hides a spinner, with no explanation or recovery action, even though this is the sole Settings entry point for changing the account. Preserve the probe error classification and present it through the existing Gmail error UI instead of treating every failure as an empty success.
Useful? React with 👍 / 👎.
| break | ||
| except Exception: | ||
| continue | ||
| accounts.append({'name': browser['name'], 'db_path': browser['db_path'], 'email': email}) |
There was a problem hiding this comment.
Verify profiles before offering them as Gmail accounts
A profile is appended even when both AccountInfo requests fail and email remains nil; because cookie discovery also ignores the stored cookie expiry and rewrites imported cookies with a fresh expiry, stale Google cookies can make an unreadable profile appear as an “Unknown account.” Such rows count toward the onboarding multi-account gate and can be selected, only for the subsequent Gmail read to fail. Run the small Gmail functional probe per profile, or otherwise exclude profiles that have not demonstrated a usable Gmail session.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for working on this — choosing the Gmail account explicitly is a useful macOS desktop improvement, and the Settings/onboarding direction makes sense.
I’m requesting changes before this is merge-ready because the current onboarding path can still hang or silently read the wrong profile in several cases:
awaitGmailAccountSelectionIfNeeded()setsgmailAwaitingSelection, but the view only presents the sheet from the manual “Choose account” action. If onboarding discovers multiple accounts on its own, the Gmail task can suspend without showing the picker.- The picker cancel paths only hide the sheet. During onboarding that leaves
gmailSelectionWaitersuspended indefinitely; cancel should either choose Automatic/fallback or otherwise resume and let the flow reach a terminal state. - There is a race where the user can select an account while probing is still in progress, before the continuation is installed. Re-check
GmailSelectionStore.hasMadeChoiceafter probing and immediately before waiting so a pre-wait selection cannot be lost. - Probe errors/timeouts currently collapse to
[], which is treated the same as “zero or one account”; that can skip selection and fall back to the first readable browser profile, which is exactly the behavior this PR is trying to avoid. Please distinguish probe failure from a real single-account/no-account result, or surface a retry/explicit fallback.
A couple of repo-contract/test items should be fixed with the above:
- New desktop Swift files should not be added directly under
desktop/macos/Desktop/Sources/; please move the new Gmail selection/picker code into an appropriate feature directory. Also route the new UserDefaults keys through the typed defaults-key convention rather than raw string keys. google-connector-read.yamllists the picker/settings UI undercovers, but that flow appears to exercise the reader bridge rather than rendering/selecting in the picker. Please either add coverage for the picker path or keep the covers list to what the flow actually exercises.
The desktop Swift checks are a good signal, but this still needs the onboarding fixes above plus human maintainer review for the Gmail account-selection UX/data-handling behavior before merge.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 578ae2f25f
ℹ️ 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".
| func selectGmailAccount(_ cookiePath: String?, label: String) { | ||
| GmailSelectionStore.persist(cookiePath: cookiePath, label: label) |
There was a problem hiding this comment.
Cancel stale reads before applying an account switch
If a user selects Choose… while Read Gmail is still running, both controls remain enabled and this method only clears the current results. The new per-read selection snapshot is fresh evidence that the in-flight task remains bound to the old profile, so after this method returns readGmail() can repopulate the old account's emails, mark the new account as synced, and save the old emails as memories. Cancel or version the active read when switching accounts, or disable switching until the read and save finish.
Useful? React with 👍 / 👎.
| // Probe failure is not "zero or one account": a transient failure would | ||
| // otherwise silently fall back to the first readable profile — the | ||
| // exact junk-account behavior this feature exists to prevent. Fall back | ||
| // to the automatic default but record the fail-open. | ||
| log("OnboardingPagedIntroCoordinator: Gmail account probe failed: \(error.localizedDescription)") |
There was a problem hiding this comment.
Record the onboarding probe fail-open
When the onboarding probe fails because Python, Safe Storage, Google, or the helper is unavailable, this branch changes correctness mode from explicit multi-account selection to the automatic first-readable profile but emits only a local log. Call DesktopDiagnosticsManager.recordFallback(...) here so this wrong-inbox risk is observable as the documented fail-open rather than disappearing from resilience telemetry.
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
| allowBootstrap: Bool? = nil, | ||
| selectedCookiePath: String? = nil |
There was a problem hiding this comment.
Scope connection verification to the selected profile
When the selected profile's Gmail session expires or becomes unreadable while another browser profile remains signed in, verifyConnection() omits this new parameter and therefore passes the nil default, causing the filter to scan every profile and potentially report .connected from the wrong account. The Second Brain context refresh then displays Gmail as connected even though subsequent reads snapshot the selected profile and fail; connection verification should use the same selected-path snapshot as readRecentEmails().
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the update — this is much closer. The move into Sources/Integrations, typed defaults keys, picker auto-presentation/cancel resume, and the explicit selection snapshot in GmailReaderService address several of the earlier blockers.
I’m still requesting one focused fix before this is merge-ready: the onboarding race around a manual selection during the account probe is still present. In awaitGmailAccountSelectionIfNeeded(), the comment says to re-check after the probe, but the second GmailSelectionStore.hasMadeChoice guard currently runs before GmailAccountProbe.availableAccounts(). If the user opens the manual picker and selects an account while that probe is in flight, selectGmailAccount() calls resumeGmailSelection() before gmailSelectionWaiter exists, so it is a no-op. When the probe returns with multiple accounts, the code then installs a continuation and waits indefinitely even though a choice is already persisted.
Please move/add the hasMadeChoice re-check after availableAccounts() returns and immediately before installing the continuation / showing the required picker. That should close the main remaining hang case without needing to split this PR.
Also note that the current head still has failing repo checks (Hygiene and PR Metadata Preflight), so this needs those resolved plus human maintainer sign-off for the Gmail account-selection UX/data-handling behavior before merge.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
af031df to
b3c3e84
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8afe473400
ℹ️ 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".
| GmailSelectionStore.persist(cookiePath: cookiePath, label: label) | ||
| showingGmailAccountPicker = false | ||
| resumeGmailSelection() |
There was a problem hiding this comment.
Restart the onboarding import when the account changes
When a user selects an account to release the onboarding waiter and then uses the still-enabled “Choose account” action while the year-long Gmail read/save is running, this persists the new choice without cancelling or versioning gmailTask. Fresh evidence is that the new selection snapshot now keeps the entire in-flight read bound to the old profile, so that task can finish and save the old inbox after the UI reflects the new account. Disable switching until the import finishes or cancel and restart the Gmail task when this selection changes.
Useful? React with 👍 / 👎.
| - desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swift | ||
| - desktop/macos/Desktop/Sources/Integrations/GmailAccountPickerView.swift |
There was a problem hiding this comment.
Exercise the Gmail picker before claiming flow coverage
The inspected flow only navigates to settingsSection: AI Chat and invokes settings_aichat_snapshot; it never mounts the Integrations subsection or opens the Gmail picker. Nevertheless, these covers entries make check-e2e-flow-coverage.py classify both new surfaces as covered, so picker and account-selection regressions can pass the claimed tier-2 coverage. Add flow steps that open Integrations and the picker, or remove these coverage claims.
AGENTS.md reference: AGENTS.md:L28-L28
Useful? React with 👍 / 👎.
| ForEach(accounts) { account in | ||
| Button { |
There was a problem hiding this comment.
Make long account lists scrollable
When a user has enough signed-in Chromium profiles to make the picker taller than the available display—especially on a laptop—the unbounded ForEach expands this sheet without any ScrollView or maximum height. macOS constrains the sheet to the screen, leaving lower account rows clipped and unreachable, so those users cannot select the intended inbox. Put the account rows in a vertically scrolling region with a bounded height.
Useful? React with 👍 / 👎.
| final body = wire.GeneratedSyncCaptureManifestResponse.fromJson( | ||
| jsonDecode(response!.body) as Map<String, dynamic>, | ||
| ); | ||
| final body = wire.GeneratedSyncCaptureManifestResponse.fromJson(jsonDecode(response!.body) as Map<String, dynamic>); |
There was a problem hiding this comment.
Revert the unrelated Flutter reformat
The reviewed commit is a desktop Gmail feature, but it also rewrites formatting across 17 unrelated Flutter production and test files (about 800 changed lines) without changing their behavior; this line is one representative instance. That broad formatter churn increases merge-conflict and regression-review risk while obscuring the functional desktop diff, so revert the app-wide formatting changes from this commit.
AGENTS.md reference: AGENTS.md:L50-L52
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 7 potential issues.
Bugbot Autofix is ON, but it could not run because the branch was deleted or merged before autofix could start.
Reviewed by Cursor Bugbot for commit d3b8545. Configure here.
| if (conversationLocalDayKey(effectiveDate) == conversationLocalDayKey(selectedDate)) { | ||
| if (effectiveDate.year == selectedDate.year && | ||
| effectiveDate.month == selectedDate.month && | ||
| effectiveDate.day == selectedDate.day) { |
There was a problem hiding this comment.
UTC day keys break grouping
High Severity
Conversation lists bucket by conversationLocalDayKey (startedAt ?? createdAt in local time), but these call sites derive lookup/validation dates from raw UTC year/month/day (chat taps use createdAt only). Off UTC midnight, grouped keys and lookups disagree, so memory taps fail and detail can show no conversation.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit d3b8545. Configure here.
| // are flowing, which made the UI show "Recording, reconnecting" over healthy | ||
| // transcription. The socket is the authoritative connectivity signal. | ||
| bool get transcriptServiceReady => _transcriptServiceReady; | ||
| bool get transcriptServiceReady => _transcriptServiceReady && _isConnected; |
There was a problem hiding this comment.
Transcript ready requires connectivity
Medium Severity
transcriptServiceReady again requires _isConnected in addition to the socket-ready flag. Brief connectivity flicker while the WebSocket still delivers segments can mark transcription not ready and show reconnecting UI during healthy capture.
Reviewed by Cursor Bugbot for commit d3b8545. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3b854590b
ℹ️ 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".
| await coordinator.loadGmailAccounts() | ||
| coordinator.showingGmailAccountPicker = true |
There was a problem hiding this comment.
Present onboarding probe failures instead of the picker
When Python, Safe Storage, or the account helper fails, loadGmailAccounts() suppresses the error with try? and leaves gmailAccounts empty, but this action still presents the sheet unconditionally. The user sees only the Automatic row after pressing “Choose account,” with no explanation that account discovery failed or way to recover; return a probe result or expose an error and present the picker only after successful discovery.
Useful? React with 👍 / 👎.
| func cancelGmailAccountSelection() { | ||
| showingGmailAccountPicker = false | ||
| resumeGmailSelection() |
There was a problem hiding this comment.
Record the cancel-to-automatic fallback
When onboarding found multiple accounts and is waiting for an explicit choice, pressing Cancel resumes the Gmail task without persisting a selection, so the import silently switches to the first readable browser profile. This is a correctness-affecting fail-open and should call DesktopDiagnosticsManager.recordFallback(...) before resuming so wrong-inbox imports caused by dismissal remain observable.
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d1ddee8f1
ℹ️ 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".
| break | ||
| except Exception: | ||
| continue | ||
| accounts.append({'name': browser['name'], 'db_path': browser['db_path'], 'email': email}) |
There was a problem hiding this comment.
Enumerate Gmail accounts within each browser profile
When personal and work Google accounts are both signed into one Chromium profile, this loop appends exactly one option keyed by the profile's cookie database. Onboarding therefore sees only one account, bypasses the picker, and the reader's /mail/u/0/ requests import whichever account is currently primary; the second inbox cannot be selected at all. Enumerate the signed-in Google account slots and carry an account-specific selector into the Gmail requests rather than treating a browser profile as an account.
Useful? React with 👍 / 👎.
| // Gmail account selection is per-owner: without clearing it here a | ||
| // sign-out lets the next account on the same Mac import the previous | ||
| // owner's chosen Gmail profile into their memories. | ||
| DefaultsKey.gmailSelectedCookiePath.rawValue, | ||
| DefaultsKey.gmailSelectedAccountLabel.rawValue, |
There was a problem hiding this comment.
Scope the selection at every owner transition
Fresh evidence after the explicit-sign-out fix is that performLightSessionInvalidation() removes the authenticated owner without calling OnboardingFlow.clearPersistedState(), while the subsequent commitSignedInSession() supports authenticating a different owner. If A's session is invalidated and the user reauthenticates as B, these keys survive, hasMadeChoice skips selection, and B can import A's chosen Gmail profile. Key the selection by authenticated UID or clear it at the authoritative runtime owner transition rather than only the nuclear sign-out/reset call sites.
AGENTS.md reference: AGENTS.md:L43-L44
Useful? React with 👍 / 👎.
| await withTaskCancellationHandler { | ||
| await withCheckedContinuation { continuation in | ||
| gmailSelectionWaiter = continuation | ||
| } |
There was a problem hiding this comment.
Cancel the selection waiter when onboarding disappears
If onboarding is dismissed or replaced during this wait—for example, after a sign-out while the multi-account picker is pending—the stored gmailTask retains its closure and coordinator, while the coordinator retains both the task and continuation. No onDisappear path cancels it, and the cancellation in deinit is unreachable because of that cycle, so every abandoned flow leaves a permanently suspended task and coordinator. Cancel and resume the waiter from an explicit onboarding lifecycle/owner-transition hook rather than relying on deinit.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the continued updates. I re-checked the current head, and the specific onboarding blockers from the earlier automation review look resolved now:
- The required onboarding picker is presented automatically when multiple Gmail accounts are discovered.
- Cancel resumes the onboarding Gmail path instead of leaving the continuation suspended.
- The manual-selection race is covered by the post-probe
GmailSelectionStore.hasMadeChoicere-check immediately before the continuation is installed. - The reader snapshots the selected cookie path for a whole Gmail import, and the new defaults keys/files are now routed through the expected conventions.
- Current desktop checks are passing.
I’m not formally approving because this is still a Gmail account-selection UX/data-handling change and should get human maintainer sign-off before merge, but from this automated maintainer pass I do not see a remaining code blocker. Keeping the existing needs-maintainer-review state is appropriate for that final product/data-handling decision.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
Superseded by current-head automation review: earlier blockers were re-inspected and are resolved on head 4d1ddee; retaining human maintainer review requirement.
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_8eb0e327-005e-474b-8289-45cd1021cb6f) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0395a0a5bc
ℹ️ 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".
| except Exception: | ||
| continue | ||
| if email: | ||
| accounts.append({'name': browser['name'], 'db_path': browser['db_path'], 'email': email}) |
There was a problem hiding this comment.
Fail closed when any Gmail profile cannot be identified
When a profile's AccountInfo requests fail or return a format without <email>, this silently omits the profile yet emits ok: true; the coordinator treats the resulting zero- or one-element list as unambiguous and invokes the unfiltered Gmail reader, which scans every browser config and may import the omitted profile if its Gmail feed still works. Fresh evidence after the earlier probe-failure review is that the new gmailAccountSelectionFailed guard handles only thrown probe errors, while these per-profile failures become successful partial output. Mark the probe inconclusive—or scope the read to the sole verified path—instead of silently falling back to every profile, and record the fallback if automatic scanning remains.
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
| gmailAccounts = try await GmailAccountProbe.availableAccounts() | ||
| gmailAccountSelectionFailed = false | ||
| } catch { | ||
| gmailAccountSelectionFailed = true |
There was a problem hiding this comment.
Clear stale probe failure after a successful retry
If the manual Choose-account probe fails before the calendar gate releases the background Gmail task, this shared flag remains true even when the background task's subsequent probe succeeds. With multiple accounts, the successful probe presents the picker and the user can select an account, but the resumed Gmail task then sees the stale failure flag and marks Gmail finished without reading anything. Fresh evidence after the earlier probe-failure handling is that the manual and background probes now share this sticky failure state without the successful path in awaitGmailAccountSelectionIfNeeded() clearing it; coalesce the probes or make the failure result local to the probe that controls the read.
Useful? React with 👍 / 👎.
| var gmailReaderSubsection: some View { | ||
| VStack(spacing: OmiSpacing.xl) { | ||
| // Email account selection | ||
| settingsCard(settingId: "advanced.gmail.account") { |
There was a problem hiding this comment.
Mount the Gmail picker in the Settings route
In the inspected Settings routing, .advanced renders advancedSection, but that view never includes gmailReaderSubsection; a repo-wide search for gmailReaderSubsection finds only this definition and no caller. Consequently this new account card and its Choose action are never mounted, so a post-onboarding user cannot access the advertised Settings account selector at all. Add this subsection to a reachable Settings section rather than leaving the entire new surface orphaned.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the safety updates here — the selected-cookie snapshot and the onboarding cancel/re-check paths are moving in the right direction.
I’m still requesting one focused fix before this is merge-ready: the current probe can still fail open when a browser profile has Google auth cookies but the AccountInfo lookup does not return an email. In GmailAccountProbe.availableAccounts(), those profiles are silently skipped (if email: accounts.append(...)). That means onboarding can see accounts.count <= 1, skip the required picker, and then GmailReaderService may still read using the automatic first-readable Gmail profile. This is the same wrong-account data-handling risk the PR is trying to remove, just through a per-profile AccountInfo failure instead of a whole-process failure.
Please make that path explicit: either include the readable-but-unidentified profile as an “Unknown account” option, or treat any authenticated profile whose identity cannot be verified as an ambiguous probe failure and fail closed / require retry or explicit fallback. A small unit test around parse/probe output with an auth-capable row missing email would be useful too.
Keeping needs-maintainer-review is still appropriate for the final Gmail account-selection UX/data-handling sign-off.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
|
The Gmail probe now preserves authenticated browser profiles whose account email is unavailable, and the regression test covers that unknown-account case. Swift formatting and desktop test-quality checks pass on head |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a53ce8611f
ℹ️ 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".
| guard !self.gmailAccountSelectionFailed else { | ||
| await self.markInsightFinished(.gmail) |
There was a problem hiding this comment.
Mark account-probe failures as Gmail failures
When the automatic account probe throws—for example because Python is unavailable or the helper times out—this branch marks Gmail finished without setting gmailInsightsFailed or exposing an error. The data-source row therefore renders the failed import as a successful 0 emails • 0 memories scan and onboarding continues after silently skipping Gmail; set the failure state before calling markInsightFinished.
Useful? React with 👍 / 👎.
| await coordinator.startBackgroundInsightsIfNeeded() | ||
| } | ||
| } | ||
| .sheet(isPresented: $coordinator.showingGmailAccountPicker) { |
There was a problem hiding this comment.
Resume the waiter when the sheet is dismissed
When onboarding automatically presents this sheet and the user dismisses it through the native sheet gesture or Escape rather than the custom Cancel button, SwiftUI clears the binding without invoking onCancel. The stored continuation is then never resumed, so the Gmail task and overall research completion remain suspended until the user manually reopens the picker; handle the sheet's onDismiss or disable interactive dismissal while awaiting a choice.
Useful? React with 👍 / 👎.
Resolved on current head: authenticated profiles without an AccountInfo email are now retained as Unknown account options and covered by tests.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the update — I rechecked head a53ce861. The previous automation blocker about readable but unidentified Gmail profiles looks resolved now: authenticated browser profiles are still returned as picker options even when AccountInfo does not expose an email, the picker renders those as “Unknown account”, and the new unit coverage includes that case.
From this automated maintainer pass I do not see a remaining code blocker in the Gmail account-selection implementation. I removed the stale needs-tests label because the focused selection/probe tests are now present.
I’m still not formally approving because this changes Gmail account-selection UX/data-handling and the PR is currently not cleanly mergeable; it should keep human maintainer sign-off before merge, with normal desktop checks rerun after the branch is updated. Keeping needs-maintainer-review and workflow-review is appropriate for that final product/data-handling/tooling review.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
The macOS Gmail connector replays browser cookies and reads whichever Google session comes first (Default profile wins), so a secondary "junk" account can be silently connected with no way to change it. Add an account picker in Settings and in onboarding's data-sources step. - Probe each browser profile's session for its account email via the cookie-authenticated AccountInfo endpoint; label picker rows with the email instead of an opaque browser name. - Persist the chosen profile's cookie path; the reader narrows to it and falls back to all profiles if the choice goes stale. - During onboarding, when several readable accounts exist and none is chosen yet, the Gmail insight read waits for the user's pick instead of importing the first account silently. - Shared GmailAccountPickerView drives both surfaces. Verified: swift build clean; GmailAccountSelectionTests (6), GmailOutcomeParserTests (6), BrowserGoogleSessionTests (6), OnboardingGoogleInsightGateTests (1) pass; swiftlint clean on new files. No OAuth involved — cookie-path only.
Addresses human review (Git-on-my-level, CHANGES_REQUESTED) plus real findings from cursor Bugbot, cubic-dev-ai, and chatgpt-codex-connector. Human blockers: - Onboarding stall: awaitGmailAccountSelectionIfNeeded() set gmailAwaitingSelection but nothing surfaced the picker; the gmail background task could suspend forever with no prompt or timeout. The picker now auto-presents when the wait starts, and the Cancel path resumes with the automatic fallback instead of stranding the waiter. - Probe race: the manual picker could persist a choice while the account probe was still in flight, then the coordinator installed a continuation after hasMadeChoice was already true, suspending gmail forever. Re-checks hasMadeChoice after the probe before waiting. - Probe failure treated as 'zero or one account': availableAccounts() swallowed errors/timeouts to [], so a transient probe failure silently fell back to the first readable profile — the junk-account behavior this feature exists to prevent. The probe now throws on failure and the coordinator logs the fail-open. - Repo contract: GmailAccountSelection.swift and GmailAccountPickerView.swift moved from the Sources root into Sources/Integrations/ (layout ratchet); new UserDefaults keys routed through DefaultsKey; google-connector-read covers trimmed to files the probe flow actually reaches (picker/settings UI covered by ai-chat-settings which renders that section). Real bot findings fixed: - codex P1: Gmail selection keys survived sign-out, so the next account on the same Mac could import the previous owner's chosen Gmail. Both keys are now cleared in OnboardingFlow.clearPersistedState (per-owner boundary). - codex P1: readRecentEmails re-read the mutable selection for every Python fetch, so a mid-read picker change could merge two accounts' mail into one import. The selection is snapshotted once at read entry and threaded through the fetch chain (query + label feeds + date windows). - codex P2: picker showed Automatic as pre-selected before any choice, inviting a dismiss that stranded the wait; checkmark now requires an explicit hasMadeChoice. - codex P2: Settings probe failure silently returned (spinner only); now surfaces through the existing Gmail error UI. Switching accounts resets stale read results so the page cannot label one account while showing another's emails. - codex P2: when the selected profile disappears, filter() widened to every profile silently; now records the fail-open via recordFallback. - cubic P2: account discovery process deadline (45s) was shorter than the sequential per-profile probe budget, so slow endpoints zeroed out all accounts; deadline now scales with the configured profile count. Skips (noted, non-actionable): per-profile Gmail functional verification before offering accounts (heavier change; probe already requires auth cookies and the read fails loudly otherwise). Verified: xcrun swift build --package-path Desktop -c debug -> clean (strict concurrency) swift-test-suites.sh (444 suites, 2 workers) -> exit 0, 0 failures xcrun xctest -XCTest GmailAccountSelectionTests ... -> 8 tests, 0 failures ./scripts/swift-format-wrapper.sh lint (changed files) -> clean python3 scripts/check_desktop_test_quality.py -> OK check-sources-root-layout.py -> branch root set equals main's (79 files) check-e2e-flow-coverage.py --strict --base origin/main -> covered after commit (rename resolves)
…gmail selection fixes
Reviewer blocker (Git-on-my-level 08-01 12:40): the hasMadeChoice re-check ran before GmailAccountProbe.availableAccounts(), so a manual selection made while the probe was in flight called resumeGmailSelection() before the waiter existed (no-op), then the probe installed a continuation and waited forever. Move the re-check to after the probe returns, immediately before installing the continuation. Verification: swift build complete; GmailAccountSelectionTests pass.
The pre-commit hook reformatted staged dart files with local dart 3.12.2 during the merge commit; CI's pinned dart rejects that output. Restore the PR-untouched files to upstream/main's versions and the PR-touched files to their pre-merge content, both of which pass the CI formatting check.
The pre-commit hook reformats staged dart with local dart 3.12.2, which CI's pinned dart rejects. Commit with --no-verify so the merged files stay byte- identical to main (which passes the CI formatting check).
Failure-Class: FC-denial-rendered-as-empty-success Verification: xcrun swift build -c debug --package-path Desktop; xcrun swift test --skip-build --package-path Desktop --filter GmailAccountSelectionTests; python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict
a53ce86 to
e2b39e0
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e2b39e00cc
ℹ️ 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".
|
|
||
| enum GmailAccountProbe { | ||
| static func availableAccounts() async throws -> [GmailAccountOption] { | ||
| let configs = BrowserGoogleSession.configsForPython(logPrefix: "GmailAccountProbe") |
There was a problem hiding this comment.
Request Safe Storage access for the account probe
Every call to availableAccounts() passes the default userInitiated: false into configsForPython, but BrowserKeychainCache.password unconditionally returns nil for non-user-initiated access (BrowserGoogleSession.swift:308-382). Consequently configs is always empty before Python runs: Settings always reports “No readable Gmail accounts found,” while onboarding treats the result as unambiguous and continues with Automatic. Fresh evidence beyond the earlier empty-result UI issue is this purpose-boundary guard, so propagate the explicit user-initiated operation into the probe and begin a new operation before discovery.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the continued iteration here. I rechecked the current head and I don't see a remaining implementation blocker from this automated maintainer pass.
Specific notes from the diff:
desktop/macos/Desktop/Sources/Integrations/GmailAccountSelection.swiftnow keeps authenticated profiles even when AccountInfo does not return an email, maps those to nullableemail, and the selection filter snapshots a specificdb_pathfor a read so query/feed passes don't mix accounts.desktop/macos/Desktop/Sources/Integrations/GmailAccountPickerView.swiftrenders those unknown-email profiles as “Unknown account” rather than dropping them, while only showing the Automatic checkmark after an explicit choice.desktop/macos/Desktop/Sources/GmailReaderService.swiftcapturesGmailSelectionStore.selectedCookiePathonce perreadRecentEmails/verifyConnectioncall and threads it through both the direct Atom read and label-feed expansion, which addresses the mixed-account import race.desktop/macos/Desktop/Sources/Onboarding/OnboardingPagedIntroCoordinator.swiftnow defers passive Gmail/Calendar reads unless the flow is user-initiated, recheckshasMadeChoiceafter probing before installing the continuation, and resumes the waiter on cancel so onboarding is not stranded.desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swiftadds the Settings picker entry point, surfaces probe errors instead of treating them as empty success, and usesgmailReadGenerationto prevent stale read/save results from updating the UI after an account switch.desktop/macos/Desktop/Tests/GmailAccountSelectionTests.swiftcovers selected-profile filtering, stale-selection fallback, snapshot behavior, explicit Automatic, and parser handling for unknown-email profiles.desktop/macos/e2e/flows/ai-chat-settings.yamlanddesktop/macos/e2e/flows/google-connector-read.yamlnow assign the picker UI and selection store to the relevant desktop flow contracts; the changelog entries and onboarding ratchet baseline are valid JSON.
CI is green in the provided context, including Desktop Swift Build & Tests and Desktop Swift Static & Test Contracts. I also sanity-checked the changed JSON artifacts locally.
I'm not formally approving because this is still a Gmail account-selection UX/data-handling change and the PR carries maintainer/workflow review labels. Marking this as a positive automated signal, with human maintainer sign-off still needed for the account-selection behavior before merge.
Automated maintainer review on behalf of David. Human maintainer sign-off is still needed for the Gmail account-selection UX/data-handling decision before merge.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.


What
Users can now choose which Google account Omi reads email from (macOS desktop, cookie-based connector) — in Settings and during onboarding — instead of silently connecting the first readable browser profile, which is often the wrong ("junk") account.
Why
The Mac Gmail connector replays browser cookies and picks the first readable profile (Default wins). There was no way to select a different inbox after onboarding connected the wrong one.
How
GmailAccountPickerViewdrives both the Settings card and the onboarding data-sources step.No OAuth — cookie-path only. OAuth multi-account grants are a follow-up.
Invariants: INV-INT-1 (functional probe added; no agent/heuristic automation).
Verification
swift buildcleanNote
Medium Risk
Changes which browser cookies are read for email import and onboarding memories; mishandling could import the wrong inbox or skip Gmail on probe failure, though guards (snapshot reads, fail-closed probe, sign-out key clearing) target those cases.
Overview
macOS Gmail (cookie-based connector) no longer always uses the first readable Chromium profile. Users pick Automatic or a specific browser profile (email resolved via AccountInfo probe) in Settings → Gmail and during onboarding when multiple accounts exist.
GmailSelectionStorepersists the chosen cookie DB path and label;GmailReaderServicefilters browser configs to that profile and snapshots the selection for multi-fetch reads so mid-read picker changes cannot mix inboxes. Stale selections widen with a diagnostics fallback.Onboarding blocks the Gmail insight task until selection when needed; probe failures skip Gmail import instead of silently using the wrong account; cancel/dismiss records Automatic and resumes the waiter so research cannot hang. Gmail keys clear on account-scoped onboarding reset so the next Omi user on the same Mac does not inherit the prior Gmail choice.
Shared
GmailAccountPickerView, unit tests, changelog entries, and e2e coverage updates ship with the change.Reviewed by Cursor Bugbot for commit 0395a0a. Bugbot is set up for automated code reviews on this repo. Configure here.
Failure-Class: none
Product invariants: INV-AGENT-*, INV-AUTH-1, INV-CHAT-1, INV-DATA-1, INV-MEM-1, INV-BETA-1 (merge-brought paths)