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.

feat(new-channels): live updates & optimistic (#1877)

teod0e5d9d7c9f8
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index 8c0a7a25ab..b64f297da9 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -34,7 +34,7 @@ export default function BlockChannel(props: BlockChannelProps) {
return (
<NewChannel
channelId={channelId}
- // targetMessageId="019c2444-b1c4-7a91-a57d-14bd684388c9"
+ targetMessageId="019b47e2-d61d-7cef-a7a3-b192c0df2f7f"
/>
);
}
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index 3c81daeff3..1bf841732c 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -1,7 +1,7 @@
import {
- flattenMessages,
- useChannelMessagesQuery,
+ makeMessageIndex,
type ChannelMessagesData,
+ useChannelMessagesQuery,
} from '@queries/channel/channel-messages';
import {
createMemo,
@@ -20,11 +20,11 @@ import {
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { createThreadManager } from './thread-manager';
import { createThreadPaginator } from './thread-paginator';
-import { createTargetMessageControlledSignal } from './target-message';
import { useUserId } from '@core/context/user';
import {
useDeleteMessageMutation,
usePatchMessageMutation,
+ useSendMessageMutation,
} from '@queries/channel/message';
import {
useAddReactionMutation,
@@ -40,6 +40,7 @@ import { createActivityTracker } from '@channel/activity-tracker';
import { useChannelActivity } from '@core/context/channels';
import { createChannelDragState } from './create-channel-drag-state';
import { ChannelDropZone } from './ChannelDropZone';
+import { buildPostMessageRequest } from '@channel/Input/message-payload';
import {
makeAttachmentTrackerPersistenceKey,
makeInputValuePersistenceKey,
@@ -53,15 +54,15 @@ type ChannelProps = {
export function Channel(props: ChannelProps) {
const userId = useUserId();
+ const sendMessageMutation = useSendMessageMutation();
const patchMessageMutation = usePatchMessageMutation();
const deleteMessageMutation = useDeleteMessageMutation();
const addReactionMutation = useAddReactionMutation();
const removeReactionMutation = useRemoveReactionMutation();
- const [targetMessageId, _setTargetMessageId] =
- createTargetMessageControlledSignal(
- () => props.channelId,
- props.targetMessageId
- );
+
+ const [targetMessageId, _setTargetMessageId] = createSignal<
+ string | undefined
+ >(props.targetMessageId);
const messagesQuery = useChannelMessagesQuery(
() => props.channelId,
@@ -81,10 +82,11 @@ export function Channel(props: ChannelProps) {
const threadListInitialScrollTarget: Accessor<ThreadListScrollTarget> = () =>
defaultThreadListTargetFromMessage(targetMessageId());
- const messages = () =>
- messagesQuery.data
- ? flattenMessages(messagesQuery.data as ChannelMessagesData)
- : [];
+ const messageIndex = createMemo(() =>
+ makeMessageIndex(messagesQuery.data as ChannelMessagesData | undefined)
+ );
+ const messages = createMemo(() => messageIndex().items);
+ const messageById = createMemo(() => messageIndex().byId);
const shift = () => threadPaginator.isShifting();
@@ -128,33 +130,39 @@ export function Channel(props: ChannelProps) {
<Show when={messages().length > 0}>
<div class="relative flex-1 min-h-0">
<ThreadList
- data={messages}
+ keys={() => messageIndex().keys}
initialScrollTarget={threadListInitialScrollTarget()}
shift={shift}
+ prepend={threadPaginator.isPrepending}
onScrollNearTop={threadPaginator.shiftPaginate}
onScrollNearBottom={threadPaginator.prependPaginate}
onNavigationReady={setThreadListNavigation}
onScrollStateChange={setThreadListScrollState}
>
{(item) => {
+ const message = () => messageById().get(item.id);
const state = threadManager.getOrCreateThreadState(item.id);
return (
- <ChannelThread
- data={() => item}
- channelId={() => props.channelId}
- getMessageActions={getMessageActions}
- isExpanded={state.isExpanded}
- setIsExpanded={state.setIsExpanded}
- isReplying={state.isReplying}
- setIsReplying={state.setIsReplying}
- replyInputState={state.replyInputState}
- setReplyInputState={state.setReplyInputState}
- listMeta={listMetaByMessageId()[item.id]}
- threadActions={{
- onDismissNewMessages:
- activityTracker.dismissNewMessages,
- }}
- />
+ <Show when={message()}>
+ {(m) => (
+ <ChannelThread
+ data={m}
+ channelId={() => props.channelId}
+ getMessageActions={getMessageActions}
+ isExpanded={state.isExpanded}
+ setIsExpanded={state.setIsExpanded}
+ isReplying={state.isReplying}
+ setIsReplying={state.setIsReplying}
+ replyInputState={state.replyInputState}
+ setReplyInputState={state.setReplyInputState}
+ listMeta={listMetaByMessageId()[item.id]}
+ threadActions={{
+ onDismissNewMessages:
+ activityTracker.dismissNewMessages,
+ }}
+ />
+ )}
+ </Show>
);
}}
</ThreadList>
@@ -181,6 +189,17 @@ export function Channel(props: ChannelProps) {
onReady={(handle) => {
dragState.setAttachFilesToChannel(handle.attachFiles);
}}
+ onSend={(snapshot) => {
+ const senderId = userId();
+ if (!senderId) return;
+
+ sendMessageMutation.mutate({
+ channelID: props.channelId,
+ senderId,
+ optimisticId: crypto.randomUUID(),
+ message: buildPostMessageRequest(snapshot),
+ });
+ }}
/>
</div>
</Suspense>
diff --git a/js/app/packages/channel/Channel/ThreadList.tsx b/js/app/packages/channel/Channel/ThreadList.tsx
index 074147510e..268dcf72c8 100644
--- a/js/app/packages/channel/Channel/ThreadList.tsx
+++ b/js/app/packages/channel/Channel/ThreadList.tsx
@@ -49,15 +49,16 @@ export type ThreadListScrollState = {
viewportSize: number;
};
-type ThreadListProps<T extends { id: string }> = {
- data: Accessor<T[]>;
- children: (item: T) => JSX.Element;
+type ThreadListProps = {
+ keys: Accessor<string[]>;
+ children: (item: { id: string }) => JSX.Element;
initialScrollTarget?: ThreadListScrollTarget;
onScrollNearTop?: () => void;
onScrollNearBottom?: () => void;
onNavigationReady?: (navigation: ThreadListNavigation) => void;
onScrollStateChange?: (state: ThreadListScrollState) => void;
shift?: Accessor<boolean>;
+ prepend?: Accessor<boolean>;
};
const NEAR_TOP_THRESHOLD = 800;
@@ -81,9 +82,10 @@ const clamp = (value: number, min: number, max: number) =>
export function shouldStickToBottomOnDataChange(
isNearBottom: boolean,
- shift?: Accessor<boolean>
+ shift?: Accessor<boolean>,
+ prepend?: Accessor<boolean>
): boolean {
- return isNearBottom && !(shift?.() ?? false);
+ return isNearBottom && !(shift?.() ?? false) && !(prepend?.() ?? false);
}
export function isExplicitScrollDown(
@@ -124,9 +126,7 @@ function getTargetAlign(target: ThreadListScrollTarget): ScrollAlignment {
}
}
-export function ThreadList<T extends { id: string }>(
- props: ThreadListProps<T>
-) {
+export function ThreadList(props: ThreadListProps) {
const [virtualHandle, setVirtualHandle] = createSignal<VirtualizerHandle>();
const [isNearBottom, setIsNearBottom] = createSignal(true);
const [didInitialScroll, setDidInitialScroll] = createSignal(false);
@@ -147,8 +147,8 @@ export function ThreadList<T extends { id: string }>(
};
const resolveTargetIndex = (target: ThreadListScrollTarget): number => {
- const items = props.data();
- const maxIndex = items.length - 1;
+ const keys = props.keys();
+ const maxIndex = keys.length - 1;
if (maxIndex < 0) return -1;
switch (target.tag) {
@@ -159,7 +159,7 @@ export function ThreadList<T extends { id: string }>(
case 'index':
return clamp(target.index, 0, maxIndex);
case 'id': {
- const idx = items.findIndex((item) => item.id === target.id);
+ const idx = keys.indexOf(target.id);
return idx === -1 ? -1 : idx;
}
}
@@ -176,7 +176,7 @@ export function ThreadList<T extends { id: string }>(
};
const getCurrentIndex = (handle: VirtualizerHandle): number => {
- const itemCount = props.data().length;
+ const itemCount = props.keys().length;
if (!itemCount) return -1;
return clamp(handle.findItemIndex(handle.scrollOffset), 0, itemCount - 1);
};
@@ -256,11 +256,17 @@ export function ThreadList<T extends { id: string }>(
createEffect(
on(
- () => props.data().length,
+ () => props.keys().length,
() => {
const handle = virtualHandle();
if (!handle || !didInitialScroll()) return;
- if (shouldStickToBottomOnDataChange(isNearBottom(), props.shift)) {
+ if (
+ shouldStickToBottomOnDataChange(
+ isNearBottom(),
+ props.shift,
+ props.prepend
+ )
+ ) {
requestAnimationFrame(() => {
scrollToTarget(handle, { tag: 'bottom', align: 'end' });
});
@@ -359,11 +365,11 @@ export function ThreadList<T extends { id: string }>(
scrollOnMount(ref);
}}
scrollRef={scrollRef}
- data={props.data()}
+ data={props.keys()}
onScroll={handleScroll}
shift={props.shift?.() ?? false}
>
- {(item) => props.children(item)}
+ {(key) => props.children({ id: key })}
</Virtualizer>
</div>
);
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 9e439f6ab4..ca650b540b 100644
--- a/js/app/packages/channel/Channel/create-channel-message-actions.ts
+++ b/js/app/packages/channel/Channel/create-channel-message-actions.ts
@@ -19,6 +19,8 @@ type AddReactionInput = {
messageId: string;
emoji: string;
userId: string;
+ threadId?: string;
+ currentReactions: MessageData['reactions'];
};
type RemoveReactionInput = {
@@ -26,6 +28,8 @@ type RemoveReactionInput = {
messageId: string;
emoji: string;
userId: string;
+ threadId?: string;
+ currentReactions: MessageData['reactions'];
};
type PatchMessageInput = {
@@ -37,6 +41,7 @@ type PatchMessageInput = {
type DeleteMessageInput = {
channelID: string;
messageID: string;
+ threadID?: string;
};
type ChannelMessageActionEffects = {
@@ -106,23 +111,32 @@ export function createChannelMessageActions(
const emoji = ctx.emoji ?? DEFAULT_REACTION_EMOJI;
const channelId = options.channelId();
- const hasReaction = hasReactionFromUser(message, emoji, userId);
+ const targetMessage = message;
+ const liveMessage = ctx.message;
+ const threadId =
+ (targetMessage as MessageData & { thread_id?: string | null })
+ .thread_id ?? undefined;
+ const hasReaction = hasReactionFromUser(liveMessage, emoji, userId);
if (hasReaction) {
options.removeReaction({
channelId,
- messageId: message.id,
+ messageId: targetMessage.id,
emoji,
userId,
+ threadId,
+ currentReactions: liveMessage.reactions,
});
return;
}
options.addReaction({
channelId,
- messageId: message.id,
+ messageId: targetMessage.id,
emoji,
userId,
+ threadId,
+ currentReactions: liveMessage.reactions,
});
}
: undefined,
@@ -159,6 +173,9 @@ export function createChannelMessageActions(
options.deleteMessage({
channelID: options.channelId(),
messageID: message.id,
+ threadID:
+ (message as MessageData & { thread_id?: string | null })
+ .thread_id ?? undefined,
});
}
: undefined,
diff --git a/js/app/packages/channel/Channel/target-message.ts b/js/app/packages/channel/Channel/target-message.ts
deleted file mode 100644
index 6116ba10de..0000000000
--- a/js/app/packages/channel/Channel/target-message.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { channelKeys } from '@queries/channel/keys';
-import { queryClient } from '@queries/client';
-import { createEffect, createSignal, on, type Accessor } from 'solid-js';
-
-export function createTargetMessageControlledSignal(
- channelId: Accessor<string>,
- initialTargetMessageId: string | undefined
-) {
- const [targetMessageId, setTargetMessageId] = createSignal<
- string | undefined
- >(initialTargetMessageId);
-
- /**
- * The paginated messages query consumes the targetMessage id as the `load_around_message_id` query parameter
- * Once we execute the first query with this query parameter we want to clear it and reset the query correctly
- */
- createEffect(
- on(targetMessageId, (curr, prev) => {
- if (curr !== prev && curr != null) {
- queryClient.resetQueries({
- queryKey: channelKeys.messages(channelId()).queryKey,
- });
- }
- })
- );
-
- return [targetMessageId, setTargetMessageId];
-}
diff --git a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
index 77b2f3aa3e..f983a9041a 100644
--- a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
+++ b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
@@ -50,146 +50,44 @@ function buildHarness(input?: {
}
describe('createChannelMessageActions', () => {
- it('gates edit/delete to own non-deleted messages', () => {
- const ownHarness = buildHarness({ userId: 'user-1' });
- const ownMessage = buildMessage({ sender_id: 'user-1', deleted_at: null });
- const ownActions = ownHarness.getMessageActions(ownMessage);
- expect(ownActions.onEdit).toBeTypeOf('function');
- expect(ownActions.onDelete).toBeTypeOf('function');
-
- const otherHarness = buildHarness({ userId: 'user-1' });
- const otherMessage = buildMessage({
- sender_id: 'user-2',
- deleted_at: null,
- });
- const otherActions = otherHarness.getMessageActions(otherMessage);
- expect(otherActions.onEdit).toBeUndefined();
- expect(otherActions.onDelete).toBeUndefined();
-
- const deletedHarness = buildHarness({ userId: 'user-1' });
- const deletedMessage = buildMessage({
- sender_id: 'user-1',
- deleted_at: '2026-02-25T00:00:00.000Z',
- });
- const deletedActions = deletedHarness.getMessageActions(deletedMessage);
- expect(deletedActions.onEdit).toBeUndefined();
- expect(deletedActions.onDelete).toBeUndefined();
- });
-
- it('gates reply to top-level non-deleted messages', () => {
- const harness = buildHarness({ userId: 'user-1' });
-
- const topLevelActions = harness.getMessageActions(
- buildMessage({ deleted_at: null, thread_id: null })
- );
- expect(topLevelActions.onReply).toBeTypeOf('function');
-
- const threadReplyActions = harness.getMessageActions(
- buildMessage({ deleted_at: null, thread_id: 'parent-message' })
- );
- expect(threadReplyActions.onReply).toBeUndefined();
-
- const deletedActions = harness.getMessageActions(
- buildMessage({ deleted_at: '2026-02-25T00:00:00.000Z' })
- );
- expect(deletedActions.onReply).toBeUndefined();
- });
-
- it('toggles reactions and uses default emoji when one is not provided', () => {
+ it('uses the live message from the reaction context when toggling', () => {
const harness = buildHarness({ userId: 'user-1' });
- const message = buildMessage({
+ const staleMessage = buildMessage({ reactions: [] });
+ const liveMessage = buildMessage({
reactions: [{ emoji: '👍', users: ['user-1'] }],
});
- const actions = harness.getMessageActions(message);
+ const actions = harness.getMessageActions(staleMessage);
- actions.onReact?.({ message });
- expect(harness.removeReaction).toHaveBeenCalledTimes(1);
- expect(harness.removeReaction).toHaveBeenCalledWith({
- channelId: 'channel-1',
- messageId: 'message-1',
- emoji: '👍',
- userId: 'user-1',
- });
-
- actions.onReact?.({ message, emoji: '😂' });
- expect(harness.addReaction).toHaveBeenCalledTimes(1);
- expect(harness.addReaction).toHaveBeenCalledWith({
- channelId: 'channel-1',
- messageId: 'message-1',
- emoji: '😂',
- userId: 'user-1',
- });
- });
-
- it('keeps react action available without a user id and no-ops on click', () => {
- const harness = buildHarness({ userId: undefined });
- const message = buildMessage();
- const actions = harness.getMessageActions(message);
-
- expect(actions.onReact).toBeTypeOf('function');
- actions.onReact?.({ message, emoji: '👍' });
+ actions.onReact?.({ message: liveMessage, emoji: '👍' });
+ expect(harness.removeReaction).toHaveBeenCalledTimes(1);
expect(harness.addReaction).not.toHaveBeenCalled();
- expect(harness.removeReaction).not.toHaveBeenCalled();
});
- it('copies links through injected effects', async () => {
- const copyToClipboard = vi
- .fn<(text: string) => Promise<void>>()
- .mockResolvedValue(undefined);
- const notifyCopyLinkSuccess = vi.fn();
- const notifyCopyLinkFailure = vi.fn();
- const harness = buildHarness({
- userId: 'user-1',
- effects: {
- getLocationHref: () => 'https://example.com/app/component/unified-list',
- copyToClipboard,
- notifyCopyLinkSuccess,
- notifyCopyLinkFailure,
- },
+ it('preserves bound thread context when reacting to a thread reply', () => {
+ const harness = buildHarness({ userId: 'user-1' });
+ const boundReply = buildMessage({
+ id: 'reply-1',
+ thread_id: 'parent-1',
+ reactions: [],
});
-
- const actions = harness.getMessageActions(buildMessage());
- await actions.onCopyLink?.({ message: buildMessage() });
-
- expect(copyToClipboard).toHaveBeenCalledTimes(1);
- expect(copyToClipboard.mock.calls[0]?.[0]).toContain(
- 'targetMessageId=message-1'
- );
- expect(copyToClipboard.mock.calls[0]?.[0]).toContain('#message-message-1');
- expect(notifyCopyLinkSuccess).toHaveBeenCalledTimes(1);
- expect(notifyCopyLinkFailure).not.toHaveBeenCalled();
- });
-
- it('edits with trimmed content and rejects empty edits', () => {
- const notifyEmptyEdit = vi.fn();
- const harness = buildHarness({
- userId: 'user-1',
- effects: {
- promptForEdit: () => ' updated content ',
- notifyEmptyEdit,
- },
+ const liveReply = buildMessage({
+ id: 'reply-1',
+ thread_id: undefined,
+ reactions: [],
});
- const message = buildMessage({ sender_id: 'user-1' });
- const actions = harness.getMessageActions(message);
+ const actions = harness.getMessageActions(boundReply);
- actions.onEdit?.({ message });
- expect(harness.patchMessage).toHaveBeenCalledWith({
- channelID: 'channel-1',
- messageID: 'message-1',
- content: 'updated content',
- });
+ actions.onReact?.({ message: liveReply, emoji: '👍' });
- const emptyHarness = buildHarness({
+ expect(harness.addReaction).toHaveBeenCalledTimes(1);
+ expect(harness.addReaction).toHaveBeenCalledWith({
+ channelId: 'channel-1',
+ messageId: 'reply-1',
+ emoji: '👍',
userId: 'user-1',
- effects: {
- promptForEdit: () => ' ',
- notifyEmptyEdit,
- },
+ threadId: 'parent-1',
+ currentReactions: [],
});
- const emptyActions = emptyHarness.getMessageActions(message);
- emptyActions.onEdit?.({ message });
- expect(notifyEmptyEdit).toHaveBeenCalledTimes(1);
- expect(emptyHarness.patchMessage).not.toHaveBeenCalled();
});
});
diff --git a/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts b/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
index 80b83da0b1..84d1fc53bb 100644
--- a/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
+++ b/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
@@ -21,6 +21,16 @@ describe('shouldStickToBottomOnDataChange', () => {
it('does not stick while shifting', () => {
expect(shouldStickToBottomOnDataChange(true, () => true)).toBe(false);
});
+
+ it('does not stick while prepending', () => {
+ expect(
+ shouldStickToBottomOnDataChange(
+ true,
+ () => false,
+ () => true
+ )
+ ).toBe(false);
+ });
});
describe('isExplicitScrollDown', () => {
diff --git a/js/app/packages/channel/Channel/thread-manager.ts b/js/app/packages/channel/Channel/thread-manager.ts
index afc0d8d656..470f47fa75 100644
--- a/js/app/packages/channel/Channel/thread-manager.ts
+++ b/js/app/packages/channel/Channel/thread-manager.ts
@@ -1,6 +1,6 @@
import { createStore } from 'solid-js/store';
import type { ThreadState } from '../Thread';
-import { createSignal } from 'solid-js';
+import { batch, createSignal, type Setter } from 'solid-js';
import type { InputSnapshot } from '@channel/Input';
type ThreadStore = Record<string, ThreadState>;
@@ -9,11 +9,21 @@ export function createThreadManager() {
function initThreadState(threadId: string): ThreadState {
const [isExpanded, setIsExpanded] = createSignal<boolean>(false);
- const [isReplying, setIsReplying] = createSignal<boolean>(false);
+ const [isReplying, setIsReplyingRaw] = createSignal<boolean>(false);
const [replyInputState, setReplyInputState] = createSignal<
InputSnapshot | undefined
>();
+ /** If you set replying from false -> true this means it must be expanded **/
+ const setIsReplying: Setter<boolean> = (val) => {
+ batch(() => {
+ const next: boolean =
+ typeof val === 'function' ? val(isReplying()) : val;
+ if (next) setIsExpanded(true);
+ setIsReplyingRaw(next);
+ });
+ };
+
const state: ThreadState = {
isExpanded,
setIsExpanded,
diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsx
index 4197fd93b6..4cc223792b 100644
--- a/js/app/packages/channel/Input/ChannelInput.tsx
+++ b/js/app/packages/channel/Input/ChannelInput.tsx
@@ -32,11 +32,13 @@ export function ChannelInput(props: ChannelInputProps) {
createInputAttachmentTracker({
initialAttachments: props.input.attachments,
});
+ let clearComposer = () => {};
const inputState = createInputState({
initialInput: props.input,
mentions: mentionsTracker.mentions,
attachmentTracker,
+ clearComposer: () => clearComposer(),
attachFiles: async (files) => {
await uploadInputAttachments({
files,
@@ -77,6 +79,7 @@ export function ChannelInput(props: ChannelInputProps) {
return true;
},
});
+ clearComposer = () => markdownEditor.controls.clear();
props.onReady?.({
clear: () => markdownEditor.controls.clear(),
diff --git a/js/app/packages/channel/Input/create-input-commands.ts b/js/app/packages/channel/Input/create-input-commands.ts
index 08f562d7a2..1dae68eba4 100644
--- a/js/app/packages/channel/Input/create-input-commands.ts
+++ b/js/app/packages/channel/Input/create-input-commands.ts
@@ -13,6 +13,7 @@ type CreateInputCommandsDeps = {
setIsSending: (value: boolean) => void;
setShowFormatRibbon: (updater: (prev: boolean) => boolean) => void;
reset: () => void;
+ clearComposer?: () => void;
removeTrackedAttachment: (id: string) => void;
attachFiles?: (files: File[]) => Promise<void> | void;
callbacks?: InputCallbacks;
@@ -37,6 +38,7 @@ export function createInputCommands(
try {
await deps.callbacks.onSend(current);
deps.reset();
+ deps.clearComposer?.();
return true;
} finally {
deps.setIsSending(false);
@@ -56,6 +58,7 @@ export function createInputCommands(
close: () => {
const current = deps.snapshot();
deps.reset();
+ deps.clearComposer?.();
deps.callbacks?.onClose?.(current);
},
removeAttachment,
diff --git a/js/app/packages/channel/Input/create-input-state.ts b/js/app/packages/channel/Input/create-input-state.ts
index a3759f7aa9..010cea4a5b 100644
--- a/js/app/packages/channel/Input/create-input-state.ts
+++ b/js/app/packages/channel/Input/create-input-state.ts
@@ -15,6 +15,7 @@ type CreateInputStateOptions = {
initialInput: InputData;
mentions: Accessor<ItemMention[]>;
attachmentTracker: InputAttachmentTracker;
+ clearComposer?: () => void;
attachFiles?: (files: File[]) => Promise<void> | void;
clearInput?: () => void;
callbacks?: InputCallbacks;
@@ -44,6 +45,7 @@ export function createInputState(options: CreateInputStateOptions): InputState {
snapshot: view.snapshot,
setIsSending: view.setIsSending,
setShowFormatRibbon: view.setShowFormatRibbon,
+ clearComposer: options.clearComposer,
reset: () => {
view.reset();
options.clearInput?.();
diff --git a/js/app/packages/channel/Input/message-payload.ts b/js/app/packages/channel/Input/message-payload.ts
new file mode 100644
index 0000000000..fc18496de9
--- /dev/null
+++ b/js/app/packages/channel/Input/message-payload.ts
@@ -0,0 +1,34 @@
+import { STATIC_IMAGE, STATIC_VIDEO } from '@core/store/cacheChannelInput';
+import type { PostMessageRequest } from '@service-comms/generated/models';
+import type { InputAttachmentData, InputSnapshot } from './types';
+
+function attachmentEntityType(
+ attachment: Pick<InputAttachmentData, 'kind'>
+): string {
+ switch (attachment.kind) {
+ case 'image':
+ return STATIC_IMAGE;
+ case 'video':
+ return STATIC_VIDEO;
+ case 'document':
+ return 'document';
+ }
+}
+
+export function buildPostMessageRequest(
+ snapshot: InputSnapshot,
+ threadId?: string
+): PostMessageRequest {
+ return {
+ content: snapshot.value,
+ thread_id: threadId,
+ mentions: snapshot.mentions.map((mention) => ({
+ entity_id: mention.itemId,
+ entity_type: mention.itemType,
+ })),
+ attachments: snapshot.attachments.map((attachment) => ({
+ entity_id: attachment.id,
+ entity_type: attachmentEntityType(attachment),
+ })),
+ };
+}
diff --git a/js/app/packages/channel/Thread/ChannelThread.tsx b/js/app/packages/channel/Thread/ChannelThread.tsx
index f7dbfa3bc6..61f346c196 100644
--- a/js/app/packages/channel/Thread/ChannelThread.tsx
+++ b/js/app/packages/channel/Thread/ChannelThread.tsx
@@ -78,67 +78,67 @@ export function ChannelThread(props: ThreadProps) {
<Show when={hasReplies() || props.isReplying()}>
<div class="relative w-full">
<Thread.RailDecorations isReplying={props.isReplying} />
- <Thread.RepliesContainer>
- <Show
- when={
- fetchRepliesEnabled() &&
- !repliesQuery.isLoading &&
- hasFetchedReplies()
- }
- fallback={
- <Thread.ReplyList
- replies={previewReplies()}
- getMessageActions={props.getMessageActions}
- />
- }
- >
- <Suspense>
- <Thread.ReplyList
- replies={fetchedReplies()}
- getMessageActions={props.getMessageActions}
- />
- </Suspense>
- </Show>
-
- <Show when={props.isReplying()}>
- <Show when={!hasReplies()}>
- <Thread.ReplyAuthor
- userId={replyUserId()}
- displayName={displayName()}
- />
+ <Suspense>
+ <Thread.RepliesContainer>
+ <Show
+ when={!repliesQuery.isLoading && hasFetchedReplies()}
+ fallback={
+ <Thread.ReplyList
+ threadId={props.data().id}
+ replies={previewReplies()}
+ getMessageActions={props.getMessageActions}
+ />
+ }
+ >
+ <Suspense>
+ <Thread.ReplyList
+ threadId={props.data().id}
+ replies={fetchedReplies()}
+ getMessageActions={props.getMessageActions}
+ />
+ </Suspense>
</Show>
- <Thread.ReplyInput
- channelId={props.channelId()}
- messageId={props.data().id}
- replyInputState={props.replyInputState}
- setReplyInputState={props.setReplyInputState}
- setIsReplying={props.setIsReplying}
- />
- </Show>
- <Show
- when={
- shouldShowCollapsedIndicator() || shouldShowReplyButton()
- }
- >
- <Thread.ActionsFooter>
- <Show when={shouldShowCollapsedIndicator()}>
- <Thread.CollapsedIndicator
- collapsedRepliesCount={collapsedRepliesCount()}
- participants={collapsedReplyUsers()}
- latestReplyAt={collapsedLatestReplyAt()}
- onClick={expand}
+ <Show when={props.isReplying()}>
+ <Show when={!hasReplies()}>
+ <Thread.ReplyAuthor
+ userId={replyUserId()}
+ displayName={displayName()}
/>
</Show>
- <Show when={shouldShowReplyButton()}>
- <Thread.ReplyButton
- onClick={() => props.setIsReplying(true)}
- aria-label="Reply"
- />
- </Show>
- </Thread.ActionsFooter>
- </Show>
- </Thread.RepliesContainer>
+ <Thread.ReplyInput
+ channelId={props.channelId()}
+ messageId={props.data().id}
+ replyInputState={props.replyInputState}
+ setReplyInputState={props.setReplyInputState}
+ setIsReplying={props.setIsReplying}
+ />
+ </Show>
+
+ <Show
+ when={
+ shouldShowCollapsedIndicator() || shouldShowReplyButton()
+ }
+ >
+ <Thread.ActionsFooter>
+ <Show when={shouldShowCollapsedIndicator()}>
+ <Thread.CollapsedIndicator
+ collapsedRepliesCount={collapsedRepliesCount()}
+ participants={collapsedReplyUsers()}
+ latestReplyAt={collapsedLatestReplyAt()}
+ onClick={expand}
+ />
+ </Show>
+ <Show when={shouldShowReplyButton()}>
+ <Thread.ReplyButton
+ onClick={() => props.setIsReplying(true)}
+ aria-label="Reply"
+ />
+ </Show>
+ </Thread.ActionsFooter>
+ </Show>
+ </Thread.RepliesContainer>
+ </Suspense>
</div>
</Show>
</div>
diff --git a/js/app/packages/channel/Thread/ThreadReplyInput.tsx b/js/app/packages/channel/Thread/ThreadReplyInput.tsx
index 7db38be9ef..0e0fdcb252 100644
--- a/js/app/packages/channel/Thread/ThreadReplyInput.tsx
+++ b/js/app/packages/channel/Thread/ThreadReplyInput.tsx
@@ -1,6 +1,9 @@
+import { useUserId } from '@core/context/user';
+import { useSendMessageMutation } from '@queries/channel/message';
import type { Accessor, Setter } from 'solid-js';
import { ChannelInput, createInputAttachmentTracker } from '../Input';
import type { InputSnapshot } from '../Input';
+import { buildPostMessageRequest } from '../Input/message-payload';
import { createEntityDropZone } from '../Channel/create-entity-drop-zone';
import { replyInputOffsetX } from './utils/thread-rail-geometry';
import { ThreadReplyInputConnector } from './ThreadReplyInputConnector';
@@ -18,6 +21,8 @@ type ThreadReplyInputProps = {
};
export function ThreadReplyInput(props: ThreadReplyInputProps) {
+ const userId = useUserId();
+ const sendMessageMutation = useSendMessageMutation();
const tracker = createInputAttachmentTracker({
persistenceKey: makeAttachmentTrackerPersistenceKey({
channelId: props.channelId,
@@ -59,9 +64,18 @@ export function ThreadReplyInput(props: ThreadReplyInputProps) {
props.setReplyInputState(undefined);
props.setIsReplying(false);
}}
- onSend={async () => {
+ onSend={(snapshot) => {
+ const senderId = userId();
+ if (!senderId) return;
+
+ sendMessageMutation.mutate({
+ channelID: props.channelId,
+ senderId,
+ optimisticId: crypto.randomUUID(),
+ message: buildPostMessageRequest(snapshot, props.messageId),
+ });
+
props.setReplyInputState(undefined);
- props.setIsReplying(false);
}}
/>
</div>
diff --git a/js/app/packages/channel/Thread/ThreadReplyList.tsx b/js/app/packages/channel/Thread/ThreadReplyList.tsx
index 7f54633088..97fad7a559 100644
--- a/js/app/packages/channel/Thread/ThreadReplyList.tsx
+++ b/js/app/packages/channel/Thread/ThreadReplyList.tsx
@@ -7,17 +7,25 @@ import {
import type { ApiThreadReply } from '@service-comms/client';
export function ThreadReplyList(props: {
+ threadId: string;
replies: Array<ApiThreadReply>;
getMessageActions?: (message: MessageData) => MessageActions | undefined;
}) {
return (
<For each={props.replies}>
- {(reply) => (
- <ChannelMessage
- message={reply}
- actions={props.getMessageActions?.(reply)}
- />
- )}
+ {(reply) => {
+ const replyMessage = () => ({
+ ...reply,
+ thread_id: props.threadId,
+ });
+
+ return (
+ <ChannelMessage
+ message={reply}
+ actions={props.getMessageActions?.(replyMessage())}
+ />
+ );
+ }}
</For>
);
}
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index 529fe9a40d..a70d449e1b 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -2,18 +2,50 @@ import { throwOnErr } from '@core/util/maybeResult';
import {
commsServiceClient,
type ApiChannelMessage,
+ type ApiThreadReply,
type ChannelMessagesPage,
} from '@service-comms/client';
+import type { Attachment as ApiAttachment } from '@service-comms/generated/models';
import { type InfiniteData, useInfiniteQuery } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
+import type { ApiCountedReaction } from '@service-storage/generated/schemas';
import { queryClient } from '../client';
import { channelKeys } from './keys';
+import {
+ captureThreadPreviewReplySnapshot,
+ insertReplyIntoThreadPreview,
+ removeReplyFromThreadPreview,
+ replaceReplyIdInThreadPreview,
+ replaceReplyReactionsInThreadPreview,
+ restoreReplyToThreadPreview,
+} from './thread-preview';
export type ChannelMessagesData = InfiniteData<
ChannelMessagesPage,
ChannelMessagesPageParam | null
>;
+export type ChannelMessagesQueryKey = ReturnType<
+ typeof channelKeys.messages
+>['queryKey'];
+
+export type IndexedChannelMessages = {
+ items: ApiChannelMessage[];
+ keys: string[];
+ byId: Map<string, ApiChannelMessage>;
+};
+
+export type TopLevelMessageSnapshot = {
+ itemIndex: number;
+ message: ApiChannelMessage;
+ pageIndex: number;
+};
+
+export type ThreadPreviewReplySnapshot = {
+ previewIndex: number;
+ reply: ApiThreadReply;
+};
+
type ChannelMessagesPageParam = {
next_cursor: string | null;
previous_cursor: string | null;
@@ -24,7 +56,7 @@ export function channelMessagesQueryOptions(
loadAroundMessageId: string | null
) {
return {
- queryKey: channelKeys.messages(channelId).queryKey,
+ queryKey: channelKeys.messages(channelId, loadAroundMessageId).queryKey,
queryFn: async ({
pageParam,
}: {
@@ -71,11 +103,399 @@ export function useChannelMessagesQuery(
export function useChannelMessagesWithIndex(channelId: Accessor<string>) {
const query = useChannelMessagesQuery(channelId, () => undefined);
- const byId = createMemo(() => {
- const flat = flattenMessages(query.data as ChannelMessagesData | undefined);
- return new Map(flat.map((m) => [m.id, m]));
+ const index = createMemo(() =>
+ makeMessageIndex(query.data as ChannelMessagesData | undefined)
+ );
+ return {
+ query,
+ index,
+ byId: createMemo(() => index().byId),
+ };
+}
+
+/** Returns the cache key for one channel message query variant. */
+export function getChannelMessagesQueryKey(
+ channelId: string,
+ loadAroundMessageId: string | null = null
+): ChannelMessagesQueryKey {
+ return channelKeys.messages(channelId, loadAroundMessageId).queryKey;
+}
+
+/** Returns the shared prefix for all channel message query variants. */
+export function getChannelMessagesQueryKeyPrefix(channelId: string) {
+ return [...channelKeys.messages._def, channelId];
+}
+
+/** Applies one updater to every cached message variant for a channel. */
+export function setChannelMessagesData(
+ channelId: string,
+ updater: (
+ data: ChannelMessagesData | undefined
+ ) => ChannelMessagesData | undefined
+) {
+ queryClient.setQueriesData<ChannelMessagesData>(
+ { queryKey: getChannelMessagesQueryKeyPrefix(channelId) },
+ updater
+ );
+}
+
+/** Returns all cached message query entries for a channel. */
+export function getChannelMessagesEntries(channelId: string) {
+ return queryClient.getQueriesData<ChannelMessagesData>({
+ queryKey: getChannelMessagesQueryKeyPrefix(channelId),
+ });
+}
+
+function mapChannelMessagesItems(
+ data: ChannelMessagesData,
+ updater: (message: ApiChannelMessage) => ApiChannelMessage
+): ChannelMessagesData {
+ let didChange = false;
+
+ const pages = data.pages.map((page) => {
+ let pageChanged = false;
+ const items = page.items.map((message) => {
+ const nextMessage = updater(message);
+ if (nextMessage !== message) {
+ didChange = true;
+ pageChanged = true;
+ }
+ return nextMessage;
+ });
+
+ return pageChanged ? { ...page, items } : page;
+ });
+
+ return didChange ? { ...data, pages } : data;
+}
+
+function filterChannelMessagesItems(
+ data: ChannelMessagesData,
+ predicate: (message: ApiChannelMessage) => boolean
+): ChannelMessagesData {
+ let didChange = false;
+
+ const pages = data.pages.map((page) => {
+ const items = page.items.filter((message) => {
+ const keep = predicate(message);
+ if (!keep) didChange = true;
+ return keep;
+ });
+
+ return items.length === page.items.length ? page : { ...page, items };
});
- return { query, byId };
+
+ return didChange ? { ...data, pages } : data;
+}
+
+export function insertTopLevelMessageIntoChannelMessages(
+ data: ChannelMessagesData | undefined,
+ message: ApiChannelMessage
+): ChannelMessagesData | undefined {
+ if (!data?.pages.length) return data;
+ if (
+ data.pages.some((page) => page.items.some((item) => item.id === message.id))
+ ) {
+ return data;
+ }
+
+ const [newestPage, ...olderPages] = data.pages;
+
+ return {
+ ...data,
+ pages: [
+ {
+ ...newestPage,
+ items: [message, ...newestPage.items],
+ },
+ ...olderPages,
+ ],
+ };
+}
+
+export function removeTopLevelMessageFromChannelMessages(
+ data: ChannelMessagesData | undefined,
+ messageId: string
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return filterChannelMessagesItems(
+ data,
+ (message) => message.id !== messageId
+ );
+}
+
+export function replaceTopLevelMessageIdInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ optimisticId: string,
+ realId: string
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) =>
+ message.id === optimisticId ? { ...message, id: realId } : message
+ );
+}
+
+export function replaceTopLevelMessageReactionsInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ messageId: string,
+ reactions: ApiCountedReaction[]
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) =>
+ message.id === messageId ? { ...message, reactions } : message
+ );
+}
+
+/** Replaces attachments on a top-level message in paginated channel caches. */
+export function replaceTopLevelMessageAttachmentsInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ messageId: string,
+ attachments: ApiAttachment[]
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) =>
+ message.id === messageId ? { ...message, attachments } : message
+ );
+}
+
+export function getTopLevelMessageSnapshot(
+ data: ChannelMessagesData | undefined,
+ messageId: string
+): TopLevelMessageSnapshot | undefined {
+ if (!data) return;
+
+ for (const [pageIndex, page] of data.pages.entries()) {
+ const itemIndex = page.items.findIndex(
+ (message) => message.id === messageId
+ );
+ if (itemIndex === -1) continue;
+ return {
+ pageIndex,
+ itemIndex,
+ message: page.items[itemIndex],
+ };
+ }
+}
+
+export function restoreTopLevelMessageInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ snapshot: TopLevelMessageSnapshot
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+ if (
+ data.pages.some((page) =>
+ page.items.some((message) => message.id === snapshot.message.id)
+ )
+ ) {
+ return data;
+ }
+
+ const page = data.pages[snapshot.pageIndex];
+ if (!page) return data;
+
+ const items = [...page.items];
+ items.splice(snapshot.itemIndex, 0, snapshot.message);
+
+ const pages = [...data.pages];
+ pages[snapshot.pageIndex] = {
+ ...page,
+ items,
+ };
+
+ return {
+ ...data,
+ pages,
+ };
+}
+
+export function insertThreadReplyIntoChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ reply: ApiThreadReply
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ const thread = insertReplyIntoThreadPreview(message.thread, reply);
+ return thread === message.thread ? message : { ...message, thread };
+ });
+}
+
+export function removeThreadReplyFromChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ replyId: string
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ const thread = removeReplyFromThreadPreview(message.thread, replyId);
+ return thread === message.thread ? message : { ...message, thread };
+ });
+}
+
+export function replaceThreadReplyIdInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ optimisticId: string,
+ realId: string
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ const thread = replaceReplyIdInThreadPreview(
+ message.thread,
+ optimisticId,
+ realId
+ );
+ return thread === message.thread ? message : { ...message, thread };
+ });
+}
+
+export function replaceThreadReplyReactionsInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ replyId: string,
+ reactions: ApiCountedReaction[]
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ const thread = replaceReplyReactionsInThreadPreview(
+ message.thread,
+ replyId,
+ reactions
+ );
+ return thread === message.thread ? message : { ...message, thread };
+ });
+}
+
+/** Replaces attachments on a thread preview reply in paginated channel caches. */
+export function replaceThreadReplyAttachmentsInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ replyId: string,
+ attachments: ApiAttachment[]
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ let didChange = false;
+ const preview = message.thread.preview.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return { ...reply, attachments };
+ });
+
+ if (!didChange) return message;
+
+ return {
+ ...message,
+ thread: {
+ ...message.thread,
+ preview,
+ },
+ };
+ });
+}
+
+export function getThreadPreviewReplySnapshot(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ replyId: string
+): ThreadPreviewReplySnapshot | undefined {
+ if (!data) return;
+
+ for (const page of data.pages) {
+ const thread = page.items.find(
+ (message) => message.id === threadId
+ )?.thread;
+ if (!thread) continue;
+ const snapshot = captureThreadPreviewReplySnapshot(thread, replyId);
+ if (snapshot) return snapshot;
+ }
+}
+
+export function restoreThreadPreviewReplyInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ snapshot?: ThreadPreviewReplySnapshot,
+ replyCreatedAt?: string
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ const thread = restoreReplyToThreadPreview(
+ message.thread,
+ snapshot,
+ replyCreatedAt
+ );
+ return thread === message.thread ? message : { ...message, thread };
+ });
+}
+
+/** Finds a top-level message across all cached variants for a channel. */
+export function findTopLevelMessageInChannelMessages(
+ channelId: string,
+ messageId: string
+): ApiChannelMessage | undefined {
+ for (const [, data] of getChannelMessagesEntries(channelId)) {
+ if (!data) continue;
+ for (const page of data.pages) {
+ const message = page.items.find((item) => item.id === messageId);
+ if (message) return message;
+ }
+ }
+}
+
+/** Finds a reply's parent thread id from cached channel messages. */
+export function findThreadIdInChannelMessages(
+ channelId: string,
+ replyId: string
+): string | undefined {
+ for (const [, data] of getChannelMessagesEntries(channelId)) {
+ if (!data) continue;
+ for (const page of data.pages) {
+ for (const message of page.items) {
+ if (message.thread.preview.some((reply) => reply.id === replyId)) {
+ return message.id;
+ }
+ }
+ }
+ }
+}
+
+/** Finds a top-level rollback snapshot across cached message variants. */
+export function findTopLevelMessageSnapshotInChannelMessages(
+ channelId: string,
+ messageId: string
+): TopLevelMessageSnapshot | undefined {
+ for (const [, data] of getChannelMessagesEntries(channelId)) {
+ const snapshot = getTopLevelMessageSnapshot(data, messageId);
+ if (snapshot) return snapshot;
+ }
+}
+
+/** Finds a thread preview rollback snapshot across cached message variants. */
+export function findThreadPreviewReplySnapshotInChannelMessages(
+ channelId: string,
+ threadId: string,
+ replyId: string
+): ThreadPreviewReplySnapshot | undefined {
+ for (const [, data] of getChannelMessagesEntries(channelId)) {
+ const snapshot = getThreadPreviewReplySnapshot(data, threadId, replyId);
+ if (snapshot) return snapshot;
+ }
}
/**
@@ -83,26 +503,34 @@ export function useChannelMessagesWithIndex(channelId: Accessor<string>) {
*/
export function softInvalidateChannelMessages(channelId: string) {
queryClient.invalidateQueries({
- queryKey: channelKeys.messages(channelId).queryKey,
+ queryKey: getChannelMessagesQueryKeyPrefix(channelId),
refetchType: 'inactive',
});
}
/**
- * Flatten all pages into a single oldest-first array for display.
+ * Build a single oldest-first message index for display and lookup.
* Pages arrive newest-first, items within each page are newest-first,
- * so we reverse both layers.
+ * so we reverse both layers in one pass.
*/
-export function flattenMessages(
+export function makeMessageIndex(
data: ChannelMessagesData | undefined
-): ApiChannelMessage[] {
- if (!data?.pages?.length) return [];
- const all: ApiChannelMessage[] = [];
+): IndexedChannelMessages {
+ const items: ApiChannelMessage[] = [];
+ const keys: string[] = [];
+ const byId = new Map<string, ApiChannelMessage>();
+
+ if (!data?.pages?.length) return { items, keys, byId };
+
for (let i = data.pages.length - 1; i >= 0; i--) {
- const items = data.pages[i].items;
- for (let j = items.length - 1; j >= 0; j--) {
- all.push(items[j]);
+ const pageItems = data.pages[i].items;
+ for (let j = pageItems.length - 1; j >= 0; j--) {
+ const message = pageItems[j];
+ items.push(message);
+ keys.push(message.id);
+ byId.set(message.id, message);
}
}
- return all;
+
+ return { items, keys, byId };
}
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
index 13704f8779..0d44a887de 100644
--- a/js/app/packages/queries/channel/keys.ts
+++ b/js/app/packages/queries/channel/keys.ts
@@ -7,8 +7,8 @@ export const channelKeys = createQueryKeys('channel', {
mentions: (channelID: string) => ({
queryKey: [channelID],
}),
- messages: (channelID: string) => ({
- queryKey: [channelID],
+ messages: (channelID: string, loadAroundMessageId: string | null = null) => ({
+ queryKey: [channelID, { loadAroundMessageId }],
}),
attachments: (channelID: string) => ({
queryKey: [channelID],
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index b101f54ea3..4f93f445e6 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -1,11 +1,14 @@
import { TrackingEvents, withAnalytics } from '@coparse/analytics';
import { toast } from '@core/component/Toast/Toast';
+import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import type { DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/maybeResult';
import { softInvalidateChannelWithID } from '@queries/channel/channel';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
+ type ApiChannelMessage,
+ type ApiThreadReply,
type IdResponse,
type MessageResponse,
} from '@service-comms/client';
@@ -19,6 +22,16 @@ import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { channelKeys, ChannelNonceKeys } from './keys';
import { createMutationNonce, registerNonce } from '../nonce';
+import {
+ captureDeleteSnapshotForTarget,
+ insertMessageIntoTargetCaches,
+ removeMessageFromTargetCaches,
+ restoreMessageInTargetCaches,
+ softInvalidateTargetCaches,
+ replaceTargetMessageId,
+ resolveMessageTarget,
+ type DeleteTargetSnapshot,
+} from './reconcile';
/**
* Register nonces for both message and attachment deduplication.
@@ -40,12 +53,15 @@ type WithSenderId<T> = T & { senderId: string };
export type InsertMessageContext = {
optimisticId: string;
+ target: ReturnType<typeof resolveMessageTarget>;
};
export type DeleteMessageContext = {
- deletedMessage: Message;
+ deletedMessage?: Message;
deletedReactions: CountedReaction[];
deletedAttachments: Attachment[];
+ target: ReturnType<typeof resolveMessageTarget>;
+ targetSnapshot?: DeleteTargetSnapshot;
};
export type UpdateMessageContext = {
@@ -55,6 +71,76 @@ export type UpdateMessageContext = {
previousUpdatedAt: DateValue;
};
+function makeOptimisticAttachments(
+ channelId: string,
+ optimisticId: string,
+ attachments: PostMessageRequest['attachments'],
+ now: string
+): Attachment[] {
+ return attachments.map((attachment) => ({
+ id: crypto.randomUUID(),
+ channel_id: channelId,
+ created_at: now,
+ message_id: optimisticId,
+ ...attachment,
+ }));
+}
+
+function makeOptimisticTopLevelMessage(
+ vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>,
+ attachments: Attachment[],
+ now: string
+): ApiChannelMessage {
+ return {
+ id: vars.optimisticId,
+ channel_id: vars.channelId,
+ sender_id: vars.senderId,
+ content: vars.content,
+ created_at: now,
+ updated_at: now,
+ deleted_at: undefined,
+ edited_at: undefined,
+ attachments: attachments.map(
+ ({ id, entity_id, entity_type, created_at }) => ({
+ id,
+ entity_id,
+ entity_type,
+ created_at,
+ })
+ ),
+ reactions: [],
+ thread: {
+ preview: [],
+ reply_count: 0,
+ latest_reply_at: null,
+ },
+ };
+}
+
+function makeOptimisticThreadReply(
+ vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>,
+ attachments: Attachment[],
+ now: string
+): ApiThreadReply {
+ return {
+ id: vars.optimisticId,
+ sender_id: vars.senderId,
+ content: vars.content,
+ created_at: now,
+ updated_at: now,
+ edited_at: undefined,
+ attachments: attachments.map(
+ ({ id, entity_id, entity_type, created_at }) => ({
+ id,
+ entity_id,
+ entity_type,
+ created_at,
+ })
+ ),
+ reactions: [],
+ };
+}
+
/**
* Optimistically insert a new message into the channel cache.
* Returns minimal context for rollback (just the optimistic ID).
@@ -65,16 +151,29 @@ export function optimisticInsertChannelMessage(
const queryKey = channelKeys.withID(vars.channelId).queryKey;
queryClient.cancelQueries({ queryKey });
- let context: InsertMessageContext | undefined;
+ const now = new Date().toISOString();
+ const newAttachments = makeOptimisticAttachments(
+ vars.channelId,
+ vars.optimisticId,
+ vars.attachments,
+ now
+ );
+ const threadId = vars.thread_id ?? undefined;
+ const target = resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.optimisticId,
+ threadId,
+ });
+ const context: InsertMessageContext = {
+ optimisticId: vars.optimisticId,
+ target,
+ };
queryClient.setQueriesData(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
- context = { optimisticId: vars.optimisticId };
- const now = new Date().toISOString();
-
const newMessage: Message = {
id: vars.optimisticId,
channel_id: vars.channelId,
@@ -87,14 +186,6 @@ export function optimisticInsertChannelMessage(
edited_at: undefined,
};
- const newAttachments: Attachment[] = vars.attachments.map((a) => ({
- id: crypto.randomUUID(),
- channel_id: vars.channelId,
- created_at: new Date().toISOString(),
- message_id: vars.optimisticId,
- ...a,
- }));
-
return {
...prev,
messages: [...prev.messages, newMessage],
@@ -103,6 +194,24 @@ export function optimisticInsertChannelMessage(
}
);
+ if (ENABLE_NEW_CHANNELS) {
+ if (target.kind === 'thread_reply') {
+ const optimisticReply = makeOptimisticThreadReply(
+ vars,
+ newAttachments,
+ now
+ );
+ insertMessageIntoTargetCaches(vars.channelId, target, optimisticReply);
+ } else {
+ const optimisticMessage = makeOptimisticTopLevelMessage(
+ vars,
+ newAttachments,
+ now
+ );
+ insertMessageIntoTargetCaches(vars.channelId, target, optimisticMessage);
+ }
+ }
+
return context;
}
@@ -129,6 +238,10 @@ export function rollbackInsertChannelMessage(
};
}
);
+
+ if (ENABLE_NEW_CHANNELS) {
+ removeMessageFromTargetCaches(channelId, context.target);
+ }
}
/**
@@ -136,7 +249,11 @@ export function rollbackInsertChannelMessage(
* Called in mutation onSuccess after server returns the real message.
*/
export function replaceOptimisticMessage(
- vars: WithChannelId<{ optimisticId: string; realId: string }>
+ vars: WithChannelId<{
+ optimisticId: string;
+ realId: string;
+ threadId?: string;
+ }>
): void {
const queryKey = channelKeys.withID(vars.channelId).queryKey;
@@ -168,6 +285,18 @@ export function replaceOptimisticMessage(
};
}
);
+
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetMessageId(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.optimisticId,
+ threadId: vars.threadId,
+ }),
+ vars.realId
+ );
+ }
}
/**
@@ -175,12 +304,23 @@ export function replaceOptimisticMessage(
* Returns minimal context: only the deleted message, reactions, and attachments.
*/
export function optimisticDeleteChannelMessage(
- vars: WithChannelId<Pick<ChannelMessage, 'message_id'>>
+ vars: WithChannelId<
+ Pick<ChannelMessage, 'message_id'> & { threadId?: string }
+ >
): DeleteMessageContext | undefined {
const queryKey = channelKeys.withID(vars.channelId).queryKey;
queryClient.cancelQueries({ queryKey });
- let context: DeleteMessageContext | undefined;
+ const target = resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.message_id,
+ threadId: vars.threadId,
+ });
+ const context: DeleteMessageContext = {
+ deletedReactions: [],
+ deletedAttachments: [],
+ target,
+ };
queryClient.setQueriesData(
{ queryKey },
@@ -192,13 +332,11 @@ export function optimisticDeleteChannelMessage(
);
if (!deletedMessage) return prev;
- context = {
- deletedMessage,
- deletedReactions: prev.reactions[vars.message_id] ?? [],
- deletedAttachments: prev.attachments.filter(
- (a) => a.message_id === vars.message_id
- ),
- };
+ context.deletedMessage = deletedMessage;
+ context.deletedReactions = prev.reactions[vars.message_id] ?? [];
+ context.deletedAttachments = prev.attachments.filter(
+ (a) => a.message_id === vars.message_id
+ );
const filteredMessages = prev.messages.filter(
(m) => m.id !== vars.message_id
@@ -222,6 +360,14 @@ export function optimisticDeleteChannelMessage(
}
);
+ if (ENABLE_NEW_CHANNELS) {
+ context.targetSnapshot = captureDeleteSnapshotForTarget(
+ vars.channelId,
+ target
+ );
+ removeMessageFromTargetCaches(vars.channelId, target);
+ }
+
return context;
}
@@ -238,6 +384,7 @@ export function rollbackDeleteChannelMessage(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
+ if (!context.deletedMessage) return prev;
return {
...prev,
@@ -252,6 +399,14 @@ export function rollbackDeleteChannelMessage(
};
}
);
+
+ if (ENABLE_NEW_CHANNELS && context.targetSnapshot) {
+ restoreMessageInTargetCaches(
+ channelId,
+ context.target,
+ context.targetSnapshot
+ );
+ }
}
/**
@@ -365,7 +520,10 @@ export function useSendMessageMutation(
},
...withCallbacks<IdResponse, Error, SendMessageParams, SendMessageContext>(
{
- onMutate: (vars) => {
+ onMutate: async (vars) => {
+ await queryClient.cancelQueries({
+ queryKey: channelKeys.withID(vars.channelID).queryKey,
+ });
// Register nonces for deduplication when WebSocket events arrive
registerMessageNonces(
vars.optimisticId,
@@ -383,6 +541,7 @@ export function useSendMessageMutation(
channelId: variables.channelID,
optimisticId: variables.optimisticId,
realId: data.id,
+ threadId: variables.message.thread_id ?? undefined,
});
track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
channelId: variables.channelID,
@@ -400,6 +559,16 @@ export function useSendMessageMutation(
},
onSettled: (_data, _error, variables) => {
softInvalidateChannelWithID(variables.channelID);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ variables.channelID,
+ resolveMessageTarget({
+ channelId: variables.channelID,
+ messageId: variables.optimisticId,
+ threadId: variables.message.thread_id ?? undefined,
+ })
+ );
+ }
},
},
callbacks
@@ -407,7 +576,11 @@ export function useSendMessageMutation(
}));
}
-type DeleteMessageParams = { channelID: string; messageID: string };
+type DeleteMessageParams = {
+ channelID: string;
+ messageID: string;
+ threadID?: string;
+};
type DeleteMutationContext = DeleteMessageContext | undefined;
@@ -441,11 +614,15 @@ export function useDeleteMessageMutation(
},
...withCallbacks<void, Error, DeleteMessageParams, DeleteMutationContext>(
{
- onMutate: (vars) => {
+ onMutate: async (vars) => {
+ await queryClient.cancelQueries({
+ queryKey: channelKeys.withID(vars.channelID).queryKey,
+ });
deleteNonce.prepare(vars);
return optimisticDeleteChannelMessage({
channelId: vars.channelID,
message_id: vars.messageID,
+ threadId: vars.threadID,
});
},
onError(error, vars, context) {
@@ -458,6 +635,16 @@ export function useDeleteMessageMutation(
onSettled: (_data, _error, vars) => {
deleteNonce.cleanup(vars);
softInvalidateChannelWithID(vars.channelID);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ vars.channelID,
+ resolveMessageTarget({
+ channelId: vars.channelID,
+ messageId: vars.messageID,
+ threadId: vars.threadID,
+ })
+ );
+ }
},
},
callbacks
diff --git a/js/app/packages/queries/channel/reaction.ts b/js/app/packages/queries/channel/reaction.ts
index 522c7d5440..4236f90419 100644
--- a/js/app/packages/queries/channel/reaction.ts
+++ b/js/app/packages/queries/channel/reaction.ts
@@ -1,4 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
+import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/maybeResult';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
@@ -12,73 +13,158 @@ import { queryClient } from '../client';
import { softInvalidateChannelWithID } from './channel';
import { channelKeys, ChannelNonceKeys } from './keys';
import { createMutationNonce } from '../nonce';
+import {
+ replaceTargetReactions,
+ softInvalidateTargetCaches,
+ resolveMessageTarget,
+ type MessageTarget,
+} from './reconcile';
type WithChannelId<T> = T & { channelId: string };
type WithUserId<T> = T & { userId: string };
+type ReactionList = GetChannelResponse['reactions'][string];
+type WithReactionState<T> = T & {
+ currentReactions?: ReactionList;
+ threadId?: string;
+};
+
export type AddReactionContext = {
messageId: string;
emoji: string;
userId: string;
- wasNewReaction: boolean;
+ previousReactions: ReactionList;
+ target: MessageTarget;
};
export type RemoveReactionContext = {
messageId: string;
emoji: string;
userId: string;
- wasLastUser: boolean;
+ previousReactions: ReactionList;
+ target: MessageTarget;
};
+function addUserReaction(
+ reactions: ReactionList | undefined,
+ emoji: string,
+ userId: string
+) {
+ const messageReactions = reactions ?? [];
+ const existing = messageReactions.find(
+ (reaction) => reaction.emoji === emoji
+ );
+
+ if (existing?.users.includes(userId)) {
+ return {
+ reactions: messageReactions,
+ didChange: false,
+ wasNewReaction: false,
+ };
+ }
+
+ return {
+ reactions: existing
+ ? messageReactions.map((reaction) =>
+ reaction.emoji === emoji
+ ? { ...reaction, users: [...reaction.users, userId] }
+ : reaction
+ )
+ : [...messageReactions, { emoji, users: [userId] }],
+ didChange: true,
+ wasNewReaction: !existing,
+ };
+}
+
+function removeUserReaction(
+ reactions: ReactionList | undefined,
+ emoji: string,
+ userId: string
+) {
+ const messageReactions = reactions ?? [];
+ const existing = messageReactions.find(
+ (reaction) => reaction.emoji === emoji
+ );
+
+ if (!existing?.users.includes(userId)) {
+ return {
+ reactions: messageReactions,
+ didChange: false,
+ wasLastUser: false,
+ };
+ }
+
+ return {
+ reactions: messageReactions
+ .map((reaction) =>
+ reaction.emoji === emoji
+ ? {
+ ...reaction,
+ users: reaction.users.filter(
+ (existingUserId) => existingUserId !== userId
+ ),
+ }
+ : reaction
+ )
+ .filter((reaction) => reaction.users.length > 0),
+ didChange: true,
+ wasLastUser: existing.users.length === 1,
+ };
+}
+
/**
* Optimistically add a reaction to a message.
* Returns minimal context for rollback.
*/
export function optimisticAddReaction(
vars: WithChannelId<
- WithUserId<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ WithUserId<
+ WithReactionState<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ >
>
): AddReactionContext | undefined {
const queryKey = channelKeys.withID(vars.channelId).queryKey;
queryClient.cancelQueries({ queryKey });
-
- let context: AddReactionContext | undefined;
+ const fallbackChannelData =
+ queryClient.getQueryData<GetChannelResponse>(queryKey);
+ const currentReactions =
+ vars.currentReactions ?? fallbackChannelData?.reactions[vars.message_id];
+ const target = resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.message_id,
+ threadId: vars.threadId,
+ });
+
+ const result = addUserReaction(currentReactions, vars.emoji, vars.userId);
+ if (!result.didChange) return;
+
+ const context: AddReactionContext = {
+ messageId: vars.message_id,
+ emoji: vars.emoji,
+ userId: vars.userId,
+ previousReactions: currentReactions ?? [],
+ target,
+ };
queryClient.setQueriesData(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
- const messageReactions = prev.reactions[vars.message_id] ?? [];
- const existing = messageReactions.find((r) => r.emoji === vars.emoji);
-
- if (existing?.users.includes(vars.userId)) return prev;
-
- context = {
- messageId: vars.message_id,
- emoji: vars.emoji,
- userId: vars.userId,
- wasNewReaction: !existing,
- };
-
- const updatedMessageReactions = existing
- ? messageReactions.map((r) =>
- r.emoji === vars.emoji
- ? { ...r, users: [...r.users, vars.userId] }
- : r
- )
- : [...messageReactions, { emoji: vars.emoji, users: [vars.userId] }];
-
return {
...prev,
reactions: {
...prev.reactions,
- [vars.message_id]: updatedMessageReactions,
+ [vars.message_id]: result.reactions,
},
};
}
);
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetReactions(vars.channelId, context.target, result.reactions);
+ }
+
return context;
}
@@ -95,35 +181,28 @@ export function rollbackAddReaction(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
-
- const messageReactions = prev.reactions[context.messageId];
- if (!messageReactions) return prev;
-
- if (context.wasNewReaction) {
- const updated = messageReactions.filter(
- (r) => r.emoji !== context.emoji
- );
- if (updated.length === 0) {
- const { [context.messageId]: _, ...rest } = prev.reactions;
- return { ...prev, reactions: rest };
- }
- return {
- ...prev,
- reactions: { ...prev.reactions, [context.messageId]: updated },
- };
- } else {
- const updated = messageReactions.map((r) =>
- r.emoji === context.emoji
- ? { ...r, users: r.users.filter((id) => id !== context.userId) }
- : r
- );
- return {
- ...prev,
- reactions: { ...prev.reactions, [context.messageId]: updated },
- };
+ if (context.previousReactions.length === 0) {
+ const { [context.messageId]: _, ...rest } = prev.reactions;
+ return { ...prev, reactions: rest };
}
+
+ return {
+ ...prev,
+ reactions: {
+ ...prev.reactions,
+ [context.messageId]: context.previousReactions,
+ },
+ };
}
);
+
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetReactions(
+ channelId,
+ context.target,
+ context.previousReactions
+ );
+ }
}
/**
@@ -132,50 +211,55 @@ export function rollbackAddReaction(
*/
export function optimisticRemoveReaction(
vars: WithChannelId<
- WithUserId<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ WithUserId<
+ WithReactionState<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ >
>
): RemoveReactionContext | undefined {
const queryKey = channelKeys.withID(vars.channelId).queryKey;
queryClient.cancelQueries({ queryKey });
-
- let context: RemoveReactionContext | undefined;
+ const fallbackChannelData =
+ queryClient.getQueryData<GetChannelResponse>(queryKey);
+ const currentReactions =
+ vars.currentReactions ?? fallbackChannelData?.reactions[vars.message_id];
+ const target = resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.message_id,
+ threadId: vars.threadId,
+ });
+
+ const result = removeUserReaction(currentReactions, vars.emoji, vars.userId);
+ if (!result.didChange) return;
+
+ const context: RemoveReactionContext = {
+ messageId: vars.message_id,
+ emoji: vars.emoji,
+ userId: vars.userId,
+ previousReactions: currentReactions ?? [],
+ target,
+ };
queryClient.setQueriesData(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
- const messageReactions = prev.reactions[vars.message_id];
- const existing = messageReactions?.find((r) => r.emoji === vars.emoji);
- if (!existing?.users.includes(vars.userId)) return prev;
-
- context = {
- messageId: vars.message_id,
- emoji: vars.emoji,
- userId: vars.userId,
- wasLastUser: existing.users.length === 1,
- };
-
- const updated = messageReactions
- .map((r) =>
- r.emoji === vars.emoji
- ? { ...r, users: r.users.filter((id) => id !== vars.userId) }
- : r
- )
- .filter((r) => r.users.length > 0);
-
- if (updated.length === 0) {
+ if (result.reactions.length === 0) {
const { [vars.message_id]: _, ...rest } = prev.reactions;
return { ...prev, reactions: rest };
}
return {
...prev,
- reactions: { ...prev.reactions, [vars.message_id]: updated },
+ reactions: { ...prev.reactions, [vars.message_id]: result.reactions },
};
}
);
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetReactions(vars.channelId, context.target, result.reactions);
+ }
+
return context;
}
@@ -192,35 +276,30 @@ export function rollbackRemoveReaction(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
-
- const messageReactions = prev.reactions[context.messageId] ?? [];
-
- const existing = messageReactions.find((r) => r.emoji === context.emoji);
-
- if (existing) {
- const updated = messageReactions.map((r) =>
- r.emoji === context.emoji
- ? { ...r, users: [...r.users, context.userId] }
- : r
- );
- return {
- ...prev,
- reactions: { ...prev.reactions, [context.messageId]: updated },
- };
- }
-
return {
...prev,
- reactions: {
- ...prev.reactions,
- [context.messageId]: [
- ...messageReactions,
- { emoji: context.emoji, users: [context.userId] },
- ],
- },
+ reactions:
+ context.previousReactions.length === 0
+ ? Object.fromEntries(
+ Object.entries(prev.reactions).filter(
+ ([messageId]) => messageId !== context.messageId
+ )
+ )
+ : {
+ ...prev.reactions,
+ [context.messageId]: context.previousReactions,
+ },
};
}
);
+
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetReactions(
+ channelId,
+ context.target,
+ context.previousReactions
+ );
+ }
}
type ReactionParams = {
@@ -228,6 +307,8 @@ type ReactionParams = {
messageId: string;
emoji: string;
userId: string;
+ currentReactions?: ReactionList;
+ threadId?: string;
};
type AddReactionMutationContext = AddReactionContext | undefined;
@@ -275,13 +356,18 @@ export function useAddReactionMutation(
AddReactionMutationContext
>(
{
- onMutate: (vars) => {
+ onMutate: async (vars) => {
+ await queryClient.cancelQueries({
+ queryKey: channelKeys.withID(vars.channelId).queryKey,
+ });
addReactionNonce.prepare(vars);
return optimisticAddReaction({
channelId: vars.channelId,
message_id: vars.messageId,
emoji: vars.emoji,
userId: vars.userId,
+ currentReactions: vars.currentReactions,
+ threadId: vars.threadId,
});
},
onError(error, vars, context) {
@@ -294,6 +380,16 @@ export function useAddReactionMutation(
onSettled: (_, __, vars) => {
addReactionNonce.cleanup(vars);
softInvalidateChannelWithID(vars.channelId);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.messageId,
+ threadId: vars.threadId,
+ })
+ );
+ }
},
},
callbacks
@@ -333,13 +429,18 @@ export function useRemoveReactionMutation(
RemoveReactionMutationContext
>(
{
- onMutate: (vars) => {
+ onMutate: async (vars) => {
+ await queryClient.cancelQueries({
+ queryKey: channelKeys.withID(vars.channelId).queryKey,
+ });
removeReactionNonce.prepare(vars);
return optimisticRemoveReaction({
channelId: vars.channelId,
message_id: vars.messageId,
emoji: vars.emoji,
userId: vars.userId,
+ currentReactions: vars.currentReactions,
+ threadId: vars.threadId,
});
},
onError(error, vars, context) {
@@ -352,6 +453,16 @@ export function useRemoveReactionMutation(
onSettled: (_, __, vars) => {
removeReactionNonce.cleanup(vars);
softInvalidateChannelWithID(vars.channelId);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.messageId,
+ threadId: vars.threadId,
+ })
+ );
+ }
},
},
callbacks
diff --git a/js/app/packages/queries/channel/reconcile.ts b/js/app/packages/queries/channel/reconcile.ts
new file mode 100644
index 0000000000..43152aaedd
--- /dev/null
+++ b/js/app/packages/queries/channel/reconcile.ts
@@ -0,0 +1,353 @@
+import {
+ findThreadIdInChannelMessages,
+ findThreadPreviewReplySnapshotInChannelMessages,
+ findTopLevelMessageSnapshotInChannelMessages,
+ insertThreadReplyIntoChannelMessages,
+ insertTopLevelMessageIntoChannelMessages,
+ removeThreadReplyFromChannelMessages,
+ removeTopLevelMessageFromChannelMessages,
+ restoreThreadPreviewReplyInChannelMessages,
+ restoreTopLevelMessageInChannelMessages,
+ replaceThreadReplyIdInChannelMessages,
+ replaceThreadReplyReactionsInChannelMessages,
+ replaceThreadReplyAttachmentsInChannelMessages,
+ replaceTopLevelMessageIdInChannelMessages,
+ replaceTopLevelMessageReactionsInChannelMessages,
+ replaceTopLevelMessageAttachmentsInChannelMessages,
+ setChannelMessagesData,
+ softInvalidateChannelMessages,
+ type ThreadPreviewReplySnapshot,
+ type TopLevelMessageSnapshot,
+} from './channel-messages';
+import {
+ getThreadRepliesEntries,
+ getThreadRepliesQueryKey,
+ getThreadReplySnapshot,
+ insertThreadReply,
+ removeThreadReply,
+ restoreThreadReply,
+ replaceThreadReplyId,
+ replaceThreadReplyReactions,
+ replaceThreadReplyAttachments,
+ softInvalidateThreadReplies,
+ type ThreadReplySnapshot,
+} from './thread-replies';
+import type { ApiChannelMessage, ApiThreadReply } from '@service-comms/client';
+import type {
+ Attachment as ApiAttachment,
+ CountedReaction,
+} from '@service-comms/generated/models';
+import type { GetChannelResponse } from './types';
+import { queryClient } from '../client';
+import { channelKeys } from './keys';
+
+export type MessageTarget =
+ | {
+ kind: 'top_level';
+ messageId: string;
+ }
+ | {
+ kind: 'thread_reply';
+ messageId: string;
+ threadId: string;
+ };
+
+export type DeleteTargetSnapshot =
+ | {
+ kind: 'top_level';
+ message?: TopLevelMessageSnapshot;
+ }
+ | {
+ kind: 'thread_reply';
+ reply?: ThreadReplySnapshot;
+ preview?: ThreadPreviewReplySnapshot;
+ };
+
+export function makeMessageTarget(args: {
+ messageId: string;
+ threadId?: string;
+}): MessageTarget {
+ if (args.threadId) {
+ return {
+ kind: 'thread_reply',
+ messageId: args.messageId,
+ threadId: args.threadId,
+ };
+ }
+
+ return {
+ kind: 'top_level',
+ messageId: args.messageId,
+ };
+}
+
+function getCachedChannel(channelId: string): GetChannelResponse | undefined {
+ return queryClient.getQueryData<GetChannelResponse>(
+ channelKeys.withID(channelId).queryKey
+ );
+}
+
+/** Finds a reply's parent thread id from cached channel data. */
+export function findThreadIdForMessage(
+ channelId: string,
+ messageId: string
+): string | undefined {
+ const directThreadId = findThreadIdInChannelMessages(channelId, messageId);
+ if (directThreadId) return directThreadId;
+
+ for (const [queryKey, replies] of getThreadRepliesEntries(channelId)) {
+ if (!replies?.some((reply) => reply.id === messageId)) continue;
+ return queryKey.at(-1) as string | undefined;
+ }
+
+ return (
+ getCachedChannel(channelId)?.messages.find(
+ (message) => message.id === messageId
+ )?.thread_id ?? undefined
+ );
+}
+
+/** Resolves whether a message target is top-level or a thread reply. */
+export function resolveMessageTarget(args: {
+ channelId: string;
+ messageId: string;
+ threadId?: string;
+}): MessageTarget {
+ if (args.threadId) {
+ return makeMessageTarget({
+ messageId: args.messageId,
+ threadId: args.threadId,
+ });
+ }
+
+ const threadId = findThreadIdForMessage(args.channelId, args.messageId);
+ if (threadId) {
+ return makeMessageTarget({
+ messageId: args.messageId,
+ threadId,
+ });
+ }
+
+ return makeMessageTarget({
+ messageId: args.messageId,
+ });
+}
+
+/** Inserts a message into the rendered caches for its target. */
+export function insertMessageIntoTargetCaches(
+ channelId: string,
+ target: MessageTarget,
+ payload: ApiChannelMessage | ApiThreadReply
+) {
+ if (target.kind === 'thread_reply') {
+ setChannelMessagesData(channelId, (prev) =>
+ insertThreadReplyIntoChannelMessages(
+ prev,
+ target.threadId,
+ payload as ApiThreadReply
+ )
+ );
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) => insertThreadReply(prev, payload as ApiThreadReply)
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ insertTopLevelMessageIntoChannelMessages(prev, payload as ApiChannelMessage)
+ );
+}
+
+/** Removes a message from the rendered caches for its target. */
+export function removeMessageFromTargetCaches(
+ channelId: string,
+ target: MessageTarget
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) => removeThreadReply(prev, target.messageId)
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ removeThreadReplyFromChannelMessages(
+ prev,
+ target.threadId,
+ target.messageId
+ )
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ removeTopLevelMessageFromChannelMessages(prev, target.messageId)
+ );
+}
+
+/** Captures rollback snapshots for a target before optimistic delete. */
+export function captureDeleteSnapshotForTarget(
+ channelId: string,
+ target: MessageTarget
+): DeleteTargetSnapshot {
+ if (target.kind === 'thread_reply') {
+ return {
+ kind: 'thread_reply',
+ reply: getThreadReplySnapshot(
+ queryClient.getQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId)
+ ),
+ target.messageId
+ ),
+ preview: findThreadPreviewReplySnapshotInChannelMessages(
+ channelId,
+ target.threadId,
+ target.messageId
+ ),
+ };
+ }
+
+ return {
+ kind: 'top_level',
+ message: findTopLevelMessageSnapshotInChannelMessages(
+ channelId,
+ target.messageId
+ ),
+ };
+}
+
+/** Restores a previously captured target snapshot into rendered caches. */
+export function restoreMessageInTargetCaches(
+ channelId: string,
+ target: MessageTarget,
+ snapshot: DeleteTargetSnapshot
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) =>
+ snapshot.kind === 'thread_reply' && snapshot.reply
+ ? restoreThreadReply(prev, snapshot.reply)
+ : prev
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ snapshot.kind === 'thread_reply'
+ ? restoreThreadPreviewReplyInChannelMessages(
+ prev,
+ target.threadId,
+ snapshot.preview,
+ snapshot.reply?.reply.created_at ??
+ snapshot.preview?.reply.created_at
+ )
+ : prev
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ snapshot.kind === 'top_level' && snapshot.message
+ ? restoreTopLevelMessageInChannelMessages(prev, snapshot.message)
+ : prev
+ );
+}
+
+/** Replaces a target message id across all rendered caches. */
+export function replaceTargetMessageId(
+ channelId: string,
+ target: MessageTarget,
+ realId: string
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) => replaceThreadReplyId(prev, target.messageId, realId)
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ replaceThreadReplyIdInChannelMessages(
+ prev,
+ target.threadId,
+ target.messageId,
+ realId
+ )
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ replaceTopLevelMessageIdInChannelMessages(prev, target.messageId, realId)
+ );
+}
+
+/** Replaces reactions for a target message across all rendered caches. */
+export function replaceTargetReactions(
+ channelId: string,
+ target: MessageTarget,
+ reactions: CountedReaction[]
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) => replaceThreadReplyReactions(prev, target.messageId, reactions)
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ replaceThreadReplyReactionsInChannelMessages(
+ prev,
+ target.threadId,
+ target.messageId,
+ reactions
+ )
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ replaceTopLevelMessageReactionsInChannelMessages(
+ prev,
+ target.messageId,
+ reactions
+ )
+ );
+}
+
+/** Replaces attachments for a target message across all rendered caches. */
+export function replaceTargetAttachments(
+ channelId: string,
+ target: MessageTarget,
+ attachments: ApiAttachment[]
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) =>
+ replaceThreadReplyAttachments(prev, target.messageId, attachments)
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ replaceThreadReplyAttachmentsInChannelMessages(
+ prev,
+ target.threadId,
+ target.messageId,
+ attachments
+ )
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ replaceTopLevelMessageAttachmentsInChannelMessages(
+ prev,
+ target.messageId,
+ attachments
+ )
+ );
+}
+
+/** Soft-invalidates the rendered caches touched by a target message. */
+export function softInvalidateTargetCaches(
+ channelId: string,
+ target?: MessageTarget
+) {
+ softInvalidateChannelMessages(channelId);
+
+ if (target?.kind === 'thread_reply') {
+ softInvalidateThreadReplies(channelId, target.threadId);
+ }
+}
diff --git a/js/app/packages/queries/channel/sync.ts b/js/app/packages/queries/channel/sync.ts
index 614c6e05bd..6023f2b1aa 100644
--- a/js/app/packages/queries/channel/sync.ts
+++ b/js/app/packages/queries/channel/sync.ts
@@ -3,11 +3,20 @@ import type {
CountedReaction,
Message as ApiMessage,
} from '@service-comms/generated/models';
+import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
+import type { ApiThreadReply } from '@service-comms/client';
import type { GetChannelResponse } from './types';
import { queryClient } from '../client';
import { softInvalidateChannelWithID } from './channel';
import { channelKeys, ChannelNonceKeys } from './keys';
import { consumeNonce } from '../nonce';
+import {
+ insertMessageIntoTargetCaches,
+ replaceTargetAttachments,
+ replaceTargetReactions,
+ softInvalidateTargetCaches,
+ resolveMessageTarget,
+} from './reconcile';
/**
* Websocket payload types
@@ -61,12 +70,72 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {
messages: [...prev.messages, payload],
};
});
+
+ if (ENABLE_NEW_CHANNELS) {
+ const threadId = payload.thread_id;
+ if (threadId) {
+ const reply: ApiThreadReply = {
+ id: payload.id,
+ sender_id: payload.sender_id,
+ content: payload.content,
+ created_at: payload.created_at,
+ updated_at: payload.updated_at,
+ edited_at: payload.edited_at,
+ attachments: [],
+ reactions: [],
+ };
+ insertMessageIntoTargetCaches(
+ payload.channel_id,
+ resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.id,
+ threadId,
+ }),
+ reply
+ );
+ } else {
+ insertMessageIntoTargetCaches(
+ payload.channel_id,
+ resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.id,
+ }),
+ {
+ id: payload.id,
+ channel_id: payload.channel_id,
+ sender_id: payload.sender_id,
+ content: payload.content,
+ created_at: payload.created_at,
+ updated_at: payload.updated_at,
+ deleted_at: payload.deleted_at,
+ edited_at: payload.edited_at,
+ attachments: [],
+ reactions: [],
+ thread: {
+ preview: [],
+ reply_count: 0,
+ latest_reply_at: null,
+ },
+ }
+ );
+ }
+ }
} catch (error) {
console.error('Failed to update message cache from websocket:', error);
}
}
softInvalidateChannelWithID(payload.channel_id);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ payload.channel_id,
+ resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.id,
+ threadId: payload.thread_id ?? undefined,
+ })
+ );
+ }
}
/**
@@ -94,12 +163,27 @@ export function handleCommsReaction(payload: CommsReactionPayload): void {
},
};
});
+
+ if (ENABLE_NEW_CHANNELS) {
+ const target = resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.message_id,
+ });
+ replaceTargetReactions(payload.channel_id, target, payload.reactions);
+ }
} catch (error) {
console.error('Failed to update reaction cache from websocket:', error);
}
}
softInvalidateChannelWithID(payload.channel_id);
+ if (ENABLE_NEW_CHANNELS) {
+ const target = resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.message_id,
+ });
+ softInvalidateTargetCaches(payload.channel_id, target);
+ }
}
/**
@@ -113,27 +197,49 @@ export function handleCommsAttachment(payload: CommsAttachmentPayload): void {
ChannelNonceKeys.ATTACHMENT,
payload.nonce
);
-
- if (isExternalUpdate) {
- try {
- const queryKey = channelKeys.withID(payload.channel_id).queryKey;
- queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
- if (!prev) return prev;
-
- const existingIds = new Set(prev.attachments.map((a) => a.id));
- const newAttachments = payload.attachments.filter(
- (a) => !existingIds.has(a.id)
- );
-
- return {
- ...prev,
- attachments: [...prev.attachments, ...newAttachments],
- };
- });
- } catch (error) {
- console.error('Failed to update attachment cache from websocket:', error);
+ const target = ENABLE_NEW_CHANNELS
+ ? resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.message_id,
+ })
+ : undefined;
+
+ try {
+ const queryKey = channelKeys.withID(payload.channel_id).queryKey;
+ queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
+ if (!prev) return prev;
+
+ const remainingAttachments = prev.attachments.filter(
+ (attachment) => attachment.message_id !== payload.message_id
+ );
+ const nextAttachments = isExternalUpdate
+ ? [
+ ...remainingAttachments,
+ ...payload.attachments.filter(
+ (attachment) =>
+ !remainingAttachments.some(
+ (existingAttachment) =>
+ existingAttachment.id === attachment.id
+ )
+ ),
+ ]
+ : [...remainingAttachments, ...payload.attachments];
+
+ return {
+ ...prev,
+ attachments: nextAttachments,
+ };
+ });
+
+ if (ENABLE_NEW_CHANNELS && target) {
+ replaceTargetAttachments(payload.channel_id, target, payload.attachments);
}
+ } catch (error) {
+ console.error('Failed to update attachment cache from websocket:', error);
}
softInvalidateChannelWithID(payload.channel_id);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(payload.channel_id, target);
+ }
}
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 d8b72ec546..081e486ceb 100644
--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -2,14 +2,12 @@
* @vitest-environment jsdom
*/
-import type { CountedReaction } from '@service-comms/generated/models';
-import type { Attachment, GetChannelResponse, Message } from '../types';
+import type { ApiChannelMessage, ApiThreadReply } from '@service-comms/client';
import { QueryClient } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
let testQueryClient: QueryClient;
-// Mock modules with side effects before importing the modules under test
vi.mock('../../client', () => ({
get queryClient() {
return testQueryClient;
@@ -25,6 +23,11 @@ vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: vi.fn(), success: vi.fn() },
}));
+vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
+ ENABLE_NEW_CHANNELS: true,
+}));
+
vi.mock('@service-comms/client', () => ({
commsServiceClient: {},
}));
@@ -33,20 +36,13 @@ vi.mock('@macro-entity', () => ({
queryKeys: { all: { channel: ['channel'] } },
}));
-// Import after mocks are set up
import {
- optimisticUpdateChannelName,
- rollbackUpdateChannelName,
-} from '../channel';
-import { channelKeys } from '../keys';
+ getChannelMessagesQueryKey,
+ type ChannelMessagesData,
+} from '../channel-messages';
import {
- optimisticDeleteChannelMessage,
optimisticInsertChannelMessage,
- optimisticUpdateChannelMessage,
- replaceOptimisticMessage,
- rollbackDeleteChannelMessage,
rollbackInsertChannelMessage,
- rollbackUpdateChannelMessage,
} from '../message';
import {
optimisticAddReaction,
@@ -54,75 +50,97 @@ import {
rollbackAddReaction,
rollbackRemoveReaction,
} from '../reaction';
+import { getThreadRepliesQueryKey } from '../thread-replies';
-function createMockMessage(overrides: Partial<Message> = {}): Message {
+function createPaginatedMessage(
+ id: string,
+ createdAt: string,
+ overrides: Partial<ApiChannelMessage> = {}
+): ApiChannelMessage {
return {
- id: `msg-${Math.random().toString(36).slice(2)}`,
+ id,
channel_id: 'channel-1',
sender_id: 'user-1',
- content: 'Test message',
- created_at: '2024-01-01T00:00:00.000Z',
- updated_at: '2024-01-01T00:00:00.000Z',
+ content: `Message ${id}`,
+ created_at: createdAt,
+ updated_at: createdAt,
deleted_at: undefined,
edited_at: undefined,
- thread_id: undefined,
+ attachments: [],
+ reactions: [],
+ thread: {
+ preview: [],
+ reply_count: 0,
+ latest_reply_at: null,
+ },
...overrides,
};
}
-function createMockAttachment(overrides: Partial<Attachment> = {}): Attachment {
+function createThreadReply(
+ id: string,
+ createdAt: string,
+ overrides: Partial<ApiThreadReply> = {}
+): ApiThreadReply {
return {
- id: `attachment-${Math.random().toString(36).slice(2)}`,
- channel_id: 'channel-1',
- message_id: 'msg-1',
- created_at: '2024-01-01T00:00:00.000Z',
- updated_at: '2024-01-01T00:00:00.000Z',
- s3_key: 'test-key',
- file_name: 'test.txt',
- file_size: 100,
- mime_type: 'text/plain',
+ id,
+ sender_id: 'user-1',
+ content: `Reply ${id}`,
+ created_at: createdAt,
+ updated_at: createdAt,
+ edited_at: undefined,
+ attachments: [],
+ reactions: [],
...overrides,
- } as Attachment;
+ };
}
-function createMockChannelResponse(
- overrides: Partial<GetChannelResponse> = {}
-): GetChannelResponse {
+function createChannelMessagesData(
+ pages: Array<Array<ApiChannelMessage>>
+): ChannelMessagesData {
return {
- channel: {
- id: 'channel-1',
- name: 'Test Channel',
- owner_id: 'user-1',
- created_at: '2024-01-01T00:00:00.000Z',
- updated_at: '2024-01-01T00:00:00.000Z',
- channel_type: 'direct_message',
- },
- messages: [],
- reactions: {},
- attachments: [],
- participants: [],
- access: 'Participant',
- ...overrides,
- } as GetChannelResponse;
+ pages: pages.map((items, index) => ({
+ items,
+ next_cursor: index === pages.length - 1 ? null : `next-${index}`,
+ previous_cursor: index === 0 ? null : `prev-${index}`,
+ })),
+ pageParams: pages.map(() => null),
+ };
}
-function seedQueryCache(
+function seedChannelMessagesCache(
channelId: string,
- data: GetChannelResponse
-): readonly unknown[] {
- const queryKey = channelKeys.withID(channelId).queryKey;
- testQueryClient.setQueryData(queryKey, data);
- return queryKey;
+ data: ChannelMessagesData
+) {
+ testQueryClient.setQueryData(getChannelMessagesQueryKey(channelId), data);
}
-function getChannelFromCache(
+function getChannelMessagesFromCache(
channelId: string
-): GetChannelResponse | undefined {
- const queryKey = channelKeys.withID(channelId).queryKey;
- return testQueryClient.getQueryData<GetChannelResponse>(queryKey);
+): ChannelMessagesData | undefined {
+ return testQueryClient.getQueryData<ChannelMessagesData>(
+ getChannelMessagesQueryKey(channelId)
+ );
}
-describe('optimisticInsertChannelMessage', () => {
+function seedThreadRepliesCache(
+ channelId: string,
+ messageId: string,
+ replies: Array<ApiThreadReply>
+) {
+ testQueryClient.setQueryData(
+ getThreadRepliesQueryKey(channelId, messageId),
+ replies
+ );
+}
+
+function getThreadRepliesFromCache(channelId: string, messageId: string) {
+ return testQueryClient.getQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, messageId)
+ );
+}
+
+describe('channel optimistic cache regressions', () => {
beforeEach(() => {
vi.clearAllMocks();
testQueryClient = new QueryClient({
@@ -137,649 +155,162 @@ describe('optimisticInsertChannelMessage', () => {
testQueryClient.clear();
});
- it('should insert a new message at the end of the messages array', () => {
- const existingMessage = createMockMessage({ id: 'existing-msg' });
- seedQueryCache(
+ it('rolls back optimistic top-level inserts when only the paginated cache is warm', () => {
+ seedChannelMessagesCache(
'channel-1',
- createMockChannelResponse({ messages: [existingMessage] })
+ createChannelMessagesData([
+ [createPaginatedMessage('existing-msg', '2024-01-03T00:00:00.000Z')],
+ ])
);
const context = optimisticInsertChannelMessage({
channelId: 'channel-1',
- optimisticId: 'optimistic-msg-1',
+ optimisticId: 'optimistic-top-level',
senderId: 'user-2',
- content: 'New message content',
- attachments: [],
- mentions: [],
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages).toHaveLength(2);
- expect(cached?.messages[0].id).toBe('existing-msg');
- expect(cached?.messages[1].id).toBe('optimistic-msg-1');
- expect(cached?.messages[1].content).toBe('New message content');
- expect(cached?.messages[1].sender_id).toBe('user-2');
- // Context should contain only the optimistic ID for rollback
- expect(context?.optimisticId).toBe('optimistic-msg-1');
- });
-
- it('should handle thread_id correctly', () => {
- seedQueryCache('channel-1', createMockChannelResponse());
-
- optimisticInsertChannelMessage({
- channelId: 'channel-1',
- optimisticId: 'optimistic-msg-1',
- senderId: 'user-1',
- content: 'Thread reply',
+ content: 'Top level optimistic message',
attachments: [],
mentions: [],
- thread_id: 'parent-msg-id',
});
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages[0].thread_id).toBe('parent-msg-id');
- });
+ expect(getChannelMessagesFromCache('channel-1')?.pages[0].items[0].id).toBe(
+ 'optimistic-top-level'
+ );
- it('should return undefined when cache is empty', () => {
- const context = optimisticInsertChannelMessage({
- channelId: 'nonexistent-channel',
- optimisticId: 'optimistic-msg-1',
- senderId: 'user-1',
- content: 'Message',
- attachments: [],
- mentions: [],
- });
+ if (context) {
+ rollbackInsertChannelMessage('channel-1', context);
+ }
- expect(context).toBeUndefined();
+ expect(getChannelMessagesFromCache('channel-1')?.pages[0].items).toEqual([
+ expect.objectContaining({ id: 'existing-msg' }),
+ ]);
});
- it('should rollback correctly using returned context', () => {
- const existingMessage = createMockMessage({ id: 'existing-msg' });
- seedQueryCache(
+ it('rolls back optimistic thread replies when only the new caches are warm', () => {
+ seedChannelMessagesCache(
'channel-1',
- createMockChannelResponse({ messages: [existingMessage] })
+ createChannelMessagesData([
+ [createPaginatedMessage('parent-msg-id', '2024-01-03T00:00:00.000Z')],
+ ])
);
+ seedThreadRepliesCache('channel-1', 'parent-msg-id', []);
const context = optimisticInsertChannelMessage({
channelId: 'channel-1',
- optimisticId: 'optimistic-msg-1',
+ optimisticId: 'optimistic-reply',
senderId: 'user-2',
- content: 'New message content',
+ content: 'Reply to rollback',
attachments: [],
mentions: [],
+ thread_id: 'parent-msg-id',
});
- // Verify insert happened
- expect(getChannelFromCache('channel-1')?.messages).toHaveLength(2);
+ expect(getThreadRepliesFromCache('channel-1', 'parent-msg-id')).toEqual([
+ expect.objectContaining({ id: 'optimistic-reply' }),
+ ]);
- // Rollback
if (context) {
rollbackInsertChannelMessage('channel-1', context);
}
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages).toHaveLength(1);
- expect(cached?.messages[0].id).toBe('existing-msg');
- });
-});
-
-describe('replaceOptimisticMessage', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should replace optimistic ID with real ID', () => {
- const optimisticMessage = createMockMessage({ id: 'optimistic-msg-1' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [optimisticMessage] })
- );
-
- replaceOptimisticMessage({
- channelId: 'channel-1',
- optimisticId: 'optimistic-msg-1',
- realId: 'real-msg-id-from-server',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages[0].id).toBe('real-msg-id-from-server');
- expect(cached?.messages[0].content).toBe(optimisticMessage.content);
- });
-
- it('should do nothing if optimistic message not found', () => {
- const message = createMockMessage({ id: 'msg-1' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [message] })
- );
-
- replaceOptimisticMessage({
- channelId: 'channel-1',
- optimisticId: 'nonexistent-optimistic-id',
- realId: 'real-id',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages[0].id).toBe('msg-1');
- });
-});
-
-describe('optimisticDeleteChannelMessage', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should remove message from the messages array', () => {
- const msg1 = createMockMessage({ id: 'msg-1' });
- const msg2 = createMockMessage({ id: 'msg-2' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [msg1, msg2] })
- );
-
- const context = optimisticDeleteChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages).toHaveLength(1);
- expect(cached?.messages[0].id).toBe('msg-2');
- // Context should contain the deleted message for rollback
- expect(context?.deletedMessage.id).toBe('msg-1');
- });
-
- it('should remove associated reactions', () => {
- const msg1 = createMockMessage({ id: 'msg-1' });
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- 'msg-2': [{ emoji: '❤️', users: ['user-2'] }],
- };
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [msg1], reactions })
- );
-
- optimisticDeleteChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toBeUndefined();
- expect(cached?.reactions['msg-2']).toBeDefined();
- });
-
- it('should remove associated attachments', () => {
- const msg1 = createMockMessage({ id: 'msg-1' });
- const attachment1 = createMockAttachment({ message_id: 'msg-1' });
- const attachment2 = createMockAttachment({ message_id: 'msg-2' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({
- messages: [msg1],
- attachments: [attachment1, attachment2],
- })
- );
-
- optimisticDeleteChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.attachments).toHaveLength(1);
- expect(cached?.attachments[0].message_id).toBe('msg-2');
- });
-
- it('should gracefully handle missing message', () => {
- const msg1 = createMockMessage({ id: 'msg-1' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [msg1] })
- );
-
- optimisticDeleteChannelMessage({
- channelId: 'channel-1',
- message_id: 'nonexistent-msg',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages).toHaveLength(1);
- expect(cached?.messages[0].id).toBe('msg-1');
- });
-
- it('should rollback correctly using returned context', () => {
- const msg1 = createMockMessage({ id: 'msg-1', content: 'Message 1' });
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- };
- const attachment1 = createMockAttachment({
- id: 'att-1',
- message_id: 'msg-1',
- });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({
- messages: [msg1],
- reactions,
- attachments: [attachment1],
- })
- );
-
- const context = optimisticDeleteChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- });
-
- // Verify delete happened
- expect(getChannelFromCache('channel-1')?.messages).toHaveLength(0);
-
- // Rollback
- if (context) {
- rollbackDeleteChannelMessage('channel-1', context);
- }
-
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages).toHaveLength(1);
- expect(cached?.messages[0].id).toBe('msg-1');
- expect(cached?.reactions['msg-1']).toHaveLength(1);
- expect(cached?.attachments).toHaveLength(1);
- });
-});
-
-describe('optimisticUpdateChannelMessage', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should update message content and timestamps', () => {
- const msg1 = createMockMessage({ id: 'msg-1', content: 'Original' });
- const msg2 = createMockMessage({ id: 'msg-2', content: 'Unchanged' });
- seedQueryCache(
- 'channel-1',
- createMockChannelResponse({ messages: [msg1, msg2] })
- );
-
- const context = optimisticUpdateChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- content: 'Updated content',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages[0].content).toBe('Updated content');
- expect(cached?.messages[0].edited_at).not.toBeUndefined();
- expect(cached?.messages[1].content).toBe('Unchanged');
- // Context should contain previous values for rollback
- expect(context?.messageId).toBe('msg-1');
- expect(context?.previousContent).toBe('Original');
+ expect(getThreadRepliesFromCache('channel-1', 'parent-msg-id')).toEqual([]);
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread.preview
+ ).toEqual([]);
});
- it('should rollback correctly using returned context', () => {
- const originalUpdatedAt = '2024-01-01T00:00:00.000Z';
- const msg1 = createMockMessage({
- id: 'msg-1',
- content: 'Original',
- updated_at: originalUpdatedAt,
- edited_at: undefined,
- });
- seedQueryCache(
+ it('restores optimistic add-reaction rollbacks from new caches without legacy data', () => {
+ seedChannelMessagesCache(
'channel-1',
- createMockChannelResponse({ messages: [msg1] })
- );
-
- const context = optimisticUpdateChannelMessage({
- channelId: 'channel-1',
- message_id: 'msg-1',
- content: 'Updated content',
- });
-
- // Verify update happened
- expect(getChannelFromCache('channel-1')?.messages[0].content).toBe(
- 'Updated content'
+ 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',
+ },
+ }),
+ ],
+ ])
);
-
- // Rollback
- if (context) {
- rollbackUpdateChannelMessage('channel-1', context);
- }
-
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.messages[0].content).toBe('Original');
- expect(cached?.messages[0].updated_at).toBe(originalUpdatedAt);
- expect(cached?.messages[0].edited_at).toBeUndefined();
- });
-});
-
-describe('optimisticAddReaction', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should add a new reaction to a message', () => {
- seedQueryCache('channel-1', createMockChannelResponse());
+ seedThreadRepliesCache('channel-1', 'parent-1', [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z'),
+ ]);
const context = optimisticAddReaction({
channelId: 'channel-1',
userId: 'user-1',
emoji: '👍',
- message_id: 'msg-1',
+ message_id: 'reply-1',
+ currentReactions: [],
+ threadId: 'parent-1',
});
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toHaveLength(1);
- expect(cached?.reactions['msg-1'][0].emoji).toBe('👍');
- expect(cached?.reactions['msg-1'][0].users).toContain('user-1');
- // Context should indicate this was a new reaction
- expect(context?.wasNewReaction).toBe(true);
- expect(context?.emoji).toBe('👍');
- });
-
- it('should add user to existing reaction', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- const context = optimisticAddReaction({
- channelId: 'channel-1',
- userId: 'user-2',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1'][0].users).toHaveLength(2);
- expect(cached?.reactions['msg-1'][0].users).toContain('user-1');
- expect(cached?.reactions['msg-1'][0].users).toContain('user-2');
- // Context should indicate this was not a new reaction
- expect(context?.wasNewReaction).toBe(false);
- });
-
- it('should not add duplicate user to reaction', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- optimisticAddReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1'][0].users).toHaveLength(1);
- });
-
- it('should add different emoji as separate reaction', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- optimisticAddReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '❤️',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toHaveLength(2);
- expect(
- cached?.reactions['msg-1'].find((r) => r.emoji === '👍')
- ).toBeDefined();
- expect(
- cached?.reactions['msg-1'].find((r) => r.emoji === '❤️')
- ).toBeDefined();
- });
-
- it('should rollback correctly using returned context', () => {
- seedQueryCache('channel-1', createMockChannelResponse());
-
- const context = optimisticAddReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- // Verify add happened
- expect(getChannelFromCache('channel-1')?.reactions['msg-1']).toHaveLength(
- 1
- );
-
- // Rollback
if (context) {
rollbackAddReaction('channel-1', context);
}
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toBeUndefined();
- });
-});
-
-describe('optimisticRemoveReaction', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should remove user from reaction', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1', 'user-2'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- const context = optimisticRemoveReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1'][0].users).toHaveLength(1);
- expect(cached?.reactions['msg-1'][0].users).not.toContain('user-1');
- expect(cached?.reactions['msg-1'][0].users).toContain('user-2');
- // Context should indicate this was not the last user
- expect(context?.wasLastUser).toBe(false);
- });
-
- it('should remove reaction entirely when last user removes it', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [
- { emoji: '👍', users: ['user-1'] },
- { emoji: '❤️', users: ['user-2'] },
- ],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- const context = optimisticRemoveReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toHaveLength(1);
- expect(cached?.reactions['msg-1'][0].emoji).toBe('❤️');
- // Context should indicate this was the last user
- expect(context?.wasLastUser).toBe(true);
- });
-
- it('should remove message key from reactions map when no reactions left', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- 'msg-2': [{ emoji: '❤️', users: ['user-2'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
-
- optimisticRemoveReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toBeUndefined();
- expect(cached?.reactions['msg-2']).toBeDefined();
- });
-
- it('should do nothing for non-existent reactions', () => {
- seedQueryCache('channel-1', createMockChannelResponse());
-
- optimisticRemoveReaction({
- channelId: 'channel-1',
- userId: 'user-1',
- emoji: '👍',
- message_id: 'msg-1',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions).toEqual({});
+ expect(
+ getThreadRepliesFromCache('channel-1', 'parent-1')?.[0].reactions
+ ).toEqual([]);
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread
+ .preview[0].reactions
+ ).toEqual([]);
});
- it('should rollback correctly using returned context', () => {
- const reactions: Record<string, CountedReaction[]> = {
- 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
- };
- seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
+ it('restores optimistic remove-reaction rollbacks from new caches without legacy data', () => {
+ seedChannelMessagesCache(
+ 'channel-1',
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('parent-1', '2024-01-03T00:00:00.000Z', {
+ thread: {
+ preview: [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z', {
+ reactions: [{ emoji: '👍', users: ['user-1'] }],
+ }),
+ ],
+ 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', {
+ reactions: [{ emoji: '👍', users: ['user-1'] }],
+ }),
+ ]);
const context = optimisticRemoveReaction({
channelId: 'channel-1',
userId: 'user-1',
emoji: '👍',
- message_id: 'msg-1',
+ message_id: 'reply-1',
+ currentReactions: [{ emoji: '👍', users: ['user-1'] }],
+ threadId: 'parent-1',
});
- // Verify remove happened
- expect(
- getChannelFromCache('channel-1')?.reactions['msg-1']
- ).toBeUndefined();
-
- // Rollback
if (context) {
rollbackRemoveReaction('channel-1', context);
}
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.reactions['msg-1']).toHaveLength(1);
- expect(cached?.reactions['msg-1'][0].users).toContain('user-1');
- });
-});
-
-describe('optimisticUpdateChannelName', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- testQueryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- afterEach(() => {
- testQueryClient.clear();
- });
-
- it('should update channel name and timestamp', () => {
- const originalUpdatedAt = '2024-01-01T00:00:00.000Z';
- seedQueryCache('channel-1', createMockChannelResponse());
-
- const context = optimisticUpdateChannelName({
- channelId: 'channel-1',
- name: 'New Channel Name',
- });
-
- const cached = getChannelFromCache('channel-1');
- expect(cached?.channel.name).toBe('New Channel Name');
- expect(cached?.channel.updated_at).not.toEqual(originalUpdatedAt);
- // Context should contain previous name for rollback
- expect(context?.previousName).toBe('Test Channel');
+ expect(
+ getThreadRepliesFromCache('channel-1', 'parent-1')?.[0].reactions
+ ).toEqual([{ emoji: '👍', users: ['user-1'] }]);
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread
+ .preview[0].reactions
+ ).toEqual([{ emoji: '👍', users: ['user-1'] }]);
});
- it('should rollback correctly using returned context', () => {
- seedQueryCache('channel-1', createMockChannelResponse());
-
- const context = optimisticUpdateChannelName({
- channelId: 'channel-1',
- name: 'New Channel Name',
- });
-
- // Verify update happened
- expect(getChannelFromCache('channel-1')?.channel.name).toBe(
- 'New Channel Name'
+ it('uses distinct query keys for target-message loads', () => {
+ expect(getChannelMessagesQueryKey('channel-1')).not.toEqual(
+ getChannelMessagesQueryKey('channel-1', 'message-42')
);
-
- // Rollback
- if (context) {
- rollbackUpdateChannelName('channel-1', context);
- }
-
- // Verify rollback restored original state
- const cached = getChannelFromCache('channel-1');
- expect(cached?.channel.name).toBe('Test Channel');
- expect(cached?.channel.updated_at).toEqual('2024-01-01T00:00:00.000Z');
});
});
diff --git a/js/app/packages/queries/channel/tests/sync.test.ts b/js/app/packages/queries/channel/tests/sync.test.ts
new file mode 100644
index 0000000000..bd0d85a6d1
--- /dev/null
+++ b/js/app/packages/queries/channel/tests/sync.test.ts
@@ -0,0 +1,246 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { ApiChannelMessage, ApiThreadReply } from '@service-comms/client';
+import type { Attachment as ApiAttachment } from '@service-comms/generated/models';
+import { QueryClient } from '@tanstack/solid-query';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+let testQueryClient: QueryClient;
+
+vi.mock('../../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+
+vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
+ ENABLE_NEW_CHANNELS: true,
+}));
+
+import type { ChannelMessagesData } from '../channel-messages';
+import { getChannelMessagesQueryKey } from '../channel-messages';
+import { channelKeys, ChannelNonceKeys } from '../keys';
+import { registerNonce } from '../../nonce';
+import { handleCommsAttachment, handleCommsReaction } from '../sync';
+import { getThreadRepliesQueryKey } from '../thread-replies';
+import type { GetChannelResponse } from '../types';
+
+function createPaginatedMessage(
+ id: string,
+ createdAt: string,
+ overrides: Partial<ApiChannelMessage> = {}
+): ApiChannelMessage {
+ return {
+ id,
+ channel_id: 'channel-1',
+ sender_id: 'user-1',
+ content: `Message ${id}`,
+ created_at: createdAt,
+ updated_at: createdAt,
+ deleted_at: undefined,
+ edited_at: undefined,
+ attachments: [],
+ reactions: [],
+ thread: {
+ preview: [],
+ reply_count: 0,
+ latest_reply_at: null,
+ },
+ ...overrides,
+ };
+}
+
+function createThreadReply(
+ id: string,
+ createdAt: string,
+ overrides: Partial<ApiThreadReply> = {}
+): ApiThreadReply {
+ return {
+ id,
+ sender_id: 'user-1',
+ content: `Reply ${id}`,
+ created_at: createdAt,
+ updated_at: createdAt,
+ edited_at: undefined,
+ attachments: [],
+ reactions: [],
+ ...overrides,
+ };
+}
+
+function createAttachment(id: string, messageId: string): ApiAttachment {
+ return {
+ id,
+ channel_id: 'channel-1',
+ message_id: messageId,
+ created_at: '2024-01-03T02:00:00.000Z',
+ updated_at: '2024-01-03T02:00:00.000Z',
+ entity_id: `entity-${id}`,
+ entity_type: 'Document',
+ s3_key: `${id}.txt`,
+ file_name: `${id}.txt`,
+ file_size: 100,
+ mime_type: 'text/plain',
+ } as ApiAttachment;
+}
+
+function createChannelMessagesData(
+ pages: Array<Array<ApiChannelMessage>>
+): ChannelMessagesData {
+ return {
+ pages: pages.map((items, index) => ({
+ items,
+ next_cursor: index === pages.length - 1 ? null : `next-${index}`,
+ previous_cursor: index === 0 ? null : `prev-${index}`,
+ })),
+ pageParams: pages.map(() => null),
+ };
+}
+
+function createMockChannelResponse(
+ overrides: Partial<GetChannelResponse> = {}
+): GetChannelResponse {
+ return {
+ channel: {
+ id: 'channel-1',
+ name: 'Test Channel',
+ owner_id: 'user-1',
+ created_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:00.000Z',
+ channel_type: 'direct_message',
+ },
+ messages: [],
+ reactions: {},
+ attachments: [],
+ participants: [],
+ access: 'Participant',
+ ...overrides,
+ } as GetChannelResponse;
+}
+
+describe('channel sync', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ afterEach(() => {
+ testQueryClient.clear();
+ });
+
+ it('replaces top-level attachments in the rendered cache', () => {
+ testQueryClient.setQueryData(
+ getChannelMessagesQueryKey('channel-1'),
+ createChannelMessagesData([
+ [createPaginatedMessage('msg-1', '2024-01-03T00:00:00.000Z')],
+ ])
+ );
+
+ handleCommsAttachment({
+ channel_id: 'channel-1',
+ message_id: 'msg-1',
+ nonce: 'external-attachment',
+ attachments: [createAttachment('att-1', 'msg-1')],
+ });
+
+ const cached = testQueryClient.getQueryData<ChannelMessagesData>(
+ getChannelMessagesQueryKey('channel-1')
+ );
+ expect(cached?.pages[0].items[0].attachments).toEqual([
+ expect.objectContaining({ id: 'att-1', message_id: 'msg-1' }),
+ ]);
+ });
+
+ it('reconciles local optimistic attachments with authoritative websocket payloads', () => {
+ testQueryClient.setQueryData(
+ getChannelMessagesQueryKey('channel-1'),
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('real-msg-1', '2024-01-03T00:00:00.000Z', {
+ attachments: [createAttachment('optimistic-att', 'real-msg-1')],
+ }),
+ ],
+ ])
+ );
+ testQueryClient.setQueryData(
+ channelKeys.withID('channel-1').queryKey,
+ createMockChannelResponse({
+ attachments: [createAttachment('optimistic-att', 'real-msg-1')],
+ })
+ );
+ registerNonce(ChannelNonceKeys.ATTACHMENT, 'local-attachment');
+
+ handleCommsAttachment({
+ channel_id: 'channel-1',
+ message_id: 'real-msg-1',
+ nonce: 'local-attachment',
+ attachments: [createAttachment('server-att', 'real-msg-1')],
+ });
+
+ const cached = testQueryClient.getQueryData<ChannelMessagesData>(
+ getChannelMessagesQueryKey('channel-1')
+ );
+ expect(cached?.pages[0].items[0].attachments).toEqual([
+ expect.objectContaining({ id: 'server-att' }),
+ ]);
+
+ const legacy = testQueryClient.getQueryData<GetChannelResponse>(
+ channelKeys.withID('channel-1').queryKey
+ );
+ expect(legacy?.attachments).toEqual([
+ expect.objectContaining({ id: 'server-att' }),
+ ]);
+ });
+
+ it('updates thread reply reactions without the legacy channel cache', () => {
+ testQueryClient.setQueryData(
+ getChannelMessagesQueryKey('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',
+ },
+ }),
+ ],
+ ])
+ );
+ testQueryClient.setQueryData(
+ getThreadRepliesQueryKey('channel-1', 'parent-1'),
+ [createThreadReply('reply-1', '2024-01-03T01:00:00.000Z')]
+ );
+
+ handleCommsReaction({
+ channel_id: 'channel-1',
+ message_id: 'reply-1',
+ nonce: 'external-reaction',
+ reactions: [{ emoji: '👍', users: ['user-1'] }],
+ });
+
+ const replies = testQueryClient.getQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey('channel-1', 'parent-1')
+ );
+ expect(replies?.[0].reactions).toEqual([
+ { emoji: '👍', users: ['user-1'] },
+ ]);
+
+ const cached = testQueryClient.getQueryData<ChannelMessagesData>(
+ getChannelMessagesQueryKey('channel-1')
+ );
+ expect(cached?.pages[0].items[0].thread.preview[0].reactions).toEqual([
+ { emoji: '👍', users: ['user-1'] },
+ ]);
+ });
+});
diff --git a/js/app/packages/queries/channel/thread-preview.ts b/js/app/packages/queries/channel/thread-preview.ts
new file mode 100644
index 0000000000..1526b26dab
--- /dev/null
+++ b/js/app/packages/queries/channel/thread-preview.ts
@@ -0,0 +1,125 @@
+import type { ApiThreadReply } from '@service-comms/client';
+import type { ApiCountedReaction } from '@service-storage/generated/schemas';
+
+export type ThreadPreviewState = {
+ preview: ApiThreadReply[];
+ reply_count: number;
+ latest_reply_at?: string | null;
+};
+
+export type ThreadPreviewReplySnapshot = {
+ previewIndex: number;
+ reply: ApiThreadReply;
+};
+
+export function insertReplyIntoThreadPreview(
+ thread: ThreadPreviewState,
+ reply: ApiThreadReply
+): ThreadPreviewState {
+ if (thread.preview.some((previewReply) => previewReply.id === reply.id)) {
+ return thread;
+ }
+
+ return {
+ ...thread,
+ latest_reply_at: reply.created_at,
+ reply_count: thread.reply_count + 1,
+ preview: [...thread.preview, reply],
+ };
+}
+
+export function removeReplyFromThreadPreview(
+ thread: ThreadPreviewState,
+ replyId: string
+): ThreadPreviewState {
+ const nextPreview = thread.preview.filter((reply) => reply.id !== replyId);
+ const didRemovePreview = nextPreview.length !== thread.preview.length;
+ if (!didRemovePreview && thread.reply_count === 0) {
+ return thread;
+ }
+
+ return {
+ ...thread,
+ latest_reply_at: didRemovePreview
+ ? (nextPreview.at(-1)?.created_at ?? null)
+ : thread.latest_reply_at,
+ reply_count: Math.max(thread.reply_count - 1, 0),
+ preview: nextPreview,
+ };
+}
+
+export function replaceReplyIdInThreadPreview(
+ thread: ThreadPreviewState,
+ optimisticId: string,
+ realId: string
+): ThreadPreviewState {
+ let didChange = false;
+ const preview = thread.preview.map((reply) => {
+ if (reply.id !== optimisticId) return reply;
+ didChange = true;
+ return { ...reply, id: realId };
+ });
+
+ return didChange ? { ...thread, preview } : thread;
+}
+
+export function replaceReplyReactionsInThreadPreview(
+ thread: ThreadPreviewState,
+ replyId: string,
+ reactions: ApiCountedReaction[]
+): ThreadPreviewState {
+ let didChange = false;
+ const preview = thread.preview.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return { ...reply, reactions };
+ });
+
+ return didChange ? { ...thread, preview } : thread;
+}
+
+export function captureThreadPreviewReplySnapshot(
+ thread: ThreadPreviewState,
+ replyId: string
+): ThreadPreviewReplySnapshot | undefined {
+ const previewIndex = thread.preview.findIndex(
+ (reply) => reply.id === replyId
+ );
+ if (previewIndex === -1) return undefined;
+
+ return {
+ previewIndex,
+ reply: thread.preview[previewIndex],
+ };
+}
+
+export function restoreReplyToThreadPreview(
+ thread: ThreadPreviewState,
+ snapshot?: ThreadPreviewReplySnapshot,
+ replyCreatedAt?: string
+): ThreadPreviewState {
+ if (
+ snapshot &&
+ thread.preview.some((reply) => reply.id === snapshot.reply.id)
+ ) {
+ return thread;
+ }
+
+ const preview = [...thread.preview];
+ if (snapshot) {
+ preview.splice(snapshot.previewIndex, 0, snapshot.reply);
+ }
+
+ return {
+ ...thread,
+ preview,
+ reply_count: thread.reply_count + 1,
+ latest_reply_at:
+ [thread.latest_reply_at, replyCreatedAt]
+ .filter((value): value is string => !!value)
+ .sort()
+ .at(-1) ??
+ preview.at(-1)?.created_at ??
+ null,
+ };
+}
diff --git a/js/app/packages/queries/channel/thread-replies.ts b/js/app/packages/queries/channel/thread-replies.ts
index 4fa6fbb1a3..3f054e4457 100644
--- a/js/app/packages/queries/channel/thread-replies.ts
+++ b/js/app/packages/queries/channel/thread-replies.ts
@@ -1,9 +1,21 @@
import { throwOnErr } from '@core/util/maybeResult';
import { type ApiThreadReply, commsServiceClient } from '@service-comms/client';
+import type { Attachment as ApiAttachment } from '@service-comms/generated/models';
+import type { ApiCountedReaction } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
import { channelKeys } from './keys';
+export type ThreadReplySnapshot = {
+ replyIndex: number;
+ reply: ApiThreadReply;
+};
+
+export type ThreadRepliesQueryKey = ReturnType<
+ typeof channelKeys.threadReplies
+>['queryKey'];
+
export function threadRepliesQueryOptions(
channelId: string,
messageId: string
@@ -33,3 +45,134 @@ export function useThreadRepliesQuery(
enabled: enabled(),
}));
}
+
+/** Returns the cache key for one thread replies query. */
+export function getThreadRepliesQueryKey(
+ channelId: string,
+ messageId: string
+): ThreadRepliesQueryKey {
+ return channelKeys.threadReplies(channelId, messageId).queryKey;
+}
+
+/** Returns the shared prefix for all thread reply queries in a channel. */
+export function getThreadRepliesQueryKeyPrefix(channelId: string) {
+ return [...channelKeys.threadReplies._def, channelId];
+}
+
+/** Returns all cached thread reply query entries for a channel. */
+export function getThreadRepliesEntries(channelId: string) {
+ return queryClient.getQueriesData<Array<ApiThreadReply>>({
+ queryKey: getThreadRepliesQueryKeyPrefix(channelId),
+ });
+}
+
+export function insertThreadReply(
+ data: Array<ApiThreadReply> | undefined,
+ reply: ApiThreadReply
+): Array<ApiThreadReply> | undefined {
+ if (!data) return [reply];
+ if (data.some((existingReply) => existingReply.id === reply.id)) {
+ return data;
+ }
+ return [...data, reply];
+}
+
+export function removeThreadReply(
+ data: Array<ApiThreadReply> | undefined,
+ replyId: string
+): Array<ApiThreadReply> | undefined {
+ if (!data) return data;
+ const nextReplies = data.filter((reply) => reply.id !== replyId);
+ return nextReplies.length === data.length ? data : nextReplies;
+}
+
+export function replaceThreadReplyId(
+ data: Array<ApiThreadReply> | undefined,
+ optimisticId: string,
+ realId: string
+): Array<ApiThreadReply> | undefined {
+ if (!data) return data;
+
+ let didChange = false;
+ const nextReplies = data.map((reply) => {
+ if (reply.id !== optimisticId) return reply;
+ didChange = true;
+ return { ...reply, id: realId };
+ });
+
+ return didChange ? nextReplies : data;
+}
+
+export function replaceThreadReplyReactions(
+ data: Array<ApiThreadReply> | undefined,
+ replyId: string,
+ reactions: ApiCountedReaction[]
+): Array<ApiThreadReply> | undefined {
+ if (!data) return data;
+
+ let didChange = false;
+ const nextReplies = data.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return { ...reply, reactions };
+ });
+
+ return didChange ? nextReplies : data;
+}
+
+/** Replaces attachments on one cached thread reply. */
+export function replaceThreadReplyAttachments(
+ data: Array<ApiThreadReply> | undefined,
+ replyId: string,
+ attachments: ApiAttachment[]
+): Array<ApiThreadReply> | undefined {
+ if (!data) return data;
+
+ let didChange = false;
+ const nextReplies = data.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return { ...reply, attachments };
+ });
+
+ return didChange ? nextReplies : data;
+}
+
+export function getThreadReplySnapshot(
+ data: Array<ApiThreadReply> | undefined,
+ replyId: string
+): ThreadReplySnapshot | undefined {
+ if (!data) return undefined;
+
+ const replyIndex = data.findIndex((reply) => reply.id === replyId);
+ if (replyIndex === -1) return undefined;
+
+ return {
+ replyIndex,
+ reply: data[replyIndex],
+ };
+}
+
+export function restoreThreadReply(
+ data: Array<ApiThreadReply> | undefined,
+ snapshot: ThreadReplySnapshot
+): Array<ApiThreadReply> | undefined {
+ if (!data) return [snapshot.reply];
+ if (data.some((reply) => reply.id === snapshot.reply.id)) {
+ return data;
+ }
+
+ const nextReplies = [...data];
+ nextReplies.splice(snapshot.replyIndex, 0, snapshot.reply);
+ return nextReplies;
+}
+
+export function softInvalidateThreadReplies(
+ channelId: string,
+ messageId: string
+) {
+ queryClient.invalidateQueries({
+ queryKey: getThreadRepliesQueryKey(channelId, messageId),
+ refetchType: 'inactive',
+ });
+}