Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): share threads at edit and let editors reply from own inbox (#9503)
Jacob Beckerman7d46c7656c8a
diff --git a/.sqlx/query-ba28ed6c5ce49470b0aef3fb0f59d392b5780cc548f331263a581d1b011eb970.json b/.sqlx/query-3b4a7b87a65ee6b8433ecdf0bd1ca23fedee82259e5f452c11728db3044a42e4.jsonsimilarity index 86%rename from .sqlx/query-ba28ed6c5ce49470b0aef3fb0f59d392b5780cc548f331263a581d1b011eb970.jsonrename to .sqlx/query-3b4a7b87a65ee6b8433ecdf0bd1ca23fedee82259e5f452c11728db3044a42e4.jsonindex ef2ae21a80..65af476c69 100644--- a/.sqlx/query-ba28ed6c5ce49470b0aef3fb0f59d392b5780cc548f331263a581d1b011eb970.json+++ b/.sqlx/query-3b4a7b87a65ee6b8433ecdf0bd1ca23fedee82259e5f452c11728db3044a42e4.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT \n -- Use trim() to remove the leading/trailing angle brackets\n trim(jsonb_path_query_first(headers_jsonb, '$[*] ? (@.name like_regex \"message-id\" flag \"i\").value') #>> '{}', '<>') as \"message_id\",\n -- The references header can have multiple IDs, so we just return it raw\n jsonb_path_query_first(headers_jsonb, '$[*] ? (@.name like_regex \"references\" flag \"i\").value') #>> '{}' as \"references\"\n FROM email_messages\n WHERE id = $1 AND link_id = $2\n ",+ "query": "\n SELECT \n -- Use trim() to remove the leading/trailing angle brackets\n trim(jsonb_path_query_first(headers_jsonb, '$[*] ? (@.name like_regex \"message-id\" flag \"i\").value') #>> '{}', '<>') as \"message_id\",\n -- The references header can have multiple IDs, so we just return it raw\n jsonb_path_query_first(headers_jsonb, '$[*] ? (@.name like_regex \"references\" flag \"i\").value') #>> '{}' as \"references\"\n FROM email_messages\n WHERE id = $1\n ","describe": {"columns": [{@@ -16,7 +16,6 @@],"parameters": {"Left": [- "Uuid","Uuid"]},@@ -25,5 +24,5 @@null]},- "hash": "ba28ed6c5ce49470b0aef3fb0f59d392b5780cc548f331263a581d1b011eb970"+ "hash": "3b4a7b87a65ee6b8433ecdf0bd1ca23fedee82259e5f452c11728db3044a42e4"}diff --git a/.sqlx/query-7cf4cbcca02d1fd81d717e8ed2362556e73d09bcec4ed897bc9dc3fc84e7d7b7.json b/.sqlx/query-7cf4cbcca02d1fd81d717e8ed2362556e73d09bcec4ed897bc9dc3fc84e7d7b7.jsonnew file mode 100644index 0000000000..42f747c934--- /dev/null+++ b/.sqlx/query-7cf4cbcca02d1fd81d717e8ed2362556e73d09bcec4ed897bc9dc3fc84e7d7b7.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT link_id, thread_id FROM email_messages WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "thread_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "7cf4cbcca02d1fd81d717e8ed2362556e73d09bcec4ed897bc9dc3fc84e7d7b7"+}diff --git a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.test.tsx b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.test.tsxindex 225bc4eead..f0bf45b530 100644--- a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.test.tsx+++ b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.test.tsx@@ -16,7 +16,7 @@ vi.mock('@app/features/email-thread/context/email-thread-state-context',() => ({useEmailThreadState: () => ({- permissions: () => ({ isOwner: true }),+ permissions: () => ({ isOwner: true, canReply: true }),thread: () => undefined,}),})diff --git a/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx b/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsxindex 0010b10fe0..d7c3b8c922 100644--- a/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx+++ b/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx@@ -190,6 +190,7 @@ function Reply(props: { replyType: ReplyType }) {inbox_visible: true,}),recipientOptions: () => [],+ ownsThreadInbox: () => true,isPersonalReply: () => false,onDraftRemoved: () => {},exitToThread: () => false,diff --git a/apps/web/src/features/email-compose/context/email-form-inputs.ts b/apps/web/src/features/email-compose/context/email-form-inputs.tsindex 88d58320ba..43bf0086b5 100644--- a/apps/web/src/features/email-compose/context/email-form-inputs.ts+++ b/apps/web/src/features/email-compose/context/email-form-inputs.ts@@ -6,6 +6,9 @@ import type { ReplyType } from '../core/reply-type';export interface EmailFormContextInputs {viewerEmail: Accessor<string | undefined>;inboxes: Accessor<SenderInbox[]>;+ /** The composer's fallback sending inbox, used when a reply's own inbox is+ * not the viewer's (a thread shared with them). */+ primaryInboxId?: Accessor<string | undefined>;}/** Only the reply capabilities consumed by the composer; the caller owns navigation. */@@ -20,6 +23,9 @@ export interface EmailReplySession {| undefined>;recipientOptions: Accessor<EmailRecipient[]>;+ /** False for a thread shared with the viewer: it sits in its owner's inbox,+ * which the viewer cannot send from. */+ ownsThreadInbox: Accessor<boolean>;isPersonalReply: Accessor<boolean>;onDraftRemoved(): void;exitToThread(target: 'last' | 'selected'): boolean;diff --git a/apps/web/src/features/email-compose/primitives/email-form-sender.test.ts b/apps/web/src/features/email-compose/primitives/email-form-sender.test.tsindex e5189a283e..ea266b1cad 100644--- a/apps/web/src/features/email-compose/primitives/email-form-sender.test.ts+++ b/apps/web/src/features/email-compose/primitives/email-form-sender.test.ts@@ -197,3 +197,80 @@ it.each(['[email protected]', '[email protected]'])(}}));++it("replies to a shared thread from the viewer's inbox, not its owner's", () =>+ createRoot((dispose) => {+ try {+ const shared = message('shared', {+ link_id: 'owner-inbox',+ from: { email: '[email protected]' },+ to: [{ email: '[email protected]' }],+ });+ const form = createEmailFormState(+ { viewerEmail: () => '[email protected]', inboxes: () => [primary] },+ { type: 'replying_to', messageId: 'shared' },+ {+ getMessageById: () => shared,+ getDraftForMessageReply: () => undefined,+ }+ );+ expect(form.selectedInboxId()).toBeUndefined();+ expect(form.recipients().to.map((item) => item.data.email)).toEqual([+ '[email protected]',+ ]);+ } finally {+ dispose();+ }+ }));++it('replies from the inbox holding the message when it is the viewer’s', () =>+ createRoot((dispose) => {+ try {+ const form = createEmailFormState(+ { viewerEmail: () => '[email protected]', inboxes: () => [primary] },+ { type: 'replying_to', messageId: 'parent' },+ {+ getMessageById: () => parent,+ getDraftForMessageReply: () => undefined,+ }+ );+ expect(form.selectedInboxId()).toBe('inbox');+ } finally {+ dispose();+ }+ }));++it('judges a shared-thread reply against the inbox it sends from', () =>+ createRoot((dispose) => {+ try {+ const sending: SenderInbox = {+ id: 'viewer-inbox',+ email_address: '[email protected]',+ };+ // The viewer wrote this message from their own inbox to the owner, who+ // shared the thread back.+ const shared = message('shared', {+ link_id: 'owner-inbox',+ from: { email: '[email protected]' },+ to: [{ email: '[email protected]' }],+ });+ const form = createEmailFormState(+ {+ viewerEmail: () => '[email protected]',+ inboxes: () => [sending],+ primaryInboxId: () => 'viewer-inbox',+ },+ { type: 'replying_to', messageId: 'shared' },+ {+ getMessageById: () => shared,+ getDraftForMessageReply: () => undefined,+ }+ );+ expect(form.senderEmail()).toBe('[email protected]');+ expect(form.recipients().to.map((item) => item.data.email)).toEqual([+ '[email protected]',+ ]);+ } finally {+ dispose();+ }+ }));diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.tsindex 294b16b576..3a0345bdd1 100644--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts@@ -124,9 +124,24 @@ export function createEmailFormState(// The inbox this compose sends from. Defaults to the inbox that owns the// thread/draft; the user can change it via the "from" selector.- const [selectedInboxId, setSelectedInboxId] = createSignal<- string | undefined- >((draft ?? replyingTo)?.link_id ?? undefined);+ const [chosenInboxId, setSelectedInboxId] = createSignal<string | undefined>(+ draft?.link_id ?? undefined+ );+ // A thread shared with the viewer sits in its owner's inbox, which the viewer+ // cannot send from; that default yields to the composer's own-inbox fallback.+ const replyInboxId = () => {+ const inboxId = replyingTo?.link_id;+ return context.inboxes().some((inbox) => inbox.id === inboxId)+ ? inboxId+ : undefined;+ };+ const selectedInboxId = () => chosenInboxId() ?? replyInboxId();+ // The inbox a reply to a shared thread actually sends from, so recipients+ // are judged against that inbox's addresses.+ const sharedReplyInboxId = () =>+ replyingTo+ ? (context.primaryInboxId?.() ?? context.inboxes()[0]?.id)+ : undefined;// Reply logic ("did I send this?") must be judged against the inbox the// message is sent from, not the account's primary email — otherwise replying// from a secondary or delegated inbox misclassifies the sender and picks the@@ -140,8 +155,7 @@ export function createEmailFormState(context.inboxes().find(- (inbox) =>- inbox.id === (selectedInboxId() ?? (draft ?? replyingTo)?.link_id)+ (inbox) => inbox.id === (selectedInboxId() ?? sharedReplyInboxId()));const senderEmail = () => {const choice = senderChoice();diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex ef28112fdc..21faf1a28e 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -202,10 +202,14 @@ export function createReplyComposer(const userEmail = props.viewerEmail;const primaryInboxId = props.accounts.primaryId;+ // A thread shared with the viewer sits in its owner's inbox; reply from one+ // of the viewer's own instead.+ const threadInboxId = () =>+ ctx.ownsThreadInbox() ? thread()?.link_id : undefined;// Capture this domain inbox ID for each asynchronous operation.const activeInboxId = () =>form.selectedInboxId() ??- thread()?.link_id ??+ threadInboxId() ??draftSeed?.link_id ??primaryInboxId() ??props.accounts.inboxes()[0]?.id;diff --git a/apps/web/src/features/email-compose/tests/reply.ts b/apps/web/src/features/email-compose/tests/reply.tsindex d7cf69b701..8e01755994 100644--- a/apps/web/src/features/email-compose/tests/reply.ts+++ b/apps/web/src/features/email-compose/tests/reply.ts@@ -56,6 +56,7 @@ export function mountReplyComposer(inbox_visible: thread.inboxVisible ?? false,}),recipientOptions: () => [],+ ownsThreadInbox: () => true,isPersonalReply: () => false,onDraftRemoved() {},exitToThread: () => false,diff --git a/apps/web/src/features/email-compose/views/reply-input-close.test.tsx b/apps/web/src/features/email-compose/views/reply-input-close.test.tsxindex dac3d35e10..bc217aa0f0 100644--- a/apps/web/src/features/email-compose/views/reply-input-close.test.tsx+++ b/apps/web/src/features/email-compose/views/reply-input-close.test.tsx@@ -144,6 +144,7 @@ function mount(draftId?: string, text = '', context = createComposeContext()) {inbox_visible: true,}),recipientOptions: () => [],+ ownsThreadInbox: () => true,isPersonalReply: () => false,onDraftRemoved,exitToThread,diff --git a/apps/web/src/features/email-compose/views/reply-input.test.tsx b/apps/web/src/features/email-compose/views/reply-input.test.tsxindex 5c8f10db38..1998b5f182 100644--- a/apps/web/src/features/email-compose/views/reply-input.test.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.test.tsx@@ -68,6 +68,7 @@ it.each([session={{thread: () => undefined,recipientOptions: () => [],+ ownsThreadInbox: () => true,isPersonalReply: () => false,onDraftRemoved() {},exitToThread: () => false,diff --git a/apps/web/src/features/email-compose/views/reply-signature-order.test.tsx b/apps/web/src/features/email-compose/views/reply-signature-order.test.tsxindex a304bdeaff..73dd2736a7 100644--- a/apps/web/src/features/email-compose/views/reply-signature-order.test.tsx+++ b/apps/web/src/features/email-compose/views/reply-signature-order.test.tsx@@ -139,6 +139,7 @@ function mount(inbox_visible: true,}),recipientOptions: () => [],+ ownsThreadInbox: () => true,isPersonalReply: () => false,onDraftRemoved() {},exitToThread: () => false,diff --git a/apps/web/src/features/email-message/views/email-message.tsx b/apps/web/src/features/email-message/views/email-message.tsxindex 3bffe6ea83..d0ae6bc767 100644--- a/apps/web/src/features/email-message/views/email-message.tsx+++ b/apps/web/src/features/email-message/views/email-message.tsx@@ -53,6 +53,8 @@ export interface EmailMessageViewProps {onUnhover?: () => void;onFocus?: (element: HTMLElement) => void;onReply?: (action: EmailMessageAction) => void;+ /** Reply actions to leave out when `onReply` is set. */+ hiddenActions?: EmailMessageAction[];onOpenAttachment?: (attachment: EmailAttachment) => void;onDownloadAttachment?: (attachment: EmailAttachment) => void;children?: JSX.Element;@@ -185,7 +187,9 @@ export function EmailMessageView(props: EmailMessageViewProps) {viewerEmail={props.viewerEmail}readReceipt={props.readReceipt}hiddenActions={- props.onReply ? undefined : ['reply', 'reply-all', 'forward']+ props.onReply+ ? props.hiddenActions+ : ['reply', 'reply-all', 'forward']}avatar={<div class="shrink-0 flex justify-center items-center size-6">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.tsindex 371aa1b790..cab57cd32f 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@@ -79,6 +79,9 @@ export type EmailThreadState = {thread: Accessor<EmailThread | undefined>;permissions: Accessor<{isOwner: boolean;+ /** Owners, and recipients the thread was shared with at edit access,+ * who reply from their own inbox. */+ canReply: boolean;}>;query: {@@ -353,7 +356,13 @@ export function createEmailThreadState(setReplyRequest(undefined);},},- permissions: () => ({ isOwner: selected()?.access_level === 'owner' }),+ permissions: () => {+ const accessLevel = selected()?.access_level;+ return {+ isOwner: accessLevel === 'owner',+ canReply: accessLevel === 'owner' || accessLevel === 'edit',+ };+ },initialLoadComplete: hasHandledTarget,onInitialDataLoad,isScrollingToMessage,diff --git a/apps/web/src/features/email-thread/primitives/reply-actions.test.ts b/apps/web/src/features/email-thread/primitives/reply-actions.test.tsindex be1176130f..047c06310a 100644--- a/apps/web/src/features/email-thread/primitives/reply-actions.test.ts+++ b/apps/web/src/features/email-thread/primitives/reply-actions.test.ts@@ -3,8 +3,9 @@ import { message } from '../tests/fixtures';import type { EmailThreadState } from './email-thread-state';import { openEmailReplyComposerForMessage } from './reply-actions';-function setup() {+function setup(permissions = { isOwner: true, canReply: true }) {const ctx = {+ permissions: () => permissions,replyRequest: { set: vi.fn() },mobileReplyComposer: { openForMessage: vi.fn() },messages: {@@ -50,4 +51,36 @@ describe('openEmailReplyComposerForMessage', () => {expect(ctx.mobileReplyComposer.openForMessage).not.toHaveBeenCalled();expect(ctx.messages.setBottomReplyOpen).toHaveBeenCalledWith(true);});++ it('lets an edit recipient of a shared thread reply but not forward', () => {+ const { ctx, state } = setup({ isOwner: false, canReply: true });+ const open = (replyType: 'reply-all' | 'forward') =>+ openEmailReplyComposerForMessage({+ ctx: state,+ isTouch: false,+ message: message('last'),+ replyType,+ isLastMessage: true,+ });++ expect(open('forward')).toBe(false);+ expect(ctx.replyRequest.set).not.toHaveBeenCalled();+ expect(open('reply-all')).toBe(true);+ expect(ctx.replyRequest.set).toHaveBeenCalledWith('last', 'reply-all');+ });++ it('opens nothing for a view-only recipient', () => {+ const { ctx, state } = setup({ isOwner: false, canReply: false });++ const opened = openEmailReplyComposerForMessage({+ ctx: state,+ isTouch: true,+ message: message('last'),+ replyType: 'reply-all',+ isLastMessage: true,+ });++ expect(opened).toBe(false);+ expect(ctx.mobileReplyComposer.openForMessage).not.toHaveBeenCalled();+ });});diff --git a/apps/web/src/features/email-thread/primitives/reply-actions.ts b/apps/web/src/features/email-thread/primitives/reply-actions.tsindex 040c96bf18..851da7154a 100644--- a/apps/web/src/features/email-thread/primitives/reply-actions.ts+++ b/apps/web/src/features/email-thread/primitives/reply-actions.ts@@ -18,6 +18,12 @@ export function openEmailReplyComposerForMessage(args: {const messageId = args.message.db_id;if (!messageId) return false;+ const permissions = args.ctx.permissions();+ if (!permissions.canReply) return false;+ // A forward re-sends the message's attachments, which only the inbox holding+ // them can do; recipients of a shared thread reply instead.+ if (args.replyType === 'forward' && !permissions.isOwner) return false;+// The reply type and focus land through the reply request: the mounted// composer's effect applies them to its own (seed-keyed) form instance.// Writing to the form registry from here would target the wrong entry —diff --git a/apps/web/src/features/email-thread/views/bottom-reply-buttons.tsx b/apps/web/src/features/email-thread/views/bottom-reply-buttons.tsxindex 9f2ea6a85f..3406e358bf 100644--- a/apps/web/src/features/email-thread/views/bottom-reply-buttons.tsx+++ b/apps/web/src/features/email-thread/views/bottom-reply-buttons.tsx@@ -122,11 +122,13 @@ export function BottomReplyButtons(props: {label="Reply"onClick={open('reply-all')}/>- <ReplyActionButton- icon={ArrowBendUpRight}- label="Forward"- onClick={open('forward')}- />+ <Show when={ctx.permissions().isOwner}>+ <ReplyActionButton+ icon={ArrowBendUpRight}+ label="Forward"+ onClick={open('forward')}+ />+ </Show></div><div class="ml-auto flex items-center gap-2">diff --git a/apps/web/src/features/email-thread/views/email-thread.tsx b/apps/web/src/features/email-thread/views/email-thread.tsxindex 727a0e90b5..57cbc005ae 100644--- a/apps/web/src/features/email-thread/views/email-thread.tsx+++ b/apps/web/src/features/email-thread/views/email-thread.tsx@@ -68,7 +68,7 @@ export function EmailThreadView(props: EmailThreadViewProps) {isTouch: threadContext.isTouch,messages: context.messages.list,allMessages: context.messages.unfiltered,- canCompose: () => context.permissions().isOwner,+ canCompose: () => context.permissions().canReply,drafts: context.drafts,bottomReply: {open: context.messages.bottomReplyOpen,@@ -110,6 +110,7 @@ export function EmailThreadView(props: EmailThreadViewProps) {context={{viewerEmail: viewContext.compose.viewerEmail,inboxes: viewContext.compose.accounts.inboxes,+ primaryInboxId: viewContext.compose.accounts.primaryId,}}formOptions={{getMessageById: (id) =>diff --git a/apps/web/src/features/email-thread/views/message-container.tsx b/apps/web/src/features/email-thread/views/message-container.tsxindex 8a8de5530d..bd3e7f016a 100644--- a/apps/web/src/features/email-thread/views/message-container.tsx+++ b/apps/web/src/features/email-thread/views/message-container.tsx@@ -59,11 +59,13 @@ export function MessageContainer(props: MessageContainerProps) {// Touch replies open full screen, so a saved one would otherwise be invisible.const touchDraft = () =>- isTouchDevice() && context.permissions().isOwner ? draftChild() : undefined;+ isTouchDevice() && context.permissions().canReply+ ? draftChild()+ : undefined;const showInlineReplyArea = createMemo(() =>- context.permissions().isOwner &&+ context.permissions().canReply &&(showInlineReplyInput() || showDesktopLastReplyControls()));@@ -134,8 +136,9 @@ export function MessageContainer(props: MessageContainerProps) {onFocus={scrollFocusedCardIntoView}onOpenAttachment={rendering.openAttachment}onDownloadAttachment={rendering.downloadAttachment}+ hiddenActions={context.permissions().isOwner ? undefined : ['forward']}onReply={- context.permissions().isOwner+ context.permissions().canReply? (replyType) =>openEmailReplyComposerForMessage({ctx: context,diff --git a/apps/web/src/features/email-thread/views/mobile-email-compose.test.tsx b/apps/web/src/features/email-thread/views/mobile-email-compose.test.tsxindex 0ecdf41a17..37bd51a998 100644--- a/apps/web/src/features/email-thread/views/mobile-email-compose.test.tsx+++ b/apps/web/src/features/email-thread/views/mobile-email-compose.test.tsx@@ -38,7 +38,7 @@ const state = {setMessageId(undefined);},},- permissions: () => ({ isOwner: true }),+ permissions: () => ({ isOwner: true, canReply: true }),messages: { unfiltered: () => [parent], setBottomReplyOpen: vi.fn() },drafts: {getDraftForMessage: () =>diff --git a/apps/web/src/features/email-thread/views/mobile-email-compose.tsx b/apps/web/src/features/email-thread/views/mobile-email-compose.tsxindex 8e93a6346e..959c204ac8 100644--- a/apps/web/src/features/email-thread/views/mobile-email-compose.tsx+++ b/apps/web/src/features/email-thread/views/mobile-email-compose.tsx@@ -12,7 +12,7 @@ export function MobileEmailCompose(props: {const replyInfo = createMemo(() => {const messageId = context.mobileReplyComposer.messageId();- if (!messageId || !context.permissions().isOwner) return;+ if (!messageId || !context.permissions().canReply) return;const replyingTo = context.messages.unfiltered()diff --git a/apps/web/src/features/email-thread/views/thread-reply-input.tsx b/apps/web/src/features/email-thread/views/thread-reply-input.tsxindex 5090d82abc..e809e16a0c 100644--- a/apps/web/src/features/email-thread/views/thread-reply-input.tsx+++ b/apps/web/src/features/email-thread/views/thread-reply-input.tsx@@ -119,6 +119,7 @@ function ThreadReplyInputSession(props: ThreadReplyInputProps) {session={{thread: ctx.thread,recipientOptions: ctx.recipientOptions,+ ownsThreadInbox: () => ctx.permissions().isOwner,isPersonalReply: () => {const message = props.replyingTo();return (diff --git a/apps/web/src/lib/core/component/ForwardToChannel.tsx b/apps/web/src/lib/core/component/ForwardToChannel.tsxindex 9fdaa57e43..b75aff0109 100644--- a/apps/web/src/lib/core/component/ForwardToChannel.tsx+++ b/apps/web/src/lib/core/component/ForwardToChannel.tsx@@ -52,10 +52,7 @@ type Recipient = WithCustomUserInput<'user' | 'contact' | 'channel'>;interface MobileForwardToChannelLayoutPropsextends Pick<ForwardToChannelProps,- | 'submitPermissionInfo'- | 'hideAccessLevelSelector'- | 'editPermissionEnabled'- | 'allowedAccessLevels'+ 'submitPermissionInfo' | 'editPermissionEnabled' | 'allowedAccessLevels'> {isAuthenticated: Accessor<boolean | undefined>;selectedOptions: Accessor<Recipient[]>;@@ -134,10 +131,7 @@ function MobileForwardToChannelLayout(</div></Show><Show- when={- props.submitPermissionInfo?.userPermissions === Permissions.OWNER &&- !props.hideAccessLevelSelector- }+ when={props.submitPermissionInfo?.userPermissions === Permissions.OWNER}><div class="px-3 py-2 flex items-center"><span class="text-sm text-ink-muted pr-2">Access:</span>@@ -185,7 +179,6 @@ interface ForwardToChannelProps {handleSubmit: () => void;canSubmit: () => boolean;}) => void;- hideAccessLevelSelector?: boolean;initialAccessLevel?: AccessLevel | null;/** Levels the picker offers; all when absent. */allowedAccessLevels?: readonly AccessLevel[];@@ -596,7 +589,6 @@ export function ForwardToChannel(props: ForwardToChannelProps) {triedToSubmit={triedToSubmit}destinationOptions={destinationOptions}submitPermissionInfo={props.submitPermissionInfo}- hideAccessLevelSelector={props.hideAccessLevelSelector}allowedAccessLevels={props.allowedAccessLevels}submitAccessLevel={submitAccessLevel}setSubmitAccessLevel={setSubmitAccessLevel}@@ -627,7 +619,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {<Showwhen={props.submitPermissionInfo?.userPermissions ===- Permissions.OWNER && !props.hideAccessLevelSelector+ Permissions.OWNER}><div class="shrink-0 pr-2 flex items-center gap-2">diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex e5cddb3c2c..a0523c051c 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -926,7 +926,7 @@ describe('agent session sharing', () => {expect(mocks.sendToChannel).toHaveBeenCalledOnce();});it('keeps context identity for existing forwarding callers without overrides', async () => {- render(() => <ForwardToChannel name="Document" hideAccessLevelSelector />);+ render(() => <ForwardToChannel name="Document" />);await selectChannel();share();expect(mocks.sendToChannel).toHaveBeenCalledWith(@@ -940,12 +940,7 @@ describe('agent session sharing', () => {it('uses the current explicit identity if it changes while mounted', async () => {const [id, setId] = createSignal('old-session');render(() => (- <ForwardToChannel- name="Session"- blockName="agent"- blockId={id()}- hideAccessLevelSelector- />+ <ForwardToChannel name="Session" blockName="agent" blockId={id()} />));setId('new-session');await selectChannel();diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex b3625d0d8b..2335720dee 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -190,6 +190,8 @@ export function shareLevelsFor(blockAlias?: ShareBlockType): readonly AccessLevel[] | undefined {if (itemType === 'form') return ['view', 'edit'];+ // Edit on a shared email thread lets the recipient reply from their own inbox.+ if (itemType === 'email') return ['view', 'edit'];if (itemType === 'document' &&blockAlias &&@@ -794,9 +796,8 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {onSubmit={() => props.setIsOpen(false)}refetch={props.refetch}name={props.name}- hideAccessLevelSelector={props.itemType === 'email'}initialAccessLevel={- props.itemType === 'email' ? 'view' : null+ props.itemType === 'email' ? 'edit' : null}allowedAccessLevels={shareLevelsFor(props.itemType,@@ -1057,7 +1058,8 @@ export function ShareModal(props: ShareModalProps) {props.itemType === 'external_chat' &&props.userPermissions === Permissions.OWNER;const editPermissionEnabled = () => {- if (props.itemType === 'agent_session') return true;+ if (props.itemType === 'agent_session' || props.itemType === 'email')+ return true;if (props.itemType === 'document' &&props.blockAlias !== 'external_chat' &&@@ -1754,9 +1756,8 @@ export function ShareModal(props: ShareModalProps) {onCancel={() => props.onOpenChange(false)}refetch={refetch}name={props.name}- hideAccessLevelSelector={props.itemType === 'email'}initialAccessLevel={- props.itemType === 'email' ? 'view' : null+ props.itemType === 'email' ? 'edit' : null}allowedAccessLevels={shareLevelsFor(props.itemType,diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex d8833850fd..9eb5c09a5c 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -144,6 +144,10 @@ tools — hexagonal, heavily feature-gated.queued goes back through `EmailRepo::revert_staged_label_change`, whichrestores the state an older write still on its way left (or the original),never a newer write's change.+- A reply target outside the caller's inboxes is admitted only through+ `SharedThreadReplyAccess` (edit access to its thread; wired in+ `document_storage_service` with `with_shared_thread_replies`). The reply+ starts a thread in the caller's inbox; other hosts keep `NoSharedThreadReplies`.- Sender discovery authorizes the inbox first. Gmail aliases use the senderprovider; Outlook exposes its verified primary address without a Gmail lookup.- Outlook links have no system label rows. Move a thread in or out of the inboxdiff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rsindex 3ad5810d36..88a2bf90f3 100644--- a/crates/email/src/domain.rs+++ b/crates/email/src/domain.rs@@ -23,6 +23,7 @@ pub mod models;#[cfg(feature = "ports")]pub mod read_receipts;pub mod senders;+pub mod shared_thread_replies;#[cfg(feature = "ports")]pub mod assembler;diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rsindex da5550bcbb..2a8008108e 100644--- a/crates/email/src/domain/service.rs+++ b/crates/email/src/domain/service.rs@@ -69,6 +69,8 @@ pub struct EmailServiceImpl<T, U, E, CS, Eam, B = NoopMacroEventBroker> {pub(crate) macro_event_broker: B,pub(crate) sent_undo_delay_secs: u32,pub(crate) sender_provider: std::sync::Arc<dyn crate::domain::senders::EmailSenderProvider>,+ pub(crate) shared_thread_replies:+ std::sync::Arc<dyn crate::domain::shared_thread_replies::SharedThreadReplyAccess>,}impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>@@ -98,6 +100,9 @@ wheresender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}}@@ -112,6 +117,15 @@ impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B> {self}+ /// Let callers reply to threads shared with them at edit access.+ pub fn with_shared_thread_replies(+ mut self,+ access: impl crate::domain::shared_thread_replies::SharedThreadReplyAccess,+ ) -> Self {+ self.shared_thread_replies = std::sync::Arc::new(access);+ self+ }+/// Replace the event broker used to publish `macro.email` events./// [`new`](Self::new) starts with a [`NoopMacroEventBroker`].pub fn with_macro_event_broker<B2: MacroEventBroker>(@@ -127,6 +141,7 @@ impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B> {macro_event_broker,sent_undo_delay_secs: self.sent_undo_delay_secs,sender_provider: self.sender_provider,+ shared_thread_replies: self.shared_thread_replies,}}diff --git a/crates/email/src/domain/service/draft.rs b/crates/email/src/domain/service/draft.rsindex 6612fad123..468589a387 100644--- a/crates/email/src/domain/service/draft.rs+++ b/crates/email/src/domain/service/draft.rs@@ -10,6 +10,7 @@ use base64::Engine;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use frecency::domain::ports::FrecencyQueryService;use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;use super::EmailServiceImpl;@@ -469,12 +470,17 @@ whereinput.provider_id = None;input.provider_thread_id = None;}+ // Authorize the reply target before validate_existing_message can move+ // the draft to another inbox, so a refused target leaves it in place.+ let reply_target = self+ .authorized_reply_target(&input, &accessible_link_ids)+ .await?;let source_inbox = self.validate_existing_message(link_id, accessible_inboxes, &mut input, defer_inbox_move).await?;let source_message_id = input.db_id;- self.validate_replying_to(link_id, &accessible_link_ids, &mut input)+ self.validate_replying_to(link_id, reply_target.as_ref(), &mut input).await?;if source_inbox.is_some() && input.db_id != source_message_id {return Err(EmailErr::InvalidSendSnapshot(@@ -691,95 +697,101 @@ whereOk(None)}+ /// The reply target, authorized on every save, before an existing reply+ /// draft is reused: that draft is found by a header the client can write.+ async fn authorized_reply_target(+ &self,+ input: &CreateDraftInput,+ accessible_link_ids: &[Uuid],+ ) -> Result<Option<SimpleMessageInfo>, EmailErr> {+ let Some(replying_to_id) = input.replying_to_id else {+ return Ok(None);+ };+ let reply_target = self+ .reply_target(input.actor.as_ref(), replying_to_id, accessible_link_ids)+ .await?;+ if reply_target.is_draft {+ return Err(EmailErr::CannotReplyToDraft);+ }+ Ok(Some(reply_target))+ }+async fn validate_replying_to(&self,link_id: Uuid,- accessible_link_ids: &[Uuid],+ reply_target: Option<&SimpleMessageInfo>,input: &mut CreateDraftInput,) -> Result<(), EmailErr> {- let Some(replying_to_id) = input.replying_to_id else {+ let Some(reply_target) = reply_target else {return Ok(());};// An explicit, validated identity must never be retargeted to a newer// reply draft by a delayed save from an obsolete composer.if input.db_id.is_some() {- let parent = self- .email_repo- .get_simple_message(replying_to_id, accessible_link_ids)- .await- .map_err(anyhow::Error::from)?- .ok_or(EmailErr::MessageNotFound(replying_to_id))?;- if parent.is_draft {- return Err(EmailErr::CannotReplyToDraft);- }return Ok(());}// The draft replying to this message lives in the inbox being sent from.if let Some(existing_draft) = self.email_repo- .get_draft_replying_to(link_id, replying_to_id)+ .get_draft_replying_to(link_id, reply_target.db_id).await.map_err(anyhow::Error::from)?{self.apply_existing_draft(input, existing_draft);} else {- self.apply_reply_target(link_id, accessible_link_ids, input, replying_to_id)- .await?;+ apply_reply_target(link_id, input, reply_target);}Ok(())}- fn apply_existing_draft(+ /// A message the caller may reply to: one in their own inboxes, or one in+ /// a thread shared with them at edit access. A shared target lives in its+ /// owner's inbox, so the reply always starts a thread in the caller's.+ async fn reply_target(&self,- input: &mut CreateDraftInput,- existing_draft: SimpleMessageInfo,- ) {- input.db_id = Some(existing_draft.db_id);- input.provider_id = existing_draft.provider_id;- input.thread_db_id = Some(existing_draft.thread_db_id);- input.provider_thread_id = existing_draft.provider_thread_id;- input.headers_json = existing_draft.headers_json;- }-- async fn apply_reply_target(- &self,- link_id: Uuid,- accessible_link_ids: &[Uuid],- input: &mut CreateDraftInput,+ actor: Option<&MacroUserIdStr<'static>>,replying_to_id: Uuid,- ) -> Result<(), EmailErr> {- let reply_target = self+ accessible_link_ids: &[Uuid],+ ) -> Result<SimpleMessageInfo, EmailErr> {+ if let Some(target) = self.email_repo.get_simple_message(replying_to_id, accessible_link_ids).await.map_err(anyhow::Error::from)?- .ok_or(EmailErr::MessageNotFound(replying_to_id))?;-- if reply_target.is_draft {- return Err(EmailErr::CannotReplyToDraft);+ {+ return Ok(target);}- if reply_target.link_id == link_id {- // Same inbox: thread into the target's existing thread.- input.thread_db_id = Some(reply_target.thread_db_id);- input.provider_thread_id = reply_target.provider_thread_id;- } else {- // The target lives in a different inbox (a different provider- // account), so it cannot thread into that account's provider- // thread. Start a fresh thread in the sending inbox; the- // Macro-In-Reply-To header below preserves the reference.- input.thread_db_id = None;- input.provider_thread_id = None;- }+ let Some(actor) = actor else {+ return Err(EmailErr::MessageNotFound(replying_to_id));+ };+ let Some(shared_link_id) = self+ .shared_thread_replies+ .reply_target_inbox(actor, replying_to_id)+ .await?+ else {+ return Err(EmailErr::MessageNotFound(replying_to_id));+ };- // Generate Macro-In-Reply-To header- input.headers_json = Some(serde_json::json!([{- "Macro-In-Reply-To": reply_target.db_id.to_string()- }]));+ self.email_repo+ .get_simple_message(replying_to_id, &[shared_link_id])+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(EmailErr::MessageNotFound(replying_to_id))+ }- Ok(())+ fn apply_existing_draft(+ &self,+ input: &mut CreateDraftInput,+ existing_draft: SimpleMessageInfo,+ ) {+ input.db_id = Some(existing_draft.db_id);+ input.provider_id = existing_draft.provider_id;+ input.thread_db_id = Some(existing_draft.thread_db_id);+ input.provider_thread_id = existing_draft.provider_thread_id;+ input.headers_json = existing_draft.headers_json;}/// Validate a client-supplied thread hint on the no-reply-target path.@@ -851,6 +863,32 @@ where}}+/// Thread a new reply draft under an authorized target.+fn apply_reply_target(+ link_id: Uuid,+ input: &mut CreateDraftInput,+ reply_target: &SimpleMessageInfo,+) {+ if reply_target.link_id == link_id {+ // Same inbox: thread into the target's existing thread.+ input.thread_db_id = Some(reply_target.thread_db_id);+ input.provider_thread_id = reply_target.provider_thread_id.clone();+ } else {+ // The target lives in a different inbox (a different provider+ // account, possibly another user's through a share), so it cannot+ // thread into that account's provider thread. Start a fresh thread in+ // the sending inbox; the Macro-In-Reply-To header below preserves the+ // reference.+ input.thread_db_id = None;+ input.provider_thread_id = None;+ }++ // Generate Macro-In-Reply-To header+ input.headers_json = Some(serde_json::json!([{+ "Macro-In-Reply-To": reply_target.db_id.to_string()+ }]));+}+/// The decision for a compose draft's client-supplied thread hint.enum ThreadHintOutcome {/// The thread exists in the sending inbox — attach, adopting itsdiff --git a/crates/email/src/domain/service/senders/test.rs b/crates/email/src/domain/service/senders/test.rsindex 0a2251bd98..6bc9c84b0a 100644--- a/crates/email/src/domain/service/senders/test.rs+++ b/crates/email/src/domain/service/senders/test.rs@@ -66,6 +66,9 @@ fn service(provider: Provider) -> EmailServiceImpl<(), (), (), (), (), ()> {macro_event_broker: (),sent_undo_delay_secs: 10,sender_provider: Arc::new(provider),+ shared_thread_replies: Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}diff --git a/crates/email/src/domain/service/user/test.rs b/crates/email/src/domain/service/user/test.rsindex ea960a3210..0c27d49957 100644--- a/crates/email/src/domain/service/user/test.rs+++ b/crates/email/src/domain/service/user/test.rs@@ -72,6 +72,9 @@ fn service(repo: FakeUserRepo) -> EmailServiceImpl<FakeUserRepo, (), (), (), (),macro_event_broker: (),sent_undo_delay_secs: 0,sender_provider: Arc::new(crate::domain::senders::UnavailableEmailSenderProvider),+ shared_thread_replies: Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}diff --git a/crates/email/src/domain/shared_thread_replies.rs b/crates/email/src/domain/shared_thread_replies.rsnew file mode 100644index 0000000000..8cdabed07e--- /dev/null+++ b/crates/email/src/domain/shared_thread_replies.rs@@ -0,0 +1,38 @@+//! Replies to threads that live in another user's inbox and were shared with+//! the caller. Entity access stays behind a port.++use std::{future::Future, pin::Pin};++use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::models::EmailErr;++/// Boxed so the service can inject the capability without propagating the+/// entity-access generics to every email consumer.+pub type ReplyTargetInboxFuture<'a> =+ Pin<Box<dyn Future<Output = Result<Option<Uuid>, EmailErr>> + Send + 'a>>;++/// Finds the inbox holding a message the caller may reply to through a share.+pub trait SharedThreadReplyAccess: Send + Sync + 'static {+ /// The inbox of `message_id` when `actor` holds edit access to its thread,+ /// so they can answer it from an inbox of their own; `None` otherwise.+ fn reply_target_inbox<'a>(+ &'a self,+ actor: &'a MacroUserIdStr<'static>,+ message_id: Uuid,+ ) -> ReplyTargetInboxFuture<'a>;+}++/// Hosts without entity access answer only messages in the caller's inboxes.+pub struct NoSharedThreadReplies;++impl SharedThreadReplyAccess for NoSharedThreadReplies {+ fn reply_target_inbox<'a>(+ &'a self,+ _actor: &'a MacroUserIdStr<'static>,+ _message_id: Uuid,+ ) -> ReplyTargetInboxFuture<'a> {+ Box::pin(async { Ok(None) })+ }+}diff --git a/crates/email/src/outbound.rs b/crates/email/src/outbound.rsindex 2bb491f00c..fa43834f85 100644--- a/crates/email/src/outbound.rs+++ b/crates/email/src/outbound.rs@@ -14,6 +14,8 @@ pub mod invitation_pg;pub mod read_receipts_pg;#[cfg(feature = "s3")]mod s3_draft_attachment_storage;+#[cfg(feature = "outbound")]+mod shared_thread_replies;#[cfg(feature = "outbound")]pub use email_pg_repo::EmailPgRepo;@@ -29,3 +31,5 @@ pub use gmail_sender_provider::GmailSenderProvider;pub use gmail_token_provider::GmailTokenProviderImpl;#[cfg(feature = "s3")]pub use s3_draft_attachment_storage::S3DraftAttachmentStorage;+#[cfg(feature = "outbound")]+pub use shared_thread_replies::EntityAccessSharedThreadReplies;diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rsindex 26a6fa654c..b48e29385a 100644--- a/crates/email/src/outbound/email_pg_repo/test.rs+++ b/crates/email/src/outbound/email_pg_repo/test.rs@@ -19,6 +19,7 @@ mod sender_names;mod senders;mod sending_inbox;mod settings;+mod shared_thread_reply;mod signal_flag;mod thread;mod thread_archive;diff --git a/crates/email/src/outbound/email_pg_repo/test/scheduled.rs b/crates/email/src/outbound/email_pg_repo/test/scheduled.rsindex 28306ced8f..783407b842 100644--- a/crates/email/src/outbound/email_pg_repo/test/scheduled.rs+++ b/crates/email/src/outbound/email_pg_repo/test/scheduled.rs@@ -155,6 +155,9 @@ async fn service_authorizes_actor_and_validates_future_time(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),email_repo: EmailPgRepo::new(pool),frecency_service: (),enqueuer: (),@@ -211,6 +214,9 @@ async fn scheduled_source_rejects_delete_and_migration_into_existing_reply(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),email_repo: EmailPgRepo::new(pool.clone()),frecency_service: FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),enqueuer: NoOpEnqueuer,@@ -515,6 +521,9 @@ async fn initial_schedule_prepares_signature_but_time_updates_preserve_content(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),email_repo: EmailPgRepo::new(pool.clone()),frecency_service: (),enqueuer: (),diff --git a/crates/email/src/outbound/email_pg_repo/test/send_attempt.rs b/crates/email/src/outbound/email_pg_repo/test/send_attempt.rsindex 45cc764b0d..332f40532c 100644--- a/crates/email/src/outbound/email_pg_repo/test/send_attempt.rs+++ b/crates/email/src/outbound/email_pg_repo/test/send_attempt.rs@@ -317,6 +317,9 @@ fn service(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}diff --git a/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs b/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rsindex bfa9fc5502..1e7188ec72 100644--- a/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs+++ b/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs@@ -40,6 +40,9 @@ fn service(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}diff --git a/crates/email/src/outbound/email_pg_repo/test/shared_thread_reply.rs b/crates/email/src/outbound/email_pg_repo/test/shared_thread_reply.rsnew file mode 100644index 0000000000..957f12519e--- /dev/null+++ b/crates/email/src/outbound/email_pg_repo/test/shared_thread_reply.rs@@ -0,0 +1,221 @@+use super::*;+use crate::domain::models::{CreateDraftInput, EmailErr};+use crate::domain::ports::NoOpEnqueuer;+use crate::domain::service::EmailServiceImpl;+use crate::domain::shared_thread_replies::{+ NoSharedThreadReplies, ReplyTargetInboxFuture, SharedThreadReplyAccess,+};+use crm::domain::service::NoOpCrmService;+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};+use macro_event_broker::NoopMacroEventBroker;++/// Grants a reply into `inbox` for any message, as an edit share would.+struct GrantsInbox(Uuid);++impl SharedThreadReplyAccess for GrantsInbox {+ fn reply_target_inbox<'a>(+ &'a self,+ _actor: &'a MacroUserIdStr<'static>,+ _message_id: Uuid,+ ) -> ReplyTargetInboxFuture<'a> {+ let inbox = self.0;+ Box::pin(async move { Ok(Some(inbox)) })+ }+}++fn service(+ pool: Pool<Postgres>,+ shared_thread_replies: impl SharedThreadReplyAccess,+) -> EmailServiceImpl<+ EmailPgRepo,+ FrecencyQueryServiceImpl<FrecencyPgStorage>,+ NoOpEnqueuer,+ NoOpCrmService,+ (),+> {+ EmailServiceImpl {+ sender_provider: Arc::new(crate::domain::senders::UnavailableEmailSenderProvider),+ shared_thread_replies: Arc::new(shared_thread_replies),+ email_repo: EmailPgRepo::new(pool.clone()),+ frecency_service: FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool)),+ enqueuer: NoOpEnqueuer,+ crm_service: NoOpCrmService,+ entity_access_management_service: (),+ macro_event_broker: NoopMacroEventBroker,+ sent_undo_delay_secs: 5,+ }+}++/// A second user with an inbox of their own; user1's thread is shared with them.+async fn insert_recipient_inbox(pool: &Pool<Postgres>) -> anyhow::Result<Uuid> {+ let inbox = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd")?;+ sqlx::query!(+ "INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+ VALUES ($1, 'macro|[email protected]', 'fa-user-2', '[email protected]', 'GMAIL', true, NOW(), NOW())",+ inbox+ )+ .execute(pool)+ .await?;+ Ok(inbox)+}++fn recipient() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn reply_to(message: Uuid) -> CreateDraftInput {+ CreateDraftInput {+ frozen_signature_html: None,+ draft_generation: 0,+ sender_email: None,+ db_id: None,+ provider_id: None,+ replying_to_id: Some(message),+ provider_thread_id: None,+ thread_db_id: None,+ subject: "Re: Hello World".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: Some("Replying from my own inbox".to_string()),+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ include_signature: None,+ actor: None,+ draft_client_binding: None,+ thread_client_binding: None,+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn shared_thread_reply_starts_a_thread_in_the_recipients_inbox(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let owner_inbox = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let owner_thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let parent = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let recipient_inbox = insert_recipient_inbox(&pool).await?;+ let service = service(pool.clone(), GrantsInbox(owner_inbox));++ let saved = service+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), reply_to(parent))+ .await?;++ assert_eq!(saved.draft.link_id, recipient_inbox);+ assert_eq!(saved.draft.replying_to_id, Some(parent));+ assert_ne!(saved.draft.thread_db_id, owner_thread);+ assert_eq!(saved.draft.provider_thread_id, None);+ assert_eq!(+ saved.draft.headers_json,+ Some(serde_json::json!([{ "Macro-In-Reply-To": parent.to_string() }]))+ );++ // Saving again (an autosave with the server id) keeps the same reply.+ let mut autosave = reply_to(parent);+ autosave.db_id = Some(saved.draft.db_id);+ autosave.draft_generation = saved.draft.draft_generation;+ let resaved = service+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), autosave)+ .await?;+ assert_eq!(resaved.draft.db_id, saved.draft.db_id);++ // The owner's thread is untouched.+ let owner_messages = sqlx::query_scalar!(+ "SELECT COUNT(*) AS \"count!\" FROM email_messages WHERE thread_id = $1",+ owner_thread+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(owner_messages, 2);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn reply_to_an_unshared_thread_is_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let parent = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let recipient_inbox = insert_recipient_inbox(&pool).await?;+ let service = service(pool, NoSharedThreadReplies);++ let result = service+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), reply_to(parent))+ .await;++ assert!(matches!(result, Err(EmailErr::MessageNotFound(id)) if id == parent));+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn reply_cannot_adopt_a_draft_planted_for_an_unshared_message(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let parent = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let recipient_inbox = insert_recipient_inbox(&pool).await?;+ let service = service(pool, NoSharedThreadReplies);++ // A draft whose client-written header names a message in another inbox.+ let mut planted = reply_to(parent);+ planted.replying_to_id = None;+ planted.headers_json = Some(serde_json::json!([{ "Macro-In-Reply-To": parent.to_string() }]));+ service+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), planted)+ .await?;++ let result = service+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), reply_to(parent))+ .await;++ assert!(matches!(result, Err(EmailErr::MessageNotFound(id)) if id == parent));+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn revoked_share_keeps_the_reply_draft_when_switching_inboxes(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let owner_inbox = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let parent = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let recipient_inbox = insert_recipient_inbox(&pool).await?;+ let other_inbox = Uuid::parse_str("dddddddd-0000-0000-0000-00000000000e")?;+ sqlx::query!(+ "INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+ VALUES ($1, 'macro|[email protected]', 'fa-user-2', '[email protected]', 'GMAIL', true, NOW(), NOW())",+ other_inbox+ )+ .execute(&pool)+ .await?;+ let saved = service(pool.clone(), GrantsInbox(owner_inbox))+ .save_draft_for_user_impl(recipient(), Some(recipient_inbox), reply_to(parent))+ .await?;++ // The share is revoked, then the recipient picks their other inbox.+ let mut switch = reply_to(parent);+ switch.db_id = Some(saved.draft.db_id);+ switch.draft_generation = saved.draft.draft_generation;+ let result = service(pool.clone(), NoSharedThreadReplies)+ .save_draft_for_user_impl(recipient(), Some(other_inbox), switch)+ .await;++ assert!(matches!(result, Err(EmailErr::MessageNotFound(id)) if id == parent));+ let kept = sqlx::query_scalar!(+ "SELECT link_id FROM email_messages WHERE id = $1",+ saved.draft.db_id+ )+ .fetch_optional(&pool)+ .await?;+ assert_eq!(kept, Some(recipient_inbox));+ Ok(())+}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.rsindex 7a585710ab..c4a8c0f455 100644--- a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs+++ b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs@@ -63,6 +63,7 @@ pub(super) fn service_with_enqueuer<E: EmailMessageEnqueuer>(macro_event_broker: original.macro_event_broker,sent_undo_delay_secs: original.sent_undo_delay_secs,sender_provider: original.sender_provider,+ shared_thread_replies: original.shared_thread_replies,}}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.rsindex fd3ed91bfe..eb6e76d8d7 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@@ -24,6 +24,9 @@ pub(super) fn service(sender_provider: std::sync::Arc::new(crate::domain::senders::UnavailableEmailSenderProvider,),+ shared_thread_replies: std::sync::Arc::new(+ crate::domain::shared_thread_replies::NoSharedThreadReplies,+ ),}}diff --git a/crates/email/src/outbound/shared_thread_replies.rs b/crates/email/src/outbound/shared_thread_replies.rsnew file mode 100644index 0000000000..237e8a6b14--- /dev/null+++ b/crates/email/src/outbound/shared_thread_replies.rs@@ -0,0 +1,72 @@+//! Shared-thread reply access backed by MacroDB and the entity-access service.++use entity_access::domain::{+ models::{AccessError, EditAccessLevel},+ ports::EntityAccessService,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::{+ models::EmailErr,+ shared_thread_replies::{ReplyTargetInboxFuture, SharedThreadReplyAccess},+};++/// Resolves a message's thread and grants a reply when the caller can edit it.+pub struct EntityAccessSharedThreadReplies<A> {+ pool: PgPool,+ access: A,+}++impl<A> EntityAccessSharedThreadReplies<A> {+ /// Create the adapter from the composition root's pool and access service.+ pub fn new(pool: PgPool, access: A) -> Self {+ Self { pool, access }+ }+}++impl<A: EntityAccessService + 'static> SharedThreadReplyAccess+ for EntityAccessSharedThreadReplies<A>+{+ fn reply_target_inbox<'a>(+ &'a self,+ actor: &'a MacroUserIdStr<'static>,+ message_id: Uuid,+ ) -> ReplyTargetInboxFuture<'a> {+ Box::pin(async move {+ let Some(message) = sqlx::query!(+ "SELECT link_id, thread_id FROM email_messages WHERE id = $1",+ message_id+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(anyhow::Error::from)?+ else {+ return Ok(None);+ };++ match self+ .access+ .generate_entity_access_receipt::<EditAccessLevel>(+ actor,+ None,+ &message.thread_id.to_string(),+ EntityType::EmailThread,+ )+ .await+ {+ Ok(_) => Ok(Some(message.link_id)),+ Err(+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_),+ ) => Ok(None),+ Err(error) => Err(EmailErr::RepoErr(anyhow::anyhow!(+ "shared thread reply access check failed: {error}"+ ))),+ }+ })+ }+}diff --git a/crates/email_db_client/src/messages/get.rs b/crates/email_db_client/src/messages/get.rsindex f91aabb66c..9ebf0d7464 100644--- a/crates/email_db_client/src/messages/get.rs+++ b/crates/email_db_client/src/messages/get.rs@@ -310,12 +310,14 @@ pub async fn fetch_messages_with_labels(Ok(processed_messages)}-// gets the headers we need for threading messages correctly+/// The headers a reply needs to thread under `message_id`. The parent may sit+/// in another inbox than the reply's: another of the sender's own, or the+/// owner's when its thread was shared with the sender. Callers pass a reply+/// target that was authorized when its draft was saved.#[tracing::instrument(skip(pool), err)]pub async fn get_message_threading_headers(pool: &PgPool,message_id: Uuid,- link_id: Uuid,) -> anyhow::Result<(Option<String>, Option<String>)> {let row_option = sqlx::query!(r#"@@ -325,10 +327,9 @@ pub async fn get_message_threading_headers(-- The references header can have multiple IDs, so we just return it rawjsonb_path_query_first(headers_jsonb, '$[*] ? (@.name like_regex "references" flag "i").value') #>> '{}' as "references"FROM email_messages- WHERE id = $1 AND link_id = $2+ WHERE id = $1"#,- message_id,- link_id+ message_id).fetch_optional(pool).await?;diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex aabc37af9e..a7ee4e0e26 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -687,6 +687,21 @@ scrolls it into view, and briefly highlights it. For navigation regressions,exercise both a recent message and one outside the first page. Open anothertarget while loading or highlighting: the previous request must not scroll thenew thread or clear its highlight. Closing the split cancels pending positioning.+### Sharing a thread++The thread's **Share** dialog forwards it to people or channels at **Can edit**+by default; its access dropdown also offers **Can view**, and the People tab+changes an existing recipient between the two. Edit lets a recipient reply:+they get Reply, Reply all, and the inline reply box, sending from an inbox of+their own (their primary unless they pick another in From), never the owner's.+Forward stays with the owner, since it re-sends attachments held in the+owner's inbox. The reply starts a thread in their inbox and threads under the original+for every other participant through `In-Reply-To`/`References`; the owner's+thread is untouched. View recipients read without a reply box, and only the+owner keeps tags and side-panel edits. To verify, share a thread from one+account at each level, open it from a second account under Shared, reply at+edit, and check the reply arrives in the first account's conversation.+The load gate and message body share one live thread source in both hosts. Cachedbody rendering should not wait for a second thread fetch, optional References,or inbox metadata. Inbox-dependent actions stay gated while ownership is unknown;diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 869fe71c32..3ab74acd4b 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -408,6 +408,12 @@ pub async fn run() -> anyhow::Result<()> {crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);+ let entity_access_service = Arc::new(+ entity_access::domain::service::EntityAccessServiceImpl::new(+ entity_access::outbound::PgAccessRepository::new(db.clone()),+ ),+ );+let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),frecency_service.clone(),@@ -431,6 +437,10 @@ pub async fn run() -> anyhow::Result<()> {)),),))+ .with_shared_thread_replies(email::outbound::EntityAccessSharedThreadReplies::new(+ db.clone(),+ (*entity_access_service).clone(),+ )).with_macro_event_broker(macro_event_broker.clone());let readonly_email_service = ReadonlyEmailPreviewAdapter(EmailServiceImpl::new(@@ -470,12 +480,6 @@ pub async fn run() -> anyhow::Result<()> {});tracing::trace!("initialized notification ingress service");- let entity_access_service = Arc::new(- entity_access::domain::service::EntityAccessServiceImpl::new(- entity_access::outbound::PgAccessRepository::new(db.clone()),- ),- );-let permission_checker = PermissionServiceImpl::new(db.clone(), entity_access_service.clone());let notification_service = NotificationServiceImpl::new(SqsNotificationIngress {diff --git a/services/email_service/src/outbound/scheduled_delivery.rs b/services/email_service/src/outbound/scheduled_delivery.rsindex 34465d7888..fa7f4c4369 100644--- a/services/email_service/src/outbound/scheduled_delivery.rs+++ b/services/email_service/src/outbound/scheduled_delivery.rs@@ -336,7 +336,7 @@ impl ScheduledDeliveryAdapter {.await.context("failed to load scheduled message")?;let (parent_message_id, references) =- generate_email_threading_headers(&self.db, message.replying_to_id, data.link_id).await;+ generate_email_threading_headers(&self.db, message.replying_to_id).await;let approved = claim.delivery.approved_snapshotdiff --git a/services/email_service/src/util/gmail/send.rs b/services/email_service/src/util/gmail/send.rsindex 4980284b72..1f8ba0460d 100644--- a/services/email_service/src/util/gmail/send.rs+++ b/services/email_service/src/util/gmail/send.rs@@ -9,15 +9,13 @@ use uuid::Uuid;pub async fn generate_email_threading_headers(db: &PgPool,replying_to_db_id: Option<Uuid>,- link_id: Uuid,) -> (Option<String>, Option<Vec<String>>) {if let Some(replying_to_db_id) = replying_to_db_id {- // Fetch headers from the parent message+ // Fetch headers from the parent message, whichever inbox holds itlet (parent_id_header, parent_references_header) =email_db_client::messages::get::get_message_threading_headers(db,replying_to_db_id,- link_id,).await.unwrap_or_else(|e| {