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): stabilize GraphQL read and archive flows (#6909)

Sean Aye719de4ae3374
diff --git a/.sqlx/query-2c60fb423d81ccbc6e60091061c57d5ab0dc8957809fc47554a1ebf416e7a6f0.json b/.sqlx/query-2c60fb423d81ccbc6e60091061c57d5ab0dc8957809fc47554a1ebf416e7a6f0.json
new file mode 100644
index 0000000000..176f6599de
--- /dev/null
+++ b/.sqlx/query-2c60fb423d81ccbc6e60091061c57d5ab0dc8957809fc47554a1ebf416e7a6f0.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_threads\n SET inbox_visible = $1, updated_at = NOW()\n WHERE id = $2 AND link_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2c60fb423d81ccbc6e60091061c57d5ab0dc8957809fc47554a1ebf416e7a6f0"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 0efd2e11ed..4464c8b490 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3150,7 +3150,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.6.18"
+version = "0.6.19"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/features/email-thread/thread-completion-adapter.tsx b/apps/web/src/features/email-thread/thread-completion-adapter.tsx
index 8601d439b0..795a6a80f6 100644
--- a/apps/web/src/features/email-thread/thread-completion-adapter.tsx
+++ b/apps/web/src/features/email-thread/thread-completion-adapter.tsx
@@ -69,7 +69,7 @@ export function createThreadCompletionAdapter(
// Only the direct unarchive fallback goes through this mutation
// (the mark-done / mark-not-done action paths toast on their own).
const archiveMutation = useUndoableArchiveThreadMutation({
- onPushed: (handle, params) => {
+ onPushed: (handle, params, disposition) => {
params.onUndoHandle?.(handle);
const message = params.archive ? 'Marked as done' : 'Marked as not done';
let toastId: number | undefined;
@@ -108,10 +108,12 @@ export function createThreadCompletionAdapter(
: bulkMarkNotificationsAsUndone(ids)
).catch(() => setDoneOverride(ids, undefined));
}
- if (!nowArchived) {
- void refetchSoupEntity(params.threadId, 'emailThread');
+ if (disposition() !== 'queued') {
+ if (!nowArchived) {
+ void refetchSoupEntity(params.threadId, 'emailThread');
+ }
+ invalidateAllSoup();
}
- invalidateAllSoup();
};
return {
@@ -207,7 +209,7 @@ export function createThreadCompletionAdapter(
linkId: toHeaderLinkId(thread.link_id),
},
{
- onSuccess: async () => {
+ onSuccess: async (disposition) => {
// The live notification stream only carries not-done
// notifications, so the thread's done ids may have aged out of
// the local cache — merge the server's view (best effort: the
@@ -230,8 +232,10 @@ export function createThreadCompletionAdapter(
toast.failure('Failed to mark as not done');
}
}
- void refetchSoupEntity(threadId, 'emailThread');
- invalidateAllSoup();
+ if (disposition !== 'queued') {
+ void refetchSoupEntity(threadId, 'emailThread');
+ invalidateAllSoup();
+ }
},
}
);
diff --git a/apps/web/src/features/email-view/queries/email-query.test.ts b/apps/web/src/features/email-view/queries/email-query.test.ts
index 4d3e1e959d..1efe78111b 100644
--- a/apps/web/src/features/email-view/queries/email-query.test.ts
+++ b/apps/web/src/features/email-view/queries/email-query.test.ts
@@ -3,6 +3,7 @@ import {
EMPTY_TAG_FACET_CONTEXT,
} from '@app/features/soup';
import type { EntityData, WithNotification } from '@entity';
+import { makeGraphqlSoupInput } from '@queries/soup/graphql/ast';
import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
import { describe, expect, it, vi } from 'vitest';
import type { EmailTab } from '../types';
@@ -66,6 +67,27 @@ const TAG_SETS = [
] as TagSetResponse[];
describe('buildEmailQuery', () => {
+ it('keeps a full admission batch below REST and GraphQL ingress recursion limits', () => {
+ const ids = Array.from(
+ { length: 100 },
+ (_, index) =>
+ `00000000-0000-0000-0000-${String(index + 1).padStart(12, '0')}`
+ );
+ const args = buildEmailQuery(
+ contextFor({ tab: 'important', facets: { read: ['unread'] } }),
+ ids
+ );
+ const graphql = makeGraphqlSoupInput({ ...args, cursor: null });
+ const depth = (value: unknown): number =>
+ value && typeof value === 'object'
+ ? 1 + Math.max(0, ...Object.values(value).map(depth))
+ : 0;
+ expect(depth(args.body)).toBeLessThan(40);
+ expect(depth(graphql)).toBeLessThan(40);
+ for (const id of ids) expect(serialize(graphql)).toContain(id);
+ expect(serialize(args.body.ef)).not.toContain('"Read"');
+ });
+
it('lists the server view each tab reads from', () => {
expect(TABS.map((tab) => [tab, emailViewForTab(tab)])).toEqual([
['important', 'inbox'],
diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.ts
index 6eb16423af..87ef0613cc 100644
--- a/apps/web/src/features/email-view/queries/email-query.ts
+++ b/apps/web/src/features/email-view/queries/email-query.ts
@@ -35,6 +35,17 @@ export const emailViewForTab = (tab: EmailTab): string =>
const anyThread = (): TargetExpr => clause.not(clause.eq('threadId', NIL_UUID));
+// Preserve a shallow tree through both the REST and GraphQL AST compilers.
+// A flat 100-way clause.or becomes a linear tree and exceeds JSON ingress depth.
+function admittedThreads(ids: readonly string[]): TargetExpr {
+ if (ids.length < 2) return clause.eq('threadId', ids[0] ?? NIL_UUID);
+ const middle = Math.floor(ids.length / 2);
+ return clause.or(
+ admittedThreads(ids.slice(0, middle)),
+ admittedThreads(ids.slice(middle))
+ );
+}
+
// Deliberately no `!isDraft` exclusion here: `isDraft` is thread-level, so
// excluding it hid whole conversations the moment a reply draft saved (#5940).
function tabClause(tab: EmailTab): TargetExpr {
@@ -78,17 +89,22 @@ function inboxClause(inboxIds: string[] | undefined): TargetExpr | undefined {
return clause.or(...inboxIds.map((id) => clause.eq('emailLinkId', id)));
}
-/** Builds the email-only Soup AST for the composable Email view. */
+/** Discovery keeps the server read filter ahead of pagination. ID-scoped
+ * admission lookups drop only read status; all other membership rules remain. */
export function buildEmailQuery(
- context: EmailQueryContext
+ context: EmailQueryContext,
+ admittedIds?: readonly string[]
): SoupAstItemsQueryArgs {
const expressions = [tabClause(context.tab)];
+ if (admittedIds) {
+ expressions.push(admittedThreads(admittedIds));
+ }
const inbox = inboxClause(context.inboxIds);
if (inbox) expressions.push(inbox);
const base = compileClause(confine({ ef: clause.and(...expressions) }));
const refinements = compileFacets(
- context.facets,
+ admittedIds ? { ...context.facets, read: [] } : context.facets,
EMAIL_FACETS,
context.facetContext
);
diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.ts
index 41cf44dcba..3b2c7a3ff0 100644
--- a/apps/web/src/features/email-view/queries/email-search.ts
+++ b/apps/web/src/features/email-view/queries/email-search.ts
@@ -72,11 +72,17 @@ function facetFilters(facets: FacetSelection): Partial<EmailFilters> {
/** Mirrors the Email view's tab, inbox, and facet scoping for service-backed search. */
export function buildEmailSearchRequest(
context: EmailQueryContext,
- search: SoupSearchRequest
+ search: SoupSearchRequest,
+ admittedIds?: readonly string[]
): SearchSoupQueryArgs {
const emailFilters: EmailFilters = {
...tabFilters(context.tab),
- ...facetFilters(context.facets),
+ ...facetFilters(
+ admittedIds ? { ...context.facets, read: [] } : context.facets
+ ),
+ ...(admittedIds
+ ? { email_thread_ids: admittedIds.length ? [...admittedIds] : [NIL_UUID] }
+ : {}),
};
if (context.inboxIds !== undefined) {
diff --git a/apps/web/src/features/email-view/queries/read-admission.test.ts b/apps/web/src/features/email-view/queries/read-admission.test.ts
new file mode 100644
index 0000000000..d58c12845e
--- /dev/null
+++ b/apps/web/src/features/email-view/queries/read-admission.test.ts
@@ -0,0 +1,53 @@
+import type { EmailEntity } from '@entity';
+import { describe, expect, it } from 'vitest';
+import { emailAdmissionBatches, mergeEmailAdmission } from './read-admission';
+
+const email = (id: string, isRead = false): EmailEntity => ({
+ type: 'email',
+ id,
+ name: id,
+ ownerId: 'viewer',
+ isRead,
+ isDraft: false,
+ isImportant: true,
+ done: false,
+});
+const ids = (emails: EmailEntity[]) => emails.map((email) => email.id);
+
+describe('email read admission order', () => {
+ it('keeps missing consecutive read rows between their discovery neighbors', () => {
+ const previous = ['a', 'b', 'c', 'd'].map((id) => email(id));
+ expect(
+ ids(mergeEmailAdmission(previous, [email('a'), email('d')]))
+ ).toEqual(['a', 'b', 'c', 'd']);
+ expect(ids(previous)).toEqual(['a', 'b', 'c', 'd']);
+ });
+ it('accepts newer discoveries and later pages without duplicating retained rows', () => {
+ const previous = ['a', 'b', 'c'].map((id) => email(id));
+ const result = mergeEmailAdmission(previous, [
+ email('new'),
+ email('a', true),
+ email('c'),
+ email('older'),
+ email('older'),
+ ]);
+ expect(ids(result)).toEqual(['new', 'a', 'b', 'c', 'older']);
+ expect(result[1].isRead).toBe(true);
+ });
+ it('keeps boundary rows when only one neighbor survives', () => {
+ expect(
+ ids(
+ mergeEmailAdmission(
+ ['a', 'b', 'c'].map((id) => email(id)),
+ [email('b')]
+ )
+ )
+ ).toEqual(['a', 'b', 'c']);
+ });
+ it('bounds every admission lookup to its complete ID page', () => {
+ const rows = Array.from({ length: 205 }, (_, i) => email(String(i)));
+ const batches = emailAdmissionBatches(rows);
+ expect(batches.map((batch) => batch.length)).toEqual([100, 100, 5]);
+ expect(batches.flat()).toEqual(ids(rows));
+ });
+});
diff --git a/apps/web/src/features/email-view/queries/read-admission.ts b/apps/web/src/features/email-view/queries/read-admission.ts
new file mode 100644
index 0000000000..5bd70934aa
--- /dev/null
+++ b/apps/web/src/features/email-view/queries/read-admission.ts
@@ -0,0 +1,50 @@
+import type { EmailEntity } from '@entity';
+
+/** Each retained lookup can return its entire explicit ID set in one page. */
+export const EMAIL_ADMISSION_BATCH_SIZE = 100;
+
+/** Keep previously admitted occurrences anchored among current discovery rows.
+ * Current rows own their metadata and relative order; missing rows keep their
+ * previous position until the ID-scoped reader determines current membership. */
+export function mergeEmailAdmission(
+ previous: readonly EmailEntity[],
+ current: readonly EmailEntity[]
+): EmailEntity[] {
+ const rows = [...new Map(current.map((email) => [email.id, email])).values()];
+ const positions = new Map(rows.map((email, index) => [email.id, index]));
+ const before = new Map<number, EmailEntity[]>();
+ let anchor = rows.length;
+ for (let index = previous.length - 1; index >= 0; index--) {
+ const email = previous[index];
+ const currentIndex = positions.get(email.id);
+ if (currentIndex !== undefined) {
+ anchor = currentIndex;
+ } else {
+ const bucket = before.get(anchor) ?? [];
+ bucket.push(email);
+ before.set(anchor, bucket);
+ }
+ }
+ return Array.from({ length: rows.length + 1 }, (_, index) => [
+ ...(before.get(index)?.reverse() ?? []),
+ ...(index < rows.length ? [rows[index]] : []),
+ ]).flat();
+}
+
+export function emailAdmissionBatches(
+ emails: readonly EmailEntity[]
+): string[][] {
+ const batches: string[][] = [];
+ for (
+ let index = 0;
+ index < emails.length;
+ index += EMAIL_ADMISSION_BATCH_SIZE
+ ) {
+ batches.push(
+ emails
+ .slice(index, index + EMAIL_ADMISSION_BATCH_SIZE)
+ .map((email) => email.id)
+ );
+ }
+ return batches;
+}
diff --git a/apps/web/src/features/email-view/queries/use-email-query.test.ts b/apps/web/src/features/email-view/queries/use-email-query.test.ts
index 9e919214b9..d885e4d87c 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.test.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.test.ts
@@ -8,6 +8,7 @@ import { batch, createRoot, createSignal } from 'solid-js';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { EmailTab, EmailViewState } from '../types';
+import { buildEmailQuery } from './email-query';
import { type EmailDataSource, useEmailDataSource } from './use-email-query';
const searchQueryMock = vi.hoisted(() => vi.fn());
@@ -68,29 +69,60 @@ function mount(search = '') {
facets: {},
collapsedSidebarSectionIds: [],
});
- const [entities, setEntities] = createSignal([email('noise')]);
+ const [entities, setDiscoveryEntities] = createSignal([email('noise')]);
+ const [retainedEntities, setRetainedEntities] = createSignal([
+ email('noise'),
+ ]);
+ const [retentionLoading, setRetentionLoading] = createSignal(false);
+ const setEntities = (rows: EmailEntity[]) =>
+ batch(() => {
+ setDiscoveryEntities(rows);
+ setRetainedEntities(rows);
+ });
const [loading, setLoading] = createSignal(false);
const [placeholder, setPlaceholder] = createSignal(false);
const [fetching, setFetching] = createSignal(false);
const [tagSetsReady, setTagSetsReady] = createSignal(true);
- const [searchEntities, setSearchEntities] = createSignal([email('search')]);
+ const [searchEntities, setSearchDiscoveryEntities] = createSignal([
+ email('search'),
+ ]);
+ const [retainedSearchEntities, setRetainedSearchEntities] = createSignal([
+ email('search'),
+ ]);
+ const setSearchEntities = (rows: EmailEntity[]) =>
+ batch(() => {
+ setSearchDiscoveryEntities(rows);
+ setRetainedSearchEntities(rows);
+ });
+ const searchRefetch = vi.fn(async () => {});
+ const retainedSearchRefetch = vi.fn(async () => {});
+ let searchCount = 0;
searchQueryMock.mockImplementation(
(
_args: Parameters<typeof useSearchSoupQuery>[0],
options: Parameters<typeof useSearchSoupQuery>[1]
- ) => ({
- // A disabled search keeps its previous data, just like placeholderData.
- get data() {
- return searchEntities();
- },
- get isEnabled() {
- return options?.().enabled ?? true;
- },
- isFetching: false,
- isFetchingNextPage: false,
- hasNextPage: true,
- error: null,
- })
+ ) => {
+ const discovery = searchCount++ === 0;
+ return {
+ get data() {
+ if (!discovery && retentionLoading())
+ throw new Error('Read pending retained search');
+ return discovery ? searchEntities() : retainedSearchEntities();
+ },
+ get isEnabled() {
+ return options?.().enabled ?? true;
+ },
+ get isSuccess() {
+ return discovery || !retentionLoading();
+ },
+ isPlaceholderData: false,
+ isFetching: false,
+ isFetchingNextPage: false,
+ hasNextPage: true,
+ error: null,
+ refetch: discovery ? searchRefetch : retainedSearchRefetch,
+ };
+ }
);
const query: SoupAstItemsQuery = {
get data() {
@@ -116,21 +148,52 @@ function mount(search = '') {
refresh: vi.fn(async () => {}),
resetToInitialPage: vi.fn(),
};
- vi.mocked(useSoupAstItemsQuery).mockReturnValue(query);
+ let listCount = 0;
+ vi.mocked(useSoupAstItemsQuery).mockImplementation(() => {
+ if (listCount++ === 0) return query;
+ return {
+ isFetching: false,
+ error: null,
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isEnabled: true,
+ transport: 'graphql',
+ fetchNextPage: vi.fn(async () => {}),
+ refetch: vi.fn(async () => {}),
+ refresh: vi.fn(async () => {}),
+ resetToInitialPage: vi.fn(),
+ get data() {
+ if (retentionLoading()) throw new Error('Read pending retained mail');
+ return { entities: retainedEntities(), groups: undefined };
+ },
+ get isLoading() {
+ return retentionLoading();
+ },
+ isPlaceholderData: false,
+ };
+ });
const source = useEmailDataSource(state, {
tagSets: () => [],
tagSetsReady,
});
return {
source,
+ query,
setState,
setEntities,
+ setDiscoveryEntities,
+ setRetainedEntities,
+ setRetentionLoading,
setLoading,
setPlaceholder,
setFetching,
setTagSetsReady,
searchEntities,
setSearchEntities,
+ setSearchDiscoveryEntities,
+ setRetainedSearchEntities,
+ searchRefetch,
+ retainedSearchRefetch,
};
});
}
@@ -192,6 +255,211 @@ describe('Email list query transitions', () => {
expect(source.hasMore()).toBe(false);
});
+ it('filters discovery before pagination while retaining a newly read row across refresh', () => {
+ const {
+ source,
+ setState,
+ setEntities,
+ setDiscoveryEntities,
+ setRetainedEntities,
+ } = mount();
+ batch(() => {
+ setState('facets', { read: ['unread'], done: ['not-done'] });
+ setEntities([
+ email('before'),
+ email('focused'),
+ { ...email('already-read'), isRead: true },
+ email('after'),
+ ]);
+ });
+ expect(ids(source)).toEqual(['before', 'focused', 'after']);
+
+ const queryArgs = vi.mocked(useSoupAstItemsQuery).mock.calls[0][0];
+ expect(queryArgs()).toEqual(
+ buildEmailQuery({
+ tab: 'noise',
+ inboxIds: ['inbox-a'],
+ facets: { read: ['unread'], done: ['not-done'] },
+ facetContext: { tagPropertyDefinitionByOptionId: new Map() },
+ })
+ );
+
+ // Both the optimistic response and the subsequent full server page keep
+ // the newly read row, in place, without admitting previously read mail.
+ const refreshed = [
+ email('before'),
+ { ...email('focused'), isRead: true },
+ { ...email('already-read'), isRead: true },
+ email('after'),
+ ];
+ setEntities(refreshed);
+ expect(ids(source)).toEqual(['before', 'focused', 'after']);
+ setDiscoveryEntities(refreshed.filter((entity) => !entity.isRead));
+ expect(ids(source)).toEqual(['before', 'focused', 'after']);
+ const lookups = vi.mocked(useSoupAstItemsQuery).mock.calls.slice(1);
+ expect(lookups.length).toBeGreaterThan(0);
+ expect(JSON.stringify(lookups[0][0]().body.ef)).not.toContain('"Read"');
+ expect(JSON.stringify(lookups[0][0]().body.ef)).toContain('focused');
+
+ // Confirmed archive/trash exclusion drops the row, despite its snapshot.
+ setRetainedEntities(refreshed.filter((entity) => entity.id !== 'focused'));
+ expect(ids(source)).toEqual(['before', 'after']);
+ });
+
+ it('discovers unread mail after 100 read threads and paginates only unread discovery', async () => {
+ const { source, query, setState, setEntities } = mount();
+ setEntities([]);
+ setState('facets', { read: ['unread'] });
+ const mailbox = [
+ ...Array.from({ length: 100 }, (_, index) => ({
+ ...email(`read-${index}`),
+ isRead: true,
+ })),
+ ...Array.from({ length: 205 }, (_, index) => email(`unread-${index}`)),
+ ];
+ const args = vi.mocked(useSoupAstItemsQuery).mock.calls[0][0];
+ // A server fixture applies the transmitted predicate before its page limit.
+ const matching = JSON.stringify(args().body.ef).includes('"Read":false')
+ ? mailbox.filter((email) => !email.isRead)
+ : mailbox;
+ setEntities(matching.slice(0, 100));
+ expect(ids(source)).toEqual(
+ matching.slice(0, 100).map((email) => email.id)
+ );
+ expect(ids(source)[0]).toBe('unread-0');
+ vi.mocked(query.fetchNextPage).mockImplementation(async () => {
+ setEntities(matching);
+ });
+ await source.loadMore();
+ expect(ids(source)).toHaveLength(205);
+ expect(query.fetchNextPage).toHaveBeenCalledOnce();
+ const lookupArgs = vi
+ .mocked(useSoupAstItemsQuery)
+ .mock.calls.slice(1)
+ .map(([args]) => args());
+ expect(lookupArgs).toHaveLength(3);
+ expect(lookupArgs.every((args) => args.params.limit === 100)).toBe(true);
+ expect(
+ lookupArgs.map(
+ (args) =>
+ (JSON.stringify(args.body.ef).match(/"ThreadId"/g) ?? []).length
+ )
+ ).toEqual([100, 100, 5]);
+ });
+
+ it('retains read search hits through a filtered search refresh using ID-scoped readless lookups', async () => {
+ const {
+ source,
+ setState,
+ setSearchDiscoveryEntities,
+ setRetainedSearchEntities,
+ searchRefetch,
+ retainedSearchRefetch,
+ } = mount('invoice');
+ setState('facets', { read: ['unread'] });
+ expect(ids(source)).toEqual(['search']);
+ batch(() => {
+ setSearchDiscoveryEntities([]);
+ setRetainedSearchEntities([{ ...email('search'), isRead: true }]);
+ });
+ await source.refresh();
+ expect(ids(source)).toEqual(['search']);
+ expect(source.items().find((row) => row.kind === 'entity')).toMatchObject({
+ entity: { isRead: true },
+ });
+ expect(searchRefetch).toHaveBeenCalledOnce();
+ expect(retainedSearchRefetch).toHaveBeenCalledOnce();
+ const discovery = searchQueryMock.mock.calls[0][0]();
+ const retained = searchQueryMock.mock.calls.at(-1)![0]();
+ expect(discovery.body.filters.email_filters.is_read).toBe(false);
+ expect(retained.body.filters.email_filters).toMatchObject({
+ email_thread_ids: ['search'],
+ importance: false,
+ link_ids: ['inbox-a'],
+ });
+ expect(retained.body.filters.email_filters.is_read).toBeUndefined();
+ expect(retained.body.query).toBe('invoice');
+ setRetainedSearchEntities([]);
+ expect(ids(source)).toEqual([]);
+ });
+
+ it('bridges pending retained reads without suspending, then honors authoritative exclusions', () => {
+ const {
+ source,
+ setState,
+ setDiscoveryEntities,
+ setRetainedEntities,
+ setRetentionLoading,
+ } = mount();
+ batch(() => {
+ setState('facets', { read: ['unread'] });
+ setRetentionLoading(true);
+ });
+ expect(ids(source)).toEqual(['noise']);
+ setDiscoveryEntities([]);
+ expect(ids(source)).toEqual(['noise']);
+ batch(() => {
+ setRetainedEntities([]);
+ setRetentionLoading(false);
+ });
+ expect(ids(source)).toEqual([]);
+ setRetentionLoading(true);
+ expect(ids(source)).toEqual([]);
+ });
+
+ it('keeps the confirmed read flag while a retained batch reloads', () => {
+ const {
+ source,
+ setState,
+ setDiscoveryEntities,
+ setRetainedEntities,
+ setRetentionLoading,
+ } = mount();
+ setState('facets', { read: ['unread'] });
+ expect(ids(source)).toEqual(['noise']);
+ batch(() => {
+ setDiscoveryEntities([]);
+ setRetainedEntities([{ ...email('noise'), isRead: true }]);
+ });
+ expect(source.items().find((row) => row.kind === 'entity')).toMatchObject({
+ entity: { isRead: true },
+ });
+ setRetentionLoading(true);
+ expect(source.items().find((row) => row.kind === 'entity')).toMatchObject({
+ entity: { isRead: true },
+ });
+ });
+
+ it('does not retain admitted hits when the search text changes', () => {
+ const {
+ source,
+ setState,
+ setSearchDiscoveryEntities,
+ setRetainedSearchEntities,
+ } = mount('invoice');
+ setState('facets', { read: ['unread'] });
+ expect(ids(source)).toEqual(['search']);
+ batch(() => {
+ setSearchDiscoveryEntities([]);
+ setRetainedSearchEntities([{ ...email('search'), isRead: true }]);
+ });
+ expect(ids(source)).toEqual(['search']);
+ setState('search', 'different');
+ expect(ids(source)).toEqual([]);
+ });
+
+ it('resets read admission when the read filter changes', () => {
+ const { source, setState, setEntities } = mount();
+ setState('facets', { read: ['unread'] });
+ expect(ids(source)).toEqual(['noise']);
+ setEntities([{ ...email('noise'), isRead: true }]);
+ expect(ids(source)).toEqual(['noise']);
+ setState('facets', { read: ['read'] });
+ expect(ids(source)).toEqual(['noise']);
+ setState('facets', { read: ['unread'] });
+ expect(ids(source)).toEqual([]);
+ });
+
it('keeps current-query cached results visible during a background refresh', () => {
const { source, setFetching } = mount();
setFetching(true);
diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.ts
index caa4977169..d5d13551fd 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.ts
@@ -6,12 +6,14 @@ import {
createSoupLoadMoreRow,
createTagFacetContext,
type SoupRow,
+ soupSearchMatchType,
tagFacetReady,
testFacets,
} from '@app/features/soup';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useUserId } from '@core/context/user';
+import { arrayEquals } from '@core/util/compareUtils';
import {
type EmailEntity,
type EntityData,
@@ -19,14 +21,16 @@ import {
type WithNotification,
} from '@entity';
import { useSoupAstItemsQuery } from '@queries/soup/items';
+import { useSearchSoupQuery } from '@queries/soup/search';
import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
-import { type Accessor, createMemo } from 'solid-js';
+import { type Accessor, createMemo, indexArray } from 'solid-js';
import { match } from 'ts-pattern';
import { EMAIL_FACETS, type EmailFacetContext } from '../filters/email-facets';
import type { EmailTab, EmailViewState } from '../types';
import { buildEmailQuery, type EmailQueryContext } from './email-query';
import { groupEmailEntitiesByDate } from './email-results';
import { buildEmailSearchRequest } from './email-search';
+import { emailAdmissionBatches, mergeEmailAdmission } from './read-admission';
export type EmailDataSourceItem = SoupRow<WithNotification<EntityData>>;
@@ -65,10 +69,13 @@ function emailMatchesTab(
type AdmittedEmails = {
scope: string;
- admittedIds: Set<string>;
items: EmailEntity[];
};
+type RetainedEmailPublication = AdmittedEmails & {
+ resolved: Map<string, EmailEntity | undefined>;
+};
+
/** Query, service search, and row assembly owned by the Email view. */
export function useEmailDataSource(
state: EmailDataSourceInput,
@@ -90,6 +97,8 @@ export function useEmailDataSource(
})
);
+ // Discovery must apply read status before pagination, not scan through
+ // pages of read mail to find an unread thread.
const queryArgs = createMemo(() => buildEmailQuery(queryContext()));
// A restored tag selection waits for the tag sets rather than listing the
// whole mailbox and then narrowing.
@@ -123,7 +132,7 @@ export function useEmailDataSource(
buildRequest: (request) => buildEmailSearchRequest(queryContext(), request),
});
- const rawEntities = createMemo<EntityData[]>((previous) => {
+ const rawEntities = createMemo<EntityData[]>(() => {
// Disabled searches can retain placeholder data for the previous facets.
if (!facetsReady()) return [];
@@ -136,70 +145,147 @@ export function useEmailDataSource(
return query.data?.entities ?? [];
}
- const results = search.data();
- if (
- results.length === 0 &&
- previous.length > 0 &&
- search.isLocalSearchSettling()
- ) {
- return previous;
- }
- return results;
- }, []);
+ // Never admit the previous text/filter query's placeholder results.
+ if (!search.usesServiceSearch() || search.searchQuery.isPlaceholderData)
+ return [];
+ return search.data();
+ });
- // Keep rows admitted after they transition from unread to read: opening a
- // thread marks it read, and with the Unread filter on the row would
- // otherwise vanish from under the preview. Changing the tab, inbox scope,
- // or read filter starts a new admission scope.
- const entities = createMemo<AdmittedEmails>(
+ const hasReadFilter = () => (state.facets.read?.length ?? 0) > 0;
+ const scope = createMemo(() =>
+ JSON.stringify([
+ userId(),
+ queryArgs().body,
+ state.facets,
+ state.search.trim(),
+ ])
+ );
+ const matchesOtherFacets = (email: EmailEntity) =>
+ testFacets(
+ { ...state.facets, read: [] },
+ EMAIL_FACETS,
+ email,
+ facetContext()
+ );
+
+ // Remember identity and position, not permanent membership. Bounded readers
+ // below keep admitted rows live without weakening discovery's read filter.
+ const admitted = createMemo<AdmittedEmails>(
(previous) => {
- const context = queryContext();
- const emails = selectEmails(rawEntities());
- const activeRead = context.facets.read ?? [];
- const scope = [
- context.tab,
- context.inboxIds?.join(',') ?? '*',
- activeRead.join(','),
- ].join('|');
- const selection = { ...context.facets, read: [] };
- const matchesOtherFacets = (email: EmailEntity) =>
- testFacets(selection, EMAIL_FACETS, email, context.facetContext);
+ const currentScope = scope();
+ if (!hasReadFilter()) return { scope: currentScope, items: [] };
+ const previousItems =
+ previous.scope === currentScope ? previous.items : [];
+ const known = new Set(previousItems.map((email) => email.id));
+ const current = selectEmails(rawEntities()).filter(
+ (email) =>
+ matchesOtherFacets(email) &&
+ (known.has(email.id) ||
+ testFacets(
+ { read: state.facets.read ?? [] },
+ EMAIL_FACETS,
+ email,
+ facetContext()
+ ))
+ );
+ return {
+ scope: currentScope,
+ items: mergeEmailAdmission(previousItems, current),
+ };
+ },
+ { scope: '', items: [] }
+ );
+
+ const admissionBatches = createMemo(
+ () => (facetsReady() ? emailAdmissionBatches(admitted().items) : []),
+ [],
+ {
+ equals: (left, right) =>
+ left.length === right.length &&
+ left.every((ids, index) => arrayEquals(ids, right[index])),
+ }
+ );
+ const retainedQueries = indexArray(admissionBatches, (ids) => {
+ const list = useSoupAstItemsQuery(
+ () => buildEmailQuery(queryContext(), ids()),
+ () => ({ enabled: facetsReady() && !search.isSearching() })
+ );
+ const searchQuery = useSearchSoupQuery(
+ () =>
+ buildEmailSearchRequest(
+ queryContext(),
+ {
+ query: state.search.trim(),
+ matchType: soupSearchMatchType(state.search),
+ },
+ ids()
+ ),
+ () => ({ enabled: facetsReady() && search.usesServiceSearch() })
+ );
+ return {
+ ids,
+ data: () =>
+ search.isSearching()
+ ? searchQuery.isSuccess && !searchQuery.isPlaceholderData
+ ? searchQuery.data
+ : undefined
+ : !list.isLoading && !list.isPlaceholderData
+ ? list.data?.entities
+ : undefined,
+ error: () => (search.isSearching() ? searchQuery.error : list.error),
+ refresh: async () => {
+ if (search.usesServiceSearch()) await searchQuery.refetch();
+ else if (!search.isSearching()) await list.refresh();
+ },
+ };
+ });
- // Without a read filter there is nothing to admit, so no ids are kept.
- if (activeRead.length === 0) {
+ const publication = createMemo<RetainedEmailPublication>(
+ (previous) => {
+ const currentScope = scope();
+ if (!facetsReady() || (!search.isSearching() && isListPending())) {
+ return { scope: currentScope, items: [], resolved: new Map() };
+ }
+ if (!hasReadFilter()) {
return {
- scope,
- admittedIds: new Set<string>(),
- items: emails.filter(matchesOtherFacets),
+ scope: currentScope,
+ items: selectEmails(rawEntities()).filter(matchesOtherFacets),
+ resolved: new Map(),
};
}
-
- const admittedIds =
- previous.scope === scope
- ? new Set(previous.admittedIds)
- : new Set<string>();
- const readSelection = { read: activeRead };
- for (const email of emails) {
- if (
- testFacets(readSelection, EMAIL_FACETS, email, context.facetContext)
- ) {
- admittedIds.add(email.id);
- }
+ // Carry the last confirmed lookup through a new batch's pending read,
+ // including explicit non-membership. Otherwise pagination can flash old
+ // unread flags or resurrect an archived row from its discovery snapshot.
+ const current = new Map(
+ previous.scope === currentScope ? previous.resolved : []
+ );
+ for (const lookup of retainedQueries()) {
+ const data = lookup.data();
+ if (data === undefined) continue;
+ const byId = new Map(
+ selectEmails(data).map((email) => [email.id, email])
+ );
+ for (const id of lookup.ids()) current.set(id, byId.get(id));
}
-
return {
- scope,
- admittedIds,
- items: emails.filter(
- (email) => admittedIds.has(email.id) && matchesOtherFacets(email)
- ),
+ scope: currentScope,
+ resolved: current,
+ items: admitted().items.flatMap((snapshot) => {
+ // Snapshots bridge the first pending lookup only; subsequent pending
+ // reads retain the canonical value or exclusion from that lookup.
+ const email = current.has(snapshot.id)
+ ? current.get(snapshot.id)
+ : snapshot;
+ return email && matchesOtherFacets(email) ? [email] : [];
+ }),
};
},
- { scope: '', admittedIds: new Set<string>(), items: [] }
+ { scope: '', items: [], resolved: new Map() }
);
+ const entities = () => publication().items;
const listEntities = createMemo((): WithNotification<EntityData>[] =>
- entities().items.map((email) =>
+ entities().map((email) =>
withEntityNotifications(email, notificationSource)
)
);
@@ -241,7 +327,7 @@ export function useEmailDataSource(
// A query held back for the tag sets is loading, not empty.
return isListPending();
}
- if (entities().items.length > 0) return false;
+ if (entities().length > 0) return false;
if (usesServiceSearch()) return search.isLoading();
return query.isLoading;
};
@@ -253,10 +339,12 @@ export function useEmailDataSource(
if (search.isSettling()) return true;
return usesServiceSearch() ? search.isFetching() : query.isFetching;
},
- error: () => {
- if (!usesServiceSearch()) return query.error ?? undefined;
- return search.error();
- },
+ error: () =>
+ (usesServiceSearch() ? search.error() : query.error) ??
+ retainedQueries()
+ .map((lookup) => lookup.error())
+ .find((error) => error instanceof Error) ??
+ undefined,
hasMore,
isLoadingMore,
loadMore: async () => {
@@ -267,11 +355,10 @@ export function useEmailDataSource(
await query.fetchNextPage();
},
refresh: async () => {
- if (usesServiceSearch()) {
- await search.refetch();
- return;
- }
- await query.refresh();
+ await Promise.all([
+ usesServiceSearch() ? search.refetch() : query.refresh(),
+ ...retainedQueries().map((lookup) => lookup.refresh()),
+ ]);
},
} satisfies EmailDataSource;
}
diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts
index b0f8d9f7f4..cd8eeb581b 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts
@@ -4,7 +4,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
threadCanBeMarkedNotDone: vi.fn(async (_id: string) => true),
- executeMarkEntitiesUndone: vi.fn(async () => {}),
+ executeMarkEntitiesUndone: vi.fn(
+ async (): Promise<'committed' | 'queued'> => 'committed'
+ ),
+ invalidateAllSoup: vi.fn(),
+ refetchSoupEntity: vi.fn(async () => {}),
resolveMarkEntitiesDoneVariables: vi.fn(
({ entities }: { entities: EntityData[] }) => ({
emailIds: entities.map((e) => e.id),
@@ -32,8 +36,8 @@ vi.mock('@queries/notification/user-notifications', () => ({
}));
vi.mock('@queries/soup/cache', () => ({
- invalidateAllSoup: vi.fn(),
- refetchSoupEntity: vi.fn(async () => {}),
+ invalidateAllSoup: mocks.invalidateAllSoup,
+ refetchSoupEntity: mocks.refetchSoupEntity,
}));
vi.mock('@app/features/next-soup/utils', () => ({
@@ -66,6 +70,20 @@ describe('makeMarkNotDoneAction', () => {
expect.objectContaining({ emailIds: ['inbound'] })
);
expect(mocks.alert).not.toHaveBeenCalled();
+ expect(mocks.invalidateAllSoup).toHaveBeenCalledOnce();
+ expect(mocks.refetchSoupEntity).toHaveBeenCalledWith(
+ 'inbound',
+ 'emailThread'
+ );
+ });
+
+ it('does not refetch REST caches after a queued unarchive', async () => {
+ mocks.executeMarkEntitiesUndone.mockResolvedValueOnce('queued');
+ await expect(createAction().execute([doneEmail('inbound')])).resolves.toBe(
+ 'queued'
+ );
+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();
+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();
});
// A send-only thread is permanently done: unarchiving reverts on the next
diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
index 60aff44917..127e1802a4 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
@@ -105,7 +105,7 @@ export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {
// them from the server and merge before restoring.
const serverNotificationIds =
await fetchDoneNotificationIdsByEventItemIds(emailIds);
- await executeMarkEntitiesUndone({
+ const disposition = await executeMarkEntitiesUndone({
emailIds,
notificationIds: [
...new Set([...notificationIds, ...serverNotificationIds]),
@@ -123,10 +123,13 @@ export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {
// and upsert it into the caches (flat, grouped parents, and expanded
// group queries), then refetch the lists so done-filtered views
// reconcile membership and ordering.
- await Promise.all(
- emailIds.map((id) => refetchSoupEntity(id, 'emailThread'))
- );
- invalidateAllSoup();
+ if (disposition !== 'queued') {
+ await Promise.all(
+ emailIds.map((id) => refetchSoupEntity(id, 'emailThread'))
+ );
+ invalidateAllSoup();
+ }
+ return disposition;
} catch (err) {
optimistic.rollback();
toast.failure('Failed to mark as not done');
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index ab2913acae..27eddb9540 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -32,6 +32,7 @@ const operationMocks = vi.hoisted(() => {
},
});
return {
+ archive: vi.fn(async (): Promise<'committed' | 'queued'> => 'committed'),
bulkMarkNotificationsAsDone: vi.fn(async () => {}),
bulkMarkNotificationsAsUndone: vi.fn(async () => {}),
cancelQueries: vi.fn(async () => {}),
@@ -39,7 +40,9 @@ const operationMocks = vi.hoisted(() => {
isErr: () => false,
value: undefined,
})),
- invalidateQueries: vi.fn(async () => {}),
+ invalidateQueries: vi.fn(
+ async (_options: { queryKey?: readonly unknown[] }) => {}
+ ),
invalidateRemindersById: vi.fn(),
invalidateSoupEntity: vi.fn(async () => {}),
setReminderCompleted: vi.fn(async () => {}),
@@ -61,6 +64,10 @@ vi.mock('@service-connection/websocket', () => ({
createConnectionBlockWebsocketEffect: vi.fn(),
createConnectionWebsocketEffect: vi.fn(),
}));
+vi.mock('@queries/email/integration', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@queries/email/integration')>()),
+ archiveEmailThread: operationMocks.archive,
+}));
vi.mock('@queries/client', () => ({
queryClient: {
cancelQueries: operationMocks.cancelQueries,
@@ -108,10 +115,11 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => {
import { setGlobalSplitManager } from '@app/signal/splitLayout';
import type { SplitManager } from '@components/app/split-layout/layoutManager';
-import type { ChannelEntityTarget, EntityData } from '@entity';
+import { type ChannelEntityTarget, type EntityData, queryKeys } from '@entity';
import type { NotificationSource, UnifiedNotification } from '@notifications';
import {
executeMarkEntitiesDone,
+ executeMarkEntitiesUndone,
getChannelEntityTarget,
getDocumentCommentTarget,
getRowClickFallbackLocation,
@@ -326,6 +334,45 @@ describe('resolveMarkEntitiesDoneVariables', () => {
});
describe('mark-done orchestration', () => {
+ const invalidatedEmailList = () =>
+ operationMocks.invalidateQueries.mock.calls.some(
+ ([options]) =>
+ JSON.stringify(options.queryKey) === JSON.stringify(queryKeys.all.email)
+ );
+
+ for (const [label, execute] of [
+ ['Done', executeMarkEntitiesDone],
+ ['Undo', executeMarkEntitiesUndone],
+ ] as const) {
+ it(`${label} does not invalidate REST email caches while the archive is queued`, async () => {
+ operationMocks.archive.mockResolvedValueOnce('queued');
+ await execute({ emailIds: ['queued'], notificationIds: [] });
+ expect(invalidatedEmailList()).toBe(false);
+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();
+ });
+ it(`${label} still reconciles committed and rejected archive writes`, async () => {
+ await execute({ emailIds: ['committed'], notificationIds: [] });
+ expect(invalidatedEmailList()).toBe(true);
+ operationMocks.invalidateQueries.mockClear();
+ operationMocks.archive.mockRejectedValueOnce(new Error('archive failed'));
+ await expect(
+ execute({ emailIds: ['failed'], notificationIds: [] })
+ ).rejects.toThrow('archive failed');
+ expect(invalidatedEmailList()).toBe(true);
+ expect(operationMocks.invalidateSoupEntity).toHaveBeenCalledWith(
+ 'failed'
+ );
+ });
+ it(`${label} defers shared-list refresh for mixed committed/queued writes`, async () => {
+ operationMocks.archive
+ .mockResolvedValueOnce('committed')
+ .mockResolvedValueOnce('queued');
+ await execute({ emailIds: ['committed', 'queued'], notificationIds: [] });
+ expect(invalidatedEmailList()).toBe(false);
+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();
+ });
+ }
+
it('executes entity notification writes directly and returns exact ids', async () => {
operationMocks.updateNotificationsForEntities.mockResolvedValueOnce([
{ id: 'entity-notification' },
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index aaa5ffa4ef..7169a83b3d 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -97,6 +97,10 @@ import {
} from '@notifications';
import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';
import { queryClient } from '@queries/client';
+import {
+ archiveEmailThread,
+ type EmailArchiveDisposition,
+} from '@queries/email/integration';
import { emailKeys } from '@queries/email/keys';
import { fetchAndCacheThread } from '@queries/email/thread';
import {
@@ -1096,18 +1100,21 @@ async function _archiveEmail(
queryClient.setQueryData(key, applyEmailOptimistic(data));
}
+ let disposition: EmailArchiveDisposition | undefined;
try {
- await emailClient.flagArchived({ value: options.archive, id });
+ disposition = await archiveEmailThread({ value: options.archive, id });
} catch (_err) {
soupTxn.rollback();
for (const [key, data] of previousEmail) {
queryClient.setQueryData(key, data);
}
} finally {
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
- invalidateSoupEntity(id),
- ]);
+ if (disposition !== 'queued') {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ invalidateSoupEntity(id),
+ ]);
+ }
}
}
@@ -1661,11 +1668,7 @@ export async function executeMarkEntitiesDone(args: {
let authoritativeNotificationIds: string[] = [];
const results = await Promise.allSettled([
- ...emailIds.map((id) =>
- throwOnErr(
- async () => await emailClient.flagArchived({ value: true, id })
- )
- ),
+ ...emailIds.map((id) => archiveEmailThread({ value: true, id })),
notificationIds.length > 0
? bulkMarkNotificationsAsDone(notificationIds)
: Promise.resolve(),
@@ -1682,6 +1685,11 @@ export async function executeMarkEntitiesDone(args: {
...setRemindersCompleted(reminderIds, true),
]);
+ const hasQueuedEmail = results
+ .slice(0, emailIds.length)
+ .some(
+ (result) => result.status === 'fulfilled' && result.value === 'queued'
+ );
const rejected = results.find(
(r): r is PromiseRejectedResult => r.status === 'rejected'
);
@@ -1693,9 +1701,13 @@ export async function executeMarkEntitiesDone(args: {
// them back, so they have to be reconciled too, not just the emails.
invalidateRemindersById(reminderIds, { refetch: true });
await Promise.all([
- queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ ...(!hasQueuedEmail
+ ? [
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ ...emailIds.map((id) => invalidateSoupEntity(id)),
+ ]
+ : []),
queryClient.invalidateQueries({ queryKey: notificationKeys.user._def }),
- ...emailIds.map((id) => invalidateSoupEntity(id)),
...reminderIds.map((id) => invalidateSoupEntity(id)),
]);
throw rejected.reason ?? new Error('Failed to mark as done');
@@ -1703,15 +1715,21 @@ export async function executeMarkEntitiesDone(args: {
invalidateRemindersById(reminderIds);
await Promise.all([
- queryClient.invalidateQueries({
- queryKey: queryKeys.all.email,
- refetchType: 'none',
- }),
+ // A shared REST list can contain both committed and queued threads. Do
+ // not fetch its pre-write server state over any queued optimistic row.
+ ...(!hasQueuedEmail
+ ? [
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.all.email,
+ refetchType: 'none',
+ }),
+ ...emailIds.map((id) => invalidateSoupEntity(id)),
+ ]
+ : []),
queryClient.invalidateQueries({
queryKey: notificationKeys.user._def,
refetchType: 'none',
}),
- ...emailIds.map((id) => invalidateSoupEntity(id)),
]);
return authoritativeNotificationIds;
@@ -1725,7 +1743,7 @@ export async function executeMarkEntitiesUndone(args: {
emailIds: string[];
notificationIds: string[];
reminderIds?: string[];
-}): Promise<void> {
+}): Promise<EmailArchiveDisposition> {
const { emailIds, notificationIds, reminderIds = [] } = args;
await Promise.all([
queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
@@ -1733,17 +1751,18 @@ export async function executeMarkEntitiesUndone(args: {
]);
const results = await Promise.allSettled([
- ...emailIds.map((id) =>
- throwOnErr(
- async () => await emailClient.flagArchived({ value: false, id })
- )
- ),
+ ...emailIds.map((id) => archiveEmailThread({ value: false, id })),
notificationIds.length > 0
? bulkMarkNotificationsAsUndone(notificationIds)
: Promise.resolve(),
...setRemindersCompleted(reminderIds, false),
]);
+ const hasQueuedEmail = results
+ .slice(0, emailIds.length)
+ .some(
+ (result) => result.status === 'fulfilled' && result.value === 'queued'
+ );
const rejected = results.find(
(r): r is PromiseRejectedResult => r.status === 'rejected'
);
@@ -1755,9 +1774,13 @@ export async function executeMarkEntitiesUndone(args: {
// unarchived thread would sit there still showing as done.
invalidateRemindersById(reminderIds, { refetch: true });
await Promise.all([
- queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ ...(!hasQueuedEmail
+ ? [
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ ...emailIds.map((id) => invalidateSoupEntity(id)),
+ ]
+ : []),
queryClient.invalidateQueries({ queryKey: notificationKeys.user._def }),
- ...emailIds.map((id) => invalidateSoupEntity(id)),
...reminderIds.map((id) => invalidateSoupEntity(id)),
]);
throw rejected.reason ?? new Error('Failed to undo');
@@ -1766,21 +1789,26 @@ export async function executeMarkEntitiesUndone(args: {
invalidateRemindersById(reminderIds);
await Promise.all([
- queryClient.invalidateQueries({
- queryKey: queryKeys.all.email,
- refetchType: 'none',
- }),
+ ...(!hasQueuedEmail
+ ? [
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.all.email,
+ refetchType: 'none',
+ }),
+ // Refetch open thread views only after the unarchive has committed.
+ ...emailIds.map((id) =>
+ queryClient.invalidateQueries({
+ queryKey: emailKeys.threadMessages(id).queryKey,
+ })
+ ),
+ ]
+ : []),
queryClient.invalidateQueries({
queryKey: notificationKeys.user._def,
refetchType: 'none',
}),
- // Refetch open thread views so the unarchive restores `inbox_visible`.
- ...emailIds.map((id) =>
- queryClient.invalidateQueries({
- queryKey: emailKeys.threadMessages(id).queryKey,
- })
- ),
]);
+ return hasQueuedEmail ? 'queued' : 'committed';
}
import { agentMessageParams } from '@app/features/block-agent/core/search-location';
diff --git a/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
index 4306bb5776..f8398c8b32 100644
--- a/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
+++ b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
@@ -14,6 +14,10 @@ export const entityResolverSchema = {
targets: ['GraphqlChannelActivity'],
argumentPaths: [['input', 'channelId']],
},
+ setEmailThreadArchived: {
+ targets: ['GraphqlSoupEmailThread'],
+ argumentPaths: [['input', 'threadId']],
+ },
setEntityProperty: {
targets: ['GraphqlProperty'],
argumentPaths: [
diff --git a/apps/web/src/lib/queries/email/integration.test.ts b/apps/web/src/lib/queries/email/integration.test.ts
new file mode 100644
index 0000000000..3831c49e60
--- /dev/null
+++ b/apps/web/src/lib/queries/email/integration.test.ts
@@ -0,0 +1,188 @@
+import { CombinedError, stringifyDocument } from '@urql/core';
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ graphql: true,
+ archive: vi.fn(),
+ mutation: vi.fn(),
+ refresh: vi.fn(),
+ revalidations: vi.fn(() => [] as unknown[]),
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableGraphqlSoup: {},
+ isFeatureEnabled: () => mocks.graphql,
+}));
+vi.mock('@service-email/client', () => ({
+ emailClient: { flagArchived: mocks.archive },
+}));
+vi.mock('@service-storage/client', () => ({ storageServiceClient: {} }));
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: () => ({ mutation: mocks.mutation }),
+}));
+vi.mock('../soup/graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: mocks.refresh,
+ getActiveGraphqlSoupRevalidations: mocks.revalidations,
+}));
+
+import {
+ SetEmailThreadArchivedDocument,
+ SoupDocument,
+} from '@service-storage/graphql/generated/graphql';
+import { archiveEmailThread } from './integration';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.graphql = true;
+ mocks.refresh.mockResolvedValue(undefined);
+ mocks.revalidations.mockReturnValue([]);
+});
+
+describe('GraphQL email archive writes', () => {
+ it.each([true, false])(
+ 'writes inboxVisible optimistically for archive=%s before the request settles',
+ async (value) => {
+ let finish!: () => void;
+ const network = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ mocks.mutation.mockReturnValue({
+ toPromise: async () => {
+ await network;
+ return {
+ data: {
+ setEmailThreadArchived: {
+ __typename: 'GraphqlSoupEmailThread',
+ id: 'thread',
+ inboxVisible: !value,
+ },
+ },
+ };
+ },
+ });
+ const result = archiveEmailThread({ id: 'thread', value }, 'secondary');
+ expect(mocks.mutation).toHaveBeenCalledWith(
+ SetEmailThreadArchivedDocument,
+ { input: { threadId: 'thread', archived: value } },
+ expect.objectContaining({
+ normalizedCacheOptimistic: expect.objectContaining({
+ optimisticResponse: {
+ setEmailThreadArchived: {
+ __typename: 'GraphqlSoupEmailThread',
+ id: 'thread',
+ inboxVisible: !value,
+ },
+ },
+ }),
+ })
+ );
+ expect(mocks.archive).not.toHaveBeenCalled();
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ finish();
+ await expect(result).resolves.toBe('committed');
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('gives Done, Undo and Redo distinct ordered mutation intents', async () => {
+ mocks.mutation.mockReturnValue({
+ toPromise: async () => ({
+ data: { setEmailThreadArchived: { id: 'thread' } },
+ }),
+ });
+ for (const value of [true, false, true])
+ await archiveEmailThread({ id: 'thread', value });
+ const calls = mocks.mutation.mock.calls;
+ expect(calls.map(([, variables]) => variables.input.archived)).toEqual([
+ true,
+ false,
+ true,
+ ]);
+ expect(
+ new Set(
+ calls.map(([, , context]) => context.normalizedCacheOptimistic.uuid)
+ ).size
+ ).toBe(3);
+ });
+
+ it('preserves replay revalidations, including continuation pages, without refetching queued writes', async () => {
+ const variables = [
+ { input: { initial: { limit: 100 } } },
+ { input: { continuation: { cursor: 'next' } } },
+ ];
+ mocks.revalidations.mockReturnValue(
+ variables.map((variables) => ({ document: SoupDocument, variables }))
+ );
+ mocks.mutation.mockReturnValue({
+ toPromise: async () => ({
+ extensions: {
+ normalizedCacheMutationDisposition: {
+ kind: 'queued',
+ transactionId: 'tx',
+ },
+ },
+ }),
+ });
+ await expect(
+ archiveEmailThread({ id: 'thread', value: true })
+ ).resolves.toBe('queued');
+ expect(
+ mocks.mutation.mock.calls[0][2].normalizedCacheOptimistic.revalidations
+ ).toEqual(
+ variables.map((variables) => ({
+ query: stringifyDocument(SoupDocument),
+ operationName: 'Soup',
+ variablesJson: JSON.stringify(variables),
+ }))
+ );
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { error: new CombinedError({ graphQLErrors: ['not authorized'] }) },
+ {
+ extensions: {
+ normalizedCacheMutationDisposition: {
+ kind: 'permanently-failed',
+ error: new Error('rejected'),
+ },
+ },
+ },
+ { data: {} },
+ ])(
+ 'does not report a rejected/missing mutation reply as success: %j',
+ async (reply) => {
+ mocks.mutation.mockReturnValue({ toPromise: async () => reply });
+ await expect(
+ archiveEmailThread({ id: 'thread', value: true })
+ ).rejects.toThrow();
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ expect(mocks.archive).not.toHaveBeenCalled();
+ }
+ );
+
+ it.each([true, false])(
+ 'keeps archive=%s on REST when GraphQL is disabled',
+ async (value) => {
+ mocks.graphql = false;
+ mocks.archive.mockResolvedValue(ok(undefined));
+ await expect(
+ archiveEmailThread({ id: 'thread', value }, 'secondary')
+ ).resolves.toBe('committed');
+ expect(mocks.archive).toHaveBeenCalledWith(
+ { id: 'thread', value },
+ 'secondary'
+ );
+ expect(mocks.mutation).not.toHaveBeenCalled();
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ }
+ );
+
+ it('preserves REST failure behavior', async () => {
+ mocks.graphql = false;
+ mocks.archive.mockResolvedValue(err(new Error('archive failed')));
+ await expect(
+ archiveEmailThread({ id: 'thread', value: true })
+ ).rejects.toThrow();
+ });
+});
diff --git a/apps/web/src/lib/queries/email/integration.ts b/apps/web/src/lib/queries/email/integration.ts
index 3ad5a95a46..05fec60c0e 100644
--- a/apps/web/src/lib/queries/email/integration.ts
+++ b/apps/web/src/lib/queries/email/integration.ts
@@ -1,14 +1,45 @@
+import {
+ enableGraphqlSoup,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/result';
import { emailClient } from '@service-email/client';
import { storageServiceClient } from '@service-storage/client';
+import { setGraphqlEmailThreadArchived } from '@service-storage/graphql-email-archive-state';
+import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
+import {
+ getActiveGraphqlSoupRevalidations,
+ refreshActiveGraphqlSoupQueries,
+} from '../soup/graphql/active-queries';
/** Provider operations used by email's production adapters alongside shared mutations. */
export const scheduleEmailMessage = (
...args: Parameters<typeof emailClient.scheduleMessage>
) => throwOnErr(() => emailClient.scheduleMessage(...args));
-export const archiveEmailThread = (
+export type EmailArchiveDisposition = 'committed' | 'queued';
+
+/** Shared archive path for Done, Not Done, send completion, and Undo/Redo.
+ * GraphQL owns optimistic state and durable replay; queued writes must not
+ * refetch the server's pre-write membership over the optimistic update. */
+export async function archiveEmailThread(
...args: Parameters<typeof emailClient.flagArchived>
-) => throwOnErr(() => emailClient.flagArchived(...args));
+): Promise<EmailArchiveDisposition> {
+ if (isFeatureEnabled(enableGraphqlSoup)) {
+ const [{ id, value }] = args;
+ const disposition = await setGraphqlEmailThreadArchived(
+ getGraphqlSoupClient(),
+ id,
+ value,
+ getActiveGraphqlSoupRevalidations()
+ );
+ if (disposition === 'committed') {
+ await refreshActiveGraphqlSoupQueries();
+ }
+ return disposition;
+ }
+ await throwOnErr(() => emailClient.flagArchived(...args));
+ return 'committed';
+}
export const unscheduleEmailMessage = (
...args: Parameters<typeof emailClient.unscheduleMessage>
) => emailClient.unscheduleMessage(...args);
diff --git a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx b/apps/web/src/lib/queries/email/read-state-graphql.test.tsx
index dc5cc12b93..f0ac58aaa9 100644
--- a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx
+++ b/apps/web/src/lib/queries/email/read-state-graphql.test.tsx
@@ -65,6 +65,7 @@ import { stringifyDocument } from '@urql/core';
import { registerGraphqlSoupRevalidations } from '../soup/graphql/active-queries';
import { emailKeys } from './keys';
import {
+ trackExternalThreadArchive,
useMarkThreadAsSeenMutation,
useMarkThreadAsUnreadMutation,
} from './thread';
@@ -98,6 +99,33 @@ beforeEach(() => {
});
afterEach(() => client.clear());
+describe('external archive disposition', () => {
+ it.each(['queued', 'committed', 'failed'] as const)(
+ 'retains the optimistic thread until a %s archive can be reconciled',
+ async (disposition) => {
+ const key = emailKeys.threadMessages('thread').queryKey;
+ client.setQueryData(key, {
+ pages: [{ inbox_visible: true }],
+ pageParams: [0],
+ });
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ await trackExternalThreadArchive(
+ 'thread',
+ disposition === 'failed'
+ ? Promise.reject(new Error('archive failed'))
+ : Promise.resolve(disposition)
+ );
+ expect(
+ client.getQueryData<{ pages: { inbox_visible: boolean }[] }>(key)
+ ?.pages[0].inbox_visible
+ ).toBe(disposition === 'failed');
+ expect(invalidate).toHaveBeenCalledTimes(
+ disposition === 'queued' ? 0 : 2
+ );
+ }
+ );
+});
+
describe('email read state with GraphQL Soup', () => {
it.each([
{ read: true, graphql: true },
diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.ts
index 7329147c7a..11ac1f0ff9 100644
--- a/apps/web/src/lib/queries/email/thread.ts
+++ b/apps/web/src/lib/queries/email/thread.ts
@@ -42,6 +42,10 @@ import {
fetchGraphqlEmailThread,
mapGraphqlThreadError,
} from './graphql/thread';
+import {
+ archiveEmailThread,
+ type EmailArchiveDisposition,
+} from './integration';
import { emailKeys } from './keys';
const THREAD_STALE_TIME = 5 * 60 * 1000;
@@ -418,6 +422,7 @@ type ArchiveThreadParams = {
};
type ArchiveThreadContext = {
previousData: InfiniteData<Thread, number> | undefined;
+ disposition?: EmailArchiveDisposition;
};
/** Optimistically set `inbox_visible` when archiving a thread. */
@@ -462,8 +467,9 @@ export async function trackExternalThreadArchive(
threadId,
archive,
});
+ let disposition: unknown;
try {
- await archived;
+ disposition = await archived;
} catch {
if (previousData) {
queryClient.setQueryData(
@@ -472,10 +478,12 @@ export async function trackExternalThreadArchive(
);
}
} finally {
- queryClient.invalidateQueries({
- queryKey: emailKeys.threadMessages(threadId).queryKey,
- });
- queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
+ if (disposition !== 'queued') {
+ queryClient.invalidateQueries({
+ queryKey: emailKeys.threadMessages(threadId).queryKey,
+ });
+ queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
+ }
}
}
@@ -484,16 +492,17 @@ export async function trackExternalThreadArchive(
* call, rollback on failure, invalidate on settle. Mirrors what
* `useUndoableArchiveThreadMutation` does through its mutation callbacks.
*/
-async function replayThreadArchive(params: ArchiveThreadParams): Promise<void> {
+async function replayThreadArchive(
+ params: ArchiveThreadParams
+): Promise<EmailArchiveDisposition> {
const { previousData } = await threadArchiveOnMutate(params);
+ let disposition: EmailArchiveDisposition | undefined;
try {
- await throwOnErr(
- async () =>
- await emailClient.flagArchived(
- { id: params.threadId, value: params.archive },
- params.linkId
- )
+ disposition = await archiveEmailThread(
+ { id: params.threadId, value: params.archive },
+ params.linkId
);
+ return disposition;
} catch (err) {
if (previousData) {
queryClient.setQueryData(
@@ -503,10 +512,12 @@ async function replayThreadArchive(params: ArchiveThreadParams): Promise<void> {
}
throw err;
} finally {
- queryClient.invalidateQueries({
- queryKey: emailKeys.threadMessages(params.threadId).queryKey,
- });
- queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
+ if (disposition !== 'queued') {
+ queryClient.invalidateQueries({
+ queryKey: emailKeys.threadMessages(params.threadId).queryKey,
+ });
+ queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
+ }
}
}
@@ -520,29 +531,27 @@ export function useUndoableArchiveThreadMutation(options: {
/** Bind side effects (e.g. an undo toast) to the pushed undo entry. */
onPushed?: (
handle: UndoHandle,
- params: ArchiveThreadParams
+ params: ArchiveThreadParams,
+ disposition: () => EmailArchiveDisposition | undefined
) => { onUndone?: () => void; onRedone?: () => void } | void;
onError?: (params: ArchiveThreadParams) => void;
}) {
return useUndoableMutation<
- void,
+ EmailArchiveDisposition,
Error,
ArchiveThreadParams,
ArchiveThreadContext
>(() => ({
mutationFn: async (params: ArchiveThreadParams) => {
- await throwOnErr(
- async () =>
- await emailClient.flagArchived(
- {
- id: params.threadId,
- value: params.archive,
- },
- params.linkId
- )
+ return await archiveEmailThread(
+ { id: params.threadId, value: params.archive },
+ params.linkId
);
},
onMutate: async (params) => await threadArchiveOnMutate(params),
+ onSuccess: (disposition, _params, context) => {
+ if (context) context.disposition = disposition;
+ },
onError: (_err, params, context) => {
if (context?.previousData) {
queryClient.setQueryData(
@@ -552,17 +561,27 @@ export function useUndoableArchiveThreadMutation(options: {
}
options.onError?.(params);
},
- onSettled: (_data, _error, params) => {
+ onSettled: (disposition, _error, params) => {
+ if (disposition === 'queued') return;
queryClient.invalidateQueries({
queryKey: emailKeys.threadMessages(params.threadId).queryKey,
});
queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });
},
- undoFn: async (params) =>
- replayThreadArchive({ ...params, archive: !params.archive }),
- redoFn: async (params) => replayThreadArchive(params),
+ undoFn: async (params, context) => {
+ const disposition = await replayThreadArchive({
+ ...params,
+ archive: !params.archive,
+ });
+ if (context) context.disposition = disposition;
+ },
+ redoFn: async (params, context) => {
+ const disposition = await replayThreadArchive(params);
+ if (context) context.disposition = disposition;
+ },
undoLabel: (params) => (params.archive ? 'Mark Done' : 'Mark Not Done'),
- onPushed: (handle, params) => options.onPushed?.(handle, params),
+ onPushed: (handle, params, context) =>
+ options.onPushed?.(handle, params, () => context?.disposition),
}));
}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-email-archive-state.ts b/apps/web/src/lib/service-clients/service-storage/graphql-email-archive-state.ts
new file mode 100644
index 0000000000..3c8de52f79
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-email-archive-state.ts
@@ -0,0 +1,38 @@
+import {
+ executeOptimisticMutation,
+ optimisticMutationDispositionOf,
+ type QueryRevalidation,
+} from '@graphql-cache/exchange/optimistic';
+import type { Client } from '@urql/core';
+import { v4 as uuidv4 } from 'uuid';
+import { SetEmailThreadArchivedDocument } from './graphql/generated/graphql';
+
+/** Archive, unarchive, and Undo share an ordered durable normalized-cache write. */
+export async function setGraphqlEmailThreadArchived(
+ client: Client,
+ threadId: string,
+ archived: boolean,
+ revalidations: readonly QueryRevalidation[] = []
+): Promise<'committed' | 'queued'> {
+ const result = await executeOptimisticMutation(
+ client,
+ SetEmailThreadArchivedDocument,
+ { input: { threadId, archived } },
+ {
+ setEmailThreadArchived: {
+ __typename: 'GraphqlSoupEmailThread',
+ id: threadId,
+ inboxVisible: !archived,
+ },
+ },
+ { uuid: uuidv4(), revalidations }
+ ).toPromise();
+ const disposition = optimisticMutationDispositionOf(result);
+ if (disposition?.kind === 'queued') return 'queued';
+ if (disposition?.kind === 'permanently-failed') throw disposition.error;
+ if (result.error) throw result.error;
+ if (!result.data?.setEmailThreadArchived) {
+ throw new Error('Email archive mutation returned no data');
+ }
+ return 'committed';
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/email-archive-state.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/email-archive-state.graphql
new file mode 100644
index 0000000000..34407b131d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/email-archive-state.graphql
@@ -0,0 +1,7 @@
+mutation SetEmailThreadArchived($input: SetEmailThreadArchivedInput!) {
+ setEmailThreadArchived(input: $input) {
+ __typename
+ id
+ inboxVisible
+ }
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index f9eac182b5..b268d3709a 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -1236,6 +1236,14 @@ export type SaveEmailDraftInput = {
to?: Array<SaveEmailDraftContactInput> | null | undefined;
};
+/** Input for archive-based Done and its inverse. No client label lookup is needed. */
+export type SetEmailThreadArchivedInput = {
+ /** True for Done; false for Mark Not Done or Undo. */
+ archived: boolean;
+ /** Thread whose inbox membership should change. */
+ threadId: string | number;
+};
+
/** Input for assigning or updating an entity property. */
export type SetEntityPropertyInput = {
/** Identifier of the entity receiving the property. */
@@ -2089,6 +2097,13 @@ export type ChannelUnreadPresenceQuery = { user: { id: string, soup: { items: Ar
export type GraphqlCrmCompanyQuickAccessFieldsFragment = { __typename: 'GraphqlSoupCrmCompany', name: string | null, teamId: string, hidden: boolean, domains: Array<string>, createdAt: string, updatedAt: string, viewedAt: string | null };
+export type SetEmailThreadArchivedMutationVariables = Exact<{
+ input: SetEmailThreadArchivedInput;
+}>;
+
+
+export type SetEmailThreadArchivedMutation = { setEmailThreadArchived: { __typename: 'GraphqlSoupEmailThread', id: string, inboxVisible: boolean } };
+
export type SaveEmailDraftMutationVariables = Exact<{
input: SaveEmailDraftInput;
}>;
@@ -11967,6 +11982,7 @@ export const UpdateNotificationsDocument = {"kind":"Document","definitions":[{"k
export const UpdateNotificationsForEntityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateNotificationsForEntity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateNotificationsForEntityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateNotificationsForEntity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDocumentMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentMentionDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMentionedInDocumentCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentMentionId"},"name":{"kind":"Name","value":"mentionId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRepliedToDocumentCommentThreadMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCommentedOnDocumentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelInviteMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelInviteInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyUserId"},"name":{"kind":"Name","value":"userId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadParentSenderId"},"name":{"kind":"Name","value":"threadParentSenderId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCallStartedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"callStartedChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"callStartedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewEmailMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"newEmailSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailToEmail"},"name":{"kind":"Name","value":"toEmail"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSubject"},"name":{"kind":"Name","value":"subject"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSnippet"},"name":{"kind":"Name","value":"snippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInboxReauthRequiredMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inboxReauthRequiredEmailAddress"},"name":{"kind":"Name","value":"emailAddress"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInviteToTeamMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamName"},"name":{"kind":"Name","value":"teamName"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamInviteId"},"name":{"kind":"Name","value":"teamInviteId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamRole"},"name":{"kind":"Name","value":"role"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskAssignedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskId"},"name":{"kind":"Name","value":"taskId"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskName"},"name":{"kind":"Name","value":"taskName"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedAssignedBy"},"name":{"kind":"Name","value":"assignedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderReminderId"},"name":{"kind":"Name","value":"reminderId"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderOccurrenceKey"},"name":{"kind":"Name","value":"occurrenceKey"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartsAt"},"name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEndsAt"},"name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartDate"},"name":{"kind":"Name","value":"startDate"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTimeZone"},"name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderMinutesBefore"},"name":{"kind":"Name","value":"minutesBefore"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAiResponseMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"aiResponseSummary"},"name":{"kind":"Name","value":"summary"}},{"kind":"Field","alias":{"kind":"Name","value":"aiResponseMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrStatusChangedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedAction"},"name":{"kind":"Name","value":"action"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedPreviousStatus"},"name":{"kind":"Name","value":"previousStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedHeadBranch"},"name":{"kind":"Name","value":"headBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedBaseBranch"},"name":{"kind":"Name","value":"baseBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedMergedAt"},"name":{"kind":"Name","value":"mergedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCheckRunMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckRunGithubId"},"name":{"kind":"Name","value":"checkRunGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckName"},"name":{"kind":"Name","value":"checkName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckStatus"},"name":{"kind":"Name","value":"checkStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunConclusion"},"name":{"kind":"Name","value":"conclusion"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckUrl"},"name":{"kind":"Name","value":"checkUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCompletedAt"},"name":{"kind":"Name","value":"completedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubReviewRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubLogin"},"name":{"kind":"Name","value":"requestedReviewerGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubUserId"},"name":{"kind":"Name","value":"requestedReviewerGithubUserId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentKind"},"name":{"kind":"Name","value":"commentKind"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentSnippet"},"name":{"kind":"Name","value":"commentSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionLocation"},"name":{"kind":"Name","value":"location"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTextSnippet"},"name":{"kind":"Name","value":"textSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrReviewMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewGithubId"},"name":{"kind":"Name","value":"reviewGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewUrl"},"name":{"kind":"Name","value":"reviewUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewSnippet"},"name":{"kind":"Name","value":"reviewSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionSettledMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledActor"},"name":{"kind":"Name","value":"actor"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledStopReason"},"name":{"kind":"Name","value":"stopReason"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledExcerpt"},"name":{"kind":"Name","value":"excerpt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionWaitingForInputMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputQuestion"},"name":{"kind":"Name","value":"question"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionMentionedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedMentionedBy"},"name":{"kind":"Name","value":"mentionedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedActionId"},"name":{"kind":"Name","value":"actionId"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationStateFields"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationMetadataFields"}}]}}]}}]} as unknown as DocumentNode<UpdateNotificationsForEntityMutation, UpdateNotificationsForEntityMutationVariables>;
export const ChannelListSoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ChannelListSoup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"emailLinks"},"directives":[{"kind":"Directive","name":{"kind":"Name","value":"cacheOnly"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"emailAddress"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ChannelListItemFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupEntityIdentityFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"isFavorited"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MailPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMailPreviewMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessagePreview"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"cacheProjection"},"directives":[{"kind":"Directive","name":{"kind":"Name","value":"cacheOnly"}}]},{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupEntityIdentityFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupAgentSession"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"sessionName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"harness"}},{"kind":"Field","name":{"kind":"Name","value":"repoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"repoBranch"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestUrl"}},{"kind":"Field","name":{"kind":"Name","value":"workingBranch"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestState"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestId"}},{"kind":"Field","name":{"kind":"Name","value":"turnState"}},{"kind":"Field","name":{"kind":"Name","value":"bot"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskSubType"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"model"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"latestInboundMessageTs"}},{"kind":"Field","name":{"kind":"Name","value":"mailAllPreview"},"directives":[{"kind":"Directive","name":{"kind":"Name","value":"cacheOnly"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MailPreviewFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"mailDraftPreview"},"directives":[{"kind":"Directive","name":{"kind":"Name","value":"cacheOnly"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MailPreviewFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"mailSentPreview"},"directives":[{"kind":"Directive","name":{"kind":"Name","value":"cacheOnly"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MailPreviewFields"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"isSignal"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isParticipant"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"sourceMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupReminder"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"scheduleType"}},{"kind":"Field","name":{"kind":"Name","value":"remindAt"}},{"kind":"Field","name":{"kind":"Name","value":"cron"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"nextRunAt"}},{"kind":"Field","name":{"kind":"Name","value":"enabled"}},{"kind":"Field","name":{"kind":"Name","value":"completedAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"referencedEntity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"subType"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCalendarEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"time"}},{"kind":"Field","name":{"kind":"Name","value":"conferenceUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isReadOnly"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ChannelListItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupItemPreviewFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"unreadNotifications"},"name":{"kind":"Name","value":"notifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"states"},"value":{"kind":"ListValue","values":[{"kind":"EnumValue","value":"UNSEEN"}]}},{"kind":"ObjectField","name":{"kind":"Name","value":"eventTypes"},"value":{"kind":"ListValue","values":[{"kind":"StringValue","value":"channel_mention","block":false},{"kind":"StringValue","value":"channel_message_send","block":false},{"kind":"StringValue","value":"channel_message_reply","block":false},{"kind":"StringValue","value":"document_mention","block":false}]}}]}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]} as unknown as DocumentNode<ChannelListSoupQuery, ChannelListSoupQueryVariables>;
export const ChannelUnreadPresenceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ChannelUnreadPresence"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"unreadNotifications"},"name":{"kind":"Name","value":"notifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"states"},"value":{"kind":"ListValue","values":[{"kind":"EnumValue","value":"UNSEEN"}]}},{"kind":"ObjectField","name":{"kind":"Name","value":"eventTypes"},"value":{"kind":"ListValue","values":[{"kind":"StringValue","value":"channel_mention","block":false},{"kind":"StringValue","value":"channel_message_send","block":false},{"kind":"StringValue","value":"channel_message_reply","block":false},{"kind":"StringValue","value":"document_mention","block":false}]}}]}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}}]}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ChannelUnreadPresenceQuery, ChannelUnreadPresenceQueryVariables>;
+export const SetEmailThreadArchivedDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SetEmailThreadArchived"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SetEmailThreadArchivedInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"setEmailThreadArchived"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}}]}}]}}]} as unknown as DocumentNode<SetEmailThreadArchivedMutation, SetEmailThreadArchivedMutationVariables>;
export const SaveEmailDraftDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SaveEmailDraft"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SaveEmailDraftInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"saveEmailDraft"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"draft"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailThreadMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"thread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailThreadMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"replyingToId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"scheduledSendTime"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"sfsId"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsDraft"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"fileName"}},{"kind":"Field","name":{"kind":"Name","value":"contentType"}},{"kind":"Field","name":{"kind":"Name","value":"sha"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"s3Key"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachmentsForwarded"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"attachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"messageProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SaveEmailDraftMutation, SaveEmailDraftMutationVariables>;
export const DeleteEmailDraftDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteEmailDraft"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DeleteEmailDraftInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteEmailDraft"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"draftId"}},{"kind":"Field","name":{"kind":"Name","value":"deleted"}},{"kind":"Field","name":{"kind":"Name","value":"threadDeleted"}}]}}]}}]} as unknown as DocumentNode<DeleteEmailDraftMutation, DeleteEmailDraftMutationVariables>;
export const MarkEmailThreadSeenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkEmailThreadSeen"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"MarkEmailThreadSeenInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"markEmailThreadSeen"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EmailReadStateFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EmailReadStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}}]}}]} as unknown as DocumentNode<MarkEmailThreadSeenMutation, MarkEmailThreadSeenMutationVariables>;
diff --git a/crates/client/cache-core/tests/email_archive_optimistic.rs b/crates/client/cache-core/tests/email_archive_optimistic.rs
new file mode 100644
index 0000000000..4e8ce9e676
--- /dev/null
+++ b/crates/client/cache-core/tests/email_archive_optimistic.rs
@@ -0,0 +1,159 @@
+//! The shipped archive document updates the same normalized email across views,
+//! composes with offline Undo, and settles without overwriting newer intent.
+
+use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};
+use cache_core::queue::{MutationClaimRequest, MutationClaimToken, MutationId};
+use cache_core::store::InMemoryStorage;
+use pollster::block_on;
+use serde_json::{Map, Value, json};
+
+const MUTATION: &str = include_str!(
+ "../../../../apps/web/src/lib/service-clients/service-storage/graphql/email-archive-state.graphql"
+);
+const QUERY: &str = r#"query Mail($input: SoupInput!) {
+ user { id soup(input: $input) { items {
+ __typename id ... on GraphqlSoupEmailThread { inboxVisible isRead }
+ } nextCursor } }
+}"#;
+
+fn variables(archived: bool) -> Map<String, Value> {
+ json!({"input": {"threadId": "thread", "archived": archived}})
+ .as_object()
+ .unwrap()
+ .clone()
+}
+fn response(archived: bool) -> Value {
+ json!({"setEmailThreadArchived": {"__typename": "GraphqlSoupEmailThread", "id": "thread", "inboxVisible": !archived}})
+}
+fn list_variables(view: &str) -> Map<String, Value> {
+ json!({"input": {"initial": {"emailView": view, "limit": 100}}})
+ .as_object()
+ .unwrap()
+ .clone()
+}
+async fn seed() -> Engine<InMemoryStorage> {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ for view in ["INBOX", "ALL"] {
+ engine.write_query(None, QUERY, Some("Mail"), &list_variables(view), &json!({
+ "user": {"id": "viewer", "soup": {"items": [{
+ "__typename": "GraphqlSoupEmailThread", "id": "thread", "inboxVisible": true, "isRead": false,
+ }], "nextCursor": null}},
+ }), None).await.unwrap();
+ }
+ engine
+}
+async fn enqueue(
+ engine: &mut Engine<InMemoryStorage>,
+ uuid: &str,
+ archived: bool,
+ now: i64,
+) -> MutationId {
+ engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ uuid,
+ query: MUTATION,
+ operation_name: Some("SetEmailThreadArchived"),
+ variables: &variables(archived),
+ data: &response(archived),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: now,
+ },
+ )
+ .await
+ .unwrap()
+ .0
+}
+async fn assert_state(engine: &mut Engine<InMemoryStorage>, visible: bool) {
+ for view in ["INBOX", "ALL"] {
+ let ReadResult::Hit { data } = engine
+ .read_query(None, QUERY, Some("Mail"), &list_variables(view))
+ .await
+ .unwrap()
+ else {
+ panic!("archive must preserve a readable cached page");
+ };
+ assert_eq!(data["user"]["soup"]["items"][0]["inboxVisible"], visible);
+ assert_eq!(
+ data["user"]["soup"]["items"][0]["isRead"], false,
+ "archive must not change read state"
+ );
+ }
+}
+async fn claim(engine: &mut Engine<InMemoryStorage>) -> MutationClaimToken {
+ let claimed = engine
+ .claim_next_mutation(MutationClaimRequest {
+ owner: "test".into(),
+ now_ms: 10,
+ lease_expires_at_ms: 1010,
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ MutationClaimToken {
+ owner: "test".into(),
+ generation: claimed.lease_generation,
+ }
+}
+
+#[test]
+fn queued_archive_and_undo_survive_reload_and_keep_the_latest_intent_during_commit() {
+ block_on(async {
+ let mut engine = seed().await;
+ let archive = enqueue(&mut engine, "11111111-1111-4111-8111-111111111111", true, 0).await;
+ assert_state(&mut engine, false).await;
+ let undo = enqueue(
+ &mut engine,
+ "22222222-2222-4222-8222-222222222222",
+ false,
+ 1,
+ )
+ .await;
+ assert_state(&mut engine, true).await;
+ let mut engine = Engine::new(engine.into_storage());
+ assert_state(&mut engine, true).await;
+ let token = claim(&mut engine).await;
+ engine
+ .commit_optimistic_write(
+ archive,
+ token,
+ MUTATION,
+ Some("SetEmailThreadArchived"),
+ &variables(true),
+ &response(true),
+ )
+ .await
+ .unwrap();
+ assert_state(&mut engine, true).await;
+ let token = claim(&mut engine).await;
+ engine
+ .commit_optimistic_write(
+ undo,
+ token,
+ MUTATION,
+ Some("SetEmailThreadArchived"),
+ &variables(false),
+ &response(false),
+ )
+ .await
+ .unwrap();
+ assert_state(&mut engine, true).await;
+ });
+}
+
+#[test]
+fn rejected_archive_rolls_back_without_changing_other_email_fields() {
+ block_on(async {
+ let mut engine = seed().await;
+ let archive = enqueue(&mut engine, "11111111-1111-4111-8111-111111111111", true, 0).await;
+ assert_state(&mut engine, false).await;
+ let token = claim(&mut engine).await;
+ engine
+ .rollback_optimistic_write(archive, token)
+ .await
+ .unwrap();
+ assert_state(&mut engine, true).await;
+ });
+}
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index 0359d83a13..171858fc84 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,8 +2,8 @@
edition = "2024"
name = "cache-wasm"
publish = false
-# Rebuild for the browser's slow SQL execution telemetry callback.
-version = "0.6.18"
+# Rebuild schema metadata for the archive/unarchive GraphQL mutation.
+version = "0.6.19"
[features]
default = []
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 940e5a3c7b..e6edc52bde 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -43,6 +43,7 @@ use uuid::Uuid;
use super::*;
+mod email_archive;
mod soup_patches;
const VALID_USER_ID: &str = "macro|[email protected]";
@@ -290,6 +291,9 @@ impl SoupService for CountingSoupService {
/// the lazy extraction actually runs.
#[derive(Clone, Default)]
struct CountingEmailService {
+ thread_is_read: Arc<Mutex<bool>>,
+ thread_archived: Arc<Mutex<bool>>,
+ archive_mutation_calls: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, bool)>>>,
inbox_calls: Arc<AtomicUsize>,
user_label_calls: Arc<AtomicUsize>,
user_link_calls: Arc<AtomicUsize>,
@@ -299,6 +303,23 @@ struct CountingEmailService {
label_mutation_calls: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, Uuid, bool)>>>,
}
+impl graphql_soup::EmailMutationThreadReader for CountingEmailService {
+ async fn read(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> async_graphql::Result<Option<SoupEnrichedEmailThreadPreview<()>>> {
+ assert_eq!(user_id.as_ref(), VALID_USER_ID);
+ let SoupItem::EmailThread(mut thread) =
+ soup_email_thread_with_read_status(thread_id, *self.thread_is_read.lock().unwrap())
+ else {
+ unreachable!()
+ };
+ thread.thread.inbox_visible = !*self.thread_archived.lock().unwrap();
+ Ok(Some(thread))
+ }
+}
+
fn test_email_err() -> EmailErr {
EmailErr::RepoErr(anyhow::anyhow!("counting email service"))
}
@@ -355,6 +376,20 @@ impl EmailUserService for CountingEmailService {
}
impl EmailService for CountingEmailService {
+ async fn set_thread_archived(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> Result<(), EmailErr> {
+ *self.thread_archived.lock().unwrap() = archived;
+ self.archive_mutation_calls
+ .lock()
+ .unwrap()
+ .push((user_id, thread_id, archived));
+ Ok(())
+ }
+
async fn get_email_thread_previews(
&self,
_req: GetEmailsRequest,
@@ -466,6 +501,7 @@ impl EmailService for CountingEmailService {
macro_id: MacroUserIdStr<'static>,
thread_id: Uuid,
) -> Result<(), EmailErr> {
+ *self.thread_is_read.lock().unwrap() = true;
self.seen_mutation_calls
.lock()
.expect("seen mutation calls lock")
@@ -478,6 +514,7 @@ impl EmailService for CountingEmailService {
macro_id: MacroUserIdStr<'static>,
thread_id: Uuid,
) -> Result<(), EmailErr> {
+ *self.thread_is_read.lock().unwrap() = false;
self.unread_mutation_calls
.lock()
.expect("unread mutation calls lock")
@@ -1130,6 +1167,9 @@ impl TestHarness {
.data(GraphqlRequestParts::new(parts))
.data(self.state.clone())
.data(self.state.email.service())
+ .data(graphql_soup::EmailMutationThreadLoader::new(
+ self.email_service.clone(),
+ ))
.data(graphql_soup::soup_item_loader(
self.soup_service.clone(),
Arc::new(self.email_service.clone()),
@@ -2157,13 +2197,13 @@ async fn latest_email_message_full_fields_request_the_full_edge_payload() {
}
#[tokio::test]
-async fn email_mutations_return_the_canonical_thread_for_normalized_cache_updates() {
+async fn email_mutations_return_primary_state_even_when_the_soup_replica_is_stale() {
let harness = harness();
let thread_id = Uuid::from_u128(44);
let label_id = Uuid::from_u128(45);
harness
.soup_service
- .set_raw_response(vec![soup_email_thread_with_read_status(thread_id, true)]);
+ .set_raw_response(vec![soup_email_thread_with_read_status(thread_id, false)]);
let seen_response = harness
.execute_authenticated_mutation(&format!(
@@ -2197,7 +2237,7 @@ async fn email_mutations_return_the_canonical_thread_for_normalized_cache_update
harness
.soup_service
- .set_raw_response(vec![soup_email_thread_with_read_status(thread_id, false)]);
+ .set_raw_response(vec![soup_email_thread_with_read_status(thread_id, true)]);
let unread_response = harness
.execute_authenticated_mutation(&format!(
r#"mutation {{ markEmailThreadUnread(input: {{threadId: "{thread_id}"}}) {{ __typename id isRead }} }}"#
@@ -2212,6 +2252,7 @@ async fn email_mutations_return_the_canonical_thread_for_normalized_cache_update
assert_eq!(unread_thread["__typename"], "GraphqlSoupEmailThread");
assert_eq!(unread_thread["id"], thread_id.to_string());
assert_eq!(unread_thread["isRead"], false);
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 0);
let expected_user = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();
assert_eq!(
diff --git a/crates/complete_graph/src/schema/test/email_archive.rs b/crates/complete_graph/src/schema/test/email_archive.rs
new file mode 100644
index 0000000000..3662975b79
--- /dev/null
+++ b/crates/complete_graph/src/schema/test/email_archive.rs
@@ -0,0 +1,100 @@
+use super::*;
+
+#[tokio::test]
+async fn ordinary_email_queries_use_the_replica_while_mutations_reload_from_primary() {
+ let harness = harness();
+ let id = Uuid::from_u128(44);
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread(id)]);
+ let query = format!(
+ r#"{{ user {{ emailThread(input: {{threadId: "{id}"}}) {{isRead inboxVisible}} }} }}"#
+ );
+ let before = harness.execute(&query).await;
+ assert!(before.errors.is_empty(), "{:?}", before.errors);
+ let before = before.data.into_json().unwrap();
+ assert_eq!(before["user"]["emailThread"]["isRead"], false);
+ assert_eq!(before["user"]["emailThread"]["inboxVisible"], true);
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 1);
+
+ let mutation = harness.execute_authenticated_mutation(&format!(
+ r#"mutation {{
+ seen: markEmailThreadSeen(input: {{threadId: "{id}"}}) {{isRead}}
+ archived: setEmailThreadArchived(input: {{threadId: "{id}", archived: true}}) {{isRead inboxVisible}}
+ }}"#
+ )).await;
+ assert!(mutation.errors.is_empty(), "{:?}", mutation.errors);
+ let mutation = mutation.data.into_json().unwrap();
+ assert_eq!(mutation["seen"]["isRead"], true);
+ assert_eq!(mutation["archived"]["isRead"], true);
+ assert_eq!(mutation["archived"]["inboxVisible"], false);
+ // Neither mutation consulted the lagging Soup reader.
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 1);
+
+ let after = harness.execute(&query).await;
+ assert!(after.errors.is_empty(), "{:?}", after.errors);
+ assert_eq!(after.data.into_json().unwrap(), before);
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 2);
+
+ // Normal reads catch up only when the replica does, not by silently
+ // escalating their pool after a mutation.
+ let SoupItem::EmailThread(mut replica) = soup_email_thread_with_read_status(id, true) else {
+ unreachable!()
+ };
+ replica.thread.inbox_visible = false;
+ harness
+ .soup_service
+ .set_raw_response(vec![SoupItem::EmailThread(replica)]);
+ let caught_up = harness.execute(&query).await;
+ assert!(caught_up.errors.is_empty(), "{:?}", caught_up.errors);
+ let caught_up = caught_up.data.into_json().unwrap();
+ assert_eq!(caught_up["user"]["emailThread"]["isRead"], true);
+ assert_eq!(caught_up["user"]["emailThread"]["inboxVisible"], false);
+}
+
+#[tokio::test]
+async fn sequential_read_mutations_do_not_reuse_the_first_mutation_snapshot() {
+ let harness = harness();
+ let id = Uuid::from_u128(44);
+ let response = harness
+ .execute_authenticated_mutation(&format!(
+ r#"mutation {{ seen: markEmailThreadSeen(input: {{threadId: "{id}"}}) {{isRead}}
+ unread: markEmailThreadUnread(input: {{threadId: "{id}"}}) {{isRead}} }}"#
+ ))
+ .await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(data["seen"]["isRead"], true);
+ assert_eq!(data["unread"]["isRead"], false);
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn archive_undo_and_redo_return_primary_state_without_reading_the_soup_replica() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(44);
+ // The replica never changes during these writes.
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread(thread_id)]);
+ for archived in [true, false, true] {
+ let response = harness.execute_authenticated_mutation(&format!(
+ r#"mutation {{ setEmailThreadArchived(input: {{threadId: "{thread_id}", archived: {archived}}}) {{__typename id inboxVisible}} }}"#
+ )).await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let thread = &data["setEmailThreadArchived"];
+ assert_eq!(thread["__typename"], "GraphqlSoupEmailThread");
+ assert_eq!(thread["id"], thread_id.to_string());
+ assert_eq!(thread["inboxVisible"], !archived);
+ }
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ *harness.email_service.archive_mutation_calls.lock().unwrap(),
+ [true, false, true].map(|archived| (
+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),
+ thread_id,
+ archived,
+ ))
+ );
+}
diff --git a/crates/email/fixtures/email_thread_archive.sql b/crates/email/fixtures/email_thread_archive.sql
new file mode 100644
index 0000000000..378e61c250
--- /dev/null
+++ b/crates/email/fixtures/email_thread_archive.sql
@@ -0,0 +1,7 @@
+-- Extend the two-inbox fixture with canonical inbound metadata and INBOX state.
+UPDATE email_threads
+SET latest_inbound_message_ts = '2025-01-01T11:00:00Z'
+WHERE id IN ('11111111-1111-1111-1111-111111111111', '33333333-3333-3333-3333-333333333333');
+
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES ('33333333-aaaa-aaaa-aaaa-333333333333', 'ffffffff-ffff-ffff-ffff-ffffffffffff');
diff --git a/crates/email/fixtures/email_thread_archive_failure.sql b/crates/email/fixtures/email_thread_archive_failure.sql
new file mode 100644
index 0000000000..274229dc9a
--- /dev/null
+++ b/crates/email/fixtures/email_thread_archive_failure.sql
@@ -0,0 +1,9 @@
+CREATE FUNCTION fail_thread_archive_update() RETURNS TRIGGER AS $$
+BEGIN
+ RAISE EXCEPTION 'archive-state test failure';
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER fail_thread_archive_update
+BEFORE UPDATE OF inbox_visible ON email_threads
+FOR EACH ROW EXECUTE FUNCTION fail_thread_archive_update();
diff --git a/crates/email/src/domain/models/error.rs b/crates/email/src/domain/models/error.rs
index a4f47de424..6ab4cbad13 100644
--- a/crates/email/src/domain/models/error.rs
+++ b/crates/email/src/domain/models/error.rs
@@ -42,6 +42,9 @@ pub enum EmailErr {
/// No messages found for thread.
#[error("No messages found for thread")]
ThreadEmpty,
+
+ #[error("thread has no received messages and cannot be unarchived")]
+ ThreadHasNoInboundMessages,
/// Thread not found.
#[error("Thread not found")]
ThreadNotFound,
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index f50ac32895..a2684ed39e 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -355,6 +355,19 @@ pub trait EmailRepo: Send + Sync + 'static {
is_read: bool,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Atomically change INBOX assignments and the thread's visibility.
+ /// The message IDs belong to the authorized thread/inbox. Visibility is
+ /// separate from `add` so an enqueue failure can restore the prior flag
+ /// while reverting only the assignments changed by that operation.
+ fn set_thread_inbox_state(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ message_ids: &[Uuid],
+ add: bool,
+ inbox_visible: bool,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Update the read status for a batch of messages, verified by link_id.
fn update_message_read_status_batch(
&self,
@@ -451,8 +464,9 @@ pub trait EmailRepo: Send + Sync + 'static {
}
}
-/// Read-only trait for fetching email thread previews.
-/// Used by soup to restrict access to only read email operations as it uses the read replica database.
+/// Read-only capability for fetching email thread previews. The composition
+/// root supplies the replica-backed service for ordinary REST/GraphQL Soup.
+/// Mutation replies reload through the primary-backed email writer instead.
pub trait EmailPreviewServiceReadOnly: Send + Sync + 'static {
fn get_email_thread_previews(
&self,
@@ -516,8 +530,9 @@ pub trait EmailContentService: Send + Sync + 'static {
}
/// Newtype adapter that restricts a full `EmailService` to read-only preview access.
-/// Wrapping is explicit so readonly wiring is intentional — a bare `EmailServiceImpl`
-/// will *not* silently satisfy `EmailPreviewServiceReadOnly`.
+/// This narrows capabilities, not consistency: the wrapped service may use a
+/// primary or replica pool. A bare `EmailServiceImpl` will not silently satisfy
+/// `EmailPreviewServiceReadOnly`.
pub struct ReadonlyEmailPreviewAdapter<T>(pub T);
impl<T: EmailService> EmailPreviewServiceReadOnly for ReadonlyEmailPreviewAdapter<T> {
@@ -684,6 +699,15 @@ pub trait EmailService: Send + Sync + 'static {
thread_id: Uuid,
) -> impl Future<Output = Result<(), EmailErr>> + Send;
+ /// Archive or unarchive a caller-owned/delegated thread. The service
+ /// resolves the thread's inbox and system label, then queues provider sync.
+ fn set_thread_archived(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+
/// Add or remove a label from a caller-accessible thread.
fn update_thread_labels_for_user(
&self,
@@ -845,6 +869,15 @@ impl EmailUserService for NoOpEmailService {
}
impl EmailService for NoOpEmailService {
+ async fn set_thread_archived(
+ &self,
+ _macro_id: MacroUserIdStr<'static>,
+ _thread_id: Uuid,
+ _archived: bool,
+ ) -> Result<(), EmailErr> {
+ Err(no_op_email_err())
+ }
+
async fn get_email_thread_previews(
&self,
_req: GetEmailsRequest,
diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rs
index 6cc0381979..c29298f1f2 100644
--- a/crates/email/src/domain/service.rs
+++ b/crates/email/src/domain/service.rs
@@ -332,6 +332,16 @@ where
self.mark_thread_seen_impl(macro_id, thread_id).await
}
+ async fn set_thread_archived(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> Result<(), EmailErr> {
+ self.set_thread_archived_impl(macro_id, thread_id, archived)
+ .await
+ }
+
async fn mark_thread_unread(
&self,
macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rs
index 6fbea6bca0..9fe428c70a 100644
--- a/crates/email/src/domain/service/thread_labels.rs
+++ b/crates/email/src/domain/service/thread_labels.rs
@@ -11,6 +11,13 @@ use uuid::Uuid;
use super::EmailServiceImpl;
+/// Facts captured before a label write, used only if provider enqueue fails.
+struct ThreadLabelRollback<'a> {
+ all_ids: &'a [Uuid],
+ changed_ids: &'a [Uuid],
+ inbox_visible: Option<bool>,
+}
+
impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B>
where
T: EmailRepo,
@@ -104,6 +111,42 @@ where
Ok(())
}
+ /// Resolve the owning inbox server-side, including delegated inboxes.
+ #[tracing::instrument(err, skip(self), fields(user_id = %macro_id, %thread_id, archived))]
+ pub(crate) async fn set_thread_archived_impl(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> Result<(), EmailErr> {
+ let link = self
+ .email_repo
+ .owned_link_for_thread(thread_id, macro_id.clone())
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::ThreadNotFound)?;
+ let thread = self
+ .email_repo
+ .thread_by_id(thread_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::ThreadNotFound)?;
+ if !archived && thread.latest_inbound_message_ts.is_none() {
+ return Err(EmailErr::ThreadHasNoInboundMessages);
+ }
+ let label = self
+ .email_repo
+ .list_labels_by_link_id(link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .into_iter()
+ .find(|label| label.provider_label_id == system_labels::INBOX)
+ .ok_or(EmailErr::LabelNotFound)?;
+ self.update_thread_labels_with_actor(&link, thread_id, label.id, !archived, Some(macro_id))
+ .await?;
+ Ok(())
+ }
+
#[tracing::instrument(err, skip(self), fields(user_id = %macro_id, %thread_id, %label_id, add))]
pub(crate) async fn update_thread_labels_for_user_impl(
&self,
@@ -130,6 +173,19 @@ where
thread_id: Uuid,
label_id: Uuid,
add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.update_thread_labels_with_actor(link, thread_id, label_id, add, None)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, link))]
+ async fn update_thread_labels_with_actor(
+ &self,
+ link: &Link,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ actor: Option<macro_user_id::user_id::MacroUserIdStr<'static>>,
) -> Result<UpdateThreadLabelsResult, EmailErr> {
let label = self
.email_repo
@@ -176,11 +232,27 @@ where
.collect(),
Err(e) => {
let err = anyhow::Error::from(e);
+ if provider_label_id == system_labels::INBOX {
+ return Err(EmailErr::RepoErr(err));
+ }
tracing::warn!(error=?err, "failed to snapshot message labels; revert would cover all messages");
all_ids.clone()
}
};
+ let previous_inbox_visible = if provider_label_id == system_labels::INBOX {
+ Some(
+ self.email_repo
+ .thread_by_id(thread_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::ThreadNotFound)?
+ .inbox_visible,
+ )
+ } else {
+ None
+ };
+
// Optimistic DB update: update all messages first
self.apply_label_db_changes(link, thread_id, &all_ids, &provider_label_id, add)
.await?;
@@ -222,8 +294,11 @@ where
self.revert_label_db_changes(
link,
thread_id,
- &all_ids,
- &changed_ids,
+ ThreadLabelRollback {
+ all_ids: &all_ids,
+ changed_ids: &changed_ids,
+ inbox_visible: previous_inbox_visible,
+ },
&provider_label_id,
add,
)
@@ -263,7 +338,7 @@ where
// writes are committed and the provider sync is queued. The provider
// echo of this change finds no label diff during inbox sync, so each
// change publishes only once.
- self.publish_thread_label_events(link, thread_id, &label, add, &cancelled_send_ids);
+ self.publish_thread_label_events(link, thread_id, &label, add, &cancelled_send_ids, actor);
Ok(UpdateThreadLabelsResult {
successful_ids: all_ids,
@@ -281,11 +356,26 @@ where
&self,
link: &Link,
thread_id: Uuid,
- all_ids: &[Uuid],
- changed_ids: &[Uuid],
+ snapshot: ThreadLabelRollback<'_>,
provider_label_id: &str,
add: bool,
) {
+ let ThreadLabelRollback {
+ all_ids,
+ changed_ids,
+ inbox_visible,
+ } = snapshot;
+ if let Some(inbox_visible) = inbox_visible {
+ if let Err(e) = self
+ .email_repo
+ .set_thread_inbox_state(thread_id, link.id, changed_ids, !add, inbox_visible)
+ .await
+ {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to revert thread inbox state after enqueue failure");
+ }
+ return;
+ }
if !changed_ids.is_empty() {
let db_result = if add {
self.email_repo
@@ -342,9 +432,9 @@ where
}
}
- /// Apply a thread label change to the DB. UNREAD assignments and read
- /// flags commit atomically; a failure propagates before provider sync or
- /// events. Other labels retain their best-effort starred side effect.
+ /// Apply a thread label change to the DB. UNREAD/read flags and INBOX/
+ /// visibility commit atomically; a failure propagates before provider sync
+ /// or events. Other labels retain their best-effort starred side effect.
async fn apply_label_db_changes(
&self,
link: &Link,
@@ -353,6 +443,13 @@ where
provider_label_id: &str,
add: bool,
) -> Result<(), EmailErr> {
+ if provider_label_id == system_labels::INBOX {
+ return self
+ .email_repo
+ .set_thread_inbox_state(thread_id, link.id, message_ids, add, add)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)));
+ }
if provider_label_id == system_labels::UNREAD {
return self
.email_repo
@@ -402,11 +499,12 @@ where
label: &LinkLabel,
add: bool,
cancelled_send_ids: &[Uuid],
+ actor: Option<macro_user_id::user_id::MacroUserIdStr<'static>>,
) {
let event = EmailMacroEvent::thread_label_change(
link.id,
link.macro_id.clone(),
- None,
+ actor.clone(),
thread_id,
LabelRef {
label_id: Some(label.id),
@@ -426,7 +524,7 @@ where
MessageSendCancelledMetadata {
link_id: link.id,
owner: link.macro_id.clone(),
- actor: None,
+ actor: actor.clone(),
message_id: *message_id,
thread_id,
reason: SendCancelReason::ThreadTrashed,
diff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rs
index f2334a5a8a..7b30e4b5ca 100644
--- a/crates/email/src/outbound/email_pg_repo.rs
+++ b/crates/email/src/outbound/email_pg_repo.rs
@@ -357,6 +357,25 @@ impl EmailRepo for EmailPgRepo {
label::set_thread_read_state(&self.pool, thread_id, link_id, message_ids, is_read).await
}
+ async fn set_thread_inbox_state(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ message_ids: &[Uuid],
+ add: bool,
+ inbox_visible: bool,
+ ) -> Result<(), Self::Err> {
+ label::set_thread_inbox_state(
+ &self.pool,
+ thread_id,
+ link_id,
+ message_ids,
+ add,
+ inbox_visible,
+ )
+ .await
+ }
+
async fn update_message_read_status_batch(
&self,
message_ids: &[Uuid],
diff --git a/crates/email/src/outbound/email_pg_repo/label.rs b/crates/email/src/outbound/email_pg_repo/label.rs
index 3ae79646e5..e9b9859734 100644
--- a/crates/email/src/outbound/email_pg_repo/label.rs
+++ b/crates/email/src/outbound/email_pg_repo/label.rs
@@ -227,6 +227,37 @@ pub(super) async fn set_thread_read_state(
tx.commit().await
}
+/// Commit INBOX assignments and the canonical thread flag in one transaction.
+#[tracing::instrument(skip(pool, message_ids), err)]
+pub(super) async fn set_thread_inbox_state(
+ pool: &PgPool,
+ thread_id: Uuid,
+ link_id: Uuid,
+ message_ids: &[Uuid],
+ add: bool,
+ inbox_visible: bool,
+) -> Result<(), sqlx::Error> {
+ let mut tx = pool.begin().await?;
+ if add {
+ insert_message_labels_batch(&mut *tx, message_ids, system_labels::INBOX, link_id).await?;
+ } else {
+ delete_message_labels_batch(&mut *tx, message_ids, system_labels::INBOX, link_id).await?;
+ }
+ sqlx::query!(
+ r#"
+ UPDATE email_threads
+ SET inbox_visible = $1, updated_at = NOW()
+ WHERE id = $2 AND link_id = $3
+ "#,
+ inbox_visible,
+ thread_id,
+ link_id,
+ )
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await
+}
+
#[tracing::instrument(skip(executor), err)]
pub(crate) async fn insert_message_labels_batch(
executor: impl sqlx::PgExecutor<'_>,
diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rs
index cc4284ad1f..6d56ffc8b2 100644
--- a/crates/email/src/outbound/email_pg_repo/test.rs
+++ b/crates/email/src/outbound/email_pg_repo/test.rs
@@ -12,6 +12,7 @@ mod project_scope_dynamic_query;
mod settings;
mod signal_flag;
mod thread;
+mod thread_archive;
mod thread_labels;
mod thread_unread;
diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs
new file mode 100644
index 0000000000..088d0c9c67
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs
@@ -0,0 +1,277 @@
+use super::thread_unread::service;
+use super::*;
+use crate::domain::models::EmailErr;
+use crate::domain::{ports::EmailMessageEnqueuer, service::EmailServiceImpl};
+
+struct RecordingBroker(Arc<std::sync::Mutex<Vec<serde_json::Value>>>);
+impl macro_event_broker::MacroEventBroker for RecordingBroker {
+ fn send_event<E: macro_event_broker::MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<
+ tokio::task::JoinHandle<Result<(), macro_event_broker::EventBrokerError>>,
+ macro_event_broker::EventBrokerError,
+ > {
+ self.0
+ .lock()
+ .unwrap()
+ .push(serde_json::to_value(event.event())?);
+ Ok(tokio::spawn(async { Ok(()) }))
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn archive_publishes_one_user_attributed_event_after_commit(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let events = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let service = service(pool).with_macro_event_broker(RecordingBroker(events.clone()));
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let id = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ service
+ .set_thread_archived_impl(owner.clone(), id, true)
+ .await?;
+ assert_inbox_state(&service.email_repo, id, false).await?;
+ let events = events.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0]["event_type"], "email.thread_archived");
+ assert_eq!(events[0]["metadata"]["actor"], owner.as_ref());
+ assert_eq!(events[0]["metadata"]["archived"], true);
+ Ok(())
+}
+
+struct FailingEnqueuer;
+impl EmailMessageEnqueuer for FailingEnqueuer {
+ type Err = anyhow::Error;
+ async fn enqueue_scheduled_message(
+ &self,
+ _: Uuid,
+ _: Uuid,
+ _: Option<i32>,
+ ) -> anyhow::Result<()> {
+ unreachable!()
+ }
+ async fn enqueue_gmail_ops_modify_labels_batch(
+ &self,
+ _: Uuid,
+ _: Vec<(Uuid, String)>,
+ _: Vec<String>,
+ _: Vec<String>,
+ ) -> anyhow::Result<()> {
+ anyhow::bail!("test queue unavailable")
+ }
+ async fn enqueue_gmail_ops_block_sender(&self, _: Uuid, _: String) -> anyhow::Result<()> {
+ unreachable!()
+ }
+ async fn enqueue_gmail_ops_unblock_sender(&self, _: Uuid, _: String) -> anyhow::Result<()> {
+ unreachable!()
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn archive_enqueue_failure_restores_only_changed_labels_and_the_original_flag(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let original = service(pool);
+ let service = EmailServiceImpl {
+ email_repo: original.email_repo,
+ frecency_service: original.frecency_service,
+ enqueuer: FailingEnqueuer,
+ crm_service: original.crm_service,
+ entity_access_management_service: original.entity_access_management_service,
+ macro_event_broker: original.macro_event_broker,
+ sent_undo_delay_secs: original.sent_undo_delay_secs,
+ };
+ let thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let first = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+ let second = Uuid::parse_str("11111111-bbbb-bbbb-bbbb-111111111111")?;
+ service
+ .email_repo
+ .delete_message_labels_batch(&[second], "INBOX", link)
+ .await?;
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(
+ MacroUserIdStr::try_from_email("[email protected]")?,
+ thread,
+ true,
+ )
+ .await,
+ Err(EmailErr::EnqueueErr(_))
+ ));
+ assert!(
+ service
+ .email_repo
+ .thread_by_id(thread)
+ .await?
+ .unwrap()
+ .inbox_visible
+ );
+ let labels = service
+ .email_repo
+ .labels_by_message_ids(&[first, second])
+ .await?;
+ for (id, expected) in [(first, true), (second, false)] {
+ assert_eq!(
+ labels
+ .get(&id)
+ .into_iter()
+ .flatten()
+ .any(|label| label.provider_label_id == "INBOX"),
+ expected
+ );
+ }
+ Ok(())
+}
+
+async fn assert_inbox_state(
+ repo: &EmailPgRepo,
+ thread_id: Uuid,
+ visible: bool,
+) -> anyhow::Result<()> {
+ let thread = repo.thread_by_id(thread_id).await?.unwrap();
+ assert_eq!(thread.inbox_visible, visible);
+ let messages = repo
+ .get_thread_label_messages(thread_id, thread.link_id)
+ .await?;
+ let ids: Vec<_> = messages.iter().map(|message| message.db_id).collect();
+ let labels = repo.labels_by_message_ids(&ids).await?;
+ for id in ids {
+ assert_eq!(
+ labels
+ .get(&id)
+ .into_iter()
+ .flatten()
+ .any(|label| label.provider_label_id == "INBOX"),
+ visible
+ );
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn archive_undo_redo_are_idempotent_and_use_the_threads_own_inbox(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let first = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let second = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ for archived in [true, true, false, false, true] {
+ service
+ .set_thread_archived_impl(owner.clone(), second, archived)
+ .await?;
+ assert_inbox_state(&service.email_repo, second, !archived).await?;
+ assert_inbox_state(&service.email_repo, first, true).await?;
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn archive_rejects_inaccessible_and_empty_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+ let first = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ for archived in [true, false] {
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(
+ MacroUserIdStr::try_from_email("[email protected]")?,
+ first,
+ archived,
+ )
+ .await,
+ Err(EmailErr::ThreadNotFound)
+ ));
+ }
+ assert_inbox_state(&service.email_repo, first, true).await?;
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(
+ MacroUserIdStr::try_from_email("[email protected]")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ true,
+ )
+ .await,
+ Err(EmailErr::ThreadEmpty)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts(
+ "email_thread_labels",
+ "email_thread_unread",
+ "email_thread_archive",
+ "email_thread_archive_failure"
+ )
+ )
+)]
+async fn failed_archive_rolls_back_inbox_label_removal(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let service = service(pool);
+ let thread = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(
+ MacroUserIdStr::try_from_email("[email protected]")?,
+ thread,
+ true,
+ )
+ .await,
+ Err(EmailErr::RepoErr(_))
+ ));
+ assert_inbox_state(&service.email_repo, thread, true).await?;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn unarchive_requires_a_canonical_inbound_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+ let thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(
+ MacroUserIdStr::try_from_email("[email protected]")?,
+ thread,
+ false,
+ )
+ .await,
+ Err(EmailErr::ThreadHasNoInboundMessages)
+ ));
+ assert_inbox_state(&service.email_repo, thread, true).await?;
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_unread.rs b/crates/email/src/outbound/email_pg_repo/test/thread_unread.rs
index b5c63b207d..80bd53dc5a 100644
--- a/crates/email/src/outbound/email_pg_repo/test/thread_unread.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/thread_unread.rs
@@ -4,7 +4,7 @@ use crm::domain::service::NoOpCrmService;
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_event_broker::NoopMacroEventBroker;
-fn service(
+pub(super) fn service(
pool: Pool<Postgres>,
) -> EmailServiceImpl<
EmailPgRepo,
diff --git a/crates/graphql_email/src/mutation.rs b/crates/graphql_email/src/mutation.rs
index c6661cf074..d6babd5dbb 100644
--- a/crates/graphql_email/src/mutation.rs
+++ b/crates/graphql_email/src/mutation.rs
@@ -35,6 +35,14 @@ pub trait EmailMutationService: Send + Sync + 'static {
thread_id: Uuid,
) -> impl Future<Output = Result<(), EmailErr>> + Send;
+ /// Archive or unarchive an owned/delegated thread through its owning inbox.
+ fn set_email_thread_archived(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+
/// Add or remove one label from every message in an accessible email thread.
fn update_email_thread_label(
&self,
@@ -82,6 +90,15 @@ where
self.mark_thread_unread(user_id, thread_id).await
}
+ async fn set_email_thread_archived(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> Result<(), EmailErr> {
+ self.set_thread_archived(user_id, thread_id, archived).await
+ }
+
async fn update_email_thread_label(
&self,
user_id: MacroUserIdStr<'static>,
@@ -161,6 +178,15 @@ pub struct MarkEmailThreadUnreadInput {
pub thread_id: ID,
}
+/// Input for archive-based Done and its inverse. No client label lookup is needed.
+#[derive(InputObject)]
+pub struct SetEmailThreadArchivedInput {
+ /// Thread whose inbox membership should change.
+ pub thread_id: ID,
+ /// True for Done; false for Mark Not Done or Undo.
+ pub archived: bool,
+}
+
/// Input for adding or removing a label from an email thread.
#[derive(InputObject)]
pub struct UpdateEmailThreadLabelInput {
@@ -383,15 +409,16 @@ fn draft_mutation_error(error: &EmailErr) -> async_graphql::Error {
}
EmailErr::Unauthorized => ("not authorized to modify email draft", "UNAUTHORIZED"),
EmailErr::RepoErr(_) => {
- return retryable_draft_error(async_graphql::Error::new("email draft mutation failed"));
+ return retryable_email_error(async_graphql::Error::new("email draft mutation failed"));
}
_ => ("email draft mutation failed", "INTERNAL"),
};
async_graphql::Error::new(message).extend_with(|_, extensions| extensions.set("code", code))
}
-/// Draft writes use stable identities, so retrying an uncertain outcome is safe.
-fn retryable_draft_error(error: async_graphql::Error) -> async_graphql::Error {
+/// State-setting writes and draft handles are idempotent; an uncertain reply
+/// must not roll back the client after the domain write already committed.
+fn retryable_email_error(error: async_graphql::Error) -> async_graphql::Error {
error.extend_with(|_, extensions| {
extensions.set("code", "INTERNAL");
extensions.set("retryable", true);
@@ -403,6 +430,9 @@ fn mutation_error(error: &EmailErr) -> async_graphql::Error {
EmailErr::ThreadNotFound | EmailErr::ThreadEmpty => "email thread not found",
EmailErr::LabelNotFound => "email label not found",
EmailErr::EmptyProviderLabelId => "email label is invalid",
+ EmailErr::ThreadHasNoInboundMessages => {
+ "thread has no received messages and cannot be unarchived"
+ }
EmailErr::Unauthorized => "not authorized to update email thread",
_ => "email thread mutation failed",
};
@@ -414,9 +444,13 @@ async fn reload_thread<O: EmailThreadMutationOutput>(
user_id: MacroUserIdStr<'static>,
thread_id: Uuid,
) -> async_graphql::Result<O::Thread> {
- O::load_email_thread(ctx, user_id, thread_id)
- .await?
- .ok_or_else(|| async_graphql::Error::new("updated email thread is unavailable"))
+ async {
+ O::load_email_thread(ctx, user_id, thread_id)
+ .await?
+ .ok_or_else(|| async_graphql::Error::new("updated email thread is unavailable"))
+ }
+ .await
+ .map_err(retryable_email_error)
}
/// GraphQL email mutations.
@@ -480,6 +514,25 @@ where
reload_thread::<O>(ctx, user_id, thread_id).await
}
+ /// Set archive-based Done and return the primary-backed canonical thread.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn set_email_thread_archived(
+ &self,
+ ctx: &Context<'_>,
+ input: SetEmailThreadArchivedInput,
+ ) -> async_graphql::Result<O::Thread> {
+ let user_id = require_authenticated_user(ctx)?;
+ let thread_id = parse_id(input.thread_id, "threadId")?;
+ ctx.data::<Arc<S>>()?
+ .set_email_thread_archived(user_id.clone(), thread_id, input.archived)
+ .await
+ .map_err(|error| {
+ tracing::error!(error = ?error, %user_id, %thread_id, "failed to set email thread archive state");
+ mutation_error(&error)
+ })?;
+ reload_thread::<O>(ctx, user_id, thread_id).await
+ }
+
/// Add or remove one label from an accessible email thread and return its authoritative cache record.
#[tracing::instrument(skip_all, err(Debug))]
async fn update_email_thread_label(
@@ -544,7 +597,7 @@ where
let draft_id = saved.draft.db_id;
let thread = reload_thread::<O>(ctx, user_id, saved.draft.thread_db_id)
.await
- .map_err(retryable_draft_error)?;
+ .map_err(retryable_email_error)?;
Ok(SaveEmailDraftPayload {
draft_id,
draft: GraphqlSoupEmailMessage::from_content(EmailContentMessage::from(
diff --git a/crates/graphql_email/src/mutation/test.rs b/crates/graphql_email/src/mutation/test.rs
index 9ffe67d858..80181aa062 100644
--- a/crates/graphql_email/src/mutation/test.rs
+++ b/crates/graphql_email/src/mutation/test.rs
@@ -5,6 +5,8 @@ use email::domain::models::{AttachmentDraft, AttachmentForwarded, MessageAttachm
use super::*;
+mod archive;
+
struct QueryRoot;
#[Object]
@@ -24,6 +26,11 @@ enum CapturedMutation {
user_id: String,
thread_id: Uuid,
},
+ Archive {
+ user_id: String,
+ thread_id: Uuid,
+ archived: bool,
+ },
Label {
user_id: String,
thread_id: Uuid,
@@ -56,11 +63,29 @@ struct CapturingEmailMutationService {
attachments_draft: Vec<AttachmentDraft>,
attachments_forwarded: Vec<AttachmentForwarded>,
reject_unread: bool,
+ reject_archive: bool,
}
const TEST_THREAD_ID: Uuid = Uuid::from_u128(0x7ead);
impl EmailMutationService for CapturingEmailMutationService {
+ async fn set_email_thread_archived(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ archived: bool,
+ ) -> Result<(), EmailErr> {
+ self.calls.lock().unwrap().push(CapturedMutation::Archive {
+ user_id: user_id.to_string(),
+ thread_id,
+ archived,
+ });
+ if self.reject_archive {
+ return Err(EmailErr::ThreadNotFound);
+ }
+ Ok(())
+ }
+
async fn mark_email_thread_seen(
&self,
user_id: MacroUserIdStr<'static>,
diff --git a/crates/graphql_email/src/mutation/test/archive.rs b/crates/graphql_email/src/mutation/test/archive.rs
new file mode 100644
index 0000000000..ae6eaf7e1a
--- /dev/null
+++ b/crates/graphql_email/src/mutation/test/archive.rs
@@ -0,0 +1,82 @@
+use super::*;
+
+#[tokio::test]
+async fn archive_reply_failure_is_retryable_after_the_write_commits() {
+ let service = Arc::new(CapturingEmailMutationService {
+ thread_load_fails: true,
+ ..Default::default()
+ });
+ let response = schema(service.clone()).execute(format!(
+ r#"mutation {{ setEmailThreadArchived(input: {{threadId: "{}", archived: true}}) {{id}} }}"#,
+ Uuid::from_u128(42),
+ )).await;
+ assert_eq!(service.calls.lock().unwrap().len(), 1);
+ assert_eq!(response.errors.len(), 1);
+ assert_eq!(
+ response.errors[0]
+ .extensions
+ .as_ref()
+ .unwrap()
+ .get("retryable"),
+ Some(&async_graphql::Value::Boolean(true))
+ );
+}
+
+#[tokio::test]
+async fn archive_and_undo_forward_identity_and_state_to_the_service() {
+ for archived in [true, false] {
+ let service = Arc::new(CapturingEmailMutationService::default());
+ let thread_id = Uuid::from_u128(42);
+ let response = schema(service.clone()).execute(format!(
+ r#"mutation {{ setEmailThreadArchived(input: {{ threadId: "{thread_id}", archived: {archived} }}) {{ id }} }}"#
+ )).await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap()["setEmailThreadArchived"]["id"],
+ thread_id.to_string()
+ );
+ assert_eq!(
+ *service.calls.lock().unwrap(),
+ vec![CapturedMutation::Archive {
+ user_id: "macro|[email protected]".into(),
+ thread_id,
+ archived,
+ }]
+ );
+ }
+}
+
+#[tokio::test]
+async fn archive_rejects_invalid_identity_and_ids_before_domain_writes() {
+ let service = Arc::new(CapturingEmailMutationService::default());
+ let unauthenticated = Schema::build(
+ QueryRoot,
+ GraphqlEmailMutation::<CapturingEmailMutationService, TestEmailThreadOutput>::new(),
+ EmptySubscription,
+ )
+ .data(service.clone())
+ .finish();
+ let query = format!(
+ r#"mutation {{ setEmailThreadArchived(input: {{threadId: "{}", archived: true}}) {{id}} }}"#,
+ Uuid::from_u128(42)
+ );
+ assert!(!unauthenticated.execute(query).await.errors.is_empty());
+ assert!(!schema(service.clone()).execute(
+ r#"mutation { setEmailThreadArchived(input: {threadId: "bad-id", archived: true}) {id} }"#
+ ).await.errors.is_empty());
+ assert!(service.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn archive_does_not_report_success_when_the_service_rejects_the_write() {
+ let service = Arc::new(CapturingEmailMutationService {
+ reject_archive: true,
+ ..Default::default()
+ });
+ let response = schema(service).execute(format!(
+ r#"mutation {{ setEmailThreadArchived(input: {{threadId: "{}", archived: true}}) {{id}} }}"#, Uuid::from_u128(42)
+ )).await;
+ assert_eq!(response.errors.len(), 1);
+ assert_eq!(response.errors[0].message, "email thread not found");
+ assert_eq!(response.data, async_graphql::Value::Null);
+}
diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rs
index e88aa4763f..23b289860b 100644
--- a/crates/graphql_soup/src/lib.rs
+++ b/crates/graphql_soup/src/lib.rs
@@ -10,6 +10,8 @@
mod inputs;
/// DataLoader-backed hydration for realtime Soup patches.
mod loaders;
+/// Primary-backed email snapshots used only for mutation replies.
+mod mutation_thread;
/// GraphQL objects representing Soup pages and entities.
mod objects;
/// Top-level Soup query resolver.
@@ -21,6 +23,9 @@ pub use loaders::{
EmailServiceInboxReader, SoupInboxReader, SoupItemDataLoader, SoupItemLoader,
SoupItemLoaderError, SoupItemLoaderKey, soup_item_loader,
};
+pub use mutation_thread::{
+ EmailMutationThreadLoader, EmailMutationThreadReader, email_mutation_thread_loader,
+};
pub use objects::{
GraphqlSoupBin, GraphqlSoupCall, GraphqlSoupChannel, GraphqlSoupChannelMessage,
GraphqlSoupChannelMessagePreview, GraphqlSoupChat, GraphqlSoupCrmCompany, GraphqlSoupDocument,
diff --git a/crates/graphql_soup/src/mutation_thread.rs b/crates/graphql_soup/src/mutation_thread.rs
new file mode 100644
index 0000000000..a919aeb051
--- /dev/null
+++ b/crates/graphql_soup/src/mutation_thread.rs
@@ -0,0 +1,102 @@
+//! Read-after-write email snapshots, separate from replica-backed Soup lists.
+
+use std::{future::Future, pin::Pin, sync::Arc};
+
+use email::domain::{
+ models::{GetEmailsRequest, PreviewView, PreviewViewStandardLabel},
+ ports::EmailService,
+};
+use filter_ast::Expr;
+use item_filters::ast::email::EmailLiteral;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
+use models_soup::email_thread::SoupEnrichedEmailThreadPreview;
+use uuid::Uuid;
+
+/// A fresh, user-scoped snapshot from the same service that performs writes.
+/// Implementations must not serve a cached or replica-backed mutation reply.
+pub trait EmailMutationThreadReader: Send + Sync + 'static {
+ /// Reload the thread after its mutation has committed.
+ fn read(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> impl Future<Output = async_graphql::Result<Option<SoupEnrichedEmailThreadPreview<()>>>> + Send;
+}
+
+/// Owned future for one uncached mutation snapshot.
+type ReadFuture = Pin<
+ Box<
+ dyn Future<Output = async_graphql::Result<Option<SoupEnrichedEmailThreadPreview<()>>>>
+ + Send,
+ >,
+>;
+/// Type-erased request-scoped reader function.
+type ReadThread = dyn Fn(MacroUserIdStr<'static>, Uuid) -> ReadFuture + Send + Sync;
+
+/// Mutation-only reader stored in request data; deliberately never caches.
+#[derive(Clone)]
+pub struct EmailMutationThreadLoader(Arc<ReadThread>);
+
+impl EmailMutationThreadLoader {
+ /// Bind a primary-backed reader, independently of the ordinary Soup loader.
+ pub fn new(reader: impl EmailMutationThreadReader) -> Self {
+ let reader = Arc::new(reader);
+ Self(Arc::new(move |user_id, thread_id| {
+ let reader = Arc::clone(&reader);
+ Box::pin(async move { reader.read(user_id, thread_id).await })
+ }))
+ }
+
+ /// Load a fresh snapshot on every call, including sequential mutations.
+ pub async fn read(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> async_graphql::Result<Option<SoupEnrichedEmailThreadPreview<()>>> {
+ (self.0)(user_id, thread_id).await
+ }
+}
+
+/// Adapter over the email writer's primary-backed domain service.
+struct PrimaryEmailReader<E>(Arc<E>);
+
+impl<E: EmailService> EmailMutationThreadReader for PrimaryEmailReader<E> {
+ async fn read(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> async_graphql::Result<Option<SoupEnrichedEmailThreadPreview<()>>> {
+ // Ownership/delegation remains the email service's policy. Never load
+ // an arbitrary thread by ID through a repository at this boundary.
+ let Some(link) = self
+ .0
+ .get_owned_link_for_thread(user_id.clone(), thread_id)
+ .await?
+ else {
+ return Ok(None);
+ };
+ let page = self
+ .0
+ .get_email_thread_previews(GetEmailsRequest {
+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::All),
+ link_ids: vec![link.id],
+ macro_id: user_id,
+ limit: Some(1),
+ query: Query::Sort(
+ SimpleSortMethod::UpdatedAt,
+ Some(Arc::new(Expr::val(EmailLiteral::ThreadId(thread_id)))),
+ ),
+ include_frecency: false,
+ team_receipt: None,
+ crm_scope: None,
+ })
+ .await?;
+ Ok(page.items.into_iter().next().map(Into::into))
+ }
+}
+
+/// Build mutation replies from the primary email service, not the Soup reader.
+pub fn email_mutation_thread_loader<E: EmailService>(service: Arc<E>) -> EmailMutationThreadLoader {
+ EmailMutationThreadLoader::new(PrimaryEmailReader(service))
+}
diff --git a/crates/graphql_soup/src/resolvers.rs b/crates/graphql_soup/src/resolvers.rs
index 682781987f..fe7dd70e34 100644
--- a/crates/graphql_soup/src/resolvers.rs
+++ b/crates/graphql_soup/src/resolvers.rs
@@ -140,7 +140,17 @@ where
thread_id: uuid::Uuid,
) -> Pin<Box<dyn Future<Output = async_graphql::Result<Option<Self::Thread>>> + Send + 'ctx>>
{
- Box::pin(resolve_soup_email_thread::<Edges>(ctx, user_id, thread_id))
+ Box::pin(async move {
+ let loader = ctx.data::<crate::EmailMutationThreadLoader>()?;
+ let Some(thread) = loader.read(user_id, thread_id).await? else {
+ return Ok(None);
+ };
+ match GraphqlSoupEntity::<Edges>::new(models_soup::item::SoupItem::EmailThread(thread))
+ {
+ GraphqlSoupEntity::EmailThread(thread) => Ok(Some(thread)),
+ _ => Err(async_graphql::Error::new("expected an email thread")),
+ }
+ })
}
}
diff --git a/crates/models_soup/src/email_thread.rs b/crates/models_soup/src/email_thread.rs
index 0eef80288d..615a87804f 100644
--- a/crates/models_soup/src/email_thread.rs
+++ b/crates/models_soup/src/email_thread.rs
@@ -1,5 +1,5 @@
use chrono::{DateTime, Utc};
-use doppleganger::Doppleganger;
+use doppleganger::{Doppleganger, Mirror};
use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -180,3 +180,15 @@ pub struct SoupEnrichedEmailThreadPreview<T = ()> {
#[serde(flatten)]
pub extra: T,
}
+
+impl From<email::domain::models::EnrichedEmailThreadPreview> for SoupEnrichedEmailThreadPreview<()> {
+ fn from(preview: email::domain::models::EnrichedEmailThreadPreview) -> Self {
+ Self {
+ thread: SoupEmailThreadPreview::mirror(preview.thread),
+ attachments: Vec::<SoupAttachment>::mirror(preview.attachments),
+ participants: Vec::<SoupContact>::mirror(preview.participants),
+ labels: Vec::<SoupLabel>::mirror(preview.labels),
+ extra: (),
+ }
+ }
+}
diff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rs
index f8830807a4..ca1d020274 100644
--- a/crates/soup/src/domain/service.rs
+++ b/crates/soup/src/domain/service.rs
@@ -17,10 +17,9 @@ use channels::domain::{
};
use cowlike::CowLike;
use crm::domain::service::CrmService;
-use doppleganger::Mirror;
use either::Either;
use email::domain::{
- models::{EnrichedEmailThreadPreview, GetEmailsRequest, PreviewView, PreviewViewStandardLabel},
+ models::{GetEmailsRequest, PreviewView, PreviewViewStandardLabel},
ports::EmailPreviewServiceReadOnly,
};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
@@ -52,10 +51,6 @@ use models_soup::{
call_record::SoupCallRecord,
comms::{SoupChannel, SoupChannelThread},
crm_company::SoupCrmCompany,
- email_thread::{
- SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview,
- SoupLabel,
- },
foreign_entity::SoupForeignEntity,
item::SoupItem,
reminder::SoupReminder,
@@ -1073,26 +1068,10 @@ where
let items: Vec<SoupItem<()>> = email_response
.items
.into_iter()
- .map(
- |EnrichedEmailThreadPreview {
- thread,
- attachments,
- labels,
- mut frecency_score,
- participants,
- ..
- }| {
- frecency_scores.push(frecency_score.take());
- let soup_email = SoupEnrichedEmailThreadPreview {
- thread: SoupEmailThreadPreview::mirror(thread),
- attachments: Vec::<SoupAttachment>::mirror(attachments),
- participants: Vec::<SoupContact>::mirror(participants),
- labels: Vec::<SoupLabel>::mirror(labels),
- extra: (),
- };
- SoupItem::EmailThread(soup_email)
- },
- )
+ .map(|mut preview| {
+ frecency_scores.push(preview.frecency_score.take());
+ SoupItem::EmailThread(preview.into())
+ })
.collect();
Ok(Either::Right(items.into_iter().zip(frecency_scores).map(
diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rs
index a586569b9e..3a00b2ae45 100644
--- a/crates/soup/src/inbound/axum_router/tests.rs
+++ b/crates/soup/src/inbound/axum_router/tests.rs
@@ -225,6 +225,15 @@ impl SoupService for MockSoup {
struct MockEmail;
impl EmailService for MockEmail {
+ async fn set_thread_archived(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ _id: uuid::Uuid,
+ _archived: bool,
+ ) -> Result<(), EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
async fn mark_thread_unread(
&self,
_macro_id: MacroUserIdStr<'static>,
@@ -692,6 +701,15 @@ struct MockEmailLinkResult {
}
impl EmailService for MockEmailLinkResult {
+ async fn set_thread_archived(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ _id: uuid::Uuid,
+ _archived: bool,
+ ) -> Result<(), EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
async fn mark_thread_unread(
&self,
_macro_id: MacroUserIdStr<'static>,
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 36fc835665..74f6065d06 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -304,6 +304,17 @@ on opening, and is omitted when no tags exist. **f** opens the filter menu.
### Read state and trash
+In the Email view, Status filters discovery on the server **before pagination**,
+for both the mailbox list and service-backed search. With Unread selected, opening
+or marking an admitted row read keeps its position across refreshes. Separate
+lookups, bounded to 100 already-admitted thread IDs each, omit only the read filter;
+they still enforce the tab, inbox, other facets, and (for search) the search text.
+A snapshot bridges a pending lookup, but a confirmed non-match removes the row,
+so archive/trash cannot be resurrected by retention. Changing the search text,
+filters, tab, inbox, or user resets admission. Check that unread mail is discovered
+even after 100 newer read threads, then verify focus through Mark Read and refresh
+in both list and search, including with more than one loaded page.
+
With GraphQL Soup enabled, **Mark read/unread** updates the normalized email row
optimistically. Permanent server errors roll it back; retryable transport failures
can leave the action in the durable queue. Mark unread sends only the thread ID;
@@ -315,7 +326,29 @@ active flat and grouped lists, including loaded continuation pages. Once replay
commits (even after a reload), those queries refresh from the server; they should
not refetch over the optimistic state merely because a write was queued. Trash
and its Undo refresh mounted GraphQL lists after the server operation finishes.
-The GraphQL-disabled REST path is unchanged.
+The GraphQL-disabled REST path is unchanged. With GraphQL enabled, archive-based
+Mark Done, Mark Not Done, and Undo/Redo use `setEmailThreadArchived`: `inboxVisible`
+updates optimistically in the normalized cache, and each reversal is a distinct
+ordered queue entry. The server resolves the thread's owning/delegated inbox;
+no client INBOX-label lookup is needed. Confirmed writes revalidate mounted lists,
+including continuation pages; queued writes retain those descriptors for replay
+without refetching over optimism. Callers preserve the queued disposition and
+skip REST/TanStack email invalidations as well, including Done/Undo batches and
+thread archive replay. Committed writes and failed non-queued batches still
+reconcile. Permanent failures roll back the failed intent.
+Check Signal/Noise removal and All's done indicator, then Undo/Redo, including an
+offline action followed by reconnect. Sent-only threads cannot be unarchived.
+
+The service retains both replica-backed Soup reads and a primary-backed email
+writer. Email mutations and their uncached reply reloads use the primary; ordinary
+GraphQL/REST lists, direct Soup lookups, and realtime Soup hydration use the replica.
+A mutation reply is fresh, but subsequent list refetches are eventually consistent
+and can still return replica-stale read/archive state. Test that boundary separately
+from mutation reply correctness. A post-commit reply-load failure is retryable;
+it must not discard the queued intent. Deploy
+the backend schema containing `setEmailThreadArchived` before this client.
+Browser WASM and native cache builds must include the regenerated schema metadata;
+native offline archive support therefore requires a full app build, not just OTA.
### Cached Mail filtering
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index c47e070fc0..7c1dc88b80 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -14,7 +14,7 @@ use axum::{
use axum_extra::extract::Cached;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use complete_graph::GraphqlRequestParts;
-use graphql_soup::soup_item_loader;
+use graphql_soup::{email_mutation_thread_loader, soup_item_loader};
use macro_authorization::{
OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
};
@@ -146,6 +146,8 @@ fn insert_graphql_context_data(
state.soup_router_state.email_service(),
state.entity_access_service.clone(),
);
+ // Ordinary queries and subscription hydration use the replica-backed
+ // Soup reader. The mutation-only loader below retains the primary reader.
let soup_item_loader = soup_item_loader(
state.soup_router_state.service(),
state.soup_router_state.email_service(),
@@ -167,6 +169,11 @@ fn insert_graphql_context_data(
data.insert(state.soup_router_state.email_service());
data.insert(state.entity_access_service.clone());
data.insert(soup_item_loader);
+ // Mutation replies must read their committed state from the primary email
+ // service. Ordinary Soup lists and subscriptions retain their own reader.
+ data.insert(email_mutation_thread_loader(
+ state.soup_router_state.email_service(),
+ ));
data.insert(complete_graph::agent_session_bot_loader(PgBotsRepo::new(
state.readonly_db.0.clone(),
)));
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index b9b35e6f50..9a7ff92eb5 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -444,11 +444,6 @@ async fn run() -> anyhow::Result<()> {
);
// Create the channel list service used by soup.
- let channel_service_for_soup = ChannelListServiceImpl::new(
- PgChannelsRepo::new(readonly_db.clone()),
- PgChannelsRepo::new(readonly_db.clone()),
- frecency_storage.clone(),
- );
// Create the legacy channel list router state for routes mounted under /comms.
let channel_list_state = ChannelListRouterState::new(
ChannelListServiceImpl::new(
@@ -947,12 +942,6 @@ async fn run() -> anyhow::Result<()> {
config.queue_wait_time_seconds,
);
- let call_record_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
- PgCallRepo::new(readonly_db.clone()),
- );
- let foreign_entity_service_for_soup =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(readonly_db.clone()));
-
let sqs_client = Arc::new(sqs_client);
let conn_gateway_client = Arc::new(conn_gateway_client);
@@ -1221,15 +1210,25 @@ async fn run() -> anyhow::Result<()> {
config.document_permission_jwt.as_ref().to_string(),
);
+ // Keep the replica-backed Soup reader alongside the primary-backed email
+ // writer in SoupRouterState. REST, GraphQL lists, and realtime hydration
+ // share this reader; only email mutations and their reply loader use the
+ // writer service, so normal list traffic never switches to the primary.
let soup_service = Arc::new(
SoupImpl::new(
PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),
frecency_service,
readonly_email_service,
- channel_service_for_soup,
- call_record_query_service,
+ ChannelListServiceImpl::new(
+ PgChannelsRepo::new(readonly_db.clone()),
+ PgChannelsRepo::new(readonly_db.clone()),
+ frecency_storage.clone(),
+ ),
+ call::domain::service::CallRecordQueryServiceImpl::new(PgCallRepo::new(
+ readonly_db.clone(),
+ )),
crm_service.clone(),
- foreign_entity_service_for_soup,
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(readonly_db.clone())),
reminders_service.clone(),
)
.with_agent_branches(agent_changes::outbound::postgres::PgChangesetRepo::new(
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index f85eb53c11..a58d26e336 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -128,6 +128,10 @@ type CompleteMutationRoot {
"""
markEmailThreadUnread(input: MarkEmailThreadUnreadInput!): GraphqlSoupEmailThread!
"""
+ Set archive-based Done and return the primary-backed canonical thread.
+ """
+ setEmailThreadArchived(input: SetEmailThreadArchivedInput!): GraphqlSoupEmailThread!
+ """
Add or remove one label from an accessible email thread and return its authoritative cache record.
"""
updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!
@@ -6287,6 +6291,20 @@ type SaveEmailDraftPayload {
thread: GraphqlSoupEmailThread!
}
+"""
+Input for archive-based Done and its inverse. No client label lookup is needed.
+"""
+input SetEmailThreadArchivedInput {
+ """
+ Thread whose inbox membership should change.
+ """
+ threadId: ID!
+ """
+ True for Done; false for Mark Not Done or Undo.
+ """
+ archived: Boolean!
+}
+
"""
Input for assigning or updating an entity property.
"""