Repository navigation
feat(desktop): Google OAuth connector for Gmail and Calendar - #10969
undivisible wants to merge 28 commits into
Conversation
There was a problem hiding this comment.
4 issues found across 19 files
Confidence score: 2/5
- In
desktop/macos/Desktop/Sources/GoogleOAuthConnection.swift,connectcan report success even when keychain persistence fails, so subsequent reads may silently fall back to cookies or appear disconnected to users. Propagate write/upsert failures through the full call chain and surface an error to the UI so success is only shown when the grant is actually stored. - In
desktop/macos/Desktop/Sources/GmailAccountSelection.swift, account selection is applied for Gmail but not in the Calendar path, which can cause Calendar reads to target the wrong profile despite the user’s explicit choice. Apply the sameGmailSelectionStore.filter(...)-styledb_pathfiltering inCalendarReaderServiceto keep behavior consistent. desktop/macos/Desktop/Sources/GoogleOAuthFlow.swiftintroduces a parallel loopback callback implementation with different lifecycle/race behavior from the existing server, increasing the chance of intermittent OAuth callback failures. Reuse or extendOAuthLoopbackCallbackServerto consolidate callback handling and reduce divergence risk.- In
desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swift, usingForEach(..., id: \.account)with optionalaccountvalues can lead to unstable or non-unique SwiftUI identity when user info lookup returns nil. Switch to a guaranteed-stable non-optional identifier for row identity to avoid list update glitches.
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/GoogleOAuthConnection.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/GoogleOAuthConnection.swift:95">
P1: OAuth connection reports success even when the grant was not persisted, so the next reader invocation falls back to cookies or shows no grant. Propagate keychain write failure through `write`/`upsert`/`connect` and surface a connection error.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/GoogleOAuthFlow.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/GoogleOAuthFlow.swift:74">
P3: This duplicates the existing OAuth loopback server with divergent callback and lifecycle handling, which has already produced different race behavior here. Reuse or extend `OAuthLoopbackCallbackServer` so OAuth flows share one hardened implementation.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/GmailAccountSelection.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/GmailAccountSelection.swift:36">
P2: The chosen account is only honored for Gmail, not Calendar. `GmailReaderService` wraps its browser configs with `GmailSelectionStore.filter(...)` so the selected `db_path` is applied, but `CalendarReaderService` simply calls `BrowserGoogleSession.configsForPython(...)` without filtering. So a user who picks a specific account still has Calendar read from whatever browser profile is readable first. If this PR intends the same per-account selection for Calendar, apply the same `GmailSelectionStore.filter` in `CalendarReaderService`.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swift:63">
P3: The account list uses `ForEach(googleOAuthAccounts, id: \.account)`, but `account` is an optional `String?` that the connect flow leaves nil whenever the userinfo lookup fails (GoogleOAuthTokenClient.fetchAccount returns nil on a non-200 or missing email). Multiple nil-account rows would produce duplicate ForEach identifiers (undefined row behavior), and the underlying upsert keys/dedupes on `account`, so a second nil-account connection would silently overwrite the first. Consider deriving a non-optional, stable id (e.g. an index-based or unique-per-connection id) instead of keying on the optional email.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| log("GoogleOAuthStore: failed to encode connections") | ||
| return | ||
| } | ||
| DesktopKeychainStore.setString( |
There was a problem hiding this comment.
P1: OAuth connection reports success even when the grant was not persisted, so the next reader invocation falls back to cookies or shows no grant. Propagate keychain write failure through write/upsert/connect and surface a connection error.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/GoogleOAuthConnection.swift, line 95:
<comment>OAuth connection reports success even when the grant was not persisted, so the next reader invocation falls back to cookies or shows no grant. Propagate keychain write failure through `write`/`upsert`/`connect` and surface a connection error.</comment>
<file context>
@@ -0,0 +1,107 @@
+ log("GoogleOAuthStore: failed to encode connections")
+ return
+ }
+ DesktopKeychainStore.setString(
+ raw, service: Self.service, account: Self.account)
+ }
</file context>
|
|
||
| /// One-shot HTTP server on 127.0.0.1:0 that captures the OAuth redirect and | ||
| /// answers it so the browser stops loading. Torn down after the first request. | ||
| final class LoopbackRedirectServer: @unchecked Sendable { |
There was a problem hiding this comment.
P3: This duplicates the existing OAuth loopback server with divergent callback and lifecycle handling, which has already produced different race behavior here. Reuse or extend OAuthLoopbackCallbackServer so OAuth flows share one hardened implementation.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/GoogleOAuthFlow.swift, line 74:
<comment>This duplicates the existing OAuth loopback server with divergent callback and lifecycle handling, which has already produced different race behavior here. Reuse or extend `OAuthLoopbackCallbackServer` so OAuth flows share one hardened implementation.</comment>
<file context>
@@ -0,0 +1,537 @@
+
+/// One-shot HTTP server on 127.0.0.1:0 that captures the OAuth redirect and
+/// answers it so the browser stops loading. Torn down after the first request.
+final class LoopbackRedirectServer: @unchecked Sendable {
+ private let listener: NWListener
+ private let queue = DispatchQueue(label: "com.omi.oauth.loopback")
</file context>
| .foregroundColor(OmiColors.textTertiary) | ||
| } | ||
|
|
||
| ForEach(googleOAuthAccounts, id: \.account) { account in |
There was a problem hiding this comment.
P3: The account list uses ForEach(googleOAuthAccounts, id: \.account), but account is an optional String? that the connect flow leaves nil whenever the userinfo lookup fails (GoogleOAuthTokenClient.fetchAccount returns nil on a non-200 or missing email). Multiple nil-account rows would produce duplicate ForEach identifiers (undefined row behavior), and the underlying upsert keys/dedupes on account, so a second nil-account connection would silently overwrite the first. Consider deriving a non-optional, stable id (e.g. an index-based or unique-per-connection id) instead of keying on the optional email.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Integrations.swift, line 63:
<comment>The account list uses `ForEach(googleOAuthAccounts, id: \.account)`, but `account` is an optional `String?` that the connect flow leaves nil whenever the userinfo lookup fails (GoogleOAuthTokenClient.fetchAccount returns nil on a non-200 or missing email). Multiple nil-account rows would produce duplicate ForEach identifiers (undefined row behavior), and the underlying upsert keys/dedupes on `account`, so a second nil-account connection would silently overwrite the first. Consider deriving a non-optional, stable id (e.g. an index-based or unique-per-connection id) instead of keying on the optional email.</comment>
<file context>
@@ -7,6 +8,122 @@ import WebKit
+ .foregroundColor(OmiColors.textTertiary)
+ }
+
+ ForEach(googleOAuthAccounts, id: \.account) { account in
+ HStack(spacing: OmiSpacing.md) {
+ Image(systemName: "envelope")
</file context>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0799bd408f
ℹ️ 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".
| static let service = "com.omi.desktop.google-oauth" | ||
| static let account = "connections" |
There was a problem hiding this comment.
Scope OAuth grants to the signed-in Omi user
The keychain service and account are fixed constants and neither reads nor writes incorporate authUserId; repository-wide search also shows no auth-owner transition that deletes this item. If user A connects Google and then user B signs into Omi on the same installation, B's Gmail/Calendar reads reuse A's access or refresh token and can save A's data into B's account. Store grants under the effective owner and switch or purge them at the authenticated-owner boundary.
Useful? React with 👍 / 👎.
| var uri: URL { | ||
| // swiftlint:disable:next force_unwrapping — fixed localhost literal cannot fail | ||
| URL(string: "http://127.0.0.1:\(listener.port?.rawValue ?? 0)/oauth/callback")! |
There was a problem hiding this comment.
Wait for the loopback listener before publishing its port
connect() calls start() and immediately reads this property, but an ephemeral NWListener does not expose its assigned port until it reaches the ready state. During that asynchronous bind, this fallback constructs http://127.0.0.1:0/..., so Google cannot return the authorization code and the connection attempt waits indefinitely or times out. Await the listener's ready callback and require a nonzero port before constructing the authorization URL.
Useful? React with 👍 / 👎.
| redirectUri: redirectUri.absoluteString, | ||
| clientId: clientId | ||
| ) | ||
| upsert(connection) |
There was a problem hiding this comment.
Verify Gmail and Calendar before persisting the connection
A successful token exchange does not prove that the user granted both requested scopes or that the Gmail and Calendar APIs are enabled, yet the grant is immediately persisted and displayed as connected. In those common configurations, every reader prefers this unusable grant over cookies and repeatedly fails with 403 instead of completing setup or falling back. Run real Gmail and Calendar probes before upsert, as required by the locked INV-INT-1 connector contract.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| if let grant = GoogleOAuthConnectionManager.shared.primaryConnection() { | ||
| let token = try await GoogleOAuthConnectionManager.shared.accessToken(account: grant.account) | ||
| let emails = try await GoogleOAuthGmailReader.readRecentEmails( | ||
| token: token, maxResults: maxResults, query: query) |
There was a problem hiding this comment.
Read from every connected OAuth account
When multiple accounts are connected, this reader always selects only primaryConnection()—the most recently inserted valid grant—and ignores every other account that the settings UI still reports as connected; CalendarReaderService.readEvents has the same behavior. Adding an account therefore silently switches imports to it and stops importing the previously connected account, recreating the wrong-inbox/data-omission problem this multi-account feature is intended to solve. Aggregate all grants or expose an explicit OAuth account selection.
Useful? React with 👍 / 👎.
| gmailAccounts = accounts | ||
| gmailAwaitingSelection = true | ||
| await withTaskCancellationHandler { | ||
| await withCheckedContinuation { continuation in | ||
| gmailSelectionWaiter = continuation |
There was a problem hiding this comment.
Present the account picker before suspending onboarding
For a fresh user with more than one readable browser account, this path sets gmailAwaitingSelection and suspends on a continuation, but that flag is not consumed anywhere and showingGmailAccountPicker remains false. The background Gmail scan therefore never resumes and onboarding remains on “Scanning your data sources...” until the user independently notices and presses “Choose account.” Set the sheet binding before awaiting selection, and make cancellation resume the waiter as well.
Useful? React with 👍 / 👎.
| static func parseEvent(_ dict: [String: Any]) -> CalendarEvent? { | ||
| guard let id = dict["id"] as? String, | ||
| let summary = dict["summary"] as? String | ||
| else { | ||
| return nil |
There was a problem hiding this comment.
Preserve Calendar events that have no summary
Google Calendar permits events without a summary, but this guard drops those events entirely even when they have valid IDs, times, attendees, or locations. The existing cookie reader explicitly maps the same case to "Untitled", so switching a user to OAuth silently removes those events from imports and generated memories. Require only the ID and use the established untitled fallback for a missing summary.
Useful? React with 👍 / 👎.
| func connectGoogleOAuth() async { | ||
| if (GoogleOAuth.clientId ?? "").isEmpty { | ||
| promptGoogleOAuthClientId() | ||
| guard let clientId = GoogleOAuth.clientId, !clientId.isEmpty else { | ||
| return |
There was a problem hiding this comment.
Let users correct OAuth client credentials after failure
The credential dialog is shown only while the stored client ID is empty, even though the ID and optional secret are persisted before any authorization or API call succeeds. A typo, wrong client type, or stale secret therefore makes every later Connect attempt reuse the bad values, and repository-wide search finds no UI path that edits or clears them; recovery requires manually deleting UserDefaults. Keep unverified credentials temporary or provide an Edit/Reset action after failed setup.
Useful? React with 👍 / 👎.
| static func attendees(_ raw: [[String: Any]]) -> [String] { | ||
| raw.compactMap { | ||
| ($0["displayName"] as? String) ?? ($0["email"] as? String) | ||
| } |
There was a problem hiding this comment.
Exclude the calendar owner from attendee projections
Google includes the calendar owner in an event's attendee array with self: true, but this parser keeps that row and usually emits the owner's display name. The existing cookie reader explicitly excludes self-attendees, so OAuth imports make ordinary meetings appear to be “With” the user themselves and feed that false participant into memory and task synthesis. Filter entries whose self field is true before choosing their display name or email.
Useful? React with 👍 / 👎.
| let body = try await GoogleOAuthGmailReader.get( | ||
| // swiftlint:disable:next force_unwrapping — fixed components cannot fail | ||
| components.url!, token: token, session: session) | ||
| let events = | ||
| (body["items"] as? [[String: Any]] ?? []).compactMap(parseEvent) |
There was a problem hiding this comment.
Follow Calendar pagination until the requested limit
The Calendar Events API can return an incomplete page together with nextPageToken even when items.count is below the requested maxResults, but this path reads only the first response and discards the token. Large onboarding imports can therefore silently omit events despite requesting up to 1,000 records; the existing cookie reader already loops over page tokens until it reaches the limit. Continue fetching pages and cap the combined result at maxResults.
Useful? React with 👍 / 👎.
| for id in ids.prefix(maxResults) { | ||
| let detail = try await get( | ||
| messagesURL.appendingPathComponent(id).appending( | ||
| queryItems: [ | ||
| URLQueryItem(name: "format", value: "metadata"), |
There was a problem hiding this comment.
Skip messages that disappear during Gmail detail fetches
Each message is listed and then fetched separately, and any single detail request error escapes the loop and discards every email accumulated so far. If a message is deleted between the list and detail calls—a normal mailbox race producing 404—the entire Gmail import fails instead of returning the remaining messages. Handle per-message 404s by skipping that ID while continuing to surface account-wide authentication and network failures.
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for pushing this forward — moving Gmail/Calendar to a real OAuth consent flow is a promising direction, but this needs changes before it is safe to merge.
Blocking issues I verified on the current head:
- CI is not green: the desktop Swift gate currently fails to compile in
GoogleOAuthFlow.swiftwith strict concurrency errors around theNWConnection.receivecallback, and the desktop launcher/script contract step is failing as well. Please get the desktop build/test contracts green. - The loopback OAuth server reads
listener.portimmediately afterstart()while binding port0.NWListenerbinds asynchronously, so the redirect URI can be built as127.0.0.1:0, causing sign-in to time out instead of completing. Please wait for the listener to become ready and use the resolved port before opening the auth URL. - The onboarding account-selection path can suspend Gmail insight loading without presenting the picker automatically; cancel only hides the sheet and does not resume the waiting continuation. Users with multiple readable accounts can get stuck in onboarding unless they manually choose/reopen the picker. Please make selection/cancel/timeout paths deterministic and non-blocking.
- OAuth grants can be persisted with
account == nilwhen userinfo lookup fails. Since upsert/dedup and SwiftUI row identity are both keyed by that optional account, multiple unknown accounts can overwrite each other or render with duplicate IDs. Please require a verified stable account identifier before storing, or introduce a non-optional stable grant id.
Because this touches OAuth, token/keychain storage, and Gmail/Calendar data access, it should also get human maintainer/security review after the correctness and CI blockers are fixed. The feature is cohesive, so I am not asking for it to be split solely due to size.
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.
Cursor Bugbot has reviewed your changes using high effort and found 5 potential issues.
There are 8 total unresolved issues (including 3 from previous reviews).
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 aa77e0f. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa77e0f756
ℹ️ 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".
| } | ||
| do { | ||
| let refreshed = try await tokenClient.refresh(stored, clientId: clientId) | ||
| if !upsert(refreshed) { |
There was a problem hiding this comment.
Prevent stale refreshes from restoring removed grants
If an expired-token refresh is in flight while the user disconnects that account, disconnect() can remove the grant and return before this unconditional upsert writes the stale connection back into the keychain. The same race can overwrite a newly reconnected grant with the old refresh result or mark it needsReconnect from the invalidGrant catch. Serialize these lifecycle operations or conditionally persist only if the stored grant is still the version that initiated the refresh.
Useful? React with 👍 / 👎.
| lock.lock() | ||
| defer { lock.unlock() } | ||
| let all = store.readAll().filter { $0.account != account } | ||
| _ = store.write(all) |
There was a problem hiding this comment.
Report keychain removal failures from disconnect
When revocation succeeds but the keychain rewrite fails, this result is discarded and disconnect() still reports success. Settings then reloads the unchanged record, while future reads keep preferring a now-revoked OAuth grant and fail instead of using the intended state. Make remove return the write result and surface a storage failure just as upsert does.
Useful? React with 👍 / 👎.
| let emails = try await GoogleOAuthGmailReader.readRecentEmails( | ||
| token: token, maxResults: maxResults, query: query) |
There was a problem hiding this comment.
Normalize OAuth failures at the reader boundary
For an OAuth-backed read that encounters a 401/403, HTTP error, or network failure, this call now leaks GoogleOAuthReaderError from a service whose established callers classify GmailReaderError; consequently gmail_read_probe falls into its unknown classification, and the equivalent Calendar probe has no generic catch at all. Translate provider errors into the existing service taxonomy so the connector's required semantic probes still return stable, actionable failure classes.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| func readRecentEmails(maxResults: Int = 50, query: String = "newer_than:1d") async throws | ||
| -> [GmailEmail] | ||
| { | ||
| if let grant = GoogleOAuthConnectionManager.shared.primaryConnection() { |
There was a problem hiding this comment.
Record the cookie-provider fallback
When grants exist but all are marked needsReconnect, primaryConnection() returns nil and this branch silently switches subsequent reads from OAuth to browser cookies; Calendar has the same provider switch. That fail-open path can recover using a different browser account but emits no shared fallback event, leaving the mode change invisible to desktop health telemetry. Record the OAuth-to-cookie outcome with DesktopDiagnosticsManager.recordFallback.
AGENTS.md reference: AGENTS.md:L91-L91
Useful? React with 👍 / 👎.
| -> [CalendarEvent] | ||
| { | ||
| await APIKeyService.shared.waitForKeys() | ||
| if let grant = GoogleOAuthConnectionManager.shared.primaryConnection() { |
There was a problem hiding this comment.
Check OAuth before waiting for legacy API keys
Even when a valid OAuth grant exists, this branch is reached only after APIKeyService.waitForKeys() completes its backend fetch and retry sequence, although the OAuth Calendar API request uses only the bearer token and does not need the legacy cookie-path API key. If the Omi key endpoint is slow or unavailable while Google remains reachable, OAuth reads and the live connection probe incur all backend timeouts before proceeding. Select OAuth first and wait for keys only in the cookie branch.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| for id in ids.prefix(maxResults) { | ||
| let detail = try await get( |
There was a problem hiding this comment.
Bound concurrency for Gmail message-detail requests
For the onboarding/import call that requests 300 emails, this loop performs every message-detail request serially after the list request, producing up to 301 network round trips whose latencies are added together. A normal populated mailbox can therefore leave onboarding or an import waiting for minutes even though Gmail permits independent detail reads. Fetch details with bounded concurrency while preserving the requested result limit.
Useful? React with 👍 / 👎.
| else { | ||
| continue | ||
| } | ||
| result[name] = value |
There was a problem hiding this comment.
Match Gmail metadata headers case-insensitively
RFC message header names are case-insensitive, but this dictionary preserves Google's returned spelling while parseMessage looks up only exact "From" and "Subject" keys. Messages whose original headers use forms such as from or subject are consequently imported with an empty sender and "(no subject)", corrupting the metadata passed into memories and synthesis. Normalize header names when building or reading this dictionary.
Useful? React with 👍 / 👎.
| - desktop/macos/Desktop/Sources/GoogleOAuthConnection.swift | ||
| - desktop/macos/Desktop/Sources/GoogleOAuthFlow.swift | ||
| - desktop/macos/Desktop/Sources/GoogleOAuthReader.swift |
There was a problem hiding this comment.
Exercise OAuth before declaring the OAuth files covered
The newly listed OAuth files are not exercised by this flow: its preconditions establish only the automation bridge, and both steps explicitly drive the BrowserGoogleSession cookie path without connecting or seeding an OAuth grant. Nevertheless these covers entries satisfy the diff-scoped E2E coverage gate, so regressions in the authorization flow, keychain store, and OAuth reader can pass while the claimed flow never reaches them. Add an OAuth-specific setup and assertion or remove these coverage claims.
AGENTS.md reference: AGENTS.md:L28-L28
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.
Enumerate accounts within each browser profile
For a Chromium profile containing multiple signed-in Google accounts, this probe appends exactly one option keyed only by the cookie database path, using whichever email the unqualified AccountInfo request returns. The subsequent Gmail feed requests likewise carry no account index, so secondary accounts in that same profile never appear in the picker and cannot be selected; Omi can still import the profile's default inbox despite this feature being presented as account selection. Represent each signed-in account separately and carry an account selector through the read path.
Useful? React with 👍 / 👎.
Stale automation review dismissed after re-review of aa77e0f: the specific loopback redirect, onboarding selection, and OAuth account identity/keychain blockers from that review were addressed. Remaining concerns are tracked in the current comment.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the follow-up fixes here. I re-reviewed the new head aa77e0f75653a9f5d2381f60136f4b41f2b074e7.
The earlier automation blockers I checked appear addressed on this head:
- The loopback redirect server now waits for the listener to report ready before constructing the redirect URI, retains an early callback for a later waiter, and settles the waiter on cancellation.
- Onboarding now automatically presents the Gmail account picker when multiple readable accounts require a choice, and cancel resumes the Gmail insight path instead of stranding the task.
- OAuth grants now reject missing verified account identity before persistence, propagate keychain write failures, scope the keychain service, and avoid optional-account row identity for the list.
- The Gmail/Calendar OAuth reader paths and tests cover the important parser and connection-manager cases, and the desktop Swift build/test gates are passing now.
I am not approving this automatically because it still touches OAuth consent, token/keychain storage, and Gmail/Calendar user-data access, so it needs human maintainer/security review before merge. There is also still a non-code CI/metadata blocker: Hygiene / PR Metadata Preflight is failing because the fix(desktop): address review blockers for Google OAuth connector commit needs the required Failure-Class: FC-<slug> | new | none declaration.
The feature is cohesive around one desktop Gmail/Calendar OAuth connector, so I am not asking for a split solely due to size.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks — I re-checked the current head aa77e0f75653a9f5d2381f60136f4b41f2b074e7 after the latest CI run.
Update from my prior automation review: the non-code Hygiene / PR Metadata Preflight blocker I called out now appears resolved, and the desktop Swift build/test + static/test contract gates are passing. I still do not see a new automation-level code blocker on the current diff.
I’m keeping this as human-review-required rather than approving automatically because the PR changes OAuth consent, token/keychain storage, and Gmail/Calendar user-data access. A maintainer/security review should still sign off on the product/security behavior before merge, especially the intended account-selection semantics for multiple connected Google grants.
The change remains cohesive around one desktop Gmail/Calendar OAuth connector, so I’m not asking for a split solely due to size.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
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_8063624d-0bb7-4704-9629-3d8c1ef63f4a) |
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_e7751796-b61e-4156-9667-d8a6255b6fbe) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 29a802f901
ℹ️ 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".
| case .found(let raw) = DesktopKeychainStore.readString( | ||
| service: Self.service, account: Self.account), | ||
| let data = raw.data(using: .utf8), | ||
| let decoded = try? JSONDecoder().decode( | ||
| [GoogleOAuthConnection].self, from: data) | ||
| else { | ||
| return [] |
There was a problem hiding this comment.
Fail closed when OAuth Keychain reads are unavailable
When the login Keychain returns .unavailable or the stored JSON cannot decode, readAll() returns the same empty array as a genuinely missing item; both reader services then interpret hasGrants() == false as permission to switch to browser cookies, potentially importing a different browser account into the current user's memories. Fresh evidence in the final code is this remaining .unavailable/decode-failure path, despite stale grants now failing closed. Preserve these failures as an error or make the provider switch explicit and recorded rather than silently returning [].
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
| if successfulReads { | ||
| return Array( | ||
| merged.values.sorted { $0.date > $1.date }.prefix(maxResults)) |
There was a problem hiding this comment.
Surface failures from every connected OAuth account
When multiple grants are active and any one account fails authentication or its network request, a success from another account makes this branch return normally and discard firstFailure; onboarding/import therefore silently omits the failed account, while verifyConnection() can still report the connector as connected. Calendar uses the same any-success policy. Return a partial-failure status or fail the aggregate read, and record the correctness-degrading fail-open outcome instead of presenting it as a complete success.
AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49
Useful? React with 👍 / 👎.
| let count = googleOAuthAccounts.count | ||
| return count == 1 | ||
| ? "1 account connected — Gmail and Calendar read through OAuth." | ||
| : "\(count) accounts connected — Gmail and Calendar read through OAuth." |
There was a problem hiding this comment.
Derive the connected summary from live functional probes
After Settings is reopened, loadGoogleOAuthAccounts() loads stored records and this summary labels every nonempty list as connected—even when all records have needsReconnect, or when access was revoked or either API became unavailable since the one-time connect probes. The row may mention reconnect for one case, but the connector-level status remains falsely green indefinitely until another read happens. Drive this summary from current Gmail and Calendar functional probes and exclude stale grants from the connected count.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| guard upsert(connection) else { | ||
| throw GoogleOAuthError.keychainWriteFailed |
There was a problem hiding this comment.
Fence OAuth connect persistence to the initiating Omi user
If the user signs out or switches Omi accounts while browser consent, token exchange, or the API probes are awaiting, this final upsert resolves GoogleOAuthStore.account from the newly current authUserId and stores the first user's Google grant under the second user. Fresh evidence after adding UID-scoped Keychain accounts is that connect() still never captures or revalidates the initiating UID across its awaits. Capture the effective owner at entry and reject persistence unless that same owner and authorization generation remain current.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| func accessToken(account: String? = nil) async throws -> String { | ||
| guard let stored = connection(account: account) else { | ||
| throw GoogleOAuthError.reconnectRequired | ||
| } | ||
| if !stored.isExpired { return stored.accessToken } |
There was a problem hiding this comment.
Refresh access tokens before their final expiry window
When an import starts shortly before expiresAt, this branch returns the nearly expired token without any safety margin; it can expire during Gmail's list/detail requests or Calendar pagination, whose 401 then marks the grant needsReconnect. Because stale grants are excluded from connection(account:), the available refresh token is never used afterward and the user is forced through consent again. Refresh with an expiry skew or retry one authentication failure through the refresh path before marking the grant stale.
Useful? React with 👍 / 👎.
| guard status >= 200 && status < 300 else { | ||
| throw GoogleOAuthReaderError.http(status) | ||
| } | ||
| return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] |
There was a problem hiding this comment.
Reject malformed successful Google API responses
If Google, a proxy, or a captive portal returns HTTP 200 with malformed JSON or an unexpected top-level shape, this fallback converts it to an empty dictionary; both readers then treat it as a successful zero-item result, and the functional probes can report the connector connected while imports silently return no data. Parse the payload strictly and throw a classified schema/network error when a successful response is not the expected JSON object.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| static var clientSecret: String? { | ||
| get { | ||
| let value = UserDefaults.standard.string(forKey: clientSecretKey) | ||
| return (value?.isEmpty ?? true) ? nil : value | ||
| } | ||
| set { UserDefaults.standard.set(newValue, forKey: clientSecretKey) } |
There was a problem hiding this comment.
Store the OAuth client secret in Keychain
Whenever a user supplies the optional OAuth client secret, this setter persists it in the standard UserDefaults preferences plist, leaving the credential readable as plaintext by other same-user processes and in ordinary preference backups. The connector already depends on DesktopKeychainStore; persist this credential there as well and use a secure text field when collecting it.
Useful? React with 👍 / 👎.
| func disconnect(account: String? = nil) async throws { | ||
| guard let stored = connection(account: account) else { return } |
There was a problem hiding this comment.
Let users remove grants that require reconnect
When a stored grant has needsReconnect == true, connection(account:) filters it out, so disconnect() returns here without revoking or removing anything; Settings also replaces the only removal action with Reconnect. If the Google account was deleted or the user does not want to reconnect, the stale record therefore persists indefinitely, keeps hasGrants() true, and makes both readers enter the OAuth branch only to fail because there are no active grants, permanently blocking the cookie path. Provide a forget/remove action that can delete stale records independently of active-token lookup.
Useful? React with 👍 / 👎.
| let query = | ||
| parts[1].contains("?") | ||
| ? String(parts[1].split(separator: "?", maxSplits: 1)[1]) : "" |
There was a problem hiding this comment.
Parse empty callback queries without indexing past the split
While the OAuth listener is active, a valid request target ending in an empty query, such as GET /oauth/callback? HTTP/1.1, satisfies contains("?"), but Swift's default split omits the trailing empty component, so indexing element [1] traps and terminates the app. Split with empty subsequences preserved or derive the query using the question-mark index without unchecked subscripting.
Useful? React with 👍 / 👎.
commented
Aug 3, 2026
|
Thanks — I re-reviewed the current head The earlier automation blockers I checked appear addressed on this head: the loopback redirect now waits for a bound port and retains early redirects; onboarding account selection resumes on cancel; nil-account grants are rejected before persistence; keychain writes are scoped/propagated; Calendar now honors the cookie account selection; OAuth reader parsing covers untitled and fractional-second Calendar events; and the added tests/e2e metadata cover the main connector paths. I’m still keeping this as human-review-required rather than approving automatically because it changes OAuth consent, token/keychain storage, and Gmail/Calendar user-data access. A maintainer/security review should sign off on the intended multi-account behavior and the product/security posture before merge. Also, GitHub currently reports the branch as not cleanly mergeable, so it will need to be brought up to date before final review/merge. The feature remains cohesive around the desktop Gmail/Calendar connector, so I am not asking for a split solely due to size. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
commented
Aug 4, 2026
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_089cf696-2f0b-458d-bbdc-265a51650ea2) |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 277502c234
ℹ️ 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 let messages = body["messages"] as? [[String: Any]] else { | ||
| throw GoogleOAuthReaderError.invalidResponse | ||
| } |
There was a problem hiding this comment.
Accept empty Google list responses during connection probes
When the newer_than:1d query matches no mail, Gmail can return a valid list response with no messages field, but this guard classifies it as malformed; the analogous items guard in the Calendar reader does the same when the probe window contains no events. Because connect() probes both readers before persisting the grant, users with no recent mail or calendar events cannot connect a correctly configured account. Treat an omitted list field as an empty array while continuing to reject malformed non-array values.
Useful? React with 👍 / 👎.
| return try lock.withLock { | ||
| let all = try store.readAll(for: UserDefaults.standard.string(forKey: .authUserId)) | ||
| let current = all.first { Self.sameAccount($0, stored) } |
There was a problem hiding this comment.
Pin refresh persistence to the initiating Omi owner
When owner A's token refresh is suspended and the app switches to owner B, this lookup resolves B's store rather than the owner that supplied stored. If both Omi users connected the same Google email, the account-only match can return B's token to A's caller; if B also joins the account-only refresh gate, B can persist A's refreshed grant. Unlike the newly fenced connect() path, accessToken() captures no owner or authorization generation, so capture it at entry, include it in the refresh key, and use it for every post-await read/write while rejecting an owner change.
Useful? React with 👍 / 👎.
| onDismiss: { | ||
| coordinator.cancelGmailAccountSelection() |
There was a problem hiding this comment.
Preserve the selected account when dismissing the picker
A successful account selection sets showingGmailAccountPicker to false, which dismisses this sheet and invokes onDismiss just as if the user had cancelled. cancelGmailAccountSelection() then immediately overwrites the selected cookie path with nil/Automatic before the suspended Gmail and Calendar imports continue, so onboarding still reads the first available browser profile rather than the account the user chose. Only run the cancellation fallback when the sheet closes without a completed selection.
Useful? React with 👍 / 👎.
| static var selectedCookiePath: String? { | ||
| get { UserDefaults.standard.string(forKey: selectedPathKey) } | ||
| set { UserDefaults.standard.set(newValue, forKey: selectedPathKey) } |
There was a problem hiding this comment.
Scope the browser account selection to the Omi owner
The selected cookie database is stored under one global UserDefaults key, so after Omi user A chooses a Gmail profile and the app switches to Omi user B, both Gmail and Calendar continue reading A's selected browser account and can save its messages or events into B's memories. The OAuth grants were made UID-scoped in this change, but the cookie-path selection feeding the same import pipeline has no owner boundary; key it by the effective Omi owner or clear it during the fenced owner transition.
Useful? React with 👍 / 👎.
| func selectGmailAccount(_ cookiePath: String?, label: String) { | ||
| GmailSelectionStore.persist(cookiePath: cookiePath, label: label) | ||
| showingGmailAccountPicker = false | ||
| gmailReadGeneration += 1 |
There was a problem hiding this comment.
Fence all in-flight imports when changing accounts
If the user chooses a different browser account while a read is running, this only advances the Gmail UI generation: an in-flight Calendar sync has no corresponding fence and can still synthesize memories and tasks from the old profile, while Gmail's second generation check occurs only after saveAsMemories has already persisted the old emails. Account selection therefore can appear to succeed while data from the previously selected account is committed afterward. Cancel or generation-fence both readers at their mutation seams before persisting any results.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
Thanks for the continued fixes here — I re-reviewed the current head 277502c234c7e9d4b7aa8f73feea213a783ff730.
One blocking repository-contract issue remains:
- The desktop source-layout guard fails because this PR adds new Swift files directly under
desktop/macos/Desktop/Sources/(GmailAccountPickerView.swift,GmailAccountSelection.swift,GoogleOAuthConnection.swift,GoogleOAuthFlow.swift, andGoogleOAuthReader.swift).desktop/macos/AGENTS.mdrequires new desktop Swift sources to live in a feature directory underDesktop/Sources/, andpython3 scripts/check-sources-root-layout.pycurrently reports:FAIL: loose Sources-root Swift files rose to 84 (baseline 77). Please move the new connector/account-selection files into an appropriate feature subdirectory and update any package/source references as needed.
The OAuth/keychain/account-selection fixes themselves look directionally good from static review, and the change remains cohesive around one desktop Gmail/Calendar connector, so I am not asking for a split. But because this PR changes OAuth consent, token/keychain storage, and Gmail/Calendar user-data access, it still needs human maintainer/security review after the layout contract is green.
Local checks I ran on this head:
python3 scripts/check-sources-root-layout.py— fails as abovepython3 scripts/check_desktop_test_quality.py— passes
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
commented
Aug 7, 2026
|
Moved the Google connector sources under |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5b29594e6
ℹ️ 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".
| } catch { | ||
| failure = error | ||
| } | ||
| guard remove(account: stored.account, expected: stored) else { |
There was a problem hiding this comment.
Remove the grant from the initiating owner's store
If the Omi user changes while token revocation is awaiting, this call resolves remove against the newly current authUserId, not the owner whose grant was loaded before the await. The new owner's store usually has no matching record, so remove returns success while the initiating owner's now-revoked grant remains persisted; switching back leaves OAuth selected, blocks the cookie path through hasGrants(), and forces an unnecessary reconnect. Capture the owner and authorization generation before revocation and use that owner for the post-await removal.
Useful? React with 👍 / 👎.
| id: id, | ||
| from: headers["from"] ?? "", | ||
| subject: headers["subject"] ?? "(no subject)", | ||
| snippet: body["snippet"] as? String ?? "", |
There was a problem hiding this comment.
Keep body snippets out of metadata-only Gmail reads
For every OAuth message that includes snippet, this copies a short excerpt of the message body into GmailEmail; saveAsMemories then uploads it as artifact content and synthesizeFromEmails sends it to the LLM. That violates this reader's stated contract of importing subject/sender metadata and “never bodies,” so the OAuth path transmits more sensitive email content than its disclosure promises. Omit the snippet from this metadata-only path or explicitly change the connector's data-use contract and user disclosure.
Useful? React with 👍 / 👎.
|
|
||
| let accounts = GmailAccountProbe.parseAccounts(json) | ||
|
|
||
| XCTAssertEqual(accounts.count, 3) |
There was a problem hiding this comment.
Align account-parser tests with the email requirement
parseAccounts now discards every row whose email is not a nonempty String, so the NSNull Arc row in this fixture is removed and this assertion deterministically receives 2 rather than 3; the second new test similarly expects 1 but receives 0. The newly added component tests therefore cannot pass as committed. Either preserve unknown-email account options in production or update both fixtures and expectations to match the intentional parser contract.
AGENTS.md reference: AGENTS.md:L28-L30
Useful? React with 👍 / 👎.
| guard let clientId = GoogleOAuth.clientId else { | ||
| throw GoogleOAuthError.reconnectRequired | ||
| } | ||
| do { | ||
| let refreshed = try await refreshGate.run( | ||
| key: stored.account ?? "legacy", | ||
| operation: { [tokenClient] in | ||
| try await tokenClient.refresh(stored, clientId: clientId) |
There was a problem hiding this comment.
Bind each refresh token to its issuing OAuth client
When a user edits the OAuth client ID or secret while grants already exist, those grants retain no record of the credentials that issued their refresh tokens, and this refresh path unconditionally uses the newly global client ID and secret. Once an older grant reaches the refresh window, Google rejects its token/client pairing and the manager marks that otherwise valid account as requiring reconnect; changing credentials for one setup can therefore break every previously connected account at expiry. Persist the issuer credentials per grant or prevent credential changes until incompatible grants are disconnected.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
Thanks for moving the connector files under Sources/Integrations — I rechecked the current head b5b29594e6, and the desktop source-layout guard and desktop test-quality guard are now green.
One blocker remains before this is ready for maintainer/security sign-off:
desktop/macos/Desktop/Tests/GmailAccountSelectionTests.swiftdoes not match the current parser behavior.GmailAccountProbe.parseAccountsnow rejects rows whoseemailis missing/empty, buttestParseAccountsMapsPythonOutputstill includes anNSNullemail row and expectsaccounts.count == 3with Arc at index 0. With the current implementation that row is filtered out, so the test expectation should be updated (or the parser changed intentionally). As written, the added test suite would fail when run.
I’m keeping this as changes-requested for the test mismatch. Separately, because this PR changes OAuth consent, token/keychain storage, and Gmail/Calendar user-data access, it should still get human maintainer/security review before merge after the test issue is fixed. The feature remains cohesive around one desktop Gmail/Calendar connector; I’m not asking for a split.
Local/static checks I ran on this head:
python3 scripts/check-sources-root-layout.py— passespython3 scripts/check_desktop_test_quality.py— passes- Static source review of the OAuth/account-selection tests and parser — found the mismatch above
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
b5b2959 to
f8f2973
Compare
left a comment
There was a problem hiding this comment.
💡 Codex Review
When the task-intelligence contract suite validates backend/config/task_intelligence_sources_v1.json, it requires every owner_paths entry to exist, but that manifest still names Desktop/Sources/GmailReaderService.swift and CalendarReaderService.swift after this commit moves both files under Sources/Integrations/. The validator therefore fails with a missing owner path before it can validate the writer registry; update both manifest entries as part of the move.
AGENTS.md reference: AGENTS.md:L88-L88
ℹ️ 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".
| expect: | ||
| result.action: "gmail_read_probe" | ||
| result.source: "oauth" |
There was a problem hiding this comment.
Require successful OAuth probe outcomes
When either OAuth reader returns a caught authentication, network, or schema error, the bridge still returns result.action and result.source: "oauth", so S2 and S3 pass without proving that Gmail or Calendar was readable. Fresh evidence in this replacement OAuth-specific flow is that both expectations still omit result.status: "connected" (and the readable classification), allowing the claimed reader coverage to succeed on an error response.
AGENTS.md reference: AGENTS.md:L28-L28
Useful? React with 👍 / 👎.
| let browserConfigs = GmailSelectionStore.filter( | ||
| BrowserGoogleSession.configsForPython(logPrefix: "GmailReaderService"), | ||
| selectedCookiePath: selectedCookiePath) |
There was a problem hiding this comment.
Forward user intent into the cookie Gmail lookup
When an existing user has no OAuth grant and starts an explicit browser-cookie import, readRecentEmails(userInitiated: true) clears the consent cache but this lookup still calls configsForPython with its default userInitiated: false. BrowserKeychainCache.password rejects every such lookup before reading even an already-authorized Safe Storage item, so the configuration list is always empty and Gmail reports noBrowserFound; GmailAccountProbe makes the same defaulted call, leaving the new picker empty as well. Carry both userInitiated and the selected cookie path through these helpers.
AGENTS.md reference: AGENTS.md:L121-L121
Useful? React with 👍 / 👎.
| guard let code = Self.code(from: redirect, expectedState: state) else { | ||
| throw GoogleOAuthError.stateMismatch | ||
| } |
There was a problem hiding this comment.
Preserve consent-denied callback errors
When the user cancels or denies Google's consent screen, the callback contains error=access_denied with the correct state, but code(from:) collapses that response to nil and this guard always throws stateMismatch. The UI consequently tells the user that the redirect did not match the sign-in attempt rather than that consent was declined; parse and validate the state separately, then surface the provider error or the existing no-code case.
Useful? React with 👍 / 👎.
| components.scheme = "http" | ||
| components.host = "127.0.0.1" | ||
| components.path = String(path) | ||
| components.query = query |
There was a problem hiding this comment.
Preserve percent encoding in the loopback callback
When Google percent-encodes a callback value, such as an authorization code containing a reserved slash or padding character, assigning the already encoded request query to URLComponents.query treats each % as a literal and encodes it again as %25. code(from:) then returns text such as 4%2F... instead of the original 4/..., and the form encoder escapes it a second time before the token exchange, causing Google to reject an otherwise valid authorization code. Assign this request-target substring as percentEncodedQuery or parse the target without reconstructing its encoding.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
Thanks for the continued work here — I re-reviewed the current head f8f2973fa11e5d4685dfc7c508773b76d9431561.
This is still not ready for maintainer/security sign-off because the current head has repository/test contract failures that match the failing desktop gates:
desktop/macos/Desktop/Tests/GmailAccountSelectionTests.swiftstill expectsGmailAccountProbe.parseAccountsto keep anNSNull/missing email row, but the implementation now filters out rows without a non-empty email. Please update the test expectation (or change the parser intentionally) so the test reflects the intended behavior.- The moved reader paths also need to be updated in
backend/config/task_intelligence_sources_v1.json: it still listsdesktop/macos/Desktop/Sources/GmailReaderService.swiftanddesktop/macos/Desktop/Sources/CalendarReaderService.swift, but this PR moved them underdesktop/macos/Desktop/Sources/Integrations/. That leaves the task-intelligence source contract pointing at missing owner paths.
The OAuth direction still looks promising, and the earlier source-layout blocker is addressed by moving the connector files under Sources/Integrations. I’m keeping the existing maintainer/security review requirement in place because this changes OAuth consent, keychain token storage, and Gmail/Calendar user-data access; after the contract failures are fixed, a human maintainer/security pass should still sign off on the product/security 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.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3893cb65e2
ℹ️ 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".
| } | ||
|
|
||
| calendarTask = Task { | ||
| await accountSelectionTask.value |
There was a problem hiding this comment.
Abort Calendar when account selection fails
When a user-initiated onboarding import has no OAuth grant or prior browser choice and GmailAccountProbe.availableAccounts() throws, the shared selection task sets gmailAccountSelectionFailed, but only the Gmail task checks that flag; the Calendar task proceeds after this await with a nil cookie selection. CalendarReaderService then widens to every browser config and may save the first readable profile's events into memories despite account disambiguation having failed. Gate Calendar on the same failure before reading, rather than silently taking the correctness-degrading automatic path.
AGENTS.md reference: AGENTS.md:L91-L91
Useful? React with 👍 / 👎.
| return activeCount == 1 | ||
| ? "1 account verified — Gmail and Calendar read through OAuth." | ||
| : "\(activeCount) accounts verified — Gmail and Calendar read through OAuth." |
There was a problem hiding this comment.
Verify every account included in the verified count
With multiple stored grants, a healthy primary account makes both probes succeed even if a secondary grant has been revoked, because the reader services probe activeConnections(), which is only the primary singleton; this branch nevertheless labels every non-needsReconnect grant as verified. Fresh evidence after the live-probe change is this mismatch between the singleton probe target and activeCount, so Settings can still report “2 accounts verified” when only one was tested. Probe each counted account or describe only the verified primary.
Useful? React with 👍 / 👎.
commented
Aug 10, 2026
|
Re-merged |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fe4b9347fc
ℹ️ 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".
| let emails = try await GoogleOAuthGmailReader.readRecentEmails( | ||
| token: token, maxResults: maxResults, query: query) |
There was a problem hiding this comment.
Fence imported rows to the initiating Omi owner
When owner A starts an OAuth Gmail import and switches Omi accounts after this provider read but before saveAsMemories or synthesizeFromEmails, the returned rows carry no RuntimeOwnerAuthorizationSnapshot; those mutation paths therefore authenticate as the now-current owner B and can persist A's mail in B's memories. Distinct from the browser-picker generation race, this OAuth path needs to capture owner authorization at import entry and thread it through every downstream save and synthesis boundary; Calendar has the same gap.
AGENTS.md reference: AGENTS.md:L43-L45
Useful? React with 👍 / 👎.
| // invalid failed connect() and verifyConnection() for any account whose | ||
| // inbox had no mail in the probe window, even though auth and scopes | ||
| // were fine. | ||
| let messages = body["messages"] as? [[String: Any]] ?? [] |
There was a problem hiding this comment.
Reject present malformed list collections
When a successful response contains messages with a non-array value, this cast treats it exactly like the valid omitted-field case, so connection probes can report a healthy empty inbox; Calendar does the same for malformed items. Fresh evidence after the prior malformed-response review is that top-level JSON is now rejected strictly, but these present malformed collection fields still collapse to []; distinguish an absent field from one with the wrong type.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| Task { | ||
| let gmail = await GmailReaderService.shared.verifyConnection() | ||
| let calendar = await CalendarReaderService.shared.verifyConnection() |
There was a problem hiding this comment.
Discard verification results after the primary account changes
When the primary account changes while this task is suspended, the Gmail probe can run against account A and the subsequent Calendar probe against account B; because no account or generation is captured and older tasks are not cancelled, that mixed or stale task can later set googleOAuthIsVerified = true for the current account list. Settings can therefore claim the selected account is verified even though neither account passed both probes, so bind both probes and their completion to one primary-account generation.
AGENTS.md reference: AGENTS.md:L87-L87
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| private func respond(connection: NWConnection, buffer: Data) { | ||
| defer { connection.cancel() } |
There was a problem hiding this comment.
Close the callback connection after the response is sent
For every OAuth callback, this defer cancels the NWConnection immediately after the asynchronous send is enqueued, so the pending HTTP response can be aborted and the browser can show a connection-reset page instead of “You can close this window.” The other in-repo NWConnection HTTP servers close from the .contentProcessed completion; do the same here so the consent flow visibly completes.
Useful? React with 👍 / 👎.
Resolved on current head: GoogleOAuthReader treats missing/empty Gmail messages as an empty successful read and GoogleOAuthTests covers the quiet-mailbox case.
commented
Aug 11, 2026
|
Thanks for the continued fixes here. I re-reviewed the current head The prior blocking empty-mail issue looks resolved on this head: Other file-specific observations from this pass:
I do not see a new automation-level code blocker in the OAuth changes after the empty-result fix. I’m still leaving this for human maintainer/security review rather than approving automatically because this is a nontrivial Gmail/Calendar OAuth + token/keychain + data-access change, and the current required desktop gates are not green. The CI failures I checked are in the desktop launcher/fault harness and a Swift strict-concurrency compile error in — Automated review by glm-5.2 for maintainer triage. by AI on behalf of David — security-sensitive OAuth/data-access flow needs maintainer sign-off before merge. |
…nector # Conflicts: # .github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a0351d143
ℹ️ 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 deleteAll(for ownerID: String? = UserDefaults.standard.string(forKey: .authUserId)) { | ||
| DesktopKeychainStore.delete(service: Self.service, account: Self.account(for: ownerID)) | ||
| } |
There was a problem hiding this comment.
Purge OAuth grants after accepted account deletion
When AuthService.signOut(acceptedAccountDeletion: true) completes, it clears the user's local account data but never calls this new UID-scoped deletion method (a repo-wide search finds no caller). Consequently, Gmail/Calendar access and refresh tokens remain in the login Keychain—and the Google grant remains remotely valid—after the user explicitly deletes their Omi account. Wire grant revocation and owner-scoped Keychain deletion into the accepted-deletion transaction while preserving grants on an ordinary sign-out.
Useful? React with 👍 / 👎.
| var failure: Error? | ||
| do { | ||
| try await tokenClient.revoke(stored) | ||
| } catch { | ||
| failure = error | ||
| } | ||
| guard remove(account: stored.account, expected: stored) else { |
There was a problem hiding this comment.
Retain grants when remote revocation fails
When Google revocation fails because the user is offline or Google returns a transient error, this still deletes the only stored refresh token and then throws. The Settings caller reloads the account list in defer, so the row disappears even though the remote grant remains valid, leaving the user unable to retry revocation from Omi. Keep the grant until revocation succeeds or persist a durable revocation retry before removing the credential.
Useful? React with 👍 / 👎.
# Conflicts: # .github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-onboarding.json # .github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json # desktop/macos/Desktop/Sources/DefaultsKey.swift
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4b3a1a63a5
ℹ️ 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".
| if account.needsReconnect { | ||
| // "Reconnect" must re-run the consent flow, not revoke | ||
| // and delete the stored grant. | ||
| await connectGoogleOAuth() |
There was a problem hiding this comment.
Reconnect the account represented by the row
When multiple Google accounts are signed in, clicking Reconnect for account A launches the same unscoped consent flow as Add account, without passing A as a login hint or validating that the returned email matches the row. Google can therefore authorize the browser's current account B, replacing/adding B's grant while A remains in needsReconnect, so the row action does not reliably repair the selected connection. Pass the target account through the flow and reject a callback that resolves to a different account.
Useful? React with 👍 / 👎.
| if oauth.hasGrants() { | ||
| return try await readRecentEmailsViaOAuth( | ||
| manager: oauth, maxResults: maxResults, query: query) |
There was a problem hiding this comment.
Record Google connector provider transitions
After a user connects or disconnects OAuth, this branch switches all Gmail reads between the cookie and OAuth providers, and Calendar has the same uninstrumented transition. Neither the manager nor the reader records the change through DesktopDiagnosticsManager.recordFallback, so production diagnostics cannot measure or correlate this provider-mode change despite the repository's explicit telemetry contract; emit the shared event at the authoritative connect/disconnect transition rather than silently changing modes.
AGENTS.md reference: AGENTS.md:L91-L91
Useful? React with 👍 / 👎.
| accessToken: accessToken, | ||
| expiresAt: Date().addingTimeInterval(expiresIn), | ||
| grantedScopes: scopes, | ||
| refreshToken: (refreshToken?.isEmpty ?? true) ? nil : refreshToken, |
There was a problem hiding this comment.
Reject connections without a refresh token
If Google's authorization-code response omits refresh_token, this still constructs a connection, passes both probes using the short-lived access token, and persists it as connected. As soon as that token reaches the refresh window, refresh deterministically throws invalidGrant because the stored token is nil, forcing reconnect and potentially repeating the same cycle. Require an offline refresh token before persisting and reporting a successful connection.
Useful? React with 👍 / 👎.
| guard let url else { | ||
| settle(with: .failure(GoogleOAuthError.redirectMissing)) | ||
| return |
There was a problem hiding this comment.
Ignore malformed non-callback loopback requests
If a browser speculative connection, local scanner, or other client closes the loopback connection before sending a complete GET request, redirectURL returns nil and this branch settles the entire OAuth waiter with redirectMissing. That aborts an otherwise valid sign-in before the real browser callback can arrive, even though the surrounding comment promises that non-callback traffic is ignored. Close and ignore unparseable requests, and only settle the waiter for a parsed /oauth/callback request.
Useful? React with 👍 / 👎.
The merge with main brought in app/ Dart sources that main has since reformatted/moved; this desktop-only OAuth PR does not change the app, so restore origin/main's versions to keep the Formatting gate green.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ab483c6a01
ℹ️ 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 let code = Self.code(from: redirect, expectedState: state) else { | ||
| throw GoogleOAuthError.stateMismatch | ||
| } | ||
| let connection = try await tokenClient.exchangeCode( |
There was a problem hiding this comment.
Revoke the grant when post-exchange validation fails
Once the authorization-code exchange succeeds, any subsequent account/scope check, Gmail or Calendar probe, owner fence, or Keychain write failure exits without revoking the newly issued refresh token. In those scenarios Omi reports that connection failed and stores no account row, while the Google authorization remains active and cannot be removed through Omi; perform a best-effort revocation whenever post-exchange validation or persistence fails.
Useful? React with 👍 / 👎.
| let oauth = GoogleOAuthConnectionManager.shared | ||
| if oauth.hasGrants() { | ||
| return try await readRecentEmailsViaOAuth( | ||
| manager: oauth, maxResults: maxResults, query: query) |
There was a problem hiding this comment.
Update the connector ground-truth docs for OAuth
This branch changes local Gmail reads from cookie-only to OAuth whenever a grant exists, but a repo-wide search still finds desktop/windows/docs/mac-parity-audit/track3-ground-truth/gt-connectors.md:6-7,23 pointing at the removed source paths and explicitly saying the Mac does not use the Google API, while desktop/macos/agent-cloud/experiments/RESEARCH-FINDINGS.md:173-182 still defines the local auth, storage, and failure boundary as browser-cookie-only. Because these documents are used as ground truth for Windows parity and agent architecture, update them to describe the new dual-provider boundary and relocated sources.
AGENTS.md reference: AGENTS.md:L33-L33
Useful? React with 👍 / 👎.
| guard RuntimeOwnerIdentity.isAuthorizationCurrent(ownerSnapshot) else { | ||
| _ = remove(account: connection.account, expected: connection, ownerID: ownerSnapshot.ownerID) | ||
| throw GoogleOAuthError.ownerChanged |
There was a problem hiding this comment.
Restore the prior grant when a fenced reconnect rolls back
If an account already has a valid stored grant, upsert removes it before inserting the replacement. When the Omi authorization generation changes in the narrow interval before this final fence, the rollback removes the replacement but cannot restore the prior grant, so switching back to the initiating owner unexpectedly loses a previously working connection. Preserve the old same-account snapshot and restore it during rollback, or stage the replacement until the final owner check can commit atomically.
Useful? React with 👍 / 👎.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d568f0f55
ℹ️ 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 disconnect(account: String? = nil) async throws { | ||
| guard let stored = rawConnection(account: account) else { return } |
There was a problem hiding this comment.
Disconnect the nil-account row instead of the first grant
When a legacy connection has account == nil and a newer named grant is stored ahead of it, Settings passes nil for the legacy row, but rawConnection(account: nil) interprets that as all.first. Clicking Disconnect on “Connected account” therefore revokes and removes the named account while leaving the intended legacy grant connected. Pass a stable row identity or connection snapshot rather than using an optional account as both identity and default selection.
Useful? React with 👍 / 👎.
| } catch { | ||
| failure = error | ||
| } | ||
| guard remove(account: stored.account, expected: stored) else { |
There was a problem hiding this comment.
Fence concurrent refreshes before completing disconnect
If an automatic token refresh writes its updated snapshot after revocation but before this removal, remove(... expected: stored) treats the refreshed snapshot as a replacement and silently leaves it in the store. Settings can then report the account as verified using the refreshed access token even though the user just disconnected it, until another disconnect or token expiry. Serialize disconnect against refresh, or mark the account as disconnecting and remove the resulting refresh snapshot before reporting success.
Useful? React with 👍 / 👎.
| if !googleOAuthIsVerified { | ||
| return "\(storedCount) account\(storedCount == 1 ? "" : "s") stored — verifying Gmail and Calendar." |
There was a problem hiding this comment.
Surface failed OAuth verification instead of “verifying”
When either Gmail or Calendar verification returns an error or needs-sign-in result, the task sets googleOAuthIsVerifying back to false while leaving googleOAuthIsVerified false, but this summary ignores the former state and continues displaying “verifying Gmail and Calendar” indefinitely. Use googleOAuthIsVerifying for the transient message and show the failed probe outcome once verification has completed.
Useful? React with 👍 / 👎.
| ) | ||
| // swiftlint:disable:next force_unwrapping — built from fixed components cannot fail | ||
| let query = URLComponents(url: url, resolvingAgainstBaseURL: false)!.queryItems ?? [] | ||
| let params = Dictionary(uniqueKeysWithValues: query.map { ($0.name, $0.value ?? "") }) |
There was a problem hiding this comment.
Avoid trapping on duplicate OAuth query fields
This test builds a trapping dictionary from URLComponents.queryItems, whose key uniqueness is not enforced by the Swift type system; if the authorization URL ever contains a repeated OAuth parameter, the test process terminates instead of producing an actionable assertion failure. Use the repository’s non-trapping merge policy, or add the permitted local static-uniqueness annotation only if the construction contract truly guarantees uniqueness.
AGENTS.md reference: desktop/macos/AGENTS.md:L170-L179
Useful? React with 👍 / 👎.
commented
Sep 26, 2026
|
Parked until org approval for GCP comes through — the OAuth client used by this connector can't be enabled in our Google Cloud org before that, so we can't validate the consent flow against a real client regardless of review state. The code itself is in good shape (empty-mail probe fix verified on the last head), and #10963 — the ordering dependency — merged in August, so nothing is blocked on the branch itself. Once GCP approval lands we'll revisit: expect a refresh of the loopback-redirect bits against the then-current Google desktop-client requirements, then a final review pass before merge. |
commented
Nov 2, 2026
|
Since my last review: addressed - the "empty Gmail/Calendar list treated as an error" blocker is fixed on this head (GoogleOAuthReader.swift:60 maps a 200 without a Verdict: the OAuth connector itself is well built - I found no security defect in it; the merge-readiness item is red desktop CI that does not appear to come from your diff. What I verified on this head:
Security: readonly Gmail/Calendar scopes, user-supplied OAuth client (no bundled secret), keychain-only token storage - solid. One accuracy nit: the PR text says "metadata only - subject/sender, never bodies", but UX: Settings -> Advanced -> Email & Calendar becomes reachable; onboarding skips the cookie picker when an OAuth grant exists; if the keychain is unavailable, Gmail/Calendar reads surface an error instead of silently using another account's cookies. Cost/perf: direct Google API calls with a 60-second refresh safety window and single-flight refresh - no per-read token exchange; metadata-level requests only. Blast radius: anyone with an OAuth grant has all Gmail/Calendar reads switch from cookies to OAuth automatically; a regression here affects imports, onboarding, and automation reads together. USER IMPACT: users can connect Google accounts with a real consent screen (no signed-in browser needed), pick which account reads use, and Gmail/Calendar imports stop depending on browser cookies. Action items: (1) re-merge current main and re-run the desktop gates - the red suites look like stale-merge fallout, not your code; (2) fix the "never bodies" claim and the e2e "every active grant" wording; (3) after CI is green this needs a maintainer's sign-off on the consent/keychain design and the #10963 ordering before merge. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
commented
Nov 2, 2026
|
Since my last review: addressed — the empty-inbox/empty-calendar blocker is fixed (GoogleOAuthReader.swift now treats a missing The OAuth implementation itself reads clean — I found no security issue in a full pass over GoogleOAuthFlow.swift, GoogleOAuthConnection.swift, and GoogleOAuthReader.swift. What needs work is CI and a few loose ends:
Security notes for the record: PKCE S256 + state + loopback listener that waits for a bound port before building the redirect URI, tokens only in the keychain (UID-scoped, client secret migrated out of UserDefaults), owner pinning around the exchange, functional probe of both APIs before persisting, single-flight refresh with rotation, revoke treating HTTP 400 as success, read-only scopes verified post-consent — all good. One product-level point for maintainers: BYO Google Cloud client ID with gmail.readonly (a restricted scope) means each user's unverified project with Google's test-user caps — workable for personal use, but the distribution model deserves a maintainer call. Cost: two extra Google API calls per connect (the pre-persist probe); reads add no spend beyond the existing path. Blast radius: existing cookie users are untouched unless they connect a grant; once connected, reads fail closed to a reconnect error rather than silently falling back to cookies — predictable and correct. USER IMPACT: once a Google account is connected, Gmail and Calendar imports read through Google's API for that account (no browser sign-in needed); users who never connect keep today's cookie behavior unchanged. What I'd still want as a reviewer: a green desktop CI run that actually executes GoogleOAuthTests, the two caption fixes, the e2e description aligned, and maintainer sign-off on the BYO-client-ID OAuth distribution model (restricted scope). Leaving the security/product decisions for human maintainer review — the OAuth flow itself looks ready for that conversation. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |

What
Add a Google OAuth connector to the macOS desktop app, replacing the browser-cookie path for Gmail and Calendar when a user connects an account. One grant per Google account; the settings UI lists them with per-account disconnect, and the existing Gmail/Calendar readers automatically prefer OAuth grants over cookies.
Depends on #10963 (both touch the settings integrations section; #10963 should merge first).
Why
The cookie connector silently reads whichever browser session exists first (the "junk inbox" problem) and requires a signed-in Chromium browser. OAuth gives a real consent flow, works without a browser, and supports multiple accounts cleanly.
How
127.0.0.1:0),access_type=offline, optional client secret for Google's newer Desktop-app client type.DesktopKeychainStore, keyed per account (email from the OpenID userinfo endpoint). Reconnecting the same account replaces its grant.GmailReaderService.readRecentEmailsandCalendarReaderService.readEventsroute through OAuth when a grant exists and fall back to cookies otherwise, so onboarding, imports, and automation keep working unchanged.Invariants: INV-INT-1 (functional probe at connect; no agent/heuristic automation; tokens in keychain only).
Product invariants affected
Review round: empty Gmail/Calendar list + merge with main
Addresses the one open blocker from the last review.
Empty list is a successful read, not an error.
GoogleOAuthGmailReader.readRecentEmailstreated a 200 response without amessagesarray as.invalidResponse. Gmail'susers.messages.listomitsmessagesentirely when the query matches nothing, so any account with no mail in the probe window failedconnect()andverifyConnection()— both probe withnewer_than:1d— despite working auth, scopes, and APIs.GoogleOAuthCalendarReader.readEventshad the identical defect onitems:events.listomitsitemsfor a window with no events, andconnect()probes a one-day calendar window. Both list paths now read a missing or empty collection as an empty result. Non-JSON bodies still fail as.invalidResponse, and 401/403 still surface as reconnect-required, so this does not mask auth failures.External source for the expected values: Google's
users.messages.listandevents.listreference both document these collection fields as omitted rather than empty when there are no results.Merged
origin/main. Main independently landed the Gmail account-selection feature this branch carried, plus auserInitiatedconsent parameter threaded through the Gmail and Calendar readers. The merge keeps main's newer account-selection code (hasMadeChoicepicker state, probe-error surfacing, result reset on selection change, missing-profile fallback telemetry) and re-applies the OAuth connector on top. Onboarding keeps this branch's stale-selection re-prompt and cancellation handling, which subsume main's post-probe recheck.Verification
make preflight— 20/20 checks pass (manifest contract, file-line ratchets, diff hygiene, architecture guardrails, product invariants, failure-class protocol, desktop changelog, e2e flow coverage, brand-ui, swift-format lint, swiftlint + baseline, test quality)testGmailListRejectsMalformedSuccessfulResponsereplaced bytestGmailListTreatsMissingMessagesAsEmptyResult,testGmailListTreatsEmptyMessagesArrayAsEmptyResult,testCalendarListTreatsMissingItemsAsEmptyResult, andtestGmailEmptyResultDoesNotMaskAuthFailure(the last one guards that the empty-result path still surfaces 401 as reconnect-required). The replaced test asserted exactly the behavior flagged as the bug.Note
High Risk
Touches OAuth/token handling in the keychain and changes which Google account data is read (OAuth vs cookies); keychain read failures intentionally keep the OAuth path fail-closed instead of silently falling back to cookies.
Overview
Adds a Google OAuth connector on macOS so Gmail and Calendar can be read via the Google APIs when grants exist, with cookie-based reads as fallback when they do not.
The new flow uses PKCE + loopback redirect, stores per-account grants in the keychain (client secret optional), probes Gmail/Calendar before persisting, refreshes tokens with owner checks, and supports primary account selection and reconnect marking. Gmail and Calendar readers route through OAuth when
hasGrants()is true; cookie paths honorGmailSelectionStoreso Calendar matches the chosen browser profile.Settings → Advanced → Email & Calendar surfaces OAuth account management and a browser Gmail account picker; onboarding blocks multi-profile Gmail import until the user picks (or cancels to automatic). Automation probes report
oauthvscookies, plusgoogle_oauth_status. Unit tests cover OAuth, account filtering, and selection parsing.Reviewed by Cursor Bugbot for commit 277502c. Bugbot is set up for automated code reviews on this repo. Configure here.
Failure-Class: none
Line-Count-Exception: desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift | 4575 -> 4597 | OAuth connector probes surfaced as automation actions; file was already 4500+ lines, growth is the new google_oauth_status probe action
Line-Count-Exception: desktop/macos/Desktop/Sources/Onboarding/OnboardingPagedIntroCoordinator.swift | 1930 -> 1952 | OAuth account-gating in onboarding import flow; small delta on an already-oversized onboarding file