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): stop outlook threads waiting forever for confirmation (#8342)

teo2b3732fff213
diff --git a/.sqlx/query-0779189cec96a9f6a3adfd6a010a4ba7e13408eb8344529cae5c9fbab1de247b.json b/.sqlx/query-0779189cec96a9f6a3adfd6a010a4ba7e13408eb8344529cae5c9fbab1de247b.json
deleted file mode 100644
index fbeed1f0c6..0000000000
--- a/.sqlx/query-0779189cec96a9f6a3adfd6a010a4ba7e13408eb8344529cae5c9fbab1de247b.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM email_pending_mailbox_state p USING email_mailbox_commands c\n WHERE p.command_id = c.id AND c.link_id = $1 AND c.generation <> $2 RETURNING p.message_id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "message_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "0779189cec96a9f6a3adfd6a010a4ba7e13408eb8344529cae5c9fbab1de247b"
-}
diff --git a/.sqlx/query-1563aedb723ca0ec27aaec850d63eaa5293f7855835eb8ebee59d5f81effa665.json b/.sqlx/query-1563aedb723ca0ec27aaec850d63eaa5293f7855835eb8ebee59d5f81effa665.json
deleted file mode 100644
index b9b49e00f5..0000000000
--- a/.sqlx/query-1563aedb723ca0ec27aaec850d63eaa5293f7855835eb8ebee59d5f81effa665.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE email_messages SET is_read = COALESCE((mailbox_state->>'is_read')::boolean,is_read),\n is_starred = COALESCE((mailbox_state->>'is_flagged')::boolean,is_starred)\n WHERE id = $1 RETURNING thread_id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "thread_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "1563aedb723ca0ec27aaec850d63eaa5293f7855835eb8ebee59d5f81effa665"
-}
diff --git a/.sqlx/query-62feb3e9e37a670ef8335f3fd44cec1b2d6ff1af13300941184898396c797972.json b/.sqlx/query-37041c5ce8c950a68297aae7d49ec61e27f1911a7dc53b48031e38be7e555037.json
similarity index 69%
rename from .sqlx/query-62feb3e9e37a670ef8335f3fd44cec1b2d6ff1af13300941184898396c797972.json
rename to .sqlx/query-37041c5ce8c950a68297aae7d49ec61e27f1911a7dc53b48031e38be7e555037.json
index f2b49c8432..1439a462a5 100644
--- a/.sqlx/query-62feb3e9e37a670ef8335f3fd44cec1b2d6ff1af13300941184898396c797972.json
+++ b/.sqlx/query-37041c5ce8c950a68297aae7d49ec61e27f1911a7dc53b48031e38be7e555037.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT m.id,m.provider_id,m.is_draft,m.is_sent,\n f.in_inbox AS \"in_inbox!\", f.in_trash AS \"in_trash!\", f.in_junk AS \"in_junk!\", f.is_present AS \"is_present!\"\n FROM email_messages m JOIN email_message_mailbox_facts f ON f.id = m.id\n WHERE m.link_id = $1 AND m.thread_id = $2 ORDER BY m.id\n ",
+ "query": "\n SELECT m.id,m.provider_id,m.is_draft,m.is_sent,m.is_read,\n f.in_inbox AS \"in_inbox!\", f.in_trash AS \"in_trash!\", f.in_junk AS \"in_junk!\", f.is_present AS \"is_present!\"\n FROM email_messages m JOIN email_message_mailbox_facts f ON f.id = m.id\n WHERE m.link_id = $1 AND m.thread_id = $2 ORDER BY m.id\n ",
"describe": {
"columns": [
{
@@ -25,21 +25,26 @@
},
{
"ordinal": 4,
- "name": "in_inbox!",
+ "name": "is_read",
"type_info": "Bool"
},
{
"ordinal": 5,
- "name": "in_trash!",
+ "name": "in_inbox!",
"type_info": "Bool"
},
{
"ordinal": 6,
- "name": "in_junk!",
+ "name": "in_trash!",
"type_info": "Bool"
},
{
"ordinal": 7,
+ "name": "in_junk!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
"name": "is_present!",
"type_info": "Bool"
}
@@ -55,11 +60,12 @@
true,
false,
false,
+ false,
true,
true,
true,
true
]
},
- "hash": "62feb3e9e37a670ef8335f3fd44cec1b2d6ff1af13300941184898396c797972"
+ "hash": "37041c5ce8c950a68297aae7d49ec61e27f1911a7dc53b48031e38be7e555037"
}
diff --git a/.sqlx/query-4193edaca3374e8931ef63bcfbabe9cd2e6e47bfba664bd1b561b902fff623c2.json b/.sqlx/query-4193edaca3374e8931ef63bcfbabe9cd2e6e47bfba664bd1b561b902fff623c2.json
deleted file mode 100644
index 9cf38ef37f..0000000000
--- a/.sqlx/query-4193edaca3374e8931ef63bcfbabe9cd2e6e47bfba664bd1b561b902fff623c2.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE email_mailbox_commands SET status = CASE WHEN status = 'pending' THEN 'cancelled' ELSE 'unknown' END,\n lease_id = NULL,lease_until = NULL,updated_at = now()\n WHERE link_id = $1 AND generation <> $2 AND status IN ('pending','running','confirming')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "4193edaca3374e8931ef63bcfbabe9cd2e6e47bfba664bd1b561b902fff623c2"
-}
diff --git a/.sqlx/query-2258654aadc902ea10a81e5ce788e08beaad8c3ffa0c2d4ba181b7a1fd308126.json b/.sqlx/query-53f70d68cec00285a797a89b97b4313ab8e251fed30d3faab333dcbd63d43ba2.json
similarity index 61%
rename from .sqlx/query-2258654aadc902ea10a81e5ce788e08beaad8c3ffa0c2d4ba181b7a1fd308126.json
rename to .sqlx/query-53f70d68cec00285a797a89b97b4313ab8e251fed30d3faab333dcbd63d43ba2.json
index a796215036..55cf18df91 100644
--- a/.sqlx/query-2258654aadc902ea10a81e5ce788e08beaad8c3ffa0c2d4ba181b7a1fd308126.json
+++ b/.sqlx/query-53f70d68cec00285a797a89b97b4313ab8e251fed30d3faab333dcbd63d43ba2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT DISTINCT ON(c.intent->>'kind',c.intent->'value'->>'name') c.id,c.intent,c.status,c.updated_at\n FROM email_mailbox_commands c WHERE c.link_id=$1 AND EXISTS(SELECT 1 FROM email_mailbox_command_targets t\n JOIN email_messages m ON m.id=t.message_id WHERE t.command_id=c.id AND m.thread_id=$2 AND m.link_id=$1)\n ORDER BY c.intent->>'kind',c.intent->'value'->>'name',c.accepted_order DESC LIMIT 100",
+ "query": "SELECT DISTINCT ON(c.intent->>'kind',c.intent->'value'->>'name') c.id,c.intent,c.status,c.updated_at\n FROM email_mailbox_commands c JOIN email_links l ON l.id=c.link_id AND l.sync_generation=c.generation\n WHERE c.link_id=$1 AND EXISTS(SELECT 1 FROM email_mailbox_command_targets t\n JOIN email_messages m ON m.id=t.message_id WHERE t.command_id=c.id AND m.thread_id=$2 AND m.link_id=$1)\n ORDER BY c.intent->>'kind',c.intent->'value'->>'name',c.accepted_order DESC LIMIT 100",
"describe": {
"columns": [
{
@@ -37,5 +37,5 @@
false
]
},
- "hash": "2258654aadc902ea10a81e5ce788e08beaad8c3ffa0c2d4ba181b7a1fd308126"
+ "hash": "53f70d68cec00285a797a89b97b4313ab8e251fed30d3faab333dcbd63d43ba2"
}
diff --git a/.sqlx/query-5665dc1ed27f81e4d4ef50769814bc9393492cae26380b1d68ecae5346e4a9b5.json b/.sqlx/query-5665dc1ed27f81e4d4ef50769814bc9393492cae26380b1d68ecae5346e4a9b5.json
deleted file mode 100644
index 51f4ec5448..0000000000
--- a/.sqlx/query-5665dc1ed27f81e4d4ef50769814bc9393492cae26380b1d68ecae5346e4a9b5.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE email_mailbox_commands SET generation = $3,lease_id = NULL,lease_until = NULL,\n status = CASE WHEN status = 'running' THEN 'pending' ELSE status END,available_at = now(),updated_at = now()\n WHERE link_id = $1 AND generation = $2 AND status IN ('pending','running','confirming')",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "5665dc1ed27f81e4d4ef50769814bc9393492cae26380b1d68ecae5346e4a9b5"
-}
diff --git a/.sqlx/query-8a9e06a11ca9c0ef914e140cfccd0f63471101cd1694a267f5ad0cebdb1fbe9a.json b/.sqlx/query-8a9e06a11ca9c0ef914e140cfccd0f63471101cd1694a267f5ad0cebdb1fbe9a.json
new file mode 100644
index 0000000000..3f8b566163
--- /dev/null
+++ b/.sqlx/query-8a9e06a11ca9c0ef914e140cfccd0f63471101cd1694a267f5ad0cebdb1fbe9a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_mailbox_commands SET generation = $3,lease_id = NULL,lease_until = NULL,\n status = 'pending',available_at = now(),updated_at = now()\n WHERE link_id = $1 AND generation = $2 AND status IN ('pending','running','confirming')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8a9e06a11ca9c0ef914e140cfccd0f63471101cd1694a267f5ad0cebdb1fbe9a"
+}
diff --git a/.sqlx/query-9dce8d3e5ade510092a4179c9794b3a926d39ae266877ece6fe2efa18fde2341.json b/.sqlx/query-9dce8d3e5ade510092a4179c9794b3a926d39ae266877ece6fe2efa18fde2341.json
new file mode 100644
index 0000000000..e14476e96b
--- /dev/null
+++ b/.sqlx/query-9dce8d3e5ade510092a4179c9794b3a926d39ae266877ece6fe2efa18fde2341.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_mailbox_commands SET generation = $2,lease_id = NULL,lease_until = NULL,\n status = 'pending',available_at = now(),updated_at = now()\n WHERE link_id = $1 AND generation <> $2 AND status IN ('pending','running','confirming')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9dce8d3e5ade510092a4179c9794b3a926d39ae266877ece6fe2efa18fde2341"
+}
diff --git a/apps/web/src/features/email-thread/context/email-thread-context.ts b/apps/web/src/features/email-thread/context/email-thread-context.ts
index efba2b34b2..f50c17bde8 100644
--- a/apps/web/src/features/email-thread/context/email-thread-context.ts
+++ b/apps/web/src/features/email-thread/context/email-thread-context.ts
@@ -44,6 +44,7 @@ export interface EmailThreadCommands {
canMarkThreadNotDone: Accessor<boolean>;
markThreadNotDone(): boolean;
isThreadMarkedUnread: Accessor<boolean>;
+ isThreadMarkedRead: Accessor<boolean>;
markThreadUnread(): boolean;
markThreadRead(): boolean;
blockSender(): boolean;
diff --git a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx b/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
index 6e4e52ac4b..0b32ce747f 100644
--- a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
+++ b/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
@@ -1,4 +1,4 @@
-import { createContext, type JSX, useContext } from 'solid-js';
+import { type Accessor, createContext, type JSX, useContext } from 'solid-js';
import type {
EmailComposeContext,
EmailComposeHost,
@@ -10,6 +10,11 @@ import type {
} from '../../email-message/core/email-message';
import type { EmailThreadContext } from './email-thread-context';
+export interface EmailThreadOrganizationStatus {
+ /** True when the user, not the opening of the thread, asked for its mark-as-read. */
+ announceRead: Accessor<boolean>;
+}
+
export interface EmailThreadViewContext {
thread: EmailThreadContext;
copySubject?: (subject: string) => void | boolean | Promise<void | boolean>;
@@ -17,7 +22,9 @@ export interface EmailThreadViewContext {
composeHost?: EmailComposeHost;
rendering: {
renderTags?: () => JSX.Element;
- renderOrganizationStatus?: () => JSX.Element;
+ renderOrganizationStatus?: (
+ status: EmailThreadOrganizationStatus
+ ) => JSX.Element;
renderInvitation?: (
message: EmailMessage,
invitation: CalendarInvitation
diff --git a/apps/web/src/features/email-thread/email-thread-operations.test.tsx b/apps/web/src/features/email-thread/email-thread-operations.test.tsx
index 563988fe3e..e34d6f7adc 100644
--- a/apps/web/src/features/email-thread/email-thread-operations.test.tsx
+++ b/apps/web/src/features/email-thread/email-thread-operations.test.tsx
@@ -9,11 +9,17 @@ vi.mock('@queries/email/cache-cleanup', () => ({
}));
vi.mock('@service-email/client', () => ({ emailClient: {} }));
afterEach(cleanup);
-const operation = (state: MailboxOperation['state']): MailboxOperation => ({
+const operation = (
+ state: MailboxOperation['state'],
+ action: MailboxOperation['action'] = {
+ kind: 'category',
+ value: { name: 'Projects', present: true },
+ }
+): MailboxOperation => ({
id: 'operation',
updated_at: '2026-10-04T00:00:00Z',
state,
- action: { kind: 'category', value: { name: 'Projects', present: true } },
+ action,
});
it('does not announce queued category changes as applied', () => {
render(() => <MailboxOperationsNotice operations={[operation('pending')]} />);
@@ -31,3 +37,40 @@ it('removes the pending notice once the provider confirms', () => {
render(() => <MailboxOperationsNotice operations={[operation('applied')]} />);
expect(screen.queryByText(/mailbox confirmation/)).toBeNull();
});
+it('does not announce the mark-as-read that opening a thread queues', () => {
+ const read = { kind: 'read', value: true } as const;
+ render(() => (
+ <MailboxOperationsNotice operations={[operation('pending', read)]} />
+ ));
+ expect(screen.queryByText(/Mark as read/)).toBeNull();
+});
+it('announces a pending mark-as-read the user asked for', () => {
+ const read = { kind: 'read', value: true } as const;
+ render(() => (
+ <MailboxOperationsNotice
+ operations={[operation('pending', read)]}
+ announceRead
+ />
+ ));
+ expect(screen.getByText(/Mark as read/).textContent).toContain(
+ 'Waiting for mailbox confirmation'
+ );
+});
+it('reports a mark-as-read that the mailbox rejected', () => {
+ const read = { kind: 'read', value: true } as const;
+ render(() => (
+ <MailboxOperationsNotice operations={[operation('failed', read)]} />
+ ));
+ expect(screen.getByText(/Mark as read/).textContent).toContain(
+ 'Could not apply this change'
+ );
+});
+it('still announces a pending mark-as-unread', () => {
+ const unread = { kind: 'read', value: false } as const;
+ render(() => (
+ <MailboxOperationsNotice operations={[operation('pending', unread)]} />
+ ));
+ expect(screen.getByText(/Mark as unread/).textContent).toContain(
+ 'Waiting for mailbox confirmation'
+ );
+});
diff --git a/apps/web/src/features/email-thread/email-thread-operations.tsx b/apps/web/src/features/email-thread/email-thread-operations.tsx
index ef6b5ee223..e9638a81e1 100644
--- a/apps/web/src/features/email-thread/email-thread-operations.tsx
+++ b/apps/web/src/features/email-thread/email-thread-operations.tsx
@@ -22,12 +22,26 @@ function actionDescription(action: MailboxAction): string {
}
}
-/** Organization changes remain visibly pending until provider confirmation. */
+/**
+ * Organization changes remain visibly pending until provider confirmation.
+ * Opening a thread also marks it read, so a pending mark-as-read is announced
+ * only when the user asked for one; its failure is always announced.
+ */
export function MailboxOperationsNotice(props: {
operations: MailboxOperation[];
+ announceRead?: boolean;
}) {
const unresolved = () =>
- props.operations.filter((operation) => operation.state !== 'applied');
+ props.operations.filter(
+ (operation) =>
+ operation.state !== 'applied' &&
+ !(
+ !props.announceRead &&
+ operation.state === 'pending' &&
+ operation.action.kind === 'read' &&
+ operation.action.value
+ )
+ );
return (
<Show when={unresolved().length}>
<div
@@ -52,10 +66,16 @@ export function MailboxOperationsNotice(props: {
export function EmailThreadOperations(props: {
threadId: string;
enabled: boolean;
+ announceRead: boolean;
}) {
const query = useThreadOperations(
() => props.threadId,
() => props.enabled
);
- return <MailboxOperationsNotice operations={query.data ?? []} />;
+ return (
+ <MailboxOperationsNotice
+ operations={query.data ?? []}
+ announceRead={props.announceRead}
+ />
+ );
}
diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsx
index 4d96246f1b..66aca418ce 100644
--- a/apps/web/src/features/email-thread/email-thread.tsx
+++ b/apps/web/src/features/email-thread/email-thread.tsx
@@ -31,6 +31,7 @@ import type {
EmailThreadContext,
EmailThreadSource,
} from './context/email-thread-context';
+import type { EmailThreadOrganizationStatus } from './context/email-thread-view-context';
import { EmailThreadOperations } from './email-thread-operations';
import { createOptimisticThreadSend } from './primitives/optimistic-send';
import { createThreadActionAdapter } from './thread-action-adapter';
@@ -89,10 +90,11 @@ export function EmailThread(props: EmailThreadProps) {
compose,
composeHost: createEmailComposeHost(),
rendering: {
- renderOrganizationStatus: () => (
+ renderOrganizationStatus: (status: EmailThreadOrganizationStatus) => (
<EmailThreadOperations
threadId={source.id()}
enabled={source.thread()?.access_level === 'owner'}
+ announceRead={status.announceRead()}
/>
),
renderOperation: (message: EmailMessage) =>
diff --git a/apps/web/src/features/email-thread/primitives/email-thread-state.ts b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
index 4fe6152067..35bce79393 100644
--- a/apps/web/src/features/email-thread/primitives/email-thread-state.ts
+++ b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
@@ -100,6 +100,9 @@ export type EmailThreadState = {
/** True when the user marked the open thread unread. Resets to false per
* thread — viewing marks it read, so the toggle starts at Mark Unread. */
isThreadMarkedUnread: Accessor<boolean>;
+ /** True when the user re-marked the open thread read, as opposed to the
+ * mark-as-read that viewing it queues. Resets to false per thread. */
+ isThreadMarkedRead: Accessor<boolean>;
/** Marks the open thread unread; the toggle then offers Mark Read. */
markThreadUnread: () => boolean;
/** Re-marks the thread read after a mark-unread. */
diff --git a/apps/web/src/features/email-thread/tests/fixtures.ts b/apps/web/src/features/email-thread/tests/fixtures.ts
index 33bbbcd4d1..ee4450ac86 100644
--- a/apps/web/src/features/email-thread/tests/fixtures.ts
+++ b/apps/web/src/features/email-thread/tests/fixtures.ts
@@ -47,6 +47,7 @@ export function createThreadContext(
canMarkThreadNotDone: () => false,
markThreadNotDone: () => false,
isThreadMarkedUnread: () => false,
+ isThreadMarkedRead: () => false,
markThreadUnread: () => false,
markThreadRead: () => false,
blockSender: () => false,
diff --git a/apps/web/src/features/email-thread/thread-read-adapter.ts b/apps/web/src/features/email-thread/thread-read-adapter.ts
index 0f40ff2432..6d4305eb50 100644
--- a/apps/web/src/features/email-thread/thread-read-adapter.ts
+++ b/apps/web/src/features/email-thread/thread-read-adapter.ts
@@ -16,7 +16,10 @@ export function createThreadReadAdapter(
toHeaderLinkId: (linkId: string | null | undefined) => string | undefined
): Pick<
EmailThreadCommands,
- 'markThreadUnread' | 'markThreadRead' | 'isThreadMarkedUnread'
+ | 'markThreadUnread'
+ | 'markThreadRead'
+ | 'isThreadMarkedUnread'
+ | 'isThreadMarkedRead'
> {
const markSeenMutation = useMarkThreadAsSeenMutation();
const markUnreadMutation = useMarkThreadAsUnreadMutation();
@@ -24,9 +27,11 @@ export function createThreadReadAdapter(
// Viewing a thread marks it read (EmailDebouncedReadMarker), so each thread
// starts with the toggle offering Mark Unread.
const [threadMarkedUnread, setThreadMarkedUnread] = createSignal(false);
+ const [threadMarkedRead, setThreadMarkedRead] = createSignal(false);
createEffect(() => {
void threadId();
setThreadMarkedUnread(false);
+ setThreadMarkedRead(false);
});
const markThreadUnread = () => {
@@ -40,6 +45,7 @@ export function createThreadReadAdapter(
const threadId = thread.db_id;
setThreadMarkedUnread(true);
+ setThreadMarkedRead(false);
markUnreadMutation.mutate(
{ threadId, linkId: thread.link_id },
{
@@ -74,6 +80,7 @@ export function createThreadReadAdapter(
const threadId = thread.db_id;
setThreadMarkedUnread(false);
+ setThreadMarkedRead(true);
markSeenMutation.mutate(
{ threadId, linkId: toHeaderLinkId(thread.link_id) },
{
@@ -86,6 +93,7 @@ export function createThreadReadAdapter(
},
onError: () => {
setThreadMarkedUnread(true);
+ setThreadMarkedRead(false);
toast.failure('Failed to mark as read');
fireAndForget(
refetchSoupEntity(threadId, 'emailThread'),
@@ -101,5 +109,6 @@ export function createThreadReadAdapter(
markThreadUnread,
markThreadRead,
isThreadMarkedUnread: threadMarkedUnread,
+ isThreadMarkedRead: threadMarkedRead,
};
}
diff --git a/apps/web/src/features/email-thread/views/email-thread.tsx b/apps/web/src/features/email-thread/views/email-thread.tsx
index e066c3448c..c25032d33c 100644
--- a/apps/web/src/features/email-thread/views/email-thread.tsx
+++ b/apps/web/src/features/email-thread/views/email-thread.tsx
@@ -100,7 +100,9 @@ export function EmailThreadView(props: EmailThreadViewProps) {
<div class="size-full select-none overscroll-none overflow-hidden flex flex-col">
{props.header}
{props.actions}
- {viewContext.rendering.renderOrganizationStatus?.()}
+ {viewContext.rendering.renderOrganizationStatus?.({
+ announceRead: context.isThreadMarkedRead,
+ })}
{/* Measure message gutters against the thread, excluding the side panel. */}
<div
class="@container w-full flex-1 flex flex-col items-center overflow-hidden"
diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.md
index bfac41de93..4b3a40c5dc 100644
--- a/crates/email/AGENTS.md
+++ b/crates/email/AGENTS.md
@@ -60,6 +60,11 @@ tools — hexagonal, heavily feature-gated.
domain service, never an outbound adapter directly from another crate.
- Sender discovery authorizes the inbox first. Gmail aliases use the sender
provider; Outlook exposes its verified primary address without a Gmail lookup.
+- Outlook organization commands only run in their link's current
+ `sync_generation`. Anything that bumps it must rebind unfinished commands as
+ `pending`, since claims skip `confirming` ones while those still block later
+ commands, as reconnect (`email_service` `mailbox_init.rs`) and `rebind_work` in
+ `outbound/mailbox_pg/lifecycle.rs` do; thread operations omit older generations.
## Related
diff --git a/crates/email/src/domain/models/mailbox_action.rs b/crates/email/src/domain/models/mailbox_action.rs
index 396d23ab6d..45fc107da8 100644
--- a/crates/email/src/domain/models/mailbox_action.rs
+++ b/crates/email/src/domain/models/mailbox_action.rs
@@ -49,6 +49,7 @@ pub struct MailboxActionMessage {
pub provider_id: Option<String>,
pub is_draft: bool,
pub is_sent: bool,
+ pub is_read: bool,
pub in_inbox: bool,
pub in_trash: bool,
pub in_junk: bool,
@@ -87,7 +88,8 @@ impl MailboxAction {
.filter_map(|m| {
let mut pending = PendingMailboxState::default();
match self {
- Self::Read(value) => pending.is_read = Some(*value),
+ Self::Read(value) if m.is_read != *value => pending.is_read = Some(*value),
+ Self::Read(_) => return None,
Self::Flagged(value) => pending.is_flagged = Some(*value),
Self::Archived(true) if m.in_inbox => pending.in_inbox = Some(false),
Self::Archived(false) if !m.is_draft && !m.in_trash && !m.in_junk => {
@@ -128,6 +130,7 @@ mod test {
provider_id: Some("inbox".into()),
is_draft: false,
is_sent: false,
+ is_read: false,
in_inbox: true,
in_trash: false,
in_junk: false,
@@ -159,6 +162,7 @@ mod test {
provider_id: Some("opaque".into()),
is_draft: false,
is_sent: false,
+ is_read: false,
in_inbox: true,
in_trash: false,
in_junk: false,
@@ -172,6 +176,50 @@ mod test {
assert_eq!(targets[0].pending.in_trash, None);
assert_eq!(targets[0].pending.in_inbox, None);
}
+
+ #[test]
+ fn read_state_targets_only_messages_that_change() {
+ let unread = MailboxActionMessage {
+ id: Uuid::now_v7(),
+ provider_id: Some("unread".into()),
+ is_draft: false,
+ is_sent: false,
+ is_read: false,
+ in_inbox: true,
+ in_trash: false,
+ in_junk: false,
+ is_present: true,
+ };
+ let read = MailboxActionMessage {
+ id: Uuid::now_v7(),
+ provider_id: Some("read".into()),
+ is_read: true,
+ ..unread.clone()
+ };
+ let draft = MailboxActionMessage {
+ id: Uuid::now_v7(),
+ provider_id: None,
+ is_draft: true,
+ ..read.clone()
+ };
+ let messages = [unread.clone(), read.clone(), draft];
+ let targets = MailboxAction::Read(true).targets(&messages);
+ assert_eq!(
+ targets.iter().map(|t| t.message_id).collect::<Vec<_>>(),
+ vec![unread.id]
+ );
+ assert_eq!(targets[0].pending.is_read, Some(true));
+ assert!(
+ MailboxAction::Read(true)
+ .targets(&[read.clone()])
+ .is_empty(),
+ "opening an already-read thread queues no provider work"
+ );
+ assert_eq!(
+ MailboxAction::Read(false).targets(&[unread, read.clone()])[0].message_id,
+ read.id
+ );
+ }
}
#[cfg(test)]
@@ -184,6 +232,7 @@ mod restore_test {
provider_id: Some("sent-to-self".into()),
is_sent: true,
is_draft: false,
+ is_read: true,
in_inbox: false,
in_trash: true,
in_junk: false,
diff --git a/crates/email/src/outbound/email_pg_repo/mailbox_action.rs b/crates/email/src/outbound/email_pg_repo/mailbox_action.rs
index 427bc88681..d91d14ecf0 100644
--- a/crates/email/src/outbound/email_pg_repo/mailbox_action.rs
+++ b/crates/email/src/outbound/email_pg_repo/mailbox_action.rs
@@ -9,7 +9,7 @@ pub(super) async fn messages(
thread_id: Uuid,
) -> Result<Vec<MailboxActionMessage>, sqlx::Error> {
sqlx::query_as!(MailboxActionMessage, r#"
- SELECT m.id,m.provider_id,m.is_draft,m.is_sent,
+ SELECT m.id,m.provider_id,m.is_draft,m.is_sent,m.is_read,
f.in_inbox AS "in_inbox!", f.in_trash AS "in_trash!", f.in_junk AS "in_junk!", f.is_present AS "is_present!"
FROM email_messages m JOIN email_message_mailbox_facts f ON f.id = m.id
WHERE m.link_id = $1 AND m.thread_id = $2 ORDER BY m.id
@@ -128,8 +128,11 @@ pub(super) async fn operations(
link: Uuid,
thread: Uuid,
) -> Result<Vec<MailboxOperation>, sqlx::Error> {
+ // A reconnect rebinds unfinished commands into the new generation; commands
+ // left in an earlier generation can never run, so they report no outcome.
let rows=sqlx::query!(r#"SELECT DISTINCT ON(c.intent->>'kind',c.intent->'value'->>'name') c.id,c.intent,c.status,c.updated_at
- FROM email_mailbox_commands c WHERE c.link_id=$1 AND EXISTS(SELECT 1 FROM email_mailbox_command_targets t
+ FROM email_mailbox_commands c JOIN email_links l ON l.id=c.link_id AND l.sync_generation=c.generation
+ WHERE c.link_id=$1 AND EXISTS(SELECT 1 FROM email_mailbox_command_targets t
JOIN email_messages m ON m.id=t.message_id WHERE t.command_id=c.id AND m.thread_id=$2 AND m.link_id=$1)
ORDER BY c.intent->>'kind',c.intent->'value'->>'name',c.accepted_order DESC LIMIT 100"#,link,thread).fetch_all(pool).await?;
rows.into_iter()
@@ -138,11 +141,17 @@ pub(super) async fn operations(
id: row.id,
action: serde_json::from_value(row.intent)
.map_err(|e| sqlx::Error::Decode(Box::new(e)))?,
+ // Nothing resumes an unknown write, so it never reads as waiting.
state: match row.status.as_str() {
+ "pending" | "running" | "confirming" => MailboxOperationState::Pending,
"succeeded" => MailboxOperationState::Applied,
- "failed" => MailboxOperationState::Failed,
- "cancelled" => MailboxOperationState::Cancelled,
- _ => MailboxOperationState::Pending,
+ "failed" | "conflict" => MailboxOperationState::Failed,
+ "cancelled" | "unknown" => MailboxOperationState::Cancelled,
+ status => {
+ return Err(sqlx::Error::Decode(
+ format!("unexpected mailbox command status {status}").into(),
+ ));
+ }
},
updated_at: row.updated_at,
})
diff --git a/crates/email/src/outbound/mailbox_pg/commands/test.rs b/crates/email/src/outbound/mailbox_pg/commands/test.rs
index a868194e62..d7cd37cbc6 100644
--- a/crates/email/src/outbound/mailbox_pg/commands/test.rs
+++ b/crates/email/src/outbound/mailbox_pg/commands/test.rs
@@ -98,6 +98,10 @@ async fn newer_intent_survives_sync_and_ack_of_an_older_command(db: PgPool) {
false,
"observed provider state stays separate"
);
+ let messages = repo
+ .mailbox_action_messages(work.mailbox.link_id, thread)
+ .await
+ .unwrap();
let second = repo
.enqueue_mailbox_action(
work.mailbox.link_id,
@@ -332,6 +336,10 @@ async fn unknown_write_is_confirmed_before_retry_and_revoked_access_stops_execut
.unwrap(),
"succeeded"
);
+ let messages = repo
+ .mailbox_action_messages(work.mailbox.link_id, thread)
+ .await
+ .unwrap();
let next = repo
.enqueue_mailbox_action(
work.mailbox.link_id,
@@ -509,6 +517,10 @@ async fn acceptance_order_wins_over_transaction_start_order(db: PgPool) {
)
.await
.unwrap();
+ let messages = repo
+ .mailbox_action_messages(work.mailbox.link_id, thread)
+ .await
+ .unwrap();
let second = repo
.enqueue_mailbox_action(
work.mailbox.link_id,
@@ -549,3 +561,62 @@ async fn acceptance_order_wins_over_transaction_start_order(db: PgPool) {
.unwrap();
assert_eq!(operations[0].id, second);
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reopening_a_read_thread_queues_no_command(db: PgPool) {
+ let (_, repo, work, thread) = setup(&db).await;
+ let link = work.mailbox.link_id;
+ let messages = repo.mailbox_action_messages(link, thread).await.unwrap();
+ repo.enqueue_mailbox_action(
+ link,
+ owner(),
+ &MailboxAction::Read(true),
+ &MailboxAction::Read(true).targets(&messages),
+ )
+ .await
+ .unwrap();
+ let messages = repo.mailbox_action_messages(link, thread).await.unwrap();
+ assert!(messages[0].is_read, "the accepted intent is the read state");
+ assert!(MailboxAction::Read(true).targets(&messages).is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unresumable_commands_are_not_reported_as_pending(db: PgPool) {
+ let (sync, repo, work, thread) = setup(&db).await;
+ let link = work.mailbox.link_id;
+ let messages = repo.mailbox_action_messages(link, thread).await.unwrap();
+ repo.enqueue_mailbox_action(
+ link,
+ owner(),
+ &MailboxAction::Read(true),
+ &MailboxAction::Read(true).targets(&messages),
+ )
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE email_mailbox_commands SET status='unknown' WHERE link_id=$1",
+ link
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+ let operations = repo.thread_mailbox_operations(link, thread).await.unwrap();
+ assert!(matches!(
+ operations[0].state,
+ crate::domain::models::mailbox_action::MailboxOperationState::Cancelled
+ ));
+ sqlx::query!(
+ "UPDATE email_links SET sync_generation=sync_generation+1 WHERE id=$1",
+ link
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+ assert!(sync.claim_command(Uuid::now_v7()).await.unwrap().is_none());
+ assert!(
+ repo.thread_mailbox_operations(link, thread)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/email/src/outbound/mailbox_pg/lifecycle.rs b/crates/email/src/outbound/mailbox_pg/lifecycle.rs
index fdfed41925..2b536a47c6 100644
--- a/crates/email/src/outbound/mailbox_pg/lifecycle.rs
+++ b/crates/email/src/outbound/mailbox_pg/lifecycle.rs
@@ -388,8 +388,16 @@ async fn rebind_work(
SELECT link_id,$3,provider_id,is_import FROM email_message_reconciliation WHERE link_id = $1 AND generation = $2 ON CONFLICT DO NOTHING"#,link,old,new).execute(&mut **tx).await.map_err(failed)?;
sqlx::query!(r#"UPDATE email_mailbox_drafts SET generation = $3,lease_id = NULL,lease_until = NULL,
state = CASE WHEN state = 'running' THEN 'pending' ELSE state END,available_at = now(),updated_at = now() WHERE link_id = $1 AND generation = $2"#,link,old,new).execute(&mut **tx).await.map_err(failed)?;
- sqlx::query!(r#"UPDATE email_mailbox_commands SET generation = $3,lease_id = NULL,lease_until = NULL,
- status = CASE WHEN status = 'running' THEN 'pending' ELSE status END,available_at = now(),updated_at = now()
- WHERE link_id = $1 AND generation = $2 AND status IN ('pending','running','confirming')"#,link,old,new).execute(&mut **tx).await.map_err(failed)?;
+ sqlx::query!(
+ r#"UPDATE email_mailbox_commands SET generation = $3,lease_id = NULL,lease_until = NULL,
+ status = 'pending',available_at = now(),updated_at = now()
+ WHERE link_id = $1 AND generation = $2 AND status IN ('pending','running','confirming')"#,
+ link,
+ old,
+ new
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(failed)?;
Ok(())
}
diff --git a/crates/email/src/outbound/mailbox_pg/lifecycle/test.rs b/crates/email/src/outbound/mailbox_pg/lifecycle/test.rs
index e531b49631..e6a80b67cc 100644
--- a/crates/email/src/outbound/mailbox_pg/lifecycle/test.rs
+++ b/crates/email/src/outbound/mailbox_pg/lifecycle/test.rs
@@ -66,6 +66,16 @@ async fn leaving_shared_custodian_rebinds_work_and_rejects_old_health_even_with_
db: PgPool,
) {
let (repo, link, replacement) = shared(&db).await;
+ let command = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ r#"INSERT INTO email_mailbox_commands(id,link_id,generation,actor_id,intent,status)
+ VALUES ($1,$2,1,'macro|[email protected]','{"kind":"read","value":true}','confirming')"#,
+ command,
+ link
+ )
+ .execute(&db)
+ .await
+ .unwrap();
let service = InboxLifecycleService::new(repo.clone(), Effects);
service.remove(&actor("leaving"), link).await.unwrap();
let row=sqlx::query!("SELECT macro_id,is_sync_active,needs_reauth,grant_id,grant_generation,sync_generation,fusionauth_user_id FROM email_links WHERE id = $1",link).fetch_one(&db).await.unwrap();
@@ -76,6 +86,18 @@ async fn leaving_shared_custodian_rebinds_work_and_rejects_old_health_even_with_
assert_eq!(row.grant_generation, 1);
assert_eq!(row.sync_generation, 2);
assert_eq!(row.fusionauth_user_id, "remaining-owner");
+ let rebound = sqlx::query!(
+ "SELECT status,generation FROM email_mailbox_commands WHERE id = $1",
+ command
+ )
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(
+ (rebound.status.as_str(), rebound.generation),
+ ("pending", 2),
+ "a confirming command is never claimed, so it must resume as pending"
+ );
assert!(matches!(
repo.record(
MailboxAccess {
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index a9f5776462..60278265d0 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -40,7 +40,8 @@ providers. Shared/delegated Microsoft mailboxes are outside this account scope;
sharing an inbox or thread inside Macro remains available.
For Outlook writes, distinguish acceptance from provider confirmation. Thread
-organization notices and inbox settings show pending or failed changes. A saved
+organization notices and inbox settings show pending or failed changes; the
+mark-as-read from opening a thread is announced only if it fails. A saved
draft can show a conflict or an uncertain delivery: use its recovery actions and
check the provider copy before choosing an explicit resend. Switching the sender
inbox copies the draft and attachments into the destination; wait for completion
diff --git a/services/email_service/src/outbound/mailbox_init.rs b/services/email_service/src/outbound/mailbox_init.rs
index 57853d9493..c941bf3874 100644
--- a/services/email_service/src/outbound/mailbox_init.rs
+++ b/services/email_service/src/outbound/mailbox_init.rs
@@ -355,31 +355,14 @@ impl MailboxInitializationRepository for PgMailboxInitialization {
macro_uuid::generate_uuid_v7(),link_id,link.sync_generation,kind
).execute(&mut *tx).await.map_err(unavailable)?;
}
- // Old leases cannot write into this generation. Keep uncertain sends
- // for reconciliation rather than treating a reconnect as permission to resend.
+ // Old leases cannot write into this generation. Organization commands
+ // read provider state before every write, so the replacement grant
+ // resumes them, with their pending state, instead of abandoning them.
sqlx::query!(r#"
- UPDATE email_mailbox_commands SET status = CASE WHEN status = 'pending' THEN 'cancelled' ELSE 'unknown' END,
- lease_id = NULL,lease_until = NULL,updated_at = now()
+ UPDATE email_mailbox_commands SET generation = $2,lease_id = NULL,lease_until = NULL,
+ status = 'pending',available_at = now(),updated_at = now()
WHERE link_id = $1 AND generation <> $2 AND status IN ('pending','running','confirming')
"#,link_id,link.sync_generation).execute(&mut *tx).await.map_err(unavailable)?;
- let affected = sqlx::query!(r#"
- DELETE FROM email_pending_mailbox_state p USING email_mailbox_commands c
- WHERE p.command_id = c.id AND c.link_id = $1 AND c.generation <> $2 RETURNING p.message_id
- "#,link_id,link.sync_generation).fetch_all(&mut *tx).await.map_err(unavailable)?;
- for pending in affected {
- let thread = sqlx::query_scalar!(r#"
- UPDATE email_messages SET is_read = COALESCE((mailbox_state->>'is_read')::boolean,is_read),
- is_starred = COALESCE((mailbox_state->>'is_flagged')::boolean,is_starred)
- WHERE id = $1 RETURNING thread_id
- "#,pending.message_id).fetch_optional(&mut *tx).await.map_err(unavailable)?;
- if let Some(thread) = thread {
- email_db_client::threads::update::recompute_thread_metadata(
- &mut tx, thread, link_id,
- )
- .await
- .map_err(unavailable)?;
- }
- }
}
sqlx::query!("INSERT INTO email_link_initializations (attempt_id,actor_id,link_id) VALUES ($1,$2,$3)",request.attempt,request.actor.as_ref(),link_id)
.execute(&mut *tx).await.map_err(unavailable)?;
diff --git a/services/email_service/src/outbound/mailbox_init/test.rs b/services/email_service/src/outbound/mailbox_init/test.rs
index 3438e37161..738719135f 100644
--- a/services/email_service/src/outbound/mailbox_init/test.rs
+++ b/services/email_service/src/outbound/mailbox_init/test.rs
@@ -330,6 +330,147 @@ async fn admission_pause_rejects_new_mailbox_but_preserves_reconnect(db: PgPool)
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reconnect_resumes_organization_commands_under_the_new_grant(db: PgPool) {
+ use email::domain::{
+ mailbox::commands::MailboxCommandRepository,
+ models::mailbox_action::{MailboxAction, MailboxActionTarget, PendingMailboxState},
+ ports::EmailRepo,
+ };
+ let owner = actor(&db, "[email protected]").await;
+ let link = MailboxInitializationService::new(
+ PgMailboxInitialization(db.clone()),
+ Grants(grant(owner.0)),
+ )
+ .initialize(attempt(&db, owner.clone()).await)
+ .await
+ .unwrap();
+ let (thread, message, other) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query!(
+ "INSERT INTO email_threads(id,link_id) VALUES($1,$2)",
+ thread,
+ link
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+ for (id, provider_id) in [(message, "outlook-message"), (other, "outlook-other")] {
+ sqlx::query!(
+ "INSERT INTO email_messages(id,link_id,thread_id,provider_id) VALUES($1,$2,$3,$4)",
+ id,
+ link,
+ thread,
+ provider_id
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+ }
+ let target_for = |message_id, provider_id: &str, is_read| MailboxActionTarget {
+ message_id,
+ provider_id: Some(provider_id.into()),
+ pending: PendingMailboxState {
+ is_read: Some(is_read),
+ ..Default::default()
+ },
+ };
+ let target = |is_read| target_for(message, "outlook-message", is_read);
+ let repo = email::outbound::EmailPgRepo::new(db.clone());
+ let retrying = repo
+ .enqueue_mailbox_action(
+ link,
+ owner.1.clone(),
+ &MailboxAction::Read(true),
+ &[target(true)],
+ )
+ .await
+ .unwrap();
+ let queued = repo
+ .enqueue_mailbox_action(
+ link,
+ owner.1.clone(),
+ &MailboxAction::Read(false),
+ &[target(false)],
+ )
+ .await
+ .unwrap();
+ let sync = email::outbound::mailbox_pg::PgMailboxSync::new(db.clone());
+ let lease = sync.claim_command(Uuid::now_v7()).await.unwrap().unwrap();
+ assert_eq!(lease.id, retrying);
+ // An authorization failure releases the lease for a later retry.
+ sync.release_command(&lease, 300).await.unwrap();
+ let confirming = repo
+ .enqueue_mailbox_action(
+ link,
+ owner.1.clone(),
+ &MailboxAction::Read(true),
+ &[target_for(other, "outlook-other", true)],
+ )
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE email_mailbox_commands SET status = 'confirming' WHERE id = $1",
+ confirming
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+
+ MailboxInitializationService::new(PgMailboxInitialization(db.clone()), Grants(grant(owner.0)))
+ .initialize(attempt(&db, owner.clone()).await)
+ .await
+ .unwrap();
+ let generation = sqlx::query_scalar!(
+ "SELECT sync_generation FROM email_links WHERE id = $1",
+ link
+ )
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(generation, lease.mailbox.sync_generation + 1);
+ let commands = sqlx::query!(
+ "SELECT id,status,generation FROM email_mailbox_commands WHERE link_id = $1 ORDER BY accepted_order",
+ link
+ )
+ .fetch_all(&db)
+ .await
+ .unwrap();
+ assert_eq!(
+ commands
+ .iter()
+ .map(|c| (c.id, c.status.as_str(), c.generation))
+ .collect::<Vec<_>>(),
+ vec![
+ (retrying, "pending", generation),
+ (queued, "pending", generation),
+ (confirming, "pending", generation)
+ ]
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT command_id FROM email_pending_mailbox_state WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&db)
+ .await
+ .unwrap(),
+ queued,
+ "the newest accepted intent stays visible across the reconnect"
+ );
+ let mut resumed = Vec::new();
+ for _ in 0..2 {
+ let lease = sync.claim_command(Uuid::now_v7()).await.unwrap().unwrap();
+ resumed.push((lease.id, lease.mailbox.sync_generation));
+ }
+ resumed.sort();
+ let mut expected = vec![(retrying, generation), (confirming, generation)];
+ expected.sort();
+ assert_eq!(
+ resumed, expected,
+ "a confirming command resumes instead of blocking later commands"
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn concurrent_gmail_and_outlook_connections_share_one_remaining_free_slot(db: PgPool) {
let owner = actor(&db, "[email protected]").await;