Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(desktop): return GitHub consent to the app through a deep link (#9350)
Eric Hayes9e49b0bb75b1
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 511bbbf1f9..7d96f7211d 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -476,8 +476,12 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription toon `meeting.join`; keep provider messages, device labels/IDs, and call-linktokens out of telemetry. See [call diagnostics](../../docs/agent-guide/calls.md#browser-call-diagnostics).- Diagnose the GraphQL mutation queue with `graphql.mutation_queue.*` spans and logs keyed by `mutation_queue.item_id`; route queue telemetry through `mutation-queue-telemetry.ts`, which dedupes per item and failure class and turns repeats into the periodic summary. Never add per-attempt `console.*` lines or record variables, draft content, or emails.-- Keep desktop Gmail and Outlook inbox consent in the system browser with a- `macro:///inbox-link-callback` return; webview origins are not desktop callbacks.+- Keep desktop OAuth consent in the system browser with a `macro://` return:+ `macro:///inbox-link-callback` for Gmail and Outlook inboxes,+ `macro:///github-link-callback` for GitHub (consumed by the navigation+ bridge without changing the route). Webview origins are not desktop+ callbacks. Settings → Integrations refetches connection status on window+ `focus`, because returning from the browser does not change page visibility.- Keep send reservations, leases, and cancellation in the email journal; the general GraphQL queue handles draft autosaves only.- Always persist composer sends in account-scoped IndexedDB and dispatch through the fetch-only email client, without a feature flag; cache health and unrelated mutation queues must not gate delivery. See `docs/architecture/email.md` for state and rollout invariants.- Retry cache bootstrap on reconnect/foreground or draft Retry only when storage was proven untouched; retain the same scope and block draft sync until the replacement queue is readable.diff --git a/apps/web/src/features/settings/GitHub.tsx b/apps/web/src/features/settings/GitHub.tsxindex 088089f0e4..7ac5673b7d 100644--- a/apps/web/src/features/settings/GitHub.tsx+++ b/apps/web/src/features/settings/GitHub.tsx@@ -10,6 +10,7 @@ import {useInitGithubLinkMutation,useReauthenticateGithubMutation,} from '@queries/auth';+import { makeEventListener } from '@solid-primitives/event-listener';import { Match, Show, Switch } from 'solid-js';import {ConnectAction,@@ -25,6 +26,12 @@ export function useGithubConnection() {const deleteGithubLink = useDeleteGithubLinkMutation();const reauthenticateGithub = useReauthenticateGithubMutation();+ // GitHub consent runs in another window or the system browser; returning to+ // the app focuses the window without changing page visibility.+ makeEventListener(window, 'focus', () =>+ fireAndForget(githubLink.refetch(), 'github-settings')+ );+const status = () =>githubLink.isSuccess ? githubLink.data.status : undefined;const username = () =>diff --git a/apps/web/src/features/settings/connections/integrations-view.tsx b/apps/web/src/features/settings/connections/integrations-view.tsxindex 5135ec8f96..8b974f4e3f 100644--- a/apps/web/src/features/settings/connections/integrations-view.tsx+++ b/apps/web/src/features/settings/connections/integrations-view.tsx@@ -14,6 +14,7 @@ import {usePipedreamConnectedSlugs,usePipedreamOverlaysQuery,} from '@queries/pipedream-connectors';+import { makeEventListener } from '@solid-primitives/event-listener';import { Button } from '@ui';import {type Accessor,@@ -73,6 +74,9 @@ export function IntegrationsView(props: IntegrationsViewProps) {function ConnectionsContent(props: IntegrationsViewProps) {const { model, ready, error, partialError, retry } = useConnectionsModel();+ // A consent finished in the system browser leaves the page visible, so the+ // queries' visibility-based focus refetch never fires on return.+ makeEventListener(window, 'focus', retry);const view = useConnectionsView();const [importSlackChannels, setImportSlackChannels] = createSignal(false);// External entry points request a connector or the complete channel import flow.diff --git a/apps/web/src/lib/core/auth/authorize-github.test.ts b/apps/web/src/lib/core/auth/authorize-github.test.tsnew file mode 100644index 0000000000..58940d0f00--- /dev/null+++ b/apps/web/src/lib/core/auth/authorize-github.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ desktop: vi.fn(),+ mobile: vi.fn(),+ invoke: vi.fn(),+ invalidate: vi.fn(),+ failure: vi.fn(),+}));+vi.mock('@core/util/platform', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@core/util/platform')>()),+ isDesktopPlatform: mocks.desktop,+}));+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({+ isNativeMobilePlatform: mocks.mobile,+}));+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));+vi.mock('@queries/auth', () => ({+ invalidateGithubLinkStatus: mocks.invalidate,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));++import {+ authorizeGithub,+ GITHUB_LINK_CALLBACK_PATH,+ handleGithubLinkCallback,+} from './authorize-github';++const AUTHORIZATION_URL = 'https://github.com/login/oauth/authorize?state=s';++beforeEach(() => {+ vi.resetAllMocks();+ mocks.desktop.mockReturnValue(true);+ mocks.mobile.mockReturnValue(false);+ mocks.invalidate.mockResolvedValue(undefined);+});++describe('desktop GitHub authorization', () => {+ it('returns through the macro deep link and opens consent in the system browser', async () => {+ const getAuthorizationUrl = vi.fn().mockResolvedValue(AUTHORIZATION_URL);+ mocks.invoke.mockResolvedValue(undefined);++ await expect(+ authorizeGithub(getAuthorizationUrl, 'Failed to connect GitHub')+ ).resolves.toBe(false);++ expect(getAuthorizationUrl).toHaveBeenCalledWith(+ 'macro:///github-link-callback'+ );+ expect(mocks.invoke).toHaveBeenCalledWith('plugin:opener|open_url', {+ url: AUTHORIZATION_URL,+ });+ expect(mocks.failure).not.toHaveBeenCalled();+ });++ it('reports a browser that fails to open', async () => {+ mocks.invoke.mockRejectedValue(new Error('no opener'));++ await authorizeGithub(+ async () => AUTHORIZATION_URL,+ 'Failed to connect GitHub'+ );++ expect(mocks.failure).toHaveBeenCalledWith('Failed to connect GitHub');+ });++ it('consumes the callback and refreshes the link status', () => {+ expect(handleGithubLinkCallback('/settings/connections')).toBe(false);+ expect(mocks.invalidate).not.toHaveBeenCalled();++ expect(handleGithubLinkCallback(GITHUB_LINK_CALLBACK_PATH)).toBe(true);+ expect(mocks.invalidate).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/lib/core/auth/authorize-github.ts b/apps/web/src/lib/core/auth/authorize-github.tsindex 890341c159..2cbab81567 100644--- a/apps/web/src/lib/core/auth/authorize-github.ts+++ b/apps/web/src/lib/core/auth/authorize-github.ts@@ -1,19 +1,46 @@-import { createNativeAuthSession } from '@core/auth/native-auth';+import {+ createNativeAuthSession,+ openDesktopAuthSession,+} from '@core/auth/native-auth';import { toast } from '@core/component/Toast/Toast';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { fireAndForget } from '@core/util/fireAndForget';+import { isDesktopPlatform } from '@core/util/platform';+import { Telemetry } from '@macro-inc/observability';import { invalidateGithubLinkStatus } from '@queries/auth';+/**+ * Where GitHub consent started from the desktop app returns. The system+ * browser cannot load the webview's own origin, so the auth service redirects+ * to this deep link once the account is linked, and the navigation bridge+ * consumes it without changing the active route.+ */+export const GITHUB_LINK_CALLBACK_PATH = '/github-link-callback';+const DESKTOP_GITHUB_LINK_CALLBACK_URL = `macro://${GITHUB_LINK_CALLBACK_PATH}`;+/*** Run a GitHub OAuth grant. On the web the browser navigates to GitHub and the- * callback returns to this page, so nothing after the call runs. On native- * mobile the grant completes in the system browser and the link status query- * is refreshed; resolves to whether that grant succeeded. Rejects when the- * authorization URL cannot be obtained.+ * callback returns to this page, so nothing after the call runs. The desktop+ * app opens consent in the system browser and learns the outcome from the+ * `macro://` callback, so it resolves to false once the browser opens. On+ * native mobile the grant completes in the system browser and the link status+ * query is refreshed; resolves to whether that grant succeeded. Rejects when+ * the authorization URL cannot be obtained.*/export async function authorizeGithub(getAuthorizationUrl: (callbackUrl: string) => Promise<string>,failureMessage: string): Promise<boolean> {+ if (isDesktopPlatform()) {+ const url = await getAuthorizationUrl(DESKTOP_GITHUB_LINK_CALLBACK_URL);+ await Telemetry.span('github.link.open_browser', async (span) => {+ const opened = await openDesktopAuthSession(url);+ if (opened.success) return;+ span.error('Unable to open GitHub connection browser');+ toast.failure(failureMessage);+ });+ return false;+ }const session = isNativeMobilePlatform()? createNativeAuthSession('github-link-callback'): undefined;@@ -33,3 +60,13 @@ export async function authorizeGithub(if (result.error !== 'User canceled login') toast.failure(failureMessage);return false;}++/**+ * Consume the desktop GitHub consent return. The auth service redirects here+ * only after linking the account, so refresh the link status for every reader.+ */+export function handleGithubLinkCallback(path: string): boolean {+ if (path !== GITHUB_LINK_CALLBACK_PATH) return false;+ fireAndForget(invalidateGithubLinkStatus(), 'github-link');+ return true;+}diff --git a/apps/web/src/lib/tauri/navigation.test.ts b/apps/web/src/lib/tauri/navigation.test.tsindex 5e9e8a45f4..f43e556e95 100644--- a/apps/web/src/lib/tauri/navigation.test.ts+++ b/apps/web/src/lib/tauri/navigation.test.ts@@ -9,11 +9,16 @@ const mocks = vi.hoisted(() => ({setPostLoginRedirect: vi.fn(),listen: vi.fn(),invoke: vi.fn(),+ invalidateGithubLinkStatus: vi.fn(),}));-vi.mock('@core/util/platform', () => ({+vi.mock('@core/util/platform', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@core/util/platform')>()),getNativeMobilePlatform: () => mocks.platform,}));+vi.mock('@queries/auth', () => ({+ invalidateGithubLinkStatus: mocks.invalidateGithubLinkStatus,+}));vi.mock('@core/util/postLoginRedirect', () => ({setPostLoginRedirect: mocks.setPostLoginRedirect,}));@@ -105,6 +110,14 @@ describe('native link session routing', () => {expect(mocks.setPostLoginRedirect).not.toHaveBeenCalled();});+ it('refreshes GitHub after desktop consent without leaving the current page', () => {+ mocks.platform = 'macos';+ mocks.invalidateGithubLinkStatus.mockResolvedValue(undefined);+ receive({ payload: { path: '/github-link-callback', query: '' } });+ expect(mocks.invalidateGithubLinkStatus).toHaveBeenCalledOnce();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });+it('ignores stale connector callbacks without routing to a missing page', () => {receive({payload: {diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.tsindex c42d6202b1..85f311f4bc 100644--- a/apps/web/src/lib/tauri/navigation.ts+++ b/apps/web/src/lib/tauri/navigation.ts@@ -1,3 +1,4 @@+import { handleGithubLinkCallback } from '@core/auth/authorize-github';import { handlePipedreamCallback } from '@core/pipedream/connect-callback';import { fireAndForget } from '@core/util/fireAndForget';import { getNativeMobilePlatform } from '@core/util/platform';@@ -27,6 +28,7 @@ export function useTauriNavigationEffect() {const unlisten = listen<NavigateEvent>('navigate', (ev) => {if (handlePipedreamCallback(ev.payload.path, ev.payload.query)) return;+ if (handleGithubLinkCallback(ev.payload.path)) return;if (ev.payload.path === '/notification') {const notificationId = new URLSearchParams(ev.payload.query).get('notificationId'