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
import { notificationKeys } from '@queries/notification/keys';
import { graphqlSoupKeys } from '@queries/soup/graphql/keys';
import { isCancelledError, QueryClient } from '@tanstack/solid-query';
import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
const { client, isTauri } = vi.hoisted(() => ({
client: { current: undefined as QueryClient | undefined },
isTauri: vi.fn(() => false),
}));
vi.mock('@queries/client', () => ({
queryPersistence: {
clear: async () => {
client.current?.clear();
},
},
get queryClient() {
return client.current;
},
}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
useAnalytics: () => ({ track: vi.fn(), reset: vi.fn() }),
}));
vi.mock('@ui', () => ({ confirmDialog: vi.fn(async () => false) }));
vi.mock('@queries/email/local-drafts', () => ({
clearLocalDrafts: vi.fn(async () => {}),
flushLocalDrafts: vi.fn(async () => {}),
listLocalDrafts: vi.fn(async () => []),
}));
vi.mock('@queries/email/send-queue', () => ({
readEmailSendIntents: vi.fn(async () => []),
settledSendAttempt: () => ({ status: 'ACCEPTED' }),
}));
vi.mock('@queries/email/outbox-session', () => ({
setEmailOutboxSession: vi.fn(),
}));
vi.mock('@core/constant/servers', async (importOriginal) => ({
...(await importOriginal<typeof import('@core/constant/servers')>()),
SERVER_HOSTS: { 'auth-logout': 'https://auth.example.com/oauth2/logout' },
}));
vi.mock('@core/util/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('@core/util/platform')>()),
isTauri,
}));
vi.mock('@core/util/cookies', () => ({ syncLoginStorage: vi.fn() }));
vi.mock('@graphql-cache/lifecycle', () => ({
clearRegisteredCaches: vi.fn(async () => {}),
}));
vi.mock('@service-storage/graphql-soup', () => ({
recordGraphqlMutationQueueCleared: vi.fn(async () => {}),
setGraphqlSoupSessionActive: vi.fn(),
}));
vi.mock('@queries/auth/user-info', () => ({
authKeys: {
userInfo: { queryKey: ['auth', 'user-info'] },
aiBillingSummary: { queryKey: ['auth', 'ai-billing-summary'] },
},
}));
vi.mock('@queries/storage/document-cache', () => ({
clearDocumentQueryCache: vi.fn(),
}));
vi.mock('@service-auth/client', () => ({
authServiceClient: { logout: vi.fn() },
}));
vi.mock('./push-registration-lifecycle', () => ({
unregisterPushRegistrationsForLogout: vi.fn(async () => {}),
}));
import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
import {
clearLocalDrafts,
flushLocalDrafts,
listLocalDrafts,
} from '@queries/email/local-drafts';
import { readEmailSendIntents } from '@queries/email/send-queue';
import { authServiceClient } from '@service-auth/client';
import { setGraphqlSoupSessionActive } from '@service-storage/graphql-soup';
import { confirmDialog } from '@ui';
import { clearLocalAuthSession, useLogout } from './logout';
describe('logout GraphQL session teardown', () => {
it('ends the GraphQL session only after the cache wipe', async () => {
client.current = new QueryClient();
const order: string[] = [];
vi.mocked(clearRegisteredCaches).mockImplementationOnce(async () => {
order.push('wipe');
});
vi.mocked(setGraphqlSoupSessionActive).mockImplementationOnce(() => {
order.push('teardown');
});
await clearLocalAuthSession();
expect(order).toEqual(['wipe', 'teardown']);
expect(setGraphqlSoupSessionActive).toHaveBeenCalledWith(false);
client.current.clear();
});
});
describe('logout notification cache isolation', () => {
it('retires pending Done buckets and rotates the display-intent session', async () => {
const queryClient = new QueryClient();
client.current = queryClient;
const first = graphqlSoupKeys.pendingDone('alice', 'old-session').queryKey;
const second = graphqlSoupKeys.pendingDone('bob', 'older-session').queryKey;
queryClient.setQueryData(first, [{ entityId: 'shared' }]);
queryClient.setQueryData(second, [{ entityId: 'shared' }]);
queryClient.setQueryData(
graphqlSoupKeys.doneSession.queryKey,
'old-session'
);
await clearLocalAuthSession();
expect(clearLocalDrafts).toHaveBeenCalled();
expect(queryClient.getQueryData(first)).toBeUndefined();
expect(queryClient.getQueryData(second)).toBeUndefined();
expect(
queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)
).toEqual(expect.any(String));
expect(
queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)
).not.toBe('old-session');
queryClient.clear();
});
it('cancels an old in-flight snapshot even when its transport ignores abort', async () => {
const queryClient = new QueryClient();
client.current = queryClient;
const queryKey = notificationKeys.user({ limit: 500 }).queryKey;
let resolveTransport!: (value: { owner: string }) => void;
const transport = new Promise<{ owner: string }>((resolve) => {
resolveTransport = resolve;
});
const request = queryClient
.fetchQuery({ queryKey, queryFn: () => transport, retry: false })
.catch((error: unknown) => error);
expect(queryClient.getQueryState(queryKey)?.fetchStatus).toBe('fetching');
await clearLocalAuthSession();
expect(isCancelledError(await request)).toBe(true);
expect(queryClient.getQueryData(queryKey)).toBeUndefined();
queryClient.setQueryData(queryKey, { owner: 'bob' });
resolveTransport({ owner: 'alice' });
await transport;
await Promise.resolve();
expect(queryClient.getQueryData(queryKey)).toEqual({ owner: 'bob' });
queryClient.clear();
});
it('evicts account notification snapshots and preferences before another login', async () => {
const queryClient = new QueryClient();
client.current = queryClient;
const keys = [
notificationKeys.user({ limit: 500 }).queryKey,
notificationKeys.entity({ eventItemId: 'reminder-1' }).queryKey,
notificationKeys.unsubscribes.queryKey,
notificationKeys.preferences.queryKey,
];
for (const key of keys) queryClient.setQueryData(key, { owner: 'alice' });
await clearLocalAuthSession();
for (const key of keys)
expect(queryClient.getQueryData(key)).toBeUndefined();
queryClient.clear();
});
});
describe('local draft logout warning', () => {
// The Tauri shell, desktop included: a webview navigation to the identity
// provider would be handed to the system browser by the navigation plugin,
// leaving the app itself signed in.
// The router writes a navigation's URL only once its transition settles, so
// the login URL must already be in place when the reload starts.
it('reloads the Tauri webview onto the login route after local cleanup', async () => {
const order: string[] = [];
client.current = new QueryClient();
isTauri.mockReturnValue(true);
vi.mocked(clearLocalDrafts).mockImplementationOnce(async () => {
order.push('clear');
});
const location = {
hash: '#/home',
reload: vi.fn(() => {
order.push(`reload ${location.hash}`);
}),
};
const replaceState = vi.fn(
(_state: unknown, _unused: string, url: string) => {
location.hash = url;
}
);
const fetchMock = vi.fn(async () => new Response());
vi.stubGlobal('window', { location, history: { replaceState } });
vi.stubGlobal('fetch', fetchMock);
const { logout, dispose } = createRoot((dispose) => ({
logout: useLogout(),
dispose,
}));
try {
await logout();
expect(order).toEqual(['clear', 'reload #/login']);
expect(fetchMock).toHaveBeenCalledWith(
'https://auth.example.com/oauth2/logout',
expect.objectContaining({ credentials: 'include', mode: 'no-cors' })
);
expect(location.reload).toHaveBeenCalledOnce();
} finally {
dispose();
isTauri.mockReturnValue(false);
vi.mocked(authServiceClient.logout).mockClear();
vi.unstubAllGlobals();
client.current.clear();
}
});
it('allows cancelling logout when drafts have unsynced changes', async () => {
vi.mocked(listLocalDrafts).mockResolvedValueOnce([
{ status: 'failed' },
] as Awaited<ReturnType<typeof listLocalDrafts>>);
const { logout, dispose } = createRoot((dispose) => ({
logout: useLogout(),
dispose,
}));
try {
await logout();
expect(confirmDialog).toHaveBeenLastCalledWith(
expect.objectContaining({
body: expect.stringContaining('1 draft(s)'),
}),
expect.anything()
);
expect(authServiceClient.logout).not.toHaveBeenCalled();
} finally {
dispose();
}
});
it('warns about queued sends after their working copies have been retired', async () => {
vi.mocked(readEmailSendIntents).mockResolvedValueOnce([
{ uuid: 'send' },
] as Awaited<ReturnType<typeof readEmailSendIntents>>);
const { logout, dispose } = createRoot((dispose) => ({
logout: useLogout(),
dispose,
}));
try {
await logout();
expect(confirmDialog).toHaveBeenLastCalledWith(
expect.objectContaining({
body: expect.stringContaining('signing out does not cancel them'),
}),
expect.anything()
);
expect(authServiceClient.logout).not.toHaveBeenCalled();
} finally {
dispose();
}
});
it('offers a warning and cancellation when local storage cannot be checked', async () => {
vi.mocked(flushLocalDrafts).mockRejectedValueOnce(
new Error('Disk unavailable')
);
const { logout, dispose } = createRoot((dispose) => ({
logout: useLogout(),
dispose,
}));
try {
await logout();
expect(confirmDialog).toHaveBeenLastCalledWith(
expect.objectContaining({
body: expect.stringContaining('could not be checked'),
}),
expect.anything()
);
expect(authServiceClient.logout).not.toHaveBeenCalled();
} finally {
dispose();
}
});
});