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(mobile): improve flaky service flow (#4902)

Peter Chinman24c1f7c4b02d
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index b28abfc17c..686abcc9ae 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -79,6 +79,7 @@ const AUTH_URLS = [
`${ROUTER_BASE_CONCAT}onboarding`,
`${ROUTER_BASE_CONCAT}signup`,
`${ROUTER_BASE_CONCAT}email-signup-callback`,
+ `${ROUTER_BASE_CONCAT}offline`,
`${ROUTER_BASE_CONCAT}welcome`,
`${ROUTER_BASE_CONCAT}team-invite`,
];
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index a9be6d15ef..d4228bceb4 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -3,40 +3,47 @@ import { SERVER_HOSTS } from '@core/constant/servers';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { syncLoginStorage } from '@core/util/cookies';
import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
-import { authKeys } from '@queries/auth/user-info';
+import { authKeys, type UserInfoData } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
import { clearDocumentQueryCache } from '@queries/storage/document-cache';
import { authServiceClient } from '@service-auth/client';
import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
+const unauthenticatedUserInfo: UserInfoData = {
+ id: '',
+ permissions: [],
+ email: '',
+ name: null,
+ licenseStatus: 'inactive',
+ tutorialComplete: false,
+ group: null,
+ hasChromeExt: false,
+ authenticated: false,
+ userId: '',
+ hasTrialed: false,
+ aiDataConsent: false,
+ referralCode: '',
+};
+
+export async function clearLocalAuthSession() {
+ document.cookie =
+ 'login=false; expires=Thu, 01 Jan 1970 00:00:00 UTC; max-age=0; path=/; SameSite=Lax';
+ syncLoginStorage(false);
+ clearDocumentQueryCache(queryClient);
+ queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);
+
+ // Queued mutations are user intent; never allow them to replay under a
+ // subsequent account sharing this anonymous device cache scope.
+ await clearRegisteredCaches();
+}
+
export function useLogout() {
const analytics = useAnalytics();
const navigate = useNavigate();
return createCallback(async () => {
- document.cookie =
- 'login=false; expires=Thu, 01 Jan 1970 00:00:00 UTC; max-age=0; path=/; SameSite=Lax';
- syncLoginStorage(false);
- clearDocumentQueryCache(queryClient);
-
- queryClient.setQueryData(authKeys.userInfo.queryKey, {
- id: '',
- permissions: [],
- email: '',
- name: null,
- licenseStatus: 'inactive',
- tutorialComplete: false,
- group: null,
- hasChromeExt: false,
- authenticated: false,
- userId: '',
- hasTrialed: false,
- });
-
- // Queued mutations are user intent; never allow them to replay under a
- // subsequent account sharing this anonymous device cache scope.
- await clearRegisteredCaches();
+ await clearLocalAuthSession();
await authServiceClient.logout();
analytics.track('sign_out');
analytics.reset();
diff --git a/apps/web/src/lib/core/util/result.ts b/apps/web/src/lib/core/util/result.ts
index 38380ef640..eb7c2ea6d6 100644
--- a/apps/web/src/lib/core/util/result.ts
+++ b/apps/web/src/lib/core/util/result.ts
@@ -24,6 +24,17 @@ export class ThrownResultError<E extends string = string> extends Error {
}
}
+/** True when `error` is a ThrownResultError carrying the given error code. */
+export function thrownResultErrorHasCode(
+ error: unknown,
+ code: string
+): boolean {
+ return (
+ error instanceof ThrownResultError &&
+ error.errors.some((e) => e.code === code)
+ );
+}
+
/** Wraps a result-returning async function to throw on error. */
export async function throwOnErr<E extends string, T>(
fn: () => Promise<Result<T, ResultError<E>[]>>
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 51333d2843..29ca8b3a4e 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -32,6 +32,7 @@ import { GlobalAppStateProvider } from '@components/app/GlobalAppState';
import { Layout } from '@components/app/Layout';
import { ReactiveFavicon } from '@components/app/ReactiveFavicon';
import { LAYOUT_ROUTE } from '@components/app/split-layout/SplitLayoutRoute';
+import { clearLocalAuthSession } from '@core/auth/logout';
import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';
import { toast } from '@core/component/Toast/Toast';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
@@ -57,6 +58,7 @@ import {
} from '@core/util/cookies';
import { licenseChannel } from '@core/util/licenseUpdateBroadcastChannel';
import { isTauri } from '@core/util/platform';
+import { thrownResultErrorHasCode } from '@core/util/result';
import { transformShortIdInUrlPathname } from '@core/util/url';
import { EntityProvider } from '@entity';
import { MaybeTauriProvider } from '@macro/tauri';
@@ -193,6 +195,46 @@ function OfflineFallback(props: { onRetry: () => Promise<unknown> }) {
);
}
+const OFFLINE_ROUTE = '/offline';
+
+function getCurrentQueryString() {
+ const params = new URLSearchParams(window.location.search);
+ return params.toString().length > 0 ? `?${params.toString()}` : '';
+}
+
+function shouldShowNativeOfflineFallback(
+ userInfoQuery: ReturnType<typeof useUserInfoQuery>
+) {
+ return (
+ userInfoQuery.isError &&
+ hasLoginCookie() &&
+ isNativeMobilePlatform() &&
+ !thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')
+ );
+}
+
+function SessionExpiredRedirect() {
+ void clearLocalAuthSession().catch((error) => {
+ console.error('Failed to clear local auth session', error);
+ });
+ return <Navigate href={`/welcome${getCurrentQueryString()}`} />;
+}
+
+function OfflineFallbackRoute() {
+ const userInfoQuery = useUserInfoQuery();
+
+ // Once the query settles into anything other than a genuine connectivity
+ // failure, bounce to the base path.
+ return (
+ <Switch fallback={<Navigate href={`/${getCurrentQueryString()}`} />}>
+ <Match when={userInfoQuery.isLoading}>{null}</Match>
+ <Match when={shouldShowNativeOfflineFallback(userInfoQuery)}>
+ <OfflineFallback onRetry={() => userInfoQuery.refetch()} />
+ </Match>
+ </Switch>
+ );
+}
+
function BasePathComponent() {
const analytics = useAnalytics();
@@ -227,9 +269,7 @@ function BasePathComponent() {
const userInfoQuery = useUserInfoQuery();
// Preserve existing query parameters when redirecting
- const params = new URLSearchParams(window.location.search);
- const queryString =
- params.toString().length > 0 ? `?${params.toString()}` : '';
+ const queryString = getCurrentQueryString();
const redirectPath = `${DEFAULT_ROUTE}${queryString}`;
return (
@@ -237,18 +277,22 @@ function BasePathComponent() {
<Match when={userInfoQuery.isLoading}>{null}</Match>
<Match
when={
- userInfoQuery.isError && hasLoginCookie() && isNativeMobilePlatform()
+ hasLoginCookie() &&
+ thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')
}
>
- <OfflineFallback onRetry={() => userInfoQuery.refetch()} />
+ <SessionExpiredRedirect />
+ </Match>
+ <Match when={userInfoQuery.data?.authenticated}>
+ <Navigate href={redirectPath} />
+ </Match>
+ <Match when={shouldShowNativeOfflineFallback(userInfoQuery)}>
+ <Navigate href={`${OFFLINE_ROUTE}${queryString}`} />
</Match>
<Match
when={!userInfoQuery.isLoading && !userInfoQuery.data?.authenticated}
>
- <Navigate href={`/welcome${window.location.search}`} />
- </Match>
- <Match when={userInfoQuery.data?.authenticated}>
- <Navigate href={redirectPath} />
+ <Navigate href={`/welcome${queryString}`} />
</Match>
</Switch>
);
@@ -362,6 +406,10 @@ const ROUTES: RouteDefinition[] = [
path: '/login',
component: () => <Login />,
},
+ {
+ path: OFFLINE_ROUTE,
+ component: OfflineFallbackRoute,
+ },
{
path: '/welcome',
component: () =>