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): soft-delete top-level messages with replies instead of removing (#3431)

teoddfe6a1e576a
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index f57ffbac1f..fc0cba0138 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -326,6 +326,20 @@ export function replaceTopLevelMessageStateInChannelMessages(
);
}
+export function markTopLevelMessageDeletedInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ messageId: string,
+ deletedAt: string | null | undefined
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) =>
+ message.id === messageId
+ ? { ...message, deleted_at: deletedAt ?? undefined }
+ : message
+ );
+}
+
function getTopLevelMessageSnapshot(
data: ChannelMessagesData | undefined,
messageId: string
@@ -643,6 +657,20 @@ function mapChannelMessagesByIdsItems(
return didChange ? next : data;
}
+/** Finds a top-level message in any cached by-ids query for the channel. */
+export function findTopLevelMessageInChannelMessagesByIds(
+ channelId: string,
+ messageId: string
+): ApiChannelMessage | undefined {
+ const entries = queryClient.getQueriesData<ApiChannelMessage[]>({
+ queryKey: getChannelMessagesByIdsQueryKeyPrefix(channelId),
+ });
+ for (const [, data] of entries) {
+ const match = data?.find((message) => message.id === messageId);
+ if (match) return match;
+ }
+}
+
export function replaceTopLevelMessageReactionsInChannelMessagesByIds(
data: ApiChannelMessage[] | undefined,
messageId: string,
@@ -689,6 +717,19 @@ export function replaceTopLevelMessageStateInChannelMessagesByIds(
);
}
+export function markTopLevelMessageDeletedInChannelMessagesByIds(
+ data: ApiChannelMessage[] | undefined,
+ messageId: string,
+ deletedAt: string | null | undefined
+): ApiChannelMessage[] | undefined {
+ if (!data) return data;
+ return mapChannelMessagesByIdsItems(data, (message) =>
+ message.id === messageId
+ ? { ...message, deleted_at: deletedAt ?? undefined }
+ : message
+ );
+}
+
/**
* Marks the by-ids message queries as stale without triggering an immediate refetch.
*/
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index 84a74b0345..c4c5d989be 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -28,7 +28,9 @@ import {
captureDeleteSnapshotForTarget,
type DeleteTargetSnapshot,
getTargetMessageState,
+ getTopLevelMessageDeletedAt,
insertMessageIntoTargetCaches,
+ markTopLevelMessageDeletedInTargetCaches,
removeMessageFromTargetCaches,
replaceTargetMessageId,
replaceTargetMessageState,
@@ -71,7 +73,13 @@ type DeleteMessageContext = {
deletedReactions: CountedReaction[];
deletedAttachments: Attachment[];
target: ReturnType<typeof resolveMessageTarget>;
+ /** Snapshot used to restore a removed thread reply on rollback. */
targetSnapshot?: DeleteTargetSnapshot;
+ /**
+ * Previous `deleted_at` value for a soft-deleted top-level message,
+ * captured so rollback can revert the optimistic mutation.
+ */
+ previousDeletedAt?: string | null;
};
type UpdateMessageContext = {
@@ -231,9 +239,14 @@ function replaceOptimisticMessage(
/**
* Optimistically delete a message from the channel cache.
- * Returns minimal context: only the deleted message, reactions, and attachments.
+ *
+ * Top-level messages are soft-deleted in place (we set `deleted_at`) so the
+ * UI renders the "this message was deleted" placeholder while preserving any
+ * thread replies hanging off the message. Thread replies don't have a
+ * `deleted_at` field in the schema, so we still remove them from the caches
+ * and capture a snapshot for rollback.
*/
-function optimisticDeleteChannelMessage(
+export function optimisticDeleteChannelMessage(
vars: WithChannelId<
Pick<ChannelMessage, 'message_id'> & { threadId?: string }
>
@@ -249,11 +262,21 @@ function optimisticDeleteChannelMessage(
target,
};
- context.targetSnapshot = captureDeleteSnapshotForTarget(
- vars.channelId,
- target
- );
- removeMessageFromTargetCaches(vars.channelId, target);
+ if (target.kind === 'top_level') {
+ context.previousDeletedAt =
+ getTopLevelMessageDeletedAt(vars.channelId, target.messageId) ?? null;
+ markTopLevelMessageDeletedInTargetCaches(
+ vars.channelId,
+ target,
+ new Date().toISOString()
+ );
+ } else {
+ context.targetSnapshot = captureDeleteSnapshotForTarget(
+ vars.channelId,
+ target
+ );
+ removeMessageFromTargetCaches(vars.channelId, target);
+ }
return context;
}
@@ -261,10 +284,19 @@ function optimisticDeleteChannelMessage(
/**
* Rollback an optimistic message delete by restoring the deleted data.
*/
-function rollbackDeleteChannelMessage(
+export function rollbackDeleteChannelMessage(
channelId: string,
context: DeleteMessageContext
): void {
+ if (context.target.kind === 'top_level') {
+ markTopLevelMessageDeletedInTargetCaches(
+ channelId,
+ context.target,
+ context.previousDeletedAt
+ );
+ return;
+ }
+
if (context.targetSnapshot) {
restoreMessageInTargetCaches(
channelId,
diff --git a/js/app/packages/queries/channel/reconcile.ts b/js/app/packages/queries/channel/reconcile.ts
index 690a15d6b3..3edfe658b0 100644
--- a/js/app/packages/queries/channel/reconcile.ts
+++ b/js/app/packages/queries/channel/reconcile.ts
@@ -8,9 +8,12 @@ import { queryClient } from '../client';
import {
findThreadIdInChannelMessages,
findThreadPreviewReplySnapshotInChannelMessages,
+ findTopLevelMessageInChannelMessagesByIds,
findTopLevelMessageSnapshotInChannelMessages,
insertThreadReplyIntoChannelMessages,
insertTopLevelMessageIntoChannelMessages,
+ markTopLevelMessageDeletedInChannelMessages,
+ markTopLevelMessageDeletedInChannelMessagesByIds,
removeThreadReplyFromChannelMessages,
removeTopLevelMessageFromChannelMessages,
replaceThreadReplyAttachmentsInChannelMessages,
@@ -188,6 +191,52 @@ export function removeMessageFromTargetCaches(
);
}
+/**
+ * Marks a top-level message as soft-deleted in the rendered caches.
+ * Pass `undefined` (or `null`) to clear the soft-delete (used for rollback).
+ *
+ * Thread replies don't have a `deleted_at` field in the schema, so this is
+ * a no-op for thread reply targets — callers should remove thread replies
+ * from caches instead.
+ */
+export function markTopLevelMessageDeletedInTargetCaches(
+ channelId: string,
+ target: MessageTarget,
+ deletedAt: string | null | undefined
+) {
+ if (target.kind !== 'top_level') return;
+
+ setChannelMessagesData(channelId, (prev) =>
+ markTopLevelMessageDeletedInChannelMessages(
+ prev,
+ target.messageId,
+ deletedAt
+ )
+ );
+ setChannelMessagesByIdsData(channelId, (prev) =>
+ markTopLevelMessageDeletedInChannelMessagesByIds(
+ prev,
+ target.messageId,
+ deletedAt
+ )
+ );
+}
+
+/** Returns the current `deleted_at` value for a top-level message, if cached. */
+export function getTopLevelMessageDeletedAt(
+ channelId: string,
+ messageId: string
+): string | null | undefined {
+ const paginated = findTopLevelMessageSnapshotInChannelMessages(
+ channelId,
+ messageId
+ );
+ if (paginated) return paginated.message.deleted_at;
+
+ return findTopLevelMessageInChannelMessagesByIds(channelId, messageId)
+ ?.deleted_at;
+}
+
/** Captures rollback snapshots for a target before optimistic delete. */
export function captureDeleteSnapshotForTarget(
channelId: string,
diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
index 8fb00437c1..b3f1f21d80 100644
--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -30,9 +30,12 @@ import {
type ChannelMessagesData,
getChannelMessagesQueryKey,
} from '../channel-messages';
+import { channelKeys } from '../keys';
import {
+ optimisticDeleteChannelMessage,
optimisticInsertChannelMessage,
optimisticUpdateChannelMessage,
+ rollbackDeleteChannelMessage,
rollbackInsertChannelMessage,
rollbackUpdateChannelMessage,
} from '../message';
@@ -446,6 +449,127 @@ describe('channel optimistic cache regressions', () => {
);
});
+ it('soft-deletes top-level messages with replies instead of removing them', () => {
+ seedChannelMessagesCache(
+ 'channel-1',
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('parent-1', '2024-01-03T00:00:00.000Z', {
+ thread: {
+ preview: [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z'),
+ createThreadReply('reply-2', '2024-01-03T02:00:00.000Z'),
+ ],
+ reply_count: 2,
+ latest_reply_at: '2024-01-03T02:00:00.000Z',
+ },
+ }),
+ ],
+ ])
+ );
+ seedThreadRepliesCache('channel-1', 'parent-1', [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z'),
+ createThreadReply('reply-2', '2024-01-03T02:00:00.000Z'),
+ ]);
+
+ const context = optimisticDeleteChannelMessage({
+ channelId: 'channel-1',
+ message_id: 'parent-1',
+ });
+
+ const message = getChannelMessagesFromCache('channel-1')?.pages[0].items[0];
+ expect(message?.id).toBe('parent-1');
+ expect(message?.deleted_at).toBeTruthy();
+ expect(message?.thread.preview).toHaveLength(2);
+ expect(getThreadRepliesFromCache('channel-1', 'parent-1')).toHaveLength(2);
+
+ if (context) {
+ rollbackDeleteChannelMessage('channel-1', context);
+ }
+
+ const restored =
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0];
+ expect(restored?.id).toBe('parent-1');
+ expect(restored?.deleted_at).toBeFalsy();
+ expect(restored?.thread.preview).toHaveLength(2);
+ });
+
+ it('removes thread replies from caches on optimistic delete and restores them on rollback', () => {
+ seedChannelMessagesCache(
+ 'channel-1',
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('parent-1', '2024-01-03T00:00:00.000Z', {
+ thread: {
+ preview: [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z'),
+ ],
+ reply_count: 1,
+ latest_reply_at: '2024-01-03T01:00:00.000Z',
+ },
+ }),
+ ],
+ ])
+ );
+ seedThreadRepliesCache('channel-1', 'parent-1', [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z'),
+ ]);
+
+ const context = optimisticDeleteChannelMessage({
+ channelId: 'channel-1',
+ message_id: 'reply-1',
+ threadId: 'parent-1',
+ });
+
+ expect(getThreadRepliesFromCache('channel-1', 'parent-1')).toEqual([]);
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread.preview
+ ).toEqual([]);
+
+ if (context) {
+ rollbackDeleteChannelMessage('channel-1', context);
+ }
+
+ expect(getThreadRepliesFromCache('channel-1', 'parent-1')).toEqual([
+ expect.objectContaining({ id: 'reply-1' }),
+ ]);
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread.preview
+ ).toEqual([expect.objectContaining({ id: 'reply-1' })]);
+ });
+
+ it('preserves a prior deleted_at on rollback when only the by-ids cache is warm', () => {
+ const previousDeletedAt = '2024-01-02T00:00:00.000Z';
+ testQueryClient.setQueryData<ApiChannelMessage[]>(
+ channelKeys.messagesByIds('channel-1', ['parent-1']).queryKey,
+ [
+ createPaginatedMessage('parent-1', '2024-01-03T00:00:00.000Z', {
+ deleted_at: previousDeletedAt,
+ }),
+ ]
+ );
+
+ const context = optimisticDeleteChannelMessage({
+ channelId: 'channel-1',
+ message_id: 'parent-1',
+ });
+
+ const byIdsAfter = testQueryClient.getQueryData<ApiChannelMessage[]>(
+ channelKeys.messagesByIds('channel-1', ['parent-1']).queryKey
+ );
+ expect(byIdsAfter?.[0].deleted_at).toBeTruthy();
+ expect(byIdsAfter?.[0].deleted_at).not.toBe(previousDeletedAt);
+
+ if (context) {
+ rollbackDeleteChannelMessage('channel-1', context);
+ }
+
+ const byIdsRolledBack = testQueryClient.getQueryData<ApiChannelMessage[]>(
+ channelKeys.messagesByIds('channel-1', ['parent-1']).queryKey
+ );
+ expect(byIdsRolledBack?.[0].deleted_at).toBe(previousDeletedAt);
+ });
+
it('uses distinct query keys for target-message loads', () => {
expect(getChannelMessagesQueryKey('channel-1')).not.toEqual(
getChannelMessagesQueryKey('channel-1', 'message-42')