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(email): unlock composers stuck on "Queued to send" (#9206)

teo6be126064370
diff --git a/apps/web/src/components/app/SessionExpiredRedirect.tsx b/apps/web/src/components/app/SessionExpiredRedirect.tsx
index 3a3117f5b8..ab2a9c67c1 100644
--- a/apps/web/src/components/app/SessionExpiredRedirect.tsx
+++ b/apps/web/src/components/app/SessionExpiredRedirect.tsx
@@ -1,10 +1,13 @@
+import { ROUTER_BASE } from '@app/constants/routerBase';
+import { reloadApp } from '@app/observability/reload';
import { clearLocalAuthSession } from '@core/auth/logout';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { confirmSessionExpired } from '@core/util/fetchWithToken';
+import { isTauri } from '@core/util/platform';
import { thrownResultErrorHasCode } from '@core/util/result';
import { authKeys, invalidateUserInfo } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
-import { Navigate, useLocation } from '@solidjs/router';
+import { Navigate, useLocation, useNavigate } from '@solidjs/router';
import { createResource, Show } from 'solid-js';
export function getCurrentQueryString(routerSearch: string) {
@@ -15,11 +18,14 @@ export function getCurrentQueryString(routerSearch: string) {
}
/**
- * Sends a session the server rejected to /welcome, after confirming it with a
- * fresh refresh; the base path and the app chrome render it on a stale login.
+ * Sends a session the server rejected to a newly loaded /welcome, after
+ * confirming it with a fresh refresh; the base path and the app chrome render
+ * it on a stale login.
*/
export function SessionExpiredRedirect() {
const location = useLocation();
+ const navigate = useNavigate();
+ const welcome = () => `/welcome${getCurrentQueryString(location.search)}`;
// The UNAUTHORIZED that got us here can come from a latched refresh failure
// without the server ever being consulted, so confirm with a fresh refresh
// before destroying local session state. If the session turns out to be
@@ -33,15 +39,26 @@ export function SessionExpiredRedirect() {
);
if (!stillUnauthorized) return false;
}
+ const destination = welcome();
await clearLocalAuthSession('session-expired').catch((error) => {
console.error('Failed to clear local auth session', error);
});
+ // End this document, as sign-out does: the cleared email draft session
+ // can never reopen in it, so signing back in here would leave email
+ // locked. The clear can unmount this component, so this cannot wait for
+ // an effect.
+ if (isTauri()) {
+ navigate(destination, { replace: true });
+ reloadApp('logout');
+ } else {
+ window.location.replace(`${ROUTER_BASE}${destination}`);
+ }
return true;
});
return (
<Show when={expired()}>
- <Navigate href={`/welcome${getCurrentQueryString(location.search)}`} />
+ <Navigate href={welcome()} />
</Show>
);
}
diff --git a/apps/web/src/lib/queries/email/local-draft-store.test.ts b/apps/web/src/lib/queries/email/local-draft-store.test.ts
index 092edb7e1f..dae0fe387a 100644
--- a/apps/web/src/lib/queries/email/local-draft-store.test.ts
+++ b/apps/web/src/lib/queries/email/local-draft-store.test.ts
@@ -567,6 +567,57 @@ describe('working-copy concurrency fences', () => {
'no longer active'
);
});
+ it('takes over another account at the same epoch only when allowed, ending its session', async () => {
+ const store = open();
+ const previous = await store.activate('other-owner', 'epoch');
+ await store.save(previous, snapshot());
+ await expect(store.activate('owner', 'epoch')).rejects.toThrow(
+ 'no longer active'
+ );
+ const owner = await store.activate(
+ 'owner',
+ 'epoch',
+ () => true,
+ () => true
+ );
+ expect(owner).toMatchObject({
+ accountId: 'owner',
+ replaced: { epoch: 'epoch' },
+ });
+ expect(owner.epoch).not.toBe('epoch');
+ expect(await store.list(owner)).toEqual([]);
+ await expect(
+ store.save(previous, snapshot('Late edit', 1))
+ ).rejects.toThrow('no longer active');
+ await expect(
+ store.activate(
+ 'other-owner',
+ 'epoch',
+ () => true,
+ () => true
+ )
+ ).rejects.toThrow('no longer active');
+ });
+ it('returns a takeover that landed before the page saw an abort', async () => {
+ const store = open();
+ await store.activate('other-owner', 'epoch');
+ landBeforeAbort();
+ const owner = await store.activate(
+ 'owner',
+ 'epoch',
+ () => true,
+ () => true
+ );
+ expect(owner).toMatchObject({ replaced: { epoch: 'epoch' } });
+ expect(
+ await store.activate(
+ 'owner',
+ 'epoch',
+ () => true,
+ () => true
+ )
+ ).toEqual(owner);
+ });
it('merges upload receipts committed after a snapshot was captured', async () => {
const store = open();
const owner = await store.activate('owner');
diff --git a/apps/web/src/lib/queries/email/local-draft-store.ts b/apps/web/src/lib/queries/email/local-draft-store.ts
index 5bdd820c87..adfb79d90d 100644
--- a/apps/web/src/lib/queries/email/local-draft-store.ts
+++ b/apps/web/src/lib/queries/email/local-draft-store.ts
@@ -14,7 +14,12 @@ type AttemptRecord = DraftAttempt & {
transactionId: string;
storageGeneration: string;
};
-export type DraftStorageSession = { accountId: string; epoch: string };
+export type DraftStorageSession = {
+ accountId: string;
+ epoch: string;
+ /** The epoch this account took over from an account that never signed out, and when. */
+ replaced?: { epoch: string; at: number };
+};
/** `writeId` identifies the save that produced the record, so a replay can recognize its own commit. */
type StoredDraft = LocalDraft & { epoch: string; writeId?: string };
const STORES = ['drafts', 'files', 'attempts', 'sends', 'meta'] as const;
@@ -160,11 +165,16 @@ export function createLocalDraftStore(
);
});
return {
- /** Account transitions clear unapproved drafts, retain approved sends, and fence old transactions. */
+ /**
+ * Account transitions clear unapproved drafts, retain approved sends, and fence old transactions.
+ * Another account's session at the same epoch is fenced unless `replaceOtherAccount()` allows
+ * a takeover, which ends that session as its sign-out would and returns a new epoch.
+ */
async activate(
accountId: string,
epoch?: string,
- isCurrent = () => true
+ isCurrent = () => true,
+ replaceOtherAccount = () => false
): Promise<DraftStorageSession> {
const fenced = new Error('This draft session is no longer active');
const result = await transaction<DraftStorageSession | Error>(
@@ -173,20 +183,32 @@ export function createLocalDraftStore(
const meta = tx.objectStore('meta');
const retired = meta.get(['retired-session', epoch ?? '']);
retired.onsuccess = () => {
- if (epoch && retired.result) {
- finish(fenced);
- return;
- }
const request = meta.get('session');
request.onsuccess = () => {
const previous = request.result as
| DraftStorageSession
| undefined;
+ if (epoch && retired.result) {
+ // A takeover from this epoch already landed, in a replay of
+ // this transaction or in another page of the same account.
+ finish(
+ previous?.accountId === accountId &&
+ previous.replaced?.epoch === epoch &&
+ isCurrent()
+ ? previous
+ : fenced
+ );
+ return;
+ }
+ const otherAccount =
+ previous &&
+ previous.accountId !== accountId &&
+ (!epoch || previous.epoch === epoch)
+ ? previous
+ : undefined;
if (
!isCurrent() ||
- (previous &&
- previous.accountId !== accountId &&
- (!epoch || previous.epoch === epoch))
+ (otherAccount && !(epoch && replaceOtherAccount()))
) {
finish(fenced);
return;
@@ -200,10 +222,15 @@ export function createLocalDraftStore(
}
for (const name of STORES)
if (name !== 'sends') tx.objectStore(name).clear();
- const session = {
- accountId,
- epoch: epoch ?? crypto.randomUUID(),
- };
+ const session: DraftStorageSession = otherAccount
+ ? {
+ accountId,
+ epoch: crypto.randomUUID(),
+ replaced: { epoch: otherAccount.epoch, at: Date.now() },
+ }
+ : { accountId, epoch: epoch ?? crypto.randomUUID() };
+ if (otherAccount)
+ meta.put(true, ['retired-session', otherAccount.epoch]);
meta.put(session, 'session');
restoreEmailSendLocks(tx, accountId);
finish(session);
diff --git a/apps/web/src/lib/queries/email/local-drafts.test.ts b/apps/web/src/lib/queries/email/local-drafts.test.ts
index 8777ae07eb..305f5c5f49 100644
--- a/apps/web/src/lib/queries/email/local-drafts.test.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.test.ts
@@ -9,7 +9,11 @@ import type { OperationResult } from '@urql/core';
import { IDBFactory } from 'fake-indexeddb';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const auth = vi.hoisted(() => ({ user: { authenticated: true, id: 'owner' } }));
+const auth = vi.hoisted(() => ({
+ user: { authenticated: true, id: 'owner' },
+ // Whether this document fetched the identity, rather than restoring it.
+ confirmed: true,
+}));
const native = vi.hoisted(() => ({ active: false }));
vi.mock('@core/util/platform', () => ({ isTauri: () => native.active }));
const telemetry = vi.hoisted(() => ({
@@ -21,7 +25,10 @@ const stagedUpload = vi.hoisted(() =>
vi.fn<() => { previewSrc: string; size: number } | undefined>()
);
vi.mock('../client', () => ({
- queryClient: { getQueryData: () => auth.user },
+ queryClient: {
+ getQueryData: () => auth.user,
+ getQueryState: () => ({ dataUpdatedAt: auth.confirmed ? Date.now() : 0 }),
+ },
}));
vi.mock('@core/mobile/nativeStagedUpload', () => ({
getNativeStagedUpload: stagedUpload,
@@ -67,6 +74,7 @@ beforeEach(async () => {
localStorage.clear();
queue.length = 0;
auth.user = { authenticated: true, id: 'owner' };
+ auth.confirmed = true;
stagedUpload.mockReset();
native.active = false;
telemetry.track.mockClear();
@@ -627,6 +635,147 @@ describe('draft queue recovery', () => {
localStorage.setItem('email-working-copies:epoch', 'new-session');
await expect(runtime.listLocalDrafts()).rejects.toThrow('no longer active');
});
+ it('lets a new document take over storage another account left without signing out', async () => {
+ auth.user = { authenticated: true, id: 'other-owner' };
+ await runtime.saveLocalDraft(input('Other account draft'));
+ await runtime.localDraftStore.close();
+ vi.resetModules();
+ auth.user = { authenticated: true, id: 'owner' };
+ runtime = await import('./local-drafts');
+ expect(await runtime.listLocalDrafts()).toEqual([]);
+ await runtime.saveLocalDraft(input('Owner draft'));
+ expect(await runtime.listLocalDrafts()).toHaveLength(1);
+ });
+ it('does not take over for an identity this document only restored', async () => {
+ const live = runtime;
+ await live.saveLocalDraft(input('Live draft'));
+ vi.resetModules();
+ auth.user = { authenticated: true, id: 'previous-owner' };
+ auth.confirmed = false;
+ const restored = await import('./local-drafts');
+ await expect(restored.listLocalDrafts()).rejects.toThrow(
+ 'no longer active'
+ );
+ auth.user = { authenticated: true, id: 'owner' };
+ expect(
+ (await live.listLocalDrafts()).map((draft) => draft.content.subject)
+ ).toEqual(['Live draft']);
+ await restored.localDraftStore.close();
+ });
+ it('fences a write captured before switching accounts away and back', async () => {
+ const prior = await runtime.saveLocalDraft(input('Before switch'));
+ const captured = await runtime.emailStorageSession();
+ for (const id of ['other-owner', 'owner']) {
+ vi.resetModules();
+ auth.user = { authenticated: true, id };
+ const page = await import('./local-drafts');
+ await page.listLocalDrafts();
+ await page.localDraftStore.close();
+ }
+ await expect(
+ runtime.localDraftStore.save(captured, {
+ ...prior,
+ key: 'late',
+ draftId: 'late',
+ expectedRevision: 0,
+ })
+ ).rejects.toThrow('no longer active');
+ });
+ it('discards draft saves the previous account queued before a takeover', async () => {
+ auth.user = { authenticated: true, id: 'other-owner' };
+ await runtime.listLocalDrafts();
+ queue.push({
+ transactionId: 'previous',
+ uuid: 'local',
+ operationName: 'SaveEmailDraft',
+ query: 'mutation SaveEmailDraft { saveEmailDraft { draftId } }',
+ superseded: false,
+ enqueuedAtMs: Date.now() - 1_000,
+ variables: { input: { draftId: 'local', subject: 'Private' } },
+ optimisticData: { saveEmailDraft: { draft: {} } },
+ });
+ await runtime.localDraftStore.close();
+ vi.resetModules();
+ auth.user = { authenticated: true, id: 'owner' };
+ runtime = await import('./local-drafts');
+ const lifecycle = runtime.localDraftQueueLifecycle(host);
+ await lifecycle.prepareMutationQueue!();
+ expect(await runtime.listLocalDrafts()).toEqual([]);
+ expect(
+ await lifecycle.beforeMutationAttempt!({
+ ...claimed(undefined),
+ transactionId: 'previous',
+ })
+ ).toBe(false);
+ });
+ it('tells a document when another tab ends its session', async () => {
+ await runtime.saveLocalDraft(input());
+ const ended = vi.fn();
+ const stop = runtime.watchEmailStorageEnded('owner', ended);
+ localStorage.setItem('email-working-copies:epoch', 'another-tab');
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'email-working-copies:epoch' })
+ );
+ stop();
+ expect(ended).toHaveBeenCalledOnce();
+ });
+ it('does not end a document that is signing itself out', async () => {
+ await runtime.saveLocalDraft(input());
+ const ended = vi.fn();
+ const stop = runtime.watchEmailStorageEnded('owner', ended);
+ await runtime.clearLocalDrafts();
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'email-working-copies:epoch' })
+ );
+ stop();
+ expect(ended).not.toHaveBeenCalled();
+ });
+ it('tells a document restored from the back/forward cache that its session ended', async () => {
+ await runtime.saveLocalDraft(input());
+ const ended = vi.fn();
+ const stop = runtime.watchEmailStorageEnded('owner', ended);
+ // The storage event fired while the document was cached.
+ localStorage.setItem('email-working-copies:epoch', 'another-tab');
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ stop();
+ expect(ended).toHaveBeenCalledOnce();
+ });
+ it('tells a document when the signed-in account is no longer its own', async () => {
+ await runtime.saveLocalDraft(input());
+ const ended = vi.fn();
+ runtime.watchEmailStorageEnded('other-owner', ended)();
+ expect(ended).toHaveBeenCalledOnce();
+ });
+ it('does not write a takeover epoch over a sign-out that ran meanwhile', async () => {
+ auth.user = { authenticated: true, id: 'other-owner' };
+ await runtime.listLocalDrafts();
+ await runtime.localDraftStore.close();
+ vi.resetModules();
+ auth.user = { authenticated: true, id: 'owner' };
+ runtime = await import('./local-drafts');
+ let signOut: Promise<void> | undefined;
+ const put = IDBObjectStore.prototype.put;
+ vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementation(function (
+ this: IDBObjectStore,
+ value: unknown,
+ key?: IDBValidKey
+ ) {
+ const request = put.call(this, value, key);
+ // The sign-out starts after the takeover passed its checks.
+ if (key === 'session' && !signOut) signOut = runtime.clearLocalDrafts();
+ return request;
+ });
+ await expect(runtime.emailStorageSession()).rejects.toThrow(
+ 'no longer active'
+ );
+ const signedOutEpoch = localStorage.getItem('email-working-copies:epoch');
+ await signOut;
+ expect(localStorage.getItem('email-working-copies:epoch')).toBe(
+ signedOutEpoch
+ );
+ });
it('rejects delayed old-editor work after logout even if authentication changes', async () => {
const prior = await runtime.saveLocalDraft(input());
const owner = await runtime.localDraftStore.activate('owner');
diff --git a/apps/web/src/lib/queries/email/local-drafts.ts b/apps/web/src/lib/queries/email/local-drafts.ts
index bac7e4f46d..d3a78c0eeb 100644
--- a/apps/web/src/lib/queries/email/local-drafts.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.ts
@@ -20,7 +20,10 @@ import type { OperationResult } from '@urql/core';
import { authKeys } from '../auth/keys';
import type { UserInfoData } from '../auth/user-info';
import { queryClient } from '../client';
-import { createLocalDraftStore } from './local-draft-store';
+import {
+ createLocalDraftStore,
+ type DraftStorageSession,
+} from './local-draft-store';
import type { EmailSendIntent } from './send-intent';
@@ -42,6 +45,7 @@ const nativeUploadLocks = new Map<string, Promise<void>>();
const pendingWrites = new Set<Promise<LocalDraft>>();
const EPOCH_KEY = 'email-working-copies:epoch';
let documentSession: { accountId: string; epoch: string } | undefined;
+let documentSessionOpened = false;
let retiredSession = false;
function storageEpoch() {
@@ -109,21 +113,85 @@ export async function emailStorageSession() {
}
documentSession ??= { accountId: user.id, epoch };
const expected = documentSession;
- return await localDraftStore.activate(
- expected.accountId,
- expected.epoch,
- () => {
- const current = queryClient.getQueryData<UserInfoData>(
- authKeys.userInfo.queryKey
- );
- return (
- !retiredSession &&
- current?.authenticated === true &&
- current.id === expected.accountId &&
- localStorage.getItem(EPOCH_KEY) === expected.epoch
- );
- }
- );
+ let session: DraftStorageSession;
+ try {
+ session = await localDraftStore.activate(
+ expected.accountId,
+ expected.epoch,
+ () => {
+ const current = queryClient.getQueryData<UserInfoData>(
+ authKeys.userInfo.queryKey
+ );
+ return (
+ !retiredSession &&
+ current?.authenticated === true &&
+ current.id === expected.accountId &&
+ localStorage.getItem(EPOCH_KEY) === expected.epoch
+ );
+ },
+ // Signing in over another account skips the sign-out that would end
+ // its session, so it still owns this epoch. Take over only from a
+ // document that has not opened storage (one that has is that account's
+ // stale tab) and whose account this document confirmed with the server
+ // (a restored identity can still name the previous account).
+ () =>
+ !documentSessionOpened &&
+ (queryClient.getQueryState(authKeys.userInfo.queryKey)?.dataUpdatedAt ??
+ 0) >= performance.timeOrigin
+ );
+ } catch (error) {
+ // A concurrent call in this document took the storage over meanwhile.
+ if (documentSession !== expected) return await emailStorageSession();
+ throw error;
+ }
+ if (session.epoch !== expected.epoch) {
+ const current = localStorage.getItem(EPOCH_KEY);
+ // A sign-out that ran meanwhile owns the epoch; never write over it.
+ if (
+ retiredSession ||
+ (current !== expected.epoch && current !== session.epoch)
+ )
+ throw new Error('This draft session is no longer active');
+ localStorage.setItem(EPOCH_KEY, session.epoch);
+ documentSession = { accountId: session.accountId, epoch: session.epoch };
+ }
+ documentSessionOpened = true;
+ return session;
+}
+
+/**
+ * Calls `ended` when this document's session can never reopen: another tab
+ * moved the epoch off it (a sign-out or another account's takeover), or the
+ * signed-in account is no longer the session's. A document signing itself
+ * out is excluded.
+ */
+export function watchEmailStorageEnded(
+ accountId: string,
+ ended: () => void
+): () => void {
+ const check = () => {
+ if (
+ documentSession &&
+ !retiredSession &&
+ (documentSession.accountId !== accountId ||
+ localStorage.getItem(EPOCH_KEY) !== documentSession.epoch)
+ )
+ ended();
+ };
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === EPOCH_KEY || event.key === null) check();
+ };
+ // A document restored from the back/forward cache missed storage events.
+ const onShow = (event: PageTransitionEvent) => {
+ if (event.persisted) check();
+ };
+ window.addEventListener('storage', onStorage);
+ window.addEventListener('pageshow', onShow);
+ check();
+ return () => {
+ window.removeEventListener('storage', onStorage);
+ window.removeEventListener('pageshow', onShow);
+ };
}
export async function listLocalDrafts(): Promise<LocalDraft[]> {
@@ -586,6 +654,7 @@ export function localDraftQueueLifecycle(
let initialized: Promise<void> | undefined;
const legacy = new Map<string, DraftAttempt>();
const migrated = new Map<string, number>();
+ const previousAccount = new Set<string>();
async function ownedBySend(mutation: ClaimedMutation | MutationInspection) {
if (
mutation.operationName !== 'SaveEmailDraft' &&
@@ -630,6 +699,12 @@ export function localDraftQueueLifecycle(
const known = legacy.get(mutation.transactionId);
if (known) return known;
const owner = await emailStorageSession();
+ // Queued before this account took the storage over: the previous account
+ // never signed out, and its sign-out would have discarded this intent.
+ if (owner.replaced && !((mutation.enqueuedAtMs ?? 0) > owner.replaced.at)) {
+ previousAccount.add(mutation.transactionId);
+ return;
+ }
const storageGeneration = await host.currentStorageGeneration();
const saved = (await localDraftStore.attempts(owner)).find(
(entry) =>
@@ -844,7 +919,7 @@ export function localDraftQueueLifecycle(
return 'defer';
if (await ownedBySend(mutation)) return false;
const attempt = await resolveAttempt(mutation);
- if (!attempt) return true;
+ if (!attempt) return !previousAccount.has(mutation.transactionId);
const owner = await emailStorageSession();
if (owner.accountId !== attempt.accountId) return false;
const local = await localDraftStore.read(owner, attempt.draftKey);
diff --git a/apps/web/src/lib/queries/email/outbox-session.test.ts b/apps/web/src/lib/queries/email/outbox-session.test.ts
index b3350a2b7f..d86c43d5fd 100644
--- a/apps/web/src/lib/queries/email/outbox-session.test.ts
+++ b/apps/web/src/lib/queries/email/outbox-session.test.ts
@@ -3,13 +3,28 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { setEmailOutboxSession } from './outbox-session';
import { useQueuedEmailSends } from './queued-sends';
-const mocks = vi.hoisted(() => ({
- read: vi.fn(),
- dispatcher: vi.fn(() => ({ dispose() {} })),
-}));
+const mocks = vi.hoisted(() => {
+ let release = () => {};
+ return {
+ read: vi.fn(),
+ dispatcher: vi.fn(() => ({ dispose() {} })),
+ reloadApp: vi.fn(),
+ flush: vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ })
+ ),
+ release: () => release(),
+ // Whether this page's draft session already ended outside it.
+ sessionEnded: false,
+ };
+});
vi.mock('@macro-inc/observability', () => ({
Telemetry: { info: vi.fn(), warn: vi.fn() },
}));
+vi.mock('@app/observability/reload', () => ({ reloadApp: mocks.reloadApp }));
+vi.mock('../client', () => ({ queryPersistence: { flush: mocks.flush } }));
vi.mock('@service-storage/email-send', () => ({
cancelEmailSend: vi.fn(),
readEmailSendStatus: vi.fn(),
@@ -24,6 +39,10 @@ vi.mock('./email-send-recovery', () => ({
vi.mock('./local-drafts', () => ({
emailStorageSession: async () => ({ accountId: 'owner', epoch: 'epoch' }),
localDraftStore: {},
+ watchEmailStorageEnded: (_accountId: string, ended: () => void) => {
+ if (mocks.sessionEnded) ended();
+ return () => {};
+ },
}));
vi.mock('./server-sends', () => ({ setServerSendSession: vi.fn() }));
vi.mock('./send-queue', () => ({
@@ -33,6 +52,7 @@ vi.mock('./send-queue', () => ({
beforeEach(() => {
vi.clearAllMocks();
+ mocks.sessionEnded = false;
vi.stubGlobal('window', { addEventListener() {}, removeEventListener() {} });
});
afterEach(() => {
@@ -56,3 +76,16 @@ it('has the outbox ready for the first compose after sign-in', async () => {
dispose();
}
});
+
+it('persists the signed-in identity before reloading a page whose draft session ended', async () => {
+ mocks.read.mockResolvedValue([]);
+ mocks.sessionEnded = true;
+ setEmailOutboxSession('owner');
+ await Promise.resolve();
+ expect(mocks.flush).toHaveBeenCalledOnce();
+ expect(mocks.reloadApp).not.toHaveBeenCalled();
+ mocks.release();
+ await vi.waitFor(() =>
+ expect(mocks.reloadApp).toHaveBeenCalledWith('logout')
+ );
+});
diff --git a/apps/web/src/lib/queries/email/outbox-session.ts b/apps/web/src/lib/queries/email/outbox-session.ts
index eb039d23b7..da355b1a84 100644
--- a/apps/web/src/lib/queries/email/outbox-session.ts
+++ b/apps/web/src/lib/queries/email/outbox-session.ts
@@ -1,12 +1,18 @@
+import { reloadApp } from '@app/observability/reload';
import { fireAndForget } from '@core/util/fireAndForget';
import {
cancelEmailSend,
readEmailSendStatus,
submitEmailSend,
} from '@service-storage/email-send';
+import { queryPersistence } from '../client';
import { createEmailSendDispatcher } from './email-send-dispatcher';
import { createEmailSendRecovery } from './email-send-recovery';
-import { emailStorageSession, localDraftStore } from './local-drafts';
+import {
+ emailStorageSession,
+ localDraftStore,
+ watchEmailStorageEnded,
+} from './local-drafts';
import { setQueuedSendSession } from './queued-sends';
import {
emailSendFailureKind,
@@ -20,6 +26,7 @@ let generation = 0;
let dispatcher: ReturnType<typeof createEmailSendDispatcher> | undefined;
let retry: ReturnType<typeof setTimeout> | undefined;
let recovery: ReturnType<typeof createEmailSendRecovery> | undefined;
+let stopWatching: (() => void) | undefined;
/** Called by the authenticated app shell, not by individual email surfaces. */
export function setEmailOutboxSession(accountId: string | undefined): void {
@@ -31,9 +38,27 @@ export function setEmailOutboxSession(accountId: string | undefined): void {
recovery?.dispose();
recovery = undefined;
dispatcher = undefined;
+ stopWatching?.();
+ stopWatching = undefined;
setServerSendSession(accountId);
setQueuedSendSession(accountId);
- if (accountId) fireAndForget(start(accountId, current), 'email-outbox');
+ if (!accountId) return;
+ // This page's draft session ended outside it; only a new page can reopen
+ // drafts. This page's own sign-out clears the account first, so it never
+ // reloads here.
+ stopWatching = watchEmailStorageEnded(accountId, () =>
+ fireAndForget(reloadForNewSession(), 'email-outbox')
+ );
+ fireAndForget(start(accountId, current), 'email-outbox');
+}
+
+/** Persist the current identity first, or the new page could restore the old one and reload again. */
+async function reloadForNewSession() {
+ try {
+ await queryPersistence.flush();
+ } finally {
+ reloadApp('logout');
+ }
}
async function start(accountId: string, current: number) {
diff --git a/apps/web/src/routes/BasePath.test.tsx b/apps/web/src/routes/BasePath.test.tsx
index 8031dc323f..07a354440f 100644
--- a/apps/web/src/routes/BasePath.test.tsx
+++ b/apps/web/src/routes/BasePath.test.tsx
@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({
hasLoginCookie: true,
nativeMobile: false,
navigate: vi.fn(),
+ reloadApp: vi.fn(),
+ tauri: false,
routerSearch: (): string => '',
setRouterSearch: (_value: string) => {},
}));
@@ -29,6 +31,15 @@ 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,
}));
@@ -83,6 +94,7 @@ vi.mock('@solidjs/router', async () => {
mocks.navigate(props.href, { replace: true });
return null;
},
+ useNavigate: () => mocks.navigate,
useLocation: () => ({
get search() {
return search();
@@ -155,6 +167,8 @@ function flush() {
beforeEach(() => {
mocks.hasLoginCookie = true;
mocks.nativeMobile = false;
+ mocks.tauri = false;
+ mocks.reloadApp.mockReset();
mocks.setRouterSearch('');
mocks.navigate.mockReset();
mocks.fetchUserInfo.mockReset();
@@ -168,6 +182,7 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.unstubAllGlobals();
dispose?.();
dispose = undefined;
setPendingNotificationNavigationId(undefined);
@@ -282,6 +297,7 @@ describe('BasePathComponent', () => {
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());
@@ -296,6 +312,7 @@ describe('BasePathComponent', () => {
replace: true,
}
);
+ expect(mocks.reloadApp).toHaveBeenCalledWith('logout');
});
});
@@ -362,7 +379,14 @@ describe('BasePathComponent', () => {
expect(mocks.confirmSessionExpired).not.toHaveBeenCalled();
});
- it('clears the session and redirects on a confirmed expiry', async () => {
+ 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);
@@ -370,9 +394,57 @@ describe('BasePathComponent', () => {
await vi.waitFor(() => {
expect(mocks.clearLocalAuthSession).toHaveBeenCalled();
- expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {
- replace: true,
- });
+ 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');
});
});
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 1f2a1ff798..3f1cd96d33 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -72,9 +72,11 @@ draft queue runner, or live-update subscriptions. Signing in activates them in
the same tab, including after a session expiry. Queued draft writes wait for
authenticated user info; unrelated mutations can continue draining.
-Verify expiry followed by signing into a different account without reloading:
-the new account's lists must load and receive live updates, and the previous
-account's cached data must be absent. Logout wipes local caches before retiring
+A confirmed expiry loads `/welcome` as a new page, as logout does, so email
+drafts work after the next sign-in. Verify expiry followed by signing into a
+different account: the new account's lists must load and receive live updates,
+email composers must accept input, and the previous account's cached data must
+be absent. Logout wipes local caches before retiring
their clients. Mounted query observers must receive the next account's data
after the wipe. Previous account data must not return through initial data,
placeholder data, or a later query reset.
diff --git a/docs/architecture/email.md b/docs/architecture/email.md
index 25c1909868..119661f9c6 100644
--- a/docs/architecture/email.md
+++ b/docs/architecture/email.md
@@ -554,6 +554,18 @@ fences the prior local lifetime, and retires send authority atomically. Newer
local edits and file bytes survive restoration. Sign-out retains approved sends
under their original account and stops dispatch; ordinary drafts retain their
existing sign-out policy.
+Signing into another account without signing out ends the previous account's
+draft session the same way: the first page that opens draft storage with an
+identity it confirmed with the server retires the old epoch, starts a new one,
+clears the previous working copies, keeps approved sends, and discards draft
+saves the previous account queued before the takeover. Pages that already
+opened storage, or whose identity is only restored, stay fenced. When a page's
+draft session ends outside it (another tab's sign-out, expiry, or takeover,
+including one missed in the back/forward cache, or a different signed-in
+account), the outbox session reloads that page; a page signing itself out does
+not. A confirmed
+session expiry loads `/welcome` as a new page, as sign-out does, because a
+cleared draft session never reopens in the same page.
The server accepts the frozen message, attachment set, send attempt, and delivery
job in one Postgres transaction. The existing recovery scanner and Gmail/Outlook