Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(auth): keep Android Google sign-in through app update reloads (#9922)

Peter Chinmanc39f7a0c9d9d
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 71fb0da0d8..c93508609b 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -507,13 +507,16 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
- Probe identity on deploy-preview origins even without a local login hint;
shared HttpOnly dev cookies are not visible to JavaScript or localStorage.
- Leave the login hint (`syncLoginStorage(true)`) before a full-page hosted
- SSO redirect; the callback sets only HttpOnly cookies, and a load without the
- hint never checks identity, so the returning user sees sign-in again.
+ SSO redirect, and as soon as a native sign-in redeems its session code; the
+ cookies are HttpOnly or in the native jar, and a load without the hint never
+ checks identity, so the user sees sign-in again over a valid session.
- Hold automatic reloads (`holdAutomaticReload`) across anything a reload would
lose. `createNativeAuthSession` holds them for the sheet: its result reaches
only the JavaScript that opened it, and leaving the app for a sign-in code
- hides the page, the moment OTA bundles apply. Holds also reach the native
- updater, whose foreground handler never asks the page. See
+ hides the page, the moment OTA bundles apply. Native sign-in (`useSsoLogin`)
+ holds them on until the session code is redeemed and the login hint is down.
+ Holds also reach the native updater, whose foreground handler never asks the
+ page. See
[reload diagnostics](tauri/src-tauri/README.md#diagnosing-unexpected-webview-reloads).
- Disable GraphQL cache sessions and clear login hints on confirmed auth 401s,
even with retained user data; preserve session state on transient failures.
diff --git a/apps/web/src/features/auth/useSsoLogin.test.ts b/apps/web/src/features/auth/useSsoLogin.test.ts
index e422f1916b..dfd5c64227 100644
--- a/apps/web/src/features/auth/useSsoLogin.test.ts
+++ b/apps/web/src/features/auth/useSsoLogin.test.ts
@@ -1,5 +1,5 @@
import type { RedirectLocation } from '@core/util/authRedirect';
-import { ok } from 'neverthrow';
+import { err, ok, ResultAsync } from 'neverthrow';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
setPostLoginRedirect: vi.fn(),
toastFailure: vi.fn(),
syncLoginStorage: vi.fn(),
+ reloadHolds: 0,
}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
@@ -54,6 +55,14 @@ vi.mock('@core/util/fetchWithToken', () => ({
vi.mock('@core/util/cookies', () => ({
syncLoginStorage: mocks.syncLoginStorage,
}));
+vi.mock('@core/util/reloadForNewerBuild', () => ({
+ holdAutomaticReload: () => {
+ mocks.reloadHolds++;
+ return () => {
+ mocks.reloadHolds--;
+ };
+ },
+}));
vi.mock('@queries/auth/user-info', () => ({
invalidateAllAfterLogin: mocks.invalidateAllAfterLogin,
}));
@@ -76,6 +85,7 @@ beforeEach(() => {
mocks.openDesktopAuthSession.mockResolvedValue({ success: true });
mocks.servers['auth-service'] = proxyAuthHost;
mocks.location.state = undefined;
+ mocks.reloadHolds = 0;
mocks.createNativeAuthSession.mockReturnValue({
callbackUrl: 'macro://android-auth/test-attempt',
authenticate: mocks.authenticate,
@@ -230,7 +240,86 @@ describe('useSsoLogin', () => {
expect(mocks.invalidateAllAfterLogin).toHaveBeenCalledOnce();
expect(mocks.initEmailLink).toHaveBeenCalledOnce();
expect(window.location.href).toBe(loginUrl);
- expect(mocks.syncLoginStorage).not.toHaveBeenCalled();
+ expect(mocks.syncLoginStorage).toHaveBeenCalledWith(true);
+ expect(mocks.track).toHaveBeenCalledWith('login', { method: 'google' }, [
+ 'posthog',
+ ]);
}
);
+
+ // An app update reload can land on the native sign-in at any point, not
+ // only while the sheet is open. A document that reloads after the session
+ // code is redeemed but before the login hint is down never checks identity
+ // and shows sign-in over the new session.
+ it('holds reloads until the redeemed native session has left the login hint', async () => {
+ mocks.nativeMobile = true;
+ const heldAt: Record<string, boolean> = {};
+ mocks.sessionLogin.mockImplementation(async () => {
+ heldAt.redeem = mocks.reloadHolds > 0;
+ return ok(undefined);
+ });
+ mocks.syncLoginStorage.mockImplementation(() => {
+ heldAt.hint = mocks.reloadHolds > 0;
+ });
+ // Record the hold as each later step finishes, not as it starts.
+ mocks.invalidateAllAfterLogin.mockImplementation(async () => {
+ await Promise.resolve();
+ heldAt.refresh = mocks.reloadHolds > 0;
+ });
+ mocks.initEmailLink.mockImplementation(() =>
+ ResultAsync.fromSafePromise(
+ (async () => {
+ await Promise.resolve();
+ heldAt.emailLink = mocks.reloadHolds > 0;
+ })()
+ )
+ );
+
+ await useSsoLogin()('google');
+
+ expect(heldAt).toEqual({
+ redeem: true,
+ hint: true,
+ refresh: true,
+ emailLink: true,
+ });
+ expect(mocks.syncLoginStorage).toHaveBeenCalledWith(true);
+ // The identity refetch can take a while; the hint must not wait for it.
+ expect(mocks.syncLoginStorage.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.invalidateAllAfterLogin.mock.invocationCallOrder[0]
+ );
+ expect(mocks.reloadHolds).toBe(0);
+ });
+
+ it('leaves no login hint when the native session code is not redeemed', async () => {
+ mocks.nativeMobile = true;
+ mocks.sessionLogin.mockResolvedValue(
+ err([{ code: 'HTTP_ERROR', message: 'invalid session code' }])
+ );
+
+ await useSsoLogin()('google');
+
+ expect(mocks.syncLoginStorage).not.toHaveBeenCalled();
+ expect(mocks.invalidateAllAfterLogin).not.toHaveBeenCalled();
+ expect(mocks.toastFailure).toHaveBeenCalledWith(
+ 'Sign-in failed. Please try again.'
+ );
+ expect(mocks.reloadHolds).toBe(0);
+ });
+
+ it('releases the hold without signing in when the sheet is canceled', async () => {
+ mocks.nativeMobile = true;
+ mocks.authenticate.mockResolvedValue({
+ success: false,
+ error: 'User canceled login',
+ });
+
+ await useSsoLogin()('google');
+
+ expect(mocks.sessionLogin).not.toHaveBeenCalled();
+ expect(mocks.syncLoginStorage).not.toHaveBeenCalled();
+ expect(mocks.toastFailure).not.toHaveBeenCalled();
+ expect(mocks.track).not.toHaveBeenCalled();
+ expect(mocks.reloadHolds).toBe(0);
+ });
});
diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.ts
index baf913193a..66e4a80905 100644
--- a/apps/web/src/features/auth/useSsoLogin.ts
+++ b/apps/web/src/features/auth/useSsoLogin.ts
@@ -14,6 +14,8 @@ import { syncLoginStorage } from '@core/util/cookies';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
import { isPlatform } from '@core/util/platform';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
+import { holdAutomaticReload } from '@core/util/reloadForNewerBuild';
+import { type Span, Telemetry } from '@macro-inc/observability';
import { invalidateAllAfterLogin } from '@queries/auth/user-info';
import { authServiceClient } from '@service-auth/client';
import { useLocation } from '@solidjs/router';
@@ -60,6 +62,59 @@ async function startDesktopSso(
}
}
+type NativeSignInOutcome = 'canceled' | 'failed' | 'redeem_failed' | 'success';
+
+type EmailLinks = ReturnType<typeof useEmailLinks>;
+
+/** Run the hosted flow in the native auth sheet and redeem its session code. */
+async function nativeSsoLogin(
+ span: Span,
+ authUrl: URL,
+ initEmailLink: EmailLinks['initEmailLink']
+): Promise<NativeSignInOutcome> {
+ const session = createNativeAuthSession('login');
+ authUrl.searchParams.set('original_url', session.callbackUrl);
+ const result = await session.authenticate(authUrl.toString());
+ const sessionCode = result.token;
+
+ if (!result.success || !sessionCode) {
+ // A canceled sheet is a deliberate user action, not a failure.
+ if (result.error === 'User canceled login') return 'canceled';
+ console.error('Authentication failed:', result.error);
+ toast.failure('Sign-in failed. Please try again.');
+ return 'failed';
+ }
+
+ const res = await span.run(() =>
+ authServiceClient.sessionLogin({ session_code: sessionCode })
+ );
+
+ if (res.isErr()) {
+ console.error('Failed to redeem session code', res.error);
+ toast.failure('Sign-in failed. Please try again.');
+ return 'redeem_failed';
+ }
+
+ // The session cookies are set. From here a reloaded document must check
+ // identity rather than show sign-in, so leave the hint now instead of
+ // waiting for the identity refetch below to write it.
+ syncLoginStorage(true);
+ // Reset token state only after the session cookies have actually
+ // changed — resetting before sessionLogin opens a window where a
+ // visibility-triggered refresh re-latches under the new generation.
+ unsetTokenPromise();
+ await invalidateAllAfterLogin();
+ await initEmailLink().match(
+ () => {},
+ (err) => {
+ if (err.tag !== 'AlreadyInitialized') {
+ console.error('Failed to init email link on login', err);
+ }
+ }
+ );
+ return 'success';
+}
+
export function useSsoLogin(opts?: {
signupMode?: boolean;
/** Started on the agent signup page: a new account becomes an agent. */
@@ -102,43 +157,31 @@ export function useSsoLogin(opts?: {
}
if (isNativeMobilePlatform()) {
- const session = createNativeAuthSession('login');
- authUrl.searchParams.set('original_url', session.callbackUrl);
- const result = await session.authenticate(authUrl.toString());
-
- if (!result.success || !result.token) {
- // A canceled sheet is a deliberate user action, not a failure.
- if (result.error !== 'User canceled login') {
- console.error('Authentication failed:', result.error);
- toast.failure('Sign-in failed. Please try again.');
- }
- return;
- }
-
- const res = await authServiceClient.sessionLogin({
- session_code: result.token,
- });
-
- if (res.isOk()) {
- // Reset token state only after the session cookies have actually
- // changed — resetting before sessionLogin opens a window where a
- // visibility-triggered refresh re-latches under the new generation.
- unsetTokenPromise();
- await invalidateAllAfterLogin();
- await initEmailLink().match(
- () => {},
- (err) => {
- if (err.tag !== 'AlreadyInitialized') {
- console.error('Failed to init email link on login', err);
- }
+ // The sheet's result reaches only this document, and a document loaded
+ // before the login hint is down never checks identity. A reload at any
+ // point in the sign-in, not only while the sheet is open, shows sign-in
+ // again over the session the user just created.
+ const releaseReloadHold = holdAutomaticReload();
+ try {
+ const outcome = await Telemetry.span(
+ 'auth.native_sign_in',
+ async (span) => {
+ const outcome = await nativeSsoLogin(span, authUrl, initEmailLink);
+ span.setAttr('auth.native_sign_in.outcome', outcome);
+ return outcome;
}
);
- } else {
- console.error('Failed to redeem session code', res.error);
- toast.failure('Sign-in failed. Please try again.');
- }
- analytics.track(analyticsEvent, { method: idp_name }, analyticsProviders);
+ if (outcome === 'success' || outcome === 'redeem_failed') {
+ analytics.track(
+ analyticsEvent,
+ { method: idp_name },
+ analyticsProviders
+ );
+ }
+ } finally {
+ releaseReloadHold();
+ }
return;
}
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 60ae1de5b8..fec68dba42 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -98,15 +98,21 @@ An update reload normally lands while the page is hidden, which is harmless for
a list and fatal for anything the page is waiting on. A native auth sheet is the
sharp case: leaving the app for a sign-in code hides the page, the reload drops
the JavaScript awaiting the sheet, and the finished sign-in has nowhere to go.
+Returning from the sheet foregrounds the app, so a reload that lands while the
+session code is still being redeemed, before the login hint is down, loses the
+sign-in just the same. The new document never checks identity and shows sign-in
+over the session in the native cookie jar.
`holdAutomaticReload` covers this work on the page and sends
`set_bundle_reload_hold` here, because the mobile foreground handler applies a
completed bundle without asking the page. `apply_update` then answers `Held` and
the bundle stays pending until the next hide or foreground after the release.
Each document sends its hold state on mount, so a hold whose owner died cannot
block updates until the next launch. Desktop has no foreground handler to hold
-and does not call the command. Mobile requires it, so the mobile native floors
-must reach a binary that has it; below that floor no bundle applies, so no
-update reload can land on a sheet.
+and does not call the command. Mobile requires it. The iOS floor reaches a
+binary that has it; the Android floor does not yet. Android binaries without
+the command still apply bundles over a pending sign-in, and their embedded
+bundle predates the page-side hold, so a fresh install's first sign-in stays
+exposed until a newer native release.
`frontend_instance_id` is generated once per document and attached to every
PostHog event (including automatic exceptions/pageviews) and OTel resource.
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 118e14fdea..8a803d8274 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -190,6 +190,11 @@ passwords and verification codes only in that browser, never in agent messages.
For browsers using the Custom Tabs fallback, verify that the callback returns to
the original Macro task. A callback for another attempt must leave the current
attempt pending; a callback after process death must not restore that attempt.
+The first Google sign-in after a fresh install must land in the app, even while
+an over-the-air update finishes downloading: an update reload during the sheet
+or the session-code redemption used to return the user to `Login`, with the
+second tap then signing straight in. Check that PostHog shows no
+`native_webview_started` reload onto `#/login` right after the `login` event.
After signing in, test background/foreground, force-stop/relaunch, logout, and
signing in as another account. An entity link opened while signed out should