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
/**
* @vitest-environment jsdom
*/
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { ThrownResultError } from '@core/util/result';
import { QueryClientProvider } from '@tanstack/solid-query';
import type { JSX } from 'solid-js';
import { render } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
clearLocalAuthSession: vi.fn(),
confirmSessionExpired: vi.fn(),
fetchUserInfo: vi.fn(),
hasLoginCookie: true,
nativeMobile: false,
navigate: vi.fn(),
reloadApp: vi.fn(),
tauri: false,
routerSearch: (): string => '',
setRouterSearch: (_value: string) => {},
}));
vi.mock('@app/features/paywall/use-checkout-completion-listener', () => ({
useCheckoutCompletionListener: () => () => false,
}));
vi.mock('@core/auth/logout', () => ({
clearLocalAuthSession: mocks.clearLocalAuthSession,
}));
vi.mock('@app/observability/reload', () => ({
reloadApp: mocks.reloadApp,
}));
vi.mock('@core/util/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('@core/util/platform')>()),
isTauri: () => mocks.tauri,
}));
vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
isNativeMobilePlatform: () => mocks.nativeMobile,
}));
vi.mock('@core/util/cookies', () => ({
hasLoginCookie: () => mocks.hasLoginCookie,
}));
vi.mock('@core/util/fetchWithToken', () => ({
confirmSessionExpired: mocks.confirmSessionExpired,
}));
// A single client instance shared with the component under test: the
// SessionExpiredRedirect confirm path reads the refetched query error straight
// off this client, so the mock must hand both sides the same cache.
vi.mock('@queries/client', async () => {
const { QueryClient } = await import('@tanstack/solid-query');
return {
queryClient: new QueryClient({
defaultOptions: { queries: { retry: false } },
}),
};
});
// Thin re-implementation of the user-info query over the mocked client, so the
// test controls fetch outcomes while keeping real query semantics (error
// state, invalidation-triggered refetches).
vi.mock('@queries/auth/user-info', async () => {
const { useQuery } = await import('@tanstack/solid-query');
const { queryClient } = await import('@queries/client');
const authKeys = { userInfo: { queryKey: ['auth', 'userInfo'] } };
return {
authKeys,
invalidateUserInfo: () =>
queryClient.invalidateQueries({ queryKey: authKeys.userInfo.queryKey }),
useUserInfoQuery: () =>
useQuery(() => ({
queryKey: authKeys.userInfo.queryKey,
queryFn: mocks.fetchUserInfo,
networkMode: 'always',
})),
};
});
vi.mock('@solidjs/router', async () => {
const { createSignal } = await import('solid-js');
const [search, setSearch] = createSignal('');
mocks.routerSearch = search;
mocks.setRouterSearch = setSearch;
return {
Navigate: (props: { href: string }) => {
mocks.navigate(props.href, { replace: true });
return null;
},
useNavigate: () => mocks.navigate,
useLocation: () => ({
get search() {
return search();
},
}),
useSearchParams: () => [
{
get upgrade() {
return new URLSearchParams(search()).get('upgrade');
},
},
() => {},
],
};
});
vi.mock('@ui', () => ({
Button: (props: { children: JSX.Element; onClick?: () => void }) => (
<button onClick={props.onClick}>{props.children}</button>
),
}));
vi.mock('@channel/queries/prefetch-channel-target', () => ({
prefetchChannelTarget: vi.fn(async () => {}),
}));
import {
receiveNotificationTap,
setPendingNotificationNavigationId,
} from '@notifications/notification-navigation-intent';
import { endNotificationOpen } from '@notifications/notification-open-trace';
import { queryClient } from '@queries/client';
import { BasePathComponent } from './BasePath';
const UNAUTHORIZED_ERROR = () =>
new ThrownResultError([
{ code: 'UNAUTHORIZED', message: 'Unauthorized access' },
]);
const SERVER_ERROR = () =>
new ThrownResultError([
{ code: 'SERVER_ERROR', message: 'Internal server error' },
]);
let dispose: (() => void) | undefined;
function renderRoute(): HTMLElement {
const container = document.createElement('div');
document.body.appendChild(container);
const disposeRender = render(
() => (
<QueryClientProvider client={queryClient}>
<BasePathComponent />
</QueryClientProvider>
),
container
);
dispose = () => {
disposeRender();
container.remove();
};
return container;
}
/** Lets in-flight query/resource promises settle before negative assertions. */
function flush() {
return new Promise((resolve) => setTimeout(resolve, 25));
}
beforeEach(() => {
mocks.hasLoginCookie = true;
mocks.nativeMobile = false;
mocks.tauri = false;
mocks.reloadApp.mockReset();
mocks.setRouterSearch('');
mocks.navigate.mockReset();
mocks.fetchUserInfo.mockReset();
mocks.confirmSessionExpired.mockReset();
mocks.clearLocalAuthSession.mockReset();
mocks.clearLocalAuthSession.mockResolvedValue(undefined);
sessionStorage.clear();
localStorage.clear();
queryClient.clear();
window.history.replaceState({}, '', '/app/');
});
afterEach(() => {
vi.unstubAllGlobals();
dispose?.();
dispose = undefined;
setPendingNotificationNavigationId(undefined);
endNotificationOpen('test_complete');
});
describe('BasePathComponent', () => {
it('chooses the tapped message before Home or a saved destination after authentication', async () => {
mocks.nativeMobile = true;
setPostLoginRedirect('/channels/previous');
const recipientId = 'macro|[email protected]';
receiveNotificationTap(
{
type: 'BACKGROUND_TAP',
payload: {
notificationId: 'notification-1',
recipientId,
navigation: {
type: 'channel',
channelId: '11111111-1111-4111-8111-111111111111',
messageId: '22222222-2222-4222-8222-222222222222',
threadId: null,
},
},
},
vi.fn()
);
let resolveIdentity!: (identity: {
authenticated: true;
userId: string;
}) => void;
mocks.fetchUserInfo.mockReturnValue(
new Promise((resolve) => {
resolveIdentity = resolve;
})
);
renderRoute();
expect(mocks.navigate).not.toHaveBeenCalled();
resolveIdentity({ authenticated: true, userId: recipientId });
await vi.waitFor(() =>
expect(mocks.navigate).toHaveBeenCalledExactlyOnceWith(
'/home/~/channel/11111111-1111-4111-8111-111111111111?channel_message_id=22222222-2222-4222-8222-222222222222&channel_thread_id=22222222-2222-4222-8222-222222222222',
{ replace: true }
)
);
});
it.each([true, false])(
'preserves a late native root query while authentication resolves (%s)',
async (authenticated) => {
mocks.nativeMobile = true;
mocks.hasLoginCookie = authenticated;
let resolveUserInfo!: (value: { authenticated: boolean }) => void;
mocks.fetchUserInfo.mockReturnValue(
new Promise<{ authenticated: boolean }>((resolve) => {
resolveUserInfo = resolve;
})
);
renderRoute();
await vi.waitFor(() => expect(mocks.fetchUserInfo).toHaveBeenCalled());
expect(mocks.navigate).not.toHaveBeenCalled();
mocks.setRouterSearch('?upgrade=true&referral_code=late');
await vi.waitFor(() =>
expect(sessionStorage.getItem('showUpgradeModal')).toBe('true')
);
resolveUserInfo({ authenticated });
await vi.waitFor(() =>
expect(mocks.navigate).toHaveBeenCalledWith(
`${authenticated ? DEFAULT_ROUTE : '/welcome'}?upgrade=true&referral_code=late`,
{ replace: true }
)
);
}
);
it('preserves native hash-router queries when entering the app', async () => {
mocks.nativeMobile = true;
mocks.setRouterSearch('?upgrade=true&referral_code=invite');
window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(
`${DEFAULT_ROUTE}${mocks.routerSearch()}`,
{ replace: true }
);
});
expect(sessionStorage.getItem('showUpgradeModal')).toBe('true');
});
it('preserves native hash-router queries when sending a new user to welcome', async () => {
mocks.nativeMobile = true;
mocks.hasLoginCookie = false;
mocks.setRouterSearch('?referral_code=invite');
window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(
'/welcome?referral_code=invite',
{
replace: true,
}
);
});
});
it('preserves native hash-router queries after confirmed session expiry', async () => {
mocks.nativeMobile = true;
mocks.tauri = true;
mocks.setRouterSearch('?referral_code=invite');
window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());
mocks.confirmSessionExpired.mockResolvedValue(true);
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(
'/welcome?referral_code=invite',
{
replace: true,
}
);
expect(mocks.reloadApp).toHaveBeenCalledWith('logout');
});
});
it('keeps browser query forwarding unchanged', async () => {
window.history.replaceState({}, '', '/app/?subscriptionSuccess=true');
mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(
`${DEFAULT_ROUTE}?subscriptionSuccess=true`,
{ replace: true }
);
});
});
it('retains a native destination until authentication succeeds', async () => {
mocks.nativeMobile = true;
mocks.hasLoginCookie = false;
mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });
setPostLoginRedirect('/task/pending');
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {
replace: true,
});
});
expect(localStorage.getItem('nativePostLoginRedirect')).not.toBeNull();
queryClient.setQueryData(['auth', 'userInfo'], { authenticated: true });
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith('/task/pending', {
replace: true,
});
});
expect(localStorage.getItem('nativePostLoginRedirect')).toBeNull();
});
it('redirects an authenticated session to the default route', async () => {
mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {
replace: true,
});
});
});
it('redirects a session without a login cookie to welcome', async () => {
mocks.hasLoginCookie = false;
mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {
replace: true,
});
});
expect(mocks.confirmSessionExpired).not.toHaveBeenCalled();
});
it('clears the session and loads welcome as a new page on a confirmed expiry', async () => {
const replace = vi.fn();
vi.stubGlobal(
'location',
Object.assign(new URL('https://macro.com/app/?referral_code=invite'), {
replace,
})
);
mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());
mocks.confirmSessionExpired.mockResolvedValue(true);
renderRoute();
await vi.waitFor(() => {
expect(mocks.clearLocalAuthSession).toHaveBeenCalled();
expect(replace).toHaveBeenCalledWith('/app/welcome?referral_code=invite');
});
});
// As clearLocalAuthSession does: the login hint goes first and the
// signed-out user info last, which unmounts the redirect before it resolves.
const signedOutClear = async () => {
mocks.hasLoginCookie = false;
await Promise.resolve();
queryClient.setQueryData(['auth', 'userInfo'], {
authenticated: false,
id: '',
});
};
it('loads welcome as a new page even when the clear unmounts the redirect', async () => {
const replace = vi.fn();
vi.stubGlobal(
'location',
Object.assign(new URL('https://macro.com/app/?referral_code=invite'), {
replace,
})
);
mocks.clearLocalAuthSession.mockImplementation(signedOutClear);
mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());
mocks.confirmSessionExpired.mockResolvedValue(true);
renderRoute();
await vi.waitFor(() => {
expect(replace).toHaveBeenCalledWith('/app/welcome?referral_code=invite');
});
});
it('reloads the native webview even when the clear unmounts the redirect', async () => {
mocks.nativeMobile = true;
mocks.tauri = true;
mocks.setRouterSearch('?referral_code=invite');
window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
mocks.clearLocalAuthSession.mockImplementation(signedOutClear);
mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());
mocks.confirmSessionExpired.mockResolvedValue(true);
renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(
'/welcome?referral_code=invite',
{ replace: true }
);
expect(mocks.reloadApp).toHaveBeenCalledWith('logout');
});
});
it('keeps a cookie-backed session off welcome when the confirm refresh fails transiently', async () => {
// A latched refresh failure surfaced UNAUTHORIZED, but the confirming
// refresh says the session is alive — and the user-info refetch then hits
// a transient server failure. The query settles into a non-UNAUTHORIZED
// error: "unknown", not "unauthenticated".
mocks.fetchUserInfo
.mockRejectedValueOnce(UNAUTHORIZED_ERROR())
.mockRejectedValue(SERVER_ERROR());
mocks.confirmSessionExpired.mockResolvedValue(false);
const container = renderRoute();
await vi.waitFor(() => {
expect(mocks.confirmSessionExpired).toHaveBeenCalled();
expect(mocks.fetchUserInfo).toHaveBeenCalledTimes(2);
});
await flush();
// The local session survives and the unknown state renders nothing
// instead of bouncing a possibly-valid session to login.
expect(mocks.clearLocalAuthSession).not.toHaveBeenCalled();
expect(mocks.navigate).not.toHaveBeenCalled();
expect(container.textContent).toBe('');
});
it('asks native users to verify their session when no local identity is available', async () => {
mocks.nativeMobile = true;
mocks.fetchUserInfo.mockRejectedValue(SERVER_ERROR());
const container = renderRoute();
await vi.waitFor(() => {
expect(container.textContent).toContain('Unable to connect.');
});
expect(mocks.navigate).not.toHaveBeenCalled();
});
it('enters the native app with a cached identity when its refresh fails', async () => {
mocks.nativeMobile = true;
mocks.fetchUserInfo.mockRejectedValue(SERVER_ERROR());
queryClient.setQueryData(['auth', 'userInfo'], { authenticated: true });
const container = renderRoute();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {
replace: true,
});
});
await flush();
expect(container.textContent).not.toContain('Unable to connect.');
});
it('enters the app after session verification succeeds', async () => {
mocks.nativeMobile = true;
mocks.fetchUserInfo
.mockRejectedValueOnce(SERVER_ERROR())
.mockResolvedValue({ authenticated: true });
const container = renderRoute();
await vi.waitFor(() => {
expect(container.textContent).toContain('Unable to connect.');
});
container.querySelector('button')?.click();
await vi.waitFor(() => {
expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {
replace: true,
});
});
});
});