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
fix(messages): delete the discussion when its root is deleted (#6789)
gbirman055ef6b2cc73
diff --git a/apps/web/src/features/channel/Channel/create-delete-message-confirmation.tsx b/apps/web/src/features/channel/Channel/create-delete-message-confirmation.tsxindex 56159fce9a..b7ae3571a5 100644--- a/apps/web/src/features/channel/Channel/create-delete-message-confirmation.tsx+++ b/apps/web/src/features/channel/Channel/create-delete-message-confirmation.tsx@@ -10,6 +10,11 @@ export type DeleteMessageConfirmation = {ConfirmationDialog: () => JSX.Element;};+/** Deleting the root of a discussion deletes the discussion under it. */+function isDiscussionRoot(input: DeleteMessageInput | undefined) {+ return !!input && input.parent.type !== 'channel' && !input.threadID;+}+/*** Wraps a `deleteMessage` mutation with a confirmation step. Deleting a* channel message is destructive, so every entry point (action menu, mobile@@ -46,14 +51,15 @@ export function createDeleteMessageConfirmation(<CloseIcon /></Dialog.CloseButton><Dialog.Title as="span" class="text-sm font-medium p-0 m-0">- Delete message+ {isDiscussionRoot(pending()) ? 'Delete comment' : 'Delete message'}</Dialog.Title></div><div class="p-3 flex flex-col gap-3"><Dialog.Description class="text-sm text-ink-muted">- This message will be permanently deleted. This action cannot be- undone.+ {isDiscussionRoot(pending())+ ? 'This comment and every reply to it will be permanently deleted. This action cannot be undone.'+ : 'This message will be permanently deleted. This action cannot be undone.'}</Dialog.Description><div class="flex justify-end gap-2">diff --git a/apps/web/src/features/channel/Channel/tests/create-delete-message-confirmation.test.tsx b/apps/web/src/features/channel/Channel/tests/create-delete-message-confirmation.test.tsxindex 694b4e1eda..772fa6ea64 100644--- a/apps/web/src/features/channel/Channel/tests/create-delete-message-confirmation.test.tsx+++ b/apps/web/src/features/channel/Channel/tests/create-delete-message-confirmation.test.tsx@@ -49,4 +49,36 @@ describe('createDeleteMessageConfirmation', () => {expect(deleteMessage).not.toHaveBeenCalled();});++ it('warns that a discussion root takes its replies with it', async () => {+ const { requestDelete, ConfirmationDialog } =+ createDeleteMessageConfirmation(vi.fn());++ render(() => <ConfirmationDialog />);++ requestDelete({+ parent: { type: 'document', id: 'doc-1' },+ messageID: 'root-1',+ });+ await screen.findByText('Delete comment');+ expect(+ screen.getByText(+ 'This comment and every reply to it will be permanently deleted. This action cannot be undone.'+ )+ ).toBeTruthy();+ });++ it('keeps the message-only warning for a reply', async () => {+ const { requestDelete, ConfirmationDialog } =+ createDeleteMessageConfirmation(vi.fn());++ render(() => <ConfirmationDialog />);++ requestDelete({+ parent: { type: 'document', id: 'doc-1' },+ messageID: 'reply-1',+ threadID: 'root-1',+ });+ await screen.findByText('Delete message');+ });});diff --git a/apps/web/src/lib/queries/messages/mutations.ts b/apps/web/src/lib/queries/messages/mutations.tsindex 29c540002f..c01d55bae3 100644--- a/apps/web/src/lib/queries/messages/mutations.ts+++ b/apps/web/src/lib/queries/messages/mutations.ts@@ -15,7 +15,11 @@ import type { MessageAttachment } from '@service-storage/generated/schemas/messaimport type { NewAttachment } from '@service-storage/generated/schemas/newAttachment';import type { SimpleMention } from '@service-storage/generated/schemas/simpleMention';import type { ThreadPatch } from '@service-storage/generated/schemas/threadPatch';-import type { MessageListItem, MessageParent } from '@service-storage/messages';+import type {+ MessageListItem,+ MessageParent,+ MessageThread,+} from '@service-storage/messages';import {type Message as EntityMessage,entityMessagesClient,@@ -29,6 +33,7 @@ import { senderFromStorageId } from './message-sender';import {captureDeleteSnapshotForTarget,type DeleteTargetSnapshot,+ getCachedThreadState,getTargetMessage,getTopLevelMessageDeletedAt,insertMessageIntoTargetCaches,@@ -41,7 +46,7 @@ import {softInvalidateTargetCaches,topLevelMessageHasReplies,} from './reconcile';-import { applyMessage, applyThreadState } from './sync';+import { applyMessage, applyRootDeletion, applyThreadState } from './sync';import { getMessageTimelineQueryKeyPrefix } from './timeline';/** Deduplicate the one committed-message event echoed by the server. */@@ -73,6 +78,12 @@ type DeleteMessageContext = {* captured so rollback can revert the optimistic mutation.*/previousDeletedAt?: string | null;+ /**+ * Thread state of a discussion root, read before this delete removed the+ * root from the caches that hold it, so the committed teardown can be+ * applied on success.+ */+ threadState?: MessageThread['state'];};type UpdateMessageContext = {@@ -246,11 +257,14 @@ function replaceOptimisticMessage(/*** Optimistically delete a message from the channel cache.*- * Top-level messages with thread replies are soft-deleted in place (we set+ * A channel root with thread replies is soft-deleted in place (we set* `deleted_at`) so the UI renders the "this message was deleted" placeholder- * while preserving the replies hanging off the message. Top-level messages- * with no replies are removed outright. Replies are removed from the caches,- * with a snapshot retained for rollback.+ * above the replies it keeps: that conversation continues without its first+ * message. Every other delete leaves nothing behind — a channel root with no+ * replies, a reply, and a document root, which takes its whole discussion with+ * it — so it is removed outright, with a snapshot retained for rollback. The+ * discussion's teardown itself is applied on success rather than here: it+ * deletes the document's mark, which a rollback could not put back.*/export function optimisticDeleteMessage(vars: WithParent<{ message_id: string; threadId?: string }>@@ -264,25 +278,22 @@ export function optimisticDeleteMessage(target,};- if (target.kind === 'top_level') {- if (- vars.parent.type === 'document' ||- topLevelMessageHasReplies(vars.parent, target.messageId)- ) {- context.previousDeletedAt =- getTopLevelMessageDeletedAt(vars.parent, target.messageId) ?? null;- markTopLevelMessageDeletedInTargetCaches(- vars.parent,- target,- new Date().toISOString()- );- } else {- context.targetSnapshot = captureDeleteSnapshotForTarget(- vars.parent,- target- );- removeMessageFromTargetCaches(vars.parent, target);- }+ if (target.kind === 'top_level' && vars.parent.type !== 'channel') {+ context.threadState = getCachedThreadState(vars.parent, target.messageId);+ }++ if (+ target.kind === 'top_level' &&+ vars.parent.type === 'channel' &&+ topLevelMessageHasReplies(vars.parent, target.messageId)+ ) {+ context.previousDeletedAt =+ getTopLevelMessageDeletedAt(vars.parent, target.messageId) ?? null;+ markTopLevelMessageDeletedInTargetCaches(+ vars.parent,+ target,+ new Date().toISOString()+ );} else {context.targetSnapshot = captureDeleteSnapshotForTarget(vars.parent,@@ -530,7 +541,7 @@ const deleteNonce = createMutationNonce<DeleteMessageParams>(*/export function useDeleteMessageMutation(callbacks?: MutationCallbacks<- void,+ EntityMessage,Error,DeleteMessageParams,DeleteMutationContext@@ -539,13 +550,18 @@ export function useDeleteMessageMutation(return useMutation(() => ({gcTime: 0,mutationFn: async (vars: DeleteMessageParams) => {- await entityMessagesClient.delete(+ return entityMessagesClient.delete(vars.parent,vars.messageID,deleteNonce.use(vars));},- ...withCallbacks<void, Error, DeleteMessageParams, DeleteMutationContext>(+ ...withCallbacks<+ EntityMessage,+ Error,+ DeleteMessageParams,+ DeleteMutationContext+ >({onMutate: async (vars) => {deleteNonce.prepare(vars);@@ -558,6 +574,9 @@ export function useDeleteMessageMutation(threadId: vars.threadID,});},+ onSuccess(data, _vars, context) {+ applyRootDeletion(data, context?.threadState);+ },onError(error, vars, context) {console.error('failed to delete message', error);toast.failure('Failed to delete message');diff --git a/apps/web/src/lib/queries/messages/reconcile.ts b/apps/web/src/lib/queries/messages/reconcile.tsindex 4c709e5907..e0de3efaf9 100644--- a/apps/web/src/lib/queries/messages/reconcile.ts+++ b/apps/web/src/lib/queries/messages/reconcile.ts@@ -291,6 +291,19 @@ export function replaceTargetMessageId();}+/** Find a root's cached thread state without inventing a partial one. */+export function getCachedThreadState(+ parent: MessageParent,+ rootId: string+): MessageThread['state'] | undefined {+ return (+ queryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, rootId)+ )?.state ??+ findTopLevelMessageSnapshotInMessageTimeline(parent, rootId)?.message.state+ );+}+/** Find a cached message without inventing a partial message representation. */export function getTargetMessage(parent: MessageParent,diff --git a/apps/web/src/lib/queries/messages/sync.ts b/apps/web/src/lib/queries/messages/sync.tsindex e06c3e084d..e117a21a46 100644--- a/apps/web/src/lib/queries/messages/sync.ts+++ b/apps/web/src/lib/queries/messages/sync.ts@@ -11,6 +11,7 @@ import { consumeNonce } from '../nonce';import { MessageNonceKeys, messageKeys } from './keys';import { normalizeMessageSender } from './message-sender';import {+ getCachedThreadState,getTargetMessage,insertMessageIntoTargetCaches,patchTargetMessage,@@ -99,6 +100,33 @@ export function applyMessage(softInvalidateTargetCaches(parent, target);}+/**+ * Deleting the root of a discussion deletes the discussion, and the response+ * carries only the root's own tombstone. Apply the committed teardown so the+ * margin and the document mark clear without waiting on the live event, using+ * the thread state `cached` before the optimistic delete dropped the root from+ * the caches; the refetch it triggers reconciles the rest. With no state to+ * build on, only that refetch can report the teardown.+ */+export function applyRootDeletion(+ message: Message,+ cached?: MessageThread['state']+) {+ const parent = message.parent;+ if (parent.type === 'channel' || message.thread_id) return;+ const state = cached ?? getCachedThreadState(parent, message.id);+ if (!state) {+ void queryClient.invalidateQueries({+ queryKey: getMessageTimelineQueryKeyPrefix(parent),+ });+ return;+ }+ applyThreadState(parent, {+ ...state,+ deleted_at: message.deleted_at ?? new Date().toISOString(),+ });+}+/** One live message protocol for channel screens, document discussions, and linked drawers. */export function handleMessageEvent(event: MessageEvent,diff --git a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx b/apps/web/src/lib/queries/messages/tests/mutations.test.tsxindex cab41f824f..70f0dd0989 100644--- a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx@@ -23,7 +23,7 @@ vi.mock('../subscription', () => ({ useMessageSubscription: () => {} }));import { messageKeys } from '../keys';import { useDeleteMessageMutation } from '../mutations';-import { handleMessageEvent } from '../sync';+import { handleMessageEvent, onThreadStateUpdated } from '../sync';import { getThreadRepliesQueryKey } from '../thread-replies';import {getMessageTimelineQueryKey,@@ -143,3 +143,142 @@ describe.each(['channel', 'document'] as const)('%s reply deletion', (type) => {});});++describe('root deletion', () => {+ const threadState = (rootId: string) => ({+ root_id: rootId,+ user_id: 'macro|[email protected]',+ resolved: false,+ created_at: time,+ updated_at: time,+ anchor: { type: 'markdown' as const, mark_id: 'mark' },+ });++ /** A discussion whose replies were written by somebody else. */+ function seed(parent: MessageParent, withThreadCache = true) {+ const replies = [+ { ...message(parent, 'reply', 'root'), sender_id: 'macro|[email protected]' },+ ];+ const state = threadState('root');+ const root: MessageListItem = {+ ...message(parent, 'root'),+ state,+ thread: { reply_count: 1, preview: replies, latest_reply_at: time },+ };+ testQueryClient.setQueryData<MessageTimelineData>(+ getMessageTimelineQueryKey(parent),+ {+ pageParams: [null],+ pages: [{ items: [root], next_cursor: null, previous_cursor: null }],+ }+ );+ if (withThreadCache)+ testQueryClient.setQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root'),+ { state, root, replies }+ );+ return { root, replies, state };+ }++ function mount() {+ let mutation!: ReturnType<typeof useDeleteMessageMutation>;+ function Harness() {+ mutation = useDeleteMessageMutation();+ return null;+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Harness />+ </QueryClientProvider>+ ));+ return mutation;+ }++ const roots = (parent: MessageParent) =>+ testQueryClient+ .getQueryData<MessageTimelineData>(getMessageTimelineQueryKey(parent))!+ .pages.flatMap((page) => page.items);++ it("takes the whole discussion, including another author's replies", async () => {+ const parent: MessageParent = { type: 'document', id: 'doc' };+ seed(parent);+ mocks.delete.mockResolvedValue({+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ });+ const deletedThreads: string[] = [];+ const stop = onThreadStateUpdated((_parent, state) => {+ if (state.deleted_at) deletedThreads.push(state.root_id);+ });++ await mount().mutateAsync({ parent, messageID: 'root' });++ expect(roots(parent)).toEqual([]);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root')+ )!;+ expect(thread.state.deleted_at).toBe(time);+ expect(thread.replies).toEqual([]);+ // The margin and the document mark clear off this notification.+ expect(deletedThreads).toEqual(['root']);+ stop();+ });++ it('tears down a root whose replies were never opened', async () => {+ // The only copy of this thread's state is the timeline item the optimistic+ // delete removes, so the teardown has to read it before that happens.+ const parent: MessageParent = { type: 'document', id: 'doc' };+ seed(parent, false);+ mocks.delete.mockResolvedValue({+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ });+ const deletedThreads: string[] = [];+ const stop = onThreadStateUpdated((_parent, state) => {+ if (state.deleted_at) deletedThreads.push(state.root_id);+ });++ await mount().mutateAsync({ parent, messageID: 'root' });++ expect(deletedThreads).toEqual(['root']);+ stop();+ });++ it('restores the discussion when the delete fails', async () => {+ const parent: MessageParent = { type: 'document', id: 'doc' };+ const { root } = seed(parent);+ mocks.delete.mockRejectedValue(new Error('nope'));++ await expect(+ mount().mutateAsync({ parent, messageID: 'root' })+ ).rejects.toThrow();++ expect(roots(parent).map((item) => item.id)).toEqual([root.id]);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root')+ )!;+ expect(thread.state.deleted_at).toBeUndefined();+ expect(thread.replies).toHaveLength(1);+ });++ it('leaves a channel root as a tombstone above its replies', async () => {+ const parent: MessageParent = { type: 'channel', id: 'channel' };+ seed(parent);+ mocks.delete.mockResolvedValue({+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ });++ await mount().mutateAsync({ parent, messageID: 'root' });++ expect(roots(parent).map((item) => !!item.deleted_at)).toEqual([true]);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root')+ )!;+ expect(thread.state.deleted_at).toBeUndefined();+ expect(thread.replies).toHaveLength(1);+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex f621a3f77d..f8ad5b2f53 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -29234,7 +29234,7 @@ export const entityMessageGetMessageResponse = zod);/**- * @summary Tombstone one message while preserving replies.+ * @summary Tombstone one message; deleting a discussion's root deletes the discussion.*/export const entityMessageDeleteMessageParams = zod.object({parent_type: zod.string(),diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 0f0c4588cf..996da35f01 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -11452,7 +11452,7 @@},"delete": {"tags": ["messages::inbound::axum_router"],- "summary": "Tombstone one message while preserving replies.",+ "summary": "Tombstone one message; deleting a discussion's root deletes the discussion.","operationId": "entity_message_delete_message","parameters": [{diff --git a/crates/messages/src/domain/api.rs b/crates/messages/src/domain/api.rsindex 42afd3b4f8..cccaa45c9e 100644--- a/crates/messages/src/domain/api.rs+++ b/crates/messages/src/domain/api.rs@@ -60,7 +60,7 @@ pub trait MessageCommands: Send + Sync + 'static {id: Uuid,input: MessagePatch,) -> Result<Message, MessageError>;- /// Tombstone a message under the common authorship and moderation policy.+ /// Tombstone a message, or delete the whole discussion when it is a root.async fn delete(&self,access: EntityAccessReceipt<MessageWrite>,@@ -254,7 +254,7 @@ mockall::mock! {) -> Result<Message, MessageError>;/// Apply partial body, mention, and attachment changes under the common policy.async fn patch(&self, access: EntityAccessReceipt<MessageWrite>, id: Uuid, input: MessagePatch) -> Result<Message, MessageError>;- /// Tombstone a message under the common authorship and moderation policy.+ /// Tombstone a message, or delete the whole discussion when it is a root.async fn delete(&self,access: EntityAccessReceipt<MessageWrite>,diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rsindex 170b018f99..7825283da0 100644--- a/crates/messages/src/domain/service.rs+++ b/crates/messages/src/domain/service.rs@@ -316,7 +316,7 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {Ok(message)}- /// Delete one message. Root deletion does not delete its discussion.+ /// Delete one message. On a discussion, deleting the root deletes the discussion.#[tracing::instrument(err, skip(self, access))]pub async fn delete(&self,@@ -328,6 +328,19 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {let actor = actor_from_receipt(&access, &parent)?;self.ensure_parent(&parent).await?;let current = self.active_message(&parent, id, false).await?;+ // A comment's replies and its place in the document belong to the comment,+ // not to its first message, so the root carries the whole discussion with+ // it. Channel roots are one message in a conversation that continues+ // without them, and keep the tombstone the channel timeline renders.+ if parent.is_discussion() && current.thread_id.is_none() {+ self.delete_discussion(&access, &parent, &actor, id, nonce)+ .await?;+ return self+ .repo+ .get(&parent, id)+ .await?+ .ok_or(MessageError::NotFound);+ }let channel_bot =matches!(parent, MessageParent::Channel(_)) && current.sender_id.as_bot().is_some();if current.sender_id != actor && !can_moderate(access.entity_permission()) && !channel_bot {@@ -439,13 +452,28 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {));}self.ensure_parent(&parent).await?;- let thread = self.active_thread(&parent, root_id).await?;+ self.delete_discussion(&access, &parent, &actor, root_id, nonce)+ .await+ }++ /// The one teardown policy: whoever may delete a discussion outright is+ /// whoever may delete it by deleting its root, since both take replies+ /// written by other people with them.+ async fn delete_discussion(+ &self,+ access: &EntityAccessReceipt<MessageWrite>,+ parent: &MessageParent,+ actor: &ChannelSender<'static>,+ root_id: Uuid,+ nonce: Option<String>,+ ) -> Result<ThreadState, MessageError> {+ let thread = self.active_thread(parent, root_id).await?;if thread.user_id != actor.as_ref() && !can_moderate(access.entity_permission()) {return Err(MessageError::Forbidden);}- let state = self.repo.delete_thread(&parent, root_id).await?;+ let state = self.repo.delete_thread(parent, root_id).await?;self.publish(MessageEvent {- parent,+ parent: parent.clone(),actor: actor.as_ref().to_owned(),nonce,change: MessageChange::ThreadUpdated {diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rsindex 801ae2b3ef..cb678d5085 100644--- a/crates/messages/src/domain/service/test.rs+++ b/crates/messages/src/domain/service/test.rs@@ -6,12 +6,22 @@ use std::sync::{Arc, Mutex};#[derive(Clone)]struct Repo {message: Message,+ replies: Vec<Message>,state: ThreadState,deletes: Arc<Mutex<Vec<Uuid>>>,+ thread_deletes: Arc<Mutex<Vec<Uuid>>>,creates: Arc<Mutex<Vec<CreateMessage>>>,edits: Arc<Mutex<Vec<EditMessage>>>,}+impl Repo {+ /// A committed teardown tombstones the root and every reply in one+ /// statement, so reads that follow it see the whole discussion gone.+ fn torn_down(&self, root: Uuid) -> bool {+ self.thread_deletes.lock().unwrap().contains(&root)+ }+}+impl MessageRepository for Repo {async fn preceding(&self,@@ -21,24 +31,50 @@ impl MessageRepository for Repo {) -> Result<Vec<Message>, MessageError> {unimplemented!()}- async fn replies(&self, _: &MessageParent, _: Uuid) -> Result<Vec<Message>, MessageError> {- Ok(vec![])+ async fn replies(+ &self,+ parent: &MessageParent,+ root: Uuid,+ ) -> Result<Vec<Message>, MessageError> {+ if self.torn_down(root) {+ return Ok(vec![]);+ }+ Ok(self+ .replies+ .iter()+ .filter(|reply| reply.parent == *parent && reply.thread_id == Some(root))+ .cloned()+ .collect())}async fn parent_exists(&self, _: &MessageParent) -> Result<bool, MessageError> {Ok(true)}async fn get(&self, parent: &MessageParent, id: Uuid) -> Result<Option<Message>, MessageError> {- Ok((self.message.parent == *parent && self.message.id == id).then(|| self.message.clone()))+ let mut message = std::iter::once(&self.message)+ .chain(&self.replies)+ .find(|message| message.parent == *parent && message.id == id)+ .cloned();+ if let Some(message) = message.as_mut()+ && self.torn_down(message.root_id())+ {+ message.deleted_at.get_or_insert_with(Utc::now);+ message.content.clear();+ }+ Ok(message)}async fn thread(&self,parent: &MessageParent,root: Uuid,) -> Result<Option<ThreadState>, MessageError> {- Ok(- (self.message.parent == *parent && self.state.root_id == root)- .then(|| self.state.clone()),- )+ let mut state = (self.message.parent == *parent && self.state.root_id == root)+ .then(|| self.state.clone());+ if let Some(state) = state.as_mut()+ && self.torn_down(root)+ {+ state.deleted_at.get_or_insert_with(Utc::now);+ }+ Ok(state)}async fn timeline(&self,@@ -88,9 +124,9 @@ impl MessageRepository for Repo {self.edits.lock().unwrap().push(command);Ok(message)}- async fn delete(&self, _: &MessageParent, id: Uuid) -> Result<Message, MessageError> {+ async fn delete(&self, parent: &MessageParent, id: Uuid) -> Result<Message, MessageError> {self.deletes.lock().unwrap().push(id);- let mut message = self.message.clone();+ let mut message = self.get(parent, id).await?.ok_or(MessageError::NotFound)?;message.deleted_at = Some(Utc::now());message.content.clear();Ok(message)@@ -120,8 +156,20 @@ impl MessageRepository for Repo {}Ok(state)}- async fn delete_thread(&self, _: &MessageParent, _: Uuid) -> Result<ThreadState, MessageError> {- panic!("single-message deletion must never delete the thread")+ async fn delete_thread(+ &self,+ _: &MessageParent,+ root: Uuid,+ ) -> Result<ThreadState, MessageError> {+ self.thread_deletes.lock().unwrap().push(root);+ let mut state = self.state.clone();+ state.deleted_at = Some(Utc::now());+ // A dead thread keeps its Markdown identity so a closed document can+ // still clear the mark; every other anchor is released with the thread.+ if !matches!(state.anchor, Some(ThreadAnchor::Markdown { .. })) {+ state.anchor = None;+ }+ Ok(state)}async fn resolve_legacy(&self,@@ -176,12 +224,26 @@ fn fixture() -> Repo {updated_at: Utc::now(),deleted_at: None,},+ replies: vec![],deletes: Arc::default(),+ thread_deletes: Arc::default(),creates: Arc::default(),edits: Arc::default(),}}+/// A reply written by someone other than the discussion's author.+fn reply_from(root: &Message, id: u128, sender: &str) -> Message {+ Message {+ id: Uuid::from_u128(id),+ thread_id: Some(root.id),+ sender_id: ChannelSender::try_from(sender.to_owned()).unwrap(),+ imported_author: None,+ content: "reply".into(),+ ..root.clone()+ }+}+fn access(user: &str, document: &str, level: AccessLevel) -> EntityAccessReceipt<MessageWrite> {EntityAccessReceipt::try_new(EntityAccessAuth::Authenticated(user.to_owned().try_into().unwrap()),@@ -280,8 +342,9 @@ async fn thread_patch_cannot_detach_pdf_annotations() {}#[tokio::test]-async fn root_deletion_tombstones_only_the_message_and_emits_shared_update() {- let repo = fixture();+async fn deleting_a_document_root_deletes_the_whole_discussion() {+ let mut repo = fixture();+ repo.replies = vec![reply_from(&repo.message, 7, "macro|[email protected]")];let events = Events::default();let service = MessageService::new(repo.clone(), events.clone());let message = service@@ -293,17 +356,69 @@ async fn root_deletion_tombstones_only_the_message_and_emits_shared_update() {.await.unwrap();assert!(message.deleted_at.is_some());- assert_eq!(*repo.deletes.lock().unwrap(), vec![repo.message.id]);- assert!(repo.state.deleted_at.is_none());- assert!(repo.state.anchor.is_some());- let events = events.0.lock().unwrap();- assert_eq!(events.len(), 1);- assert!(- matches!(&events[0].change, MessageChange::MessageDeleted { message } if message.root_id() == repo.message.id)- );- assert_eq!(events[0].nonce.as_deref(), Some("nonce"));+ assert!(message.content.is_empty());+ assert_eq!(*repo.thread_deletes.lock().unwrap(), vec![repo.message.id]);+ // The teardown covers the root, so no second single-message delete runs.+ assert!(repo.deletes.lock().unwrap().is_empty());+ {+ let published = events.0.lock().unwrap();+ assert_eq!(published.len(), 1);+ assert_eq!(published[0].nonce.as_deref(), Some("nonce"));+ assert!(+ matches!(&published[0].change, MessageChange::ThreadUpdated { state } if state.deleted_at.is_some())+ );+ }+ // Another author's replies go with the discussion instead of outliving it.+ let view = access("macro|[email protected]", "doc", AccessLevel::Comment)+ .try_into_requirement()+ .unwrap();assert!(matches!(- events[0].change,+ service.get_thread(view, repo.message.id).await,+ Err(MessageError::NotFound)+ ));+ let mut input = post_input();+ input.thread_id = Some(repo.message.id);+ assert!(matches!(+ service+ .post(+ access("macro|[email protected]", "doc", AccessLevel::Comment),+ input+ )+ .await,+ Err(MessageError::NotFound)+ ));+}++#[tokio::test]+async fn a_reply_author_can_delete_their_reply_but_not_the_root_above_it() {+ let mut repo = fixture();+ repo.replies = vec![reply_from(&repo.message, 7, "macro|[email protected]")];+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let denied = service+ .delete(+ access("macro|[email protected]", "doc", AccessLevel::Comment),+ repo.message.id,+ None,+ )+ .await;+ assert!(matches!(denied, Err(MessageError::Forbidden)));+ assert!(repo.thread_deletes.lock().unwrap().is_empty());+ assert!(events.0.lock().unwrap().is_empty());+ let tombstone = service+ .delete(+ access("macro|[email protected]", "doc", AccessLevel::Comment),+ repo.replies[0].id,+ None,+ )+ .await+ .unwrap();+ assert!(tombstone.deleted_at.is_some());+ assert_eq!(*repo.deletes.lock().unwrap(), vec![repo.replies[0].id]);+ assert!(repo.thread_deletes.lock().unwrap().is_empty());+ let published = events.0.lock().unwrap();+ assert!(matches!(+ published[0].change,MessageChange::MessageDeleted { .. }));}@@ -321,6 +436,7 @@ async fn other_commenter_cannot_delete_but_parent_owner_can_moderate() {.await;assert!(matches!(denied, Err(MessageError::Forbidden)));assert!(repo.deletes.lock().unwrap().is_empty());+ assert!(repo.thread_deletes.lock().unwrap().is_empty());service.delete(access("macro|[email protected]", "doc", AccessLevel::Owner),@@ -329,6 +445,36 @@ async fn other_commenter_cannot_delete_but_parent_owner_can_moderate() {).await.unwrap();+ assert_eq!(*repo.thread_deletes.lock().unwrap(), vec![repo.message.id]);+}++#[tokio::test]+async fn a_channel_root_keeps_its_thread_and_its_tombstone() {+ let mut repo = fixture();+ // The fixture's author is the principal `channel_access` authenticates.+ repo.message.parent = MessageParent::Channel(Uuid::from_u128(20));+ repo.replies = vec![reply_from(&repo.message, 7, "macro|[email protected]")];+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let message = service+ .delete(channel_access(), repo.message.id, None)+ .await+ .unwrap();+ assert!(message.deleted_at.is_some());+ assert_eq!(*repo.deletes.lock().unwrap(), vec![repo.message.id]);+ assert!(repo.thread_deletes.lock().unwrap().is_empty());+ {+ let published = events.0.lock().unwrap();+ assert_eq!(published.len(), 1);+ assert!(matches!(+ published[0].change,+ MessageChange::MessageDeleted { .. }+ ));+ }+ // The conversation under it continues: the replies stay live and repliable.+ let mut input = post_input();+ input.thread_id = Some(repo.message.id);+ service.post(channel_access(), input).await.unwrap();}#[tokio::test]diff --git a/crates/messages/src/inbound/axum_router.rs b/crates/messages/src/inbound/axum_router.rsindex 15f78976cf..5502a8ec47 100644--- a/crates/messages/src/inbound/axum_router.rs+++ b/crates/messages/src/inbound/axum_router.rs@@ -253,7 +253,7 @@ pub struct NonceQuery {}#[utoipa::path(operation_id = "entity_message_delete_message", delete, path = "/messages/{parent_type}/{parent_id}/items/{id}", params(("parent_type" = String, Path), ("parent_id" = String, Path), ("id" = Uuid, Path), NonceQuery), responses((status = 200, body = Message)))]-/// Tombstone one message while preserving replies.+/// Tombstone one message; deleting a discussion's root deletes the discussion.pub async fn delete_message<A, Auth>(State(state): State<MessagesRouterState<A, Auth>>,user: MacroAuthorizationExtractor<Auth, AnyPrincipal>,diff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rsindex 25dc2fe929..14c179cca0 100644--- a/crates/messages/src/outbound/pg_message_repo/test.rs+++ b/crates/messages/src/outbound/pg_message_repo/test.rs@@ -165,6 +165,27 @@ async fn thread_identity_tombstones_and_parent_isolation(pool: PgPool) {);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_deleted_discussion_reads_back_as_a_root_tombstone_without_replies(pool: PgPool) {+ setup(&pool).await;+ let repo = PgMessageRepository::new(pool.clone());+ let parent = MessageParent::parse("document", "message-doc-a").unwrap();+ let root = repo+ .create(command("message-doc-a", None, "root"))+ .await+ .unwrap();+ repo.create(command("message-doc-a", Some(root.id), "reply"))+ .await+ .unwrap();+ repo.delete_thread(&parent, root.id).await.unwrap();+ // Deleting a root reads the message back after the teardown to answer the+ // caller; that read is the tombstone, not the live root it started from.+ let tombstone = repo.get(&parent, root.id).await.unwrap().unwrap();+ assert!(tombstone.deleted_at.is_some());+ assert!(tombstone.content.is_empty());+ assert!(repo.replies(&parent, root.id).await.unwrap().is_empty());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn deleted_markdown_threads_keep_paged_cleanup_identity(pool: PgPool) {setup(&pool).await;diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex d689b11e87..eaebafc289 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -406,7 +406,10 @@ Touch keeps separate `Attach images` andcomposer, `type_text`, then click `Send comment` (Enter also submits). The comment rendersabove the composer with author + timestamp. `@`-mentions in comments notify the mentioneduser. Editing a discussion comment keeps the attachment and send controls, with no-trash button. On mobile, the new-comment composer is docked above the navigation bar,+trash button. Deleting a comment's first message deletes the whole discussion —+the confirmation reads `Delete comment`, the replies under it go too, and an+anchored comment's highlight clears from the document. Deleting a reply removes+only that reply. On mobile, the new-comment composer is docked above the navigation bar,replacing Ask AI and New when commenting is available in documents and tasks.When the comment composer is unavailable, the default Ask AI row appears instead.Tap `Leave a comment...`@@ -468,7 +471,8 @@ thread opens in a drawer with a pinned reply composer; long-press any messagefor edit, delete, copy-link, and reaction actions.A document thread carries no thread-level controls above it. Deleting the root-message leaves a tombstone and retains its replies. `Copy link` targets the+message deletes the whole discussion, replies included, and answers with the+root's tombstone. `Copy link` targets thespecific comment with `comment_id=<message id>`. Previously copied numeric linksstill resolve under current document permissions. Deleting an anchored Markdowndiscussion removes its mark while preserving the document text and anydiff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 24f84e21d0..8deee31b39 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -1887,7 +1887,7 @@ export class Sdk extends HeyApiClient {}/**- * Tombstone one message while preserving replies.+ * Tombstone one message; deleting a discussion's root deletes the discussion.*/public entityMessageDeleteMessage<ThrowOnError extends boolean = false>(options: Options<EntityMessageDeleteMessageData, ThrowOnError>): RequestResult<EntityMessageDeleteMessageResponses, unknown, ThrowOnError> {return (options.client ?? this.client).delete<EntityMessageDeleteMessageResponses, unknown, ThrowOnError>({ url: '/messages/{parent_type}/{parent_id}/items/{id}', ...options });diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 0f0c4588cf..996da35f01 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -11452,7 +11452,7 @@},"delete": {"tags": ["messages::inbound::axum_router"],- "summary": "Tombstone one message while preserving replies.",+ "summary": "Tombstone one message; deleting a discussion's root deletes the discussion.","operationId": "entity_message_delete_message","parameters": [{