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): preserve thread scroll during draft saves (#8161)

Peter Chinmanef62593d156d
diff --git a/Cargo.lock b/Cargo.lock
index 29205ee03e..b8d2484400 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16877,6 +16877,7 @@ dependencies = [
"ego-tree",
"getopts",
"html5ever 0.26.0",
+ "indexmap 2.14.0",
"once_cell",
"selectors 0.25.0",
"tendril 0.4.3",
@@ -21975,6 +21976,7 @@ dependencies = [
"rustls-webpki 0.103.15",
"schemars 1.2.1",
"scopeguard",
+ "scraper",
"security-framework-sys",
"semver",
"serde",
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ca273991d3..0ca215be01 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -67,6 +67,10 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
### General
- All API/network calls live in service-clients.
+- Draft autosaves preserve active email thread messages; evict inactive legacy
+ caches on save and the active cache on thread exit. Revalidate GraphQL thread
+ pages only when a save cannot patch the message list (missing snapshot or a
+ move between inboxes).
- Shared server-state queries and mutations live in `src/lib/queries`; keep
feature-specific query orchestration with its owning feature.
- Reactive GraphQL reads use `createLiveQuery` for a document and
diff --git a/apps/web/src/lib/queries/email/draft-cache.test.ts b/apps/web/src/lib/queries/email/draft-cache.test.ts
new file mode 100644
index 0000000000..c1d8c0542e
--- /dev/null
+++ b/apps/web/src/lib/queries/email/draft-cache.test.ts
@@ -0,0 +1,69 @@
+import { QueryClient, QueryObserver } from '@tanstack/query-core';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import {
+ clearSavedDraftThreadCache,
+ markThreadDraftSaved,
+} from './draft-cache';
+import { emailKeys } from './keys';
+
+vi.mock('../client', () => ({
+ get queryClient() {
+ return client;
+ },
+}));
+
+let client: QueryClient;
+
+beforeEach(() => {
+ client = new QueryClient();
+});
+
+afterEach(() => {
+ clearSavedDraftThreadCache('thread');
+ client.clear();
+});
+
+it('evicts inactive messages when a save finishes after thread cleanup', () => {
+ const key = emailKeys.threadMessages('thread').queryKey;
+ const otherKey = emailKeys.threadMessages('other-thread').queryKey;
+ const metadataKey = emailKeys.thread('thread').queryKey;
+ client.setQueryData(key, { body: 'Old draft' });
+ client.setQueryData(otherKey, { body: 'Other draft' });
+ client.setQueryData(metadataKey, { subject: 'Subject' });
+ clearSavedDraftThreadCache('thread');
+
+ markThreadDraftSaved('thread');
+
+ expect(client.getQueryState(key)).toBeUndefined();
+ expect(client.getQueryData(otherKey)).toEqual({ body: 'Other draft' });
+ expect(client.getQueryData(metadataKey)).toEqual({ subject: 'Subject' });
+});
+
+it('preserves active messages and their state until thread cleanup', () => {
+ const key = emailKeys.threadMessages('thread').queryKey;
+ const data = { body: 'Visible draft' };
+ client.setQueryData(key, data);
+ const fetch = vi.fn(async () => data);
+ const observer = new QueryObserver(client, {
+ queryKey: key,
+ queryFn: fetch,
+ staleTime: Infinity,
+ });
+ const changed = vi.fn();
+ const unsubscribe = observer.subscribe(changed);
+ const query = client.getQueryCache().find({ queryKey: key });
+ const state = client.getQueryState(key);
+
+ markThreadDraftSaved('thread');
+ markThreadDraftSaved('thread');
+
+ expect(client.getQueryCache().find({ queryKey: key })).toBe(query);
+ expect(client.getQueryState(key)).toBe(state);
+ expect(client.getQueryData(key)).toBe(data);
+ expect(changed).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+
+ unsubscribe();
+ clearSavedDraftThreadCache('thread');
+ expect(client.getQueryState(key)).toBeUndefined();
+});
diff --git a/apps/web/src/lib/queries/email/draft-cache.ts b/apps/web/src/lib/queries/email/draft-cache.ts
index 9f8f3ad1b5..39ee882eed 100644
--- a/apps/web/src/lib/queries/email/draft-cache.ts
+++ b/apps/web/src/lib/queries/email/draft-cache.ts
@@ -7,6 +7,11 @@ const savedThreads = new Set<string>();
export function markThreadDraftSaved(threadId: string) {
savedThreads.add(threadId);
+ // A save can settle after thread cleanup, or without mounting the thread.
+ queryClient.removeQueries({
+ queryKey: emailKeys.threadMessages(threadId).queryKey,
+ type: 'inactive',
+ });
}
export function clearSavedDraftThreadCache(threadId: string) {
diff --git a/apps/web/src/lib/queries/email/draft-queue.test.ts b/apps/web/src/lib/queries/email/draft-queue.test.ts
index d2ae9c87ca..48f80ea071 100644
--- a/apps/web/src/lib/queries/email/draft-queue.test.ts
+++ b/apps/web/src/lib/queries/email/draft-queue.test.ts
@@ -8,6 +8,10 @@ import type {
import { type Client, createClient, type Operation } from '@urql/core';
import { beforeEach, expect, it, vi } from 'vitest';
import { map, pipe } from 'wonka';
+import { queryClient } from '../client';
+import { refetchSoupEntity } from '../soup/cache';
+import { markThreadDraftSaved } from './draft-cache';
+import { emailKeys } from './keys';
import {
localDraftMessage,
readLocalDraft,
@@ -80,9 +84,11 @@ beforeEach(() => {
vi.resetAllMocks();
mocks.queueBlocked = false;
mocks.cacheEnabled = true;
+ vi.mocked(queryClient.invalidateQueries).mockResolvedValue(undefined);
+ vi.mocked(refetchSoupEntity).mockResolvedValue(undefined);
});
-async function setup() {
+async function setup(committed = false) {
const operations: Operation[] = [];
const client = createClient({
url: 'http://example.test/graphql',
@@ -96,9 +102,12 @@ async function setup() {
operation,
stale: false,
hasNext: false,
+ ...(committed
+ ? { data: optimisticContextOf(operation)?.optimisticResponse }
+ : {}),
extensions: {
normalizedCacheMutationDisposition: {
- kind: 'queued',
+ kind: committed ? 'committed' : 'queued',
transactionId: 'queued',
},
},
@@ -152,6 +161,23 @@ async function setup() {
return { operations, local, draftResult, threadResult };
}
+it('keeps active thread messages intact after a committed draft save', async () => {
+ await setup(true);
+ expect(await saveEmailDraftQueued({ args })).toEqual({
+ kind: 'committed',
+ draftId: serverId,
+ threadId: 'server-thread',
+ });
+ expect(markThreadDraftSaved).toHaveBeenCalledWith('server-thread');
+ expect(queryClient.invalidateQueries).toHaveBeenCalledExactlyOnceWith({
+ queryKey: emailKeys.previews._def,
+ });
+ expect(refetchSoupEntity).toHaveBeenCalledWith(
+ 'server-thread',
+ 'emailThread'
+ );
+});
+
it.each(['save', 'delete'] as const)(
'blocks an uncached fallback %s before changing local intent or sending a request',
async (operation) => {
diff --git a/apps/web/src/lib/queries/email/draft-queue.ts b/apps/web/src/lib/queries/email/draft-queue.ts
index 117f13f759..ae6f65e287 100644
--- a/apps/web/src/lib/queries/email/draft-queue.ts
+++ b/apps/web/src/lib/queries/email/draft-queue.ts
@@ -328,9 +328,6 @@ export async function saveEmailDraftQueued(input: {
reportError
);
}
- void queryClient.invalidateQueries({
- queryKey: emailKeys.threadMessages(outcome.threadId).queryKey,
- });
} catch (error) {
reportError(error);
}
diff --git a/apps/web/src/lib/queries/email/draft.ts b/apps/web/src/lib/queries/email/draft.ts
index 1d1df75cce..00015c0011 100644
--- a/apps/web/src/lib/queries/email/draft.ts
+++ b/apps/web/src/lib/queries/email/draft.ts
@@ -10,6 +10,7 @@ import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { refreshEmailThreadCache } from './cache-cleanup';
+import { markThreadDraftSaved } from './draft-cache';
import { emailKeys } from './keys';
type CreateDraftParams = {
@@ -47,18 +48,12 @@ export function useSaveDraftMutation(
.catch(Telemetry.error);
const threadId = data.draft.thread_db_id;
if (!threadId) return;
+ markThreadDraftSaved(threadId);
if (!vars.skipSoupRefetch) {
void refetchSoupEntity(threadId, 'emailThread').catch(
Telemetry.error
);
}
- // Reopening the thread reads the messages cache; drop it so the
- // saved draft body isn't served stale.
- void queryClient
- .invalidateQueries({
- queryKey: emailKeys.threadMessages(threadId).queryKey,
- })
- .catch(Telemetry.error);
} catch (error) {
Telemetry.error(error);
}
diff --git a/apps/web/src/lib/queries/email/graphql/draft.test.ts b/apps/web/src/lib/queries/email/graphql/draft.test.ts
index 0f0d873483..da83e565b5 100644
--- a/apps/web/src/lib/queries/email/graphql/draft.test.ts
+++ b/apps/web/src/lib/queries/email/graphql/draft.test.ts
@@ -137,6 +137,7 @@ it('creates a complete standalone thread with the account classification and sta
cacheProjection: null,
});
expect(thread.mailDraftState?.baseline.messageCount).toBe(0);
+ expect(optimisticContextOf(operations[0])?.revalidations).toEqual([]);
expect(optimisticContextOf(operations[0])?.identityBindings).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -219,6 +220,7 @@ it('keeps canonical same-inbox reply updates without aliasing the conversation',
})
);
expect(context.linkPatches).toHaveLength(1);
+ expect(context.revalidations).toEqual([]);
expect(context.optimisticResponse).toMatchObject({
saveEmailDraft: {
thread: { id: args.threadDbId, messages: [{ id: args.draftId }] },
@@ -240,6 +242,9 @@ it('does not infer a local thread from an uncached reply hint', async () => {
})
);
expect(context.linkPatches).toEqual([]);
+ expect(context.revalidations).toContainEqual(
+ expect.objectContaining({ operationName: 'EmailThreadPage' })
+ );
});
it.each([args.senderLinkId, 'other-inbox'])(
diff --git a/apps/web/src/lib/queries/email/graphql/draft.ts b/apps/web/src/lib/queries/email/graphql/draft.ts
index 3f6cd60385..1ec4e9b620 100644
--- a/apps/web/src/lib/queries/email/graphql/draft.ts
+++ b/apps/web/src/lib/queries/email/graphql/draft.ts
@@ -240,8 +240,8 @@ function optimisticDraftEntity(
* full message entity spliced into the thread page's message list — so a
* reopened composer (or a relaunched app) sees the draft through the
* ordinary thread read. On commit the layer is replaced by the server's
- * records, and the persisted thread-page revalidation reconciles list
- * membership and any attachment state this record cannot know.
+ * records. Soup revalidation reconciles list membership; the thread page
+ * only needs a separate read when its message list cannot be patched.
*/
export async function executeGraphqlSaveEmailDraft(
client: Client,
@@ -350,10 +350,17 @@ export async function executeGraphqlSaveEmailDraft(
: [],
revalidations: [
...getActiveGraphqlSoupRevalidations(),
- {
- document: EmailThreadPageDocument,
- variables: threadPageVariables,
- },
+ // Ordinary autosaves already return the draft and thread records.
+ // Refetch only when a missing snapshot or inbox move prevents the
+ // message-list patch; otherwise a save can reset the open thread.
+ ...(canPatchThread
+ ? []
+ : [
+ {
+ document: EmailThreadPageDocument,
+ variables: threadPageVariables,
+ },
+ ]),
],
}
).toPromise();
diff --git a/apps/web/src/lib/queries/email/write-completion.test.tsx b/apps/web/src/lib/queries/email/write-completion.test.tsx
index fd7b9f0fb0..41aacb08c6 100644
--- a/apps/web/src/lib/queries/email/write-completion.test.tsx
+++ b/apps/web/src/lib/queries/email/write-completion.test.tsx
@@ -1,6 +1,8 @@
import { err, ok } from 'neverthrow';
import { beforeEach, expect, it, vi } from 'vitest';
import { useSaveDraftMutation } from './draft';
+import { clearSavedDraftThreadCache } from './draft-cache';
+import { emailKeys } from './keys';
import { mountEmailMutation } from './tests/mutation';
import { useSendMessageMutation, useUnscheduleMessageMutation } from './thread';
@@ -9,6 +11,7 @@ const mocks = vi.hoisted(() => ({
send: vi.fn(),
unschedule: vi.fn(),
invalidate: vi.fn(),
+ remove: vi.fn(),
refetch: vi.fn(),
track: vi.fn(),
report: vi.fn(),
@@ -22,7 +25,10 @@ vi.mock('@service-email/client', () => ({
},
}));
vi.mock('../client', () => ({
- queryClient: { invalidateQueries: mocks.invalidate },
+ queryClient: {
+ invalidateQueries: mocks.invalidate,
+ removeQueries: mocks.remove,
+ },
}));
vi.mock('../soup/cache', () => ({
refetchSoupEntity: mocks.refetch,
@@ -72,6 +78,31 @@ it('returns the saved identity when a subsequent cache refresh rejects', async (
expect(mocks.save.mock.calls[0][0]).not.toHaveProperty('send_time');
});
+it('defers saved thread message eviction until leaving the thread', async () => {
+ mocks.save.mockResolvedValue(
+ ok({
+ draft: { db_id: 'draft', thread_db_id: 'saved-thread', link_id: 'inbox' },
+ })
+ );
+ const mutation = mountEmailMutation(useSaveDraftMutation);
+ await mutation.mutateAsync({ draft: { subject: 'Saved' } });
+ expect(mocks.invalidate).toHaveBeenCalledExactlyOnceWith({
+ queryKey: emailKeys.previews._def,
+ });
+ expect(mocks.refetch).toHaveBeenCalledWith('saved-thread', 'emailThread');
+ expect(mocks.remove).toHaveBeenCalledExactlyOnceWith({
+ queryKey: emailKeys.threadMessages('saved-thread').queryKey,
+ type: 'inactive',
+ });
+ mocks.remove.mockClear();
+ clearSavedDraftThreadCache('saved-thread');
+ expect(mocks.remove).toHaveBeenCalledExactlyOnceWith({
+ queryKey: emailKeys.threadMessages('saved-thread').queryKey,
+ });
+ clearSavedDraftThreadCache('saved-thread');
+ expect(mocks.remove).toHaveBeenCalledOnce();
+});
+
it('keeps send successful and reconciles caches when analytics throws', async () => {
const response = {
message: { db_id: 'sent', thread_db_id: 'thread', link_id: 'inbox' },
diff --git a/crates/email_utils/AGENTS.md b/crates/email_utils/AGENTS.md
index 83eb3d08ef..544ee8118d 100644
--- a/crates/email_utils/AGENTS.md
+++ b/crates/email_utils/AGENTS.md
@@ -41,6 +41,8 @@ sender/generic-address checks.
## Gotchas
+- Enable `scraper`'s `deterministic` feature: thread reads recompute replyless
+ HTML, and shuffled attributes rebuild otherwise unchanged email bodies.
- Sanitization is security-sensitive (XSS via email HTML): any allowlist
change needs a test proving the previously-dangerous input is now stripped,
not just that benign input survives.
diff --git a/crates/email_utils/Cargo.toml b/crates/email_utils/Cargo.toml
index d21dc0bc07..e5cad19c31 100644
--- a/crates/email_utils/Cargo.toml
+++ b/crates/email_utils/Cargo.toml
@@ -10,6 +10,6 @@ ego-tree = { workspace = true }
html2text = "0.16.5"
lazy_static = { workspace = true }
regex = { workspace = true }
-scraper = { workspace = true }
+scraper = { workspace = true, features = ["deterministic"] }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/email_utils/src/body_replyless/test.rs b/crates/email_utils/src/body_replyless/test.rs
index 81b5fa3f31..9b41d372df 100644
--- a/crates/email_utils/src/body_replyless/test.rs
+++ b/crates/email_utils/src/body_replyless/test.rs
@@ -1,5 +1,18 @@
use super::compute_body_replyless;
+#[test]
+fn reply_html_preserves_attribute_order_across_thread_reads() {
+ let html = r#"<div dir="ltr" class="reply" style="color: blue"><a href="https://example.com" title="A &amp; B" target="_blank">Reply</a></div><blockquote>Older message</blockquote>"#;
+ let expected = r#"<div dir="ltr" class="reply" style="color: blue"><a href="https://example.com" title="A &amp; B" target="_blank">Reply</a></div>"#;
+
+ for _ in 0..32 {
+ assert_eq!(
+ compute_body_replyless(None, Some(html), None).as_deref(),
+ Some(expected)
+ );
+ }
+}
+
#[test]
fn test_extract_message_reply_outlook_test_1() {
let full_email = include_str!("testdata/outlook-test-1/full.html");
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index 0c01022733..9d2ad4288f 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -123,6 +123,7 @@ rustls = { version = "0.23", default-features = false, features = ["logging", "p
rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }
schemars = { version = "1", features = ["chrono04", "uuid1"] }
scopeguard = { version = "1" }
+scraper = { version = "0.18", features = ["deterministic"] }
semver = { version = "1", features = ["serde"] }
serde = { version = "1", features = ["alloc", "derive", "rc"] }
serde_core = { version = "1", features = ["alloc", "rc"] }
@@ -274,6 +275,7 @@ rustls = { version = "0.23", default-features = false, features = ["logging", "p
rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }
schemars = { version = "1", features = ["chrono04", "uuid1"] }
scopeguard = { version = "1" }
+scraper = { version = "0.18", features = ["deterministic"] }
semver = { version = "1", features = ["serde"] }
serde = { version = "1", features = ["alloc", "derive", "rc"] }
serde_core = { version = "1", features = ["alloc", "rc"] }
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index a41ca8f058..77d9fcffc7 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -316,6 +316,13 @@ and press Enter or Space. Removal is a separate button named `Remove <filename>`
Removing a forwarded file keeps the received original.
When checking draft autosave, edit the body of a draft with uploaded or forwarded
attachments, wait for the save, and reopen it; the attachments should remain visible.
+In a long thread, scroll away from the bottom while a draft save is pending.
+After repeated saves, the scroll position, editor selection, and received-message
+DOM must remain stable on desktop and mobile. Reopening must show the saved body.
+Repeat with a save completing after the thread closes; reopening must still
+load the latest saved draft.
+Ordinary queued saves must not request another `EmailThreadPage`; a missing
+thread snapshot or a move between inboxes still requires reconciliation.
AI email tool drafts persist body-only edits; changing recipients or the subject
is not required to save the body.