Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(channels): allow any participant to delete bot messages (#3985)

teo2aa00a1e3ba6
diff --git a/js/app/packages/channel/Channel/create-channel-hotkeys.ts b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
index ede4ed736d..fffe847b6b 100644
--- a/js/app/packages/channel/Channel/create-channel-hotkeys.ts
+++ b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
@@ -3,6 +3,7 @@ import { TOKENS } from '@core/hotkey/tokens';
import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
import type { Accessor } from 'solid-js';
import type { MessageActions, MessageData } from '../Message';
+import { isBotMessage } from '../Thread/utils/message-actions';
import type { MessageSelection } from './create-message-selection';
import type { ThreadListNavigation } from './ThreadList';
@@ -24,13 +25,24 @@ export function canReplyToSelectedMessageFromHotkey(input: {
}) {
return input.hasSelection && !input.isEditing;
}
-export function canEditOrDeleteSelectedMessageFromHotkey(input: {
+export function canEditSelectedMessageFromHotkey(input: {
hasSelection: boolean;
isEditing: boolean;
isOwnMessage: boolean;
}) {
return canReplyToSelectedMessageFromHotkey(input) && input.isOwnMessage;
}
+export function canDeleteSelectedMessageFromHotkey(input: {
+ hasSelection: boolean;
+ isEditing: boolean;
+ isOwnMessage: boolean;
+ isBotMessage: boolean;
+}) {
+ return (
+ canReplyToSelectedMessageFromHotkey(input) &&
+ (input.isOwnMessage || input.isBotMessage)
+ );
+}
export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
const [attachMessageList, messageListScope] =
@@ -120,7 +132,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
condition: () => {
if (!canRunSelectionActionHotkeys()) return false;
const msg = getSelectedMessage();
- return canEditOrDeleteSelectedMessageFromHotkey({
+ return canEditSelectedMessageFromHotkey({
hasSelection: true,
isEditing: options.isEditing(),
isOwnMessage: !!msg && msg.sender_id === options.userId(),
@@ -143,10 +155,11 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
condition: () => {
if (!canRunSelectionActionHotkeys()) return false;
const msg = getSelectedMessage();
- return canEditOrDeleteSelectedMessageFromHotkey({
+ return canDeleteSelectedMessageFromHotkey({
hasSelection: true,
isEditing: options.isEditing(),
isOwnMessage: !!msg && msg.sender_id === options.userId(),
+ isBotMessage: !!msg && isBotMessage(msg),
});
},
keyDownHandler: () => {
diff --git a/js/app/packages/channel/Channel/create-channel-message-actions.ts b/js/app/packages/channel/Channel/create-channel-message-actions.ts
index 3e6da17692..d108f3bf8d 100644
--- a/js/app/packages/channel/Channel/create-channel-message-actions.ts
+++ b/js/app/packages/channel/Channel/create-channel-message-actions.ts
@@ -9,7 +9,8 @@ import type {
} from '../Message';
import {
buildMessageLink,
- canEditOrDeleteMessage,
+ canDeleteMessage,
+ canEditMessage,
canReplyToMessage,
DEFAULT_REACTION_EMOJI,
hasReactionFromUser,
@@ -100,7 +101,8 @@ export function createChannelMessageActions(
return (message) => {
const currentUserId = options.userId();
- const canEditDelete = canEditOrDeleteMessage(message, currentUserId);
+ const canEdit = canEditMessage(message, currentUserId);
+ const canDelete = canDeleteMessage(message, currentUserId);
const canReply = canReplyToMessage(message);
const isDeleted = !!message.deleted_at;
@@ -172,8 +174,8 @@ export function createChannelMessageActions(
}
}
: undefined,
- onEdit: canEditDelete ? options.onEdit : undefined,
- onDelete: canEditDelete
+ onEdit: canEdit ? options.onEdit : undefined,
+ onDelete: canDelete
? () => {
options.deleteMessage({
channelID: options.channelId(),
diff --git a/js/app/packages/channel/Thread/create-thread-hotkeys.ts b/js/app/packages/channel/Thread/create-thread-hotkeys.ts
index 0166a34a70..a8fb60f401 100644
--- a/js/app/packages/channel/Thread/create-thread-hotkeys.ts
+++ b/js/app/packages/channel/Thread/create-thread-hotkeys.ts
@@ -11,6 +11,7 @@ import { type Accessor, onCleanup } from 'solid-js';
import type { MessageSelection } from '../Channel/create-message-selection';
import type { MessageActions, MessageData } from '../Message';
import { scrollMessageIntoView } from '../scroll-utils';
+import { isBotMessage } from './utils/message-actions';
type CreateThreadHotkeysOptions = {
messageListScopeId: string;
@@ -37,7 +38,7 @@ export function canReplyToThreadFromHotkey(input: {
return input.isThreadFocused && !input.isEditing;
}
-export function canEditOrDeleteThreadReplyFromHotkey(input: {
+export function canEditThreadReplyFromHotkey(input: {
isThreadFocused: boolean;
isEditing: boolean;
hasSelectedReply: boolean;
@@ -50,6 +51,20 @@ export function canEditOrDeleteThreadReplyFromHotkey(input: {
);
}
+export function canDeleteThreadReplyFromHotkey(input: {
+ isThreadFocused: boolean;
+ isEditing: boolean;
+ hasSelectedReply: boolean;
+ isOwnReply: boolean;
+ isBotReply: boolean;
+}) {
+ return (
+ canReplyToThreadFromHotkey(input) &&
+ input.hasSelectedReply &&
+ (input.isOwnReply || input.isBotReply)
+ );
+}
+
export function createThreadHotkeys(options: CreateThreadHotkeysOptions) {
const scope = options.messageListScopeId;
const group = createHotkeyGroup();
@@ -178,7 +193,7 @@ export function createThreadHotkeys(options: CreateThreadHotkeysOptions) {
const replyId = options.replySelection.selectedId();
if (!replyId) return false;
const reply = getReplyById(replyId);
- return canEditOrDeleteThreadReplyFromHotkey({
+ return canEditThreadReplyFromHotkey({
isThreadFocused: options.isThreadFocused(),
isEditing: options.isEditing(),
hasSelectedReply: !!replyId,
@@ -208,11 +223,12 @@ export function createThreadHotkeys(options: CreateThreadHotkeysOptions) {
const replyId = options.replySelection.selectedId();
if (!replyId) return false;
const reply = getReplyById(replyId);
- return canEditOrDeleteThreadReplyFromHotkey({
+ return canDeleteThreadReplyFromHotkey({
isThreadFocused: options.isThreadFocused(),
isEditing: options.isEditing(),
hasSelectedReply: !!replyId,
isOwnReply: !!reply && reply.sender_id === options.userId(),
+ isBotReply: !!reply && isBotMessage(reply),
});
},
keyDownHandler: () => {
diff --git a/js/app/packages/channel/Thread/tests/message-actions.test.ts b/js/app/packages/channel/Thread/tests/message-actions.test.ts
index fa37d727f2..607f89ef21 100644
--- a/js/app/packages/channel/Thread/tests/message-actions.test.ts
+++ b/js/app/packages/channel/Thread/tests/message-actions.test.ts
@@ -3,29 +3,45 @@ import { describe, expect, it } from 'vitest';
import {
buildMessageLink,
buildQuoteReplyValue,
- canEditOrDeleteMessage,
+ canDeleteMessage,
+ canEditMessage,
canReplyToMessage,
DEFAULT_REACTION_EMOJI,
hasReactionFromUser,
} from '../utils/message-actions';
describe('message-actions helpers', () => {
- it('allows edit/delete only for own non-deleted messages', () => {
+ it('allows edit only for own non-deleted messages', () => {
expect(
- canEditOrDeleteMessage(
- { sender_id: 'user-1', deleted_at: null },
- 'user-1'
- )
+ canEditMessage({ sender_id: 'user-1', deleted_at: null }, 'user-1')
).toBe(true);
expect(
- canEditOrDeleteMessage(
- { sender_id: 'user-2', deleted_at: null },
+ canEditMessage({ sender_id: 'user-2', deleted_at: null }, 'user-1')
+ ).toBe(false);
+ expect(
+ canEditMessage({ sender_id: 'bot|bot-1', deleted_at: null }, 'user-1')
+ ).toBe(false);
+ expect(
+ canEditMessage(
+ { sender_id: 'user-1', deleted_at: '2026-02-25T00:00:00.000Z' },
'user-1'
)
).toBe(false);
+ });
+
+ it('allows delete for own and bot non-deleted messages', () => {
+ expect(
+ canDeleteMessage({ sender_id: 'user-1', deleted_at: null }, 'user-1')
+ ).toBe(true);
+ expect(
+ canDeleteMessage({ sender_id: 'user-2', deleted_at: null }, 'user-1')
+ ).toBe(false);
expect(
- canEditOrDeleteMessage(
- { sender_id: 'user-1', deleted_at: '2026-02-25T00:00:00.000Z' },
+ canDeleteMessage({ sender_id: 'bot|bot-1', deleted_at: null }, 'user-1')
+ ).toBe(true);
+ expect(
+ canDeleteMessage(
+ { sender_id: 'bot|bot-1', deleted_at: '2026-02-25T00:00:00.000Z' },
'user-1'
)
).toBe(false);
diff --git a/js/app/packages/channel/Thread/utils/index.ts b/js/app/packages/channel/Thread/utils/index.ts
index 712cf2331d..6ab7406694 100644
--- a/js/app/packages/channel/Thread/utils/index.ts
+++ b/js/app/packages/channel/Thread/utils/index.ts
@@ -1,10 +1,12 @@
export {
type ActionableMessage,
buildMessageLink,
- canEditOrDeleteMessage,
+ canDeleteMessage,
+ canEditMessage,
canReplyToMessage,
DEFAULT_REACTION_EMOJI,
hasReactionFromUser,
+ isBotMessage,
isOwnMessage,
} from './message-actions';
diff --git a/js/app/packages/channel/Thread/utils/message-actions.ts b/js/app/packages/channel/Thread/utils/message-actions.ts
index 8731c8419c..17324ab3df 100644
--- a/js/app/packages/channel/Thread/utils/message-actions.ts
+++ b/js/app/packages/channel/Thread/utils/message-actions.ts
@@ -4,6 +4,7 @@ import type { MessageData } from '../../Message';
export const DEFAULT_REACTION_EMOJI = '👍';
const EMPTY_REPLY_PARAGRAPH = ' ';
+const BOT_SENDER_PREFIX = 'bot|';
export type ActionableMessage = Pick<
MessageData,
@@ -20,13 +21,29 @@ export function isOwnMessage(
return message.sender_id === currentUserId;
}
-export function canEditOrDeleteMessage(
+export function isBotMessage(
+ message: Pick<ActionableMessage, 'sender_id'>
+): boolean {
+ return message.sender_id.startsWith(BOT_SENDER_PREFIX);
+}
+
+export function canEditMessage(
message: Pick<ActionableMessage, 'sender_id' | 'deleted_at'>,
currentUserId: string | undefined
): boolean {
return isOwnMessage(message, currentUserId) && !message.deleted_at;
}
+export function canDeleteMessage(
+ message: Pick<ActionableMessage, 'sender_id' | 'deleted_at'>,
+ currentUserId: string | undefined
+): boolean {
+ return (
+ (isOwnMessage(message, currentUserId) || isBotMessage(message)) &&
+ !message.deleted_at
+ );
+}
+
export function canReplyToMessage(
message: Pick<ActionableMessage, 'thread_id' | 'deleted_at'>
): boolean {
diff --git a/rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json b/rust/cloud-storage/.sqlx/query-1d06080a159da4e120eefc7c7579fdcf0a2d85ec3fcd3365aabf71a439ad218f.json
similarity index 64%
rename from rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json
rename to rust/cloud-storage/.sqlx/query-1d06080a159da4e120eefc7c7579fdcf0a2d85ec3fcd3365aabf71a439ad218f.json
index daf77cdfde..b0e03b4370 100644
--- a/rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json
+++ b/rust/cloud-storage/.sqlx/query-1d06080a159da4e120eefc7c7579fdcf0a2d85ec3fcd3365aabf71a439ad218f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT sender_id\n FROM comms_messages\n WHERE id = $1 AND channel_id = $2\n ORDER BY created_at ASC\n ",
+ "query": "\n SELECT sender_id\n FROM comms_messages\n WHERE id = $1 AND channel_id = $2 AND deleted_at IS NULL\n ORDER BY created_at ASC\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
false
]
},
- "hash": "cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384"
+ "hash": "1d06080a159da4e120eefc7c7579fdcf0a2d85ec3fcd3365aabf71a439ad218f"
}
diff --git a/rust/cloud-storage/channel_bots/src/domain/service.rs b/rust/cloud-storage/channel_bots/src/domain/service.rs
index 411c2de508..a7d8c716ef 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service.rs
@@ -5,7 +5,7 @@ use std::fmt::Write as _;
use std::sync::Arc;
use channels::domain::models::{ParticipantRole, PatchMessageRequest, PostMessageRequest, Sender};
-use channels::domain::ports::ChannelService;
+use channels::domain::ports::{ChannelMutationErr, ChannelService};
use uuid::Uuid;
use super::models::BotEvent;
@@ -287,8 +287,11 @@ where
}
};
- // 4. Replace the "thinking" message with the answer.
- self.channels
+ // 4. Replace the "thinking" message with the answer. A NotFound here
+ // means a participant deleted the thinking message while the agent
+ // ran — treat that as the user not wanting a response.
+ match self
+ .channels
.patch_message(
actor,
ParticipantRole::Member,
@@ -302,9 +305,15 @@ where
nonce: None,
},
)
- .await?;
-
- Ok(())
+ .await
+ {
+ Ok(()) => Ok(()),
+ Err(ChannelMutationErr::NotFound(_)) => {
+ tracing::info!(%message_id, "thinking message was deleted; dropping bot response");
+ Ok(())
+ }
+ Err(err) => Err(err.into()),
+ }
}
}
diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
index 854ca0653f..e361ae89a1 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
@@ -3,8 +3,8 @@ use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use channels::domain::models::{
AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,
- ChannelParticipant, MessagePageDirection, MutatedMessage, ResolvedChannelMessage, Sender,
- ThreadReply,
+ ChannelParticipant, MessagePageDirection, MutatedMessage, PostMessageResponse,
+ ResolvedChannelMessage, Sender, ThreadReply,
};
use channels::domain::ports::{
ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelService,
@@ -118,6 +118,147 @@ impl AgentResponder for TestResponder {
}
}
+/// Channel service fake for the post-thinking-then-patch flow. Posting always
+/// succeeds; patching either records the content or reports the message as
+/// missing (deleted while the agent ran).
+struct MutationChannelService {
+ thinking_deleted: bool,
+ patched: Mutex<Vec<String>>,
+}
+
+impl MutationChannelService {
+ fn new(thinking_deleted: bool) -> Self {
+ Self {
+ thinking_deleted,
+ patched: Mutex::new(Vec::new()),
+ }
+ }
+}
+
+impl ChannelService for MutationChannelService {
+ fn get_channel_messages(
+ &self,
+ _channel_id: Uuid,
+ _query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
+ _limit: u16,
+ _filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'static>>,
+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn get_channel_attachments(
+ &self,
+ _channel_id: Uuid,
+ _query: Query<Uuid, CreatedAt, ()>,
+ _limit: u16,
+ _attachment_type: Option<ChannelAttachmentType>,
+ ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn get_channel_participants(
+ &self,
+ _channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn get_message_context(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _before: i64,
+ _after: i64,
+ ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {
+ async move { Ok(Vec::new()) }
+ }
+
+ fn get_attachment_references(
+ &self,
+ _entity_type: String,
+ _entity_id: String,
+ _user_id: String,
+ ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send
+ {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn get_channel_messages_around(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _limit: u16,
+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn get_thread_replies(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn resolve_message(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {
+ async move { unimplemented!("not needed for mutation tests") }
+ }
+
+ fn post_message(
+ &self,
+ _actor: Sender,
+ _channel_id: Uuid,
+ _req: PostMessageRequest,
+ ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {
+ async move {
+ Ok(PostMessageResponse {
+ id: Uuid::new_v4().to_string(),
+ nonce: None,
+ })
+ }
+ }
+
+ fn patch_message(
+ &self,
+ _actor: Sender,
+ _actor_role: ParticipantRole,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ req: PatchMessageRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ if !self.thinking_deleted {
+ self.patched
+ .lock()
+ .unwrap()
+ .extend(req.content.clone().into_iter());
+ }
+ let thinking_deleted = self.thinking_deleted;
+ async move {
+ if thinking_deleted {
+ return Err(ChannelMutationErr::NotFound(
+ "message not found".to_string(),
+ ));
+ }
+ Ok(())
+ }
+ }
+}
+
+struct FixedResponder(&'static str);
+
+#[async_trait]
+impl AgentResponder for FixedResponder {
+ async fn respond(&self, _user_id: &str, _prompt: String) -> anyhow::Result<String> {
+ Ok(self.0.to_string())
+ }
+}
+
fn user_id(email: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()
}
@@ -184,6 +325,49 @@ fn mention_event(
}
}
+#[tokio::test]
+async fn handle_patches_thinking_message_with_reply() {
+ let channel_id = Uuid::new_v4();
+ let channels = Arc::new(MutationChannelService::new(false));
+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(FixedResponder("the answer")));
+
+ handler
+ .handle(&mention_event(
+ channel_id,
+ Uuid::new_v4(),
+ None,
+ "@macro help",
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(
+ channels.patched.lock().unwrap().clone(),
+ vec!["the answer".to_string()]
+ );
+}
+
+#[tokio::test]
+async fn handle_drops_reply_when_thinking_message_was_deleted() {
+ let channel_id = Uuid::new_v4();
+ let channels = Arc::new(MutationChannelService::new(true));
+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(FixedResponder("the answer")));
+
+ handler
+ .handle(&mention_event(
+ channel_id,
+ Uuid::new_v4(),
+ None,
+ "@macro help",
+ ))
+ .await
+ .unwrap();
+
+ assert!(channels.patched.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn top_level_prompt_marks_trigger_inline_in_channel_context() {
let channel_id = Uuid::new_v4();
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index 44c92c95dc..6ad4396ca5 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -305,7 +305,7 @@ pub trait ChannelRepo: Send + Sync + 'static {
message_id: Uuid,
) -> impl Future<Output = Result<MutatedMessage, Self::Err>> + Send;
- /// Fetch the owner of a message within a channel.
+ /// Fetch the owner of an active (non-deleted) message within a channel.
fn get_message_owner(
&self,
channel_id: Uuid,
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 43db90ace8..8019f6e24b 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -700,7 +700,12 @@ where
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?
.ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
- if owner.as_str() != actor_storage_id.as_str() && !is_admin_or_owner(actor_role) {
+ // Any participant may delete bot-authored messages.
+ let owner_is_bot = Sender::parse_storage_str(&owner).is_ok_and(|owner| owner.is_bot());
+ if owner.as_str() != actor_storage_id.as_str()
+ && !owner_is_bot
+ && !is_admin_or_owner(actor_role)
+ {
return Err(ChannelMutationErr::Unauthorized(
"user is not authorized to delete this message".to_string(),
));
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index 6319d8b75d..fe333de253 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -5,11 +5,11 @@ use crate::domain::{
Activity, ActivityType, BotId, BotSenderProfile, ChannelAttachment, ChannelAttachmentType,
ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMetadata,
ChannelParticipant, ChannelType, CountedReaction, CreateEntityMentionOptions,
- EntityMention, MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
- NewChannelAttachment, ParticipantRole, PatchChannelRequest, PatchMessageRequest,
- PostMessageRequest, PostReactionRequest, ReactionAction, ReferencedShareItem,
- ReferencedShareItemType, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
- ThreadReplyRow, TopLevelMessageRow,
+ DeleteMessageQuery, EntityMention, MessageAttachment, MessagePageDirection,
+ MutatedAttachment, MutatedMessage, NewChannelAttachment, ParticipantRole,
+ PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostReactionRequest,
+ ReactionAction, ReferencedShareItem, ReferencedShareItemType, ResolvedChannelMessage,
+ Sender, SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
ports::{
ChannelEventDispatcher, ChannelReferenceSharePermissions, ChannelRepo, MockChannelRepo,
@@ -667,7 +667,11 @@ impl ChannelRepo for FakeMutationRepo {
_channel_id: Uuid,
_message_id: Uuid,
) -> Result<Option<String>, Self::Err> {
- Ok(Some(self.state.lock().unwrap().owner.clone()))
+ let state = self.state.lock().unwrap();
+ if state.message.deleted_at.is_some() {
+ return Ok(None);
+ }
+ Ok(Some(state.owner.clone()))
}
async fn get_participants(
@@ -960,6 +964,96 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
assert_eq!(recipients[0].as_ref(), "macro|[email protected]");
}
+#[tokio::test]
+async fn patch_of_deleted_message_is_not_found() {
+ let channel_id = Uuid::new_v4();
+ let bot_sender = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
+ let repo = FakeMutationRepo::new(channel_id, &bot_sender);
+ let message_id = repo.state.lock().unwrap().message.id;
+ repo.state.lock().unwrap().message.deleted_at = Some(Utc::now());
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .patch_message(
+ Sender::parse_storage_str(&bot_sender).unwrap(),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: Some("late reply".to_string()),
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: None,
+ nonce: None,
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, ChannelMutationErr::NotFound(_)));
+ assert!(events.events.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn member_can_delete_bot_authored_message() {
+ let channel_id = Uuid::new_v4();
+ let bot_sender = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
+ let repo = FakeMutationRepo::new(channel_id, &bot_sender);
+ let message_id = repo.state.lock().unwrap().message.id;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.delete_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ DeleteMessageQuery { nonce: None },
+ )
+ .await
+ .unwrap();
+
+ let emitted = events.events.lock().unwrap();
+ assert_eq!(emitted.len(), 1);
+ assert!(matches!(&emitted[0], ChannelEvent::MessageDeleted { .. }));
+}
+
+#[tokio::test]
+async fn member_cannot_delete_other_users_message() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .delete_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ DeleteMessageQuery { nonce: None },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, ChannelMutationErr::Unauthorized(_)));
+ assert!(events.events.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn reaction_mutation_emits_grouped_reaction_event() {
let channel_id = Uuid::new_v4();
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index b70549ba0b..cbcdbaf973 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -419,7 +419,7 @@ async fn get_message_owner(
r#"
SELECT sender_id
FROM comms_messages
- WHERE id = $1 AND channel_id = $2
+ WHERE id = $1 AND channel_id = $2 AND deleted_at IS NULL
ORDER BY created_at ASC
"#,
message_id,