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(channels): optimistic channels + part one deblockification (#1243)

teo55703ed41db6
diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsx
index 1a960939bc..75a68e2a55 100644
--- a/js/app/packages/app/component/EntityModal/RenameView.tsx
+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx
@@ -2,10 +2,13 @@ import { useUpsertSavedViewMutation } from '@app/component/Soup';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import type { ViewConfigBase } from '@app/component/ViewConfig';
import { unwrapSignals } from '@core/util/unwrapSignals';
-import { optimisticUpdateChannelName } from '@queries/channel/channel';
+import {
+ optimisticUpdateChannelName,
+ rollbackUpdateChannelName,
+ type UpdateChannelNameContext,
+} from '@queries/channel/channel';
import { channelKeys } from '@queries/channel/keys';
import { queryClient } from '@queries/client';
-import type { GetChannelResponse } from '@service-comms/generated/models';
import { createMemo, createSignal, onMount } from 'solid-js';
import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';
import type { EntityData } from '../../../macro-entity/src/types/entity';
@@ -21,24 +24,26 @@ export const RenameView = (props: {
onMutate(variables) {
if (variables.entity.type !== 'channel') return;
- const queryKey = channelKeys.withID(variables.entity.id).queryKey;
-
- const previousData: GetChannelResponse | undefined =
- queryClient.getQueryData(queryKey);
-
- optimisticUpdateChannelName(variables.entity.id, variables.newName);
- return { previousData };
+ const context = optimisticUpdateChannelName({
+ channelId: variables.entity.id,
+ name: variables.newName,
+ });
+ return { context, channelId: variables.entity.id };
},
onError(
_,
- variables,
- onMutateResult: { previousData: GetChannelResponse | undefined }
+ _variables,
+ onMutateResult: {
+ context: UpdateChannelNameContext | undefined;
+ channelId: string;
+ }
) {
- const queryKey = channelKeys.withID(variables.entity.id).queryKey;
- queryClient.setQueriesData(
- { queryKey },
- () => onMutateResult.previousData
- );
+ if (onMutateResult?.context) {
+ rollbackUpdateChannelName(
+ onMutateResult.channelId,
+ onMutateResult.context
+ );
+ }
},
onSettled(_, __, variables) {
// TODO: fix the backend so that the /channels/{id} endpoint returns the updated name
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 5f0780bd97..c82154b946 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -3,7 +3,8 @@ import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
import { withAnalytics } from '@coparse/analytics';
import { ChannelsContextProvider } from '@core/context/channels';
-import { UserContextProvider } from '@core/context/user';
+import { UserContextProvider, useUserId } from '@core/context/user';
+import { QuerySyncProvider } from '@queries/sync/SyncProvider';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { toast } from '@core/component/Toast/Toast';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
@@ -338,6 +339,11 @@ const clearBodyInlineStyleColor = () => {
document.body.style.backgroundColor = '';
};
+function QuerySyncProviderWithUserId() {
+ const userId = useUserId();
+ return <QuerySyncProvider userId={userId} />;
+}
+
export function Root() {
setHotkeyRoot(useHotKeyRoot());
@@ -389,6 +395,7 @@ export function Root() {
<MetaProvider>
<EntityProvider>
<UserContextProvider>
+ <QuerySyncProviderWithUserId />
<UserInfoSideEffects />
<ConfiguredGlobalAppStateProvider>
<ChannelsContextProvider>
diff --git a/js/app/packages/block-channel/component/AttachmentsModal.tsx b/js/app/packages/block-channel/component/AttachmentsModal.tsx
index 182273d538..58f76d73e9 100644
--- a/js/app/packages/block-channel/component/AttachmentsModal.tsx
+++ b/js/app/packages/block-channel/component/AttachmentsModal.tsx
@@ -1,8 +1,6 @@
import { SplitDrawer } from '@app/component/split-layout/components/SplitDrawer';
import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
-import { messageAttachmentsStore } from '@block-channel/signal/attachment';
-import { channelStore } from '@block-channel/signal/channel';
-import { threadsStore } from '@block-channel/signal/threads';
+import { filterSafeAttachments } from '@block-channel/utils/attachments';
import { type BlockAlias, type BlockName, useBlockId } from '@core/block';
import { InlineItemPreview } from '@core/component/ItemPreview';
import { toast } from '@core/component/Toast/Toast';
@@ -10,6 +8,11 @@ import { Tooltip } from '@core/component/Tooltip';
import { UserIcon } from '@core/component/UserIcon';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
+import { useChannelQuery } from '@queries/channel/channel';
+import {
+ getTopLevelMessages,
+ getThreadMessages,
+} from '@queries/channel/derived';
import { tryMacroId, useDisplayName } from '@core/user';
import { isErr } from '@core/util/maybeResult';
import BracketLeft from '@macro-icons/macro-group-bracket-left.svg';
@@ -29,6 +32,8 @@ export function AttachmentsModal() {
const currentBlockId = useBlockId();
const { replaceOrInsertSplit } = useSplitLayout();
+ const channel = useChannelQuery(() => currentBlockId);
+
const [mentionsResource] = createResource(() =>
commsServiceClient.getMentions({ channel_id: currentBlockId })
);
@@ -50,7 +55,9 @@ export function AttachmentsModal() {
return mentions;
})();
- const all = [...(messageAttachmentsStore.get.all || []), ...mentions];
+ const channelAttachments = channel.data?.attachments ?? [];
+ const safeAttachments = filterSafeAttachments(channelAttachments);
+ const all = [...safeAttachments, ...mentions];
return all
.filter(
(a) => !a.entity_type.startsWith('static/') && a.entity_type !== 'user'
@@ -66,6 +73,15 @@ export function AttachmentsModal() {
replaceOrInsertSplit({ type: blockName, id: blockId });
};
+ const messageSenderMap = createMemo(() => {
+ const data = channel.data;
+ if (!data) return new Map<string, string>();
+ const topLevel = getTopLevelMessages(data);
+ const threads = getThreadMessages(data);
+ const all = [...topLevel, ...Object.values(threads).flat()];
+ return new Map(all.map((m) => [m.id, m.sender_id]));
+ });
+
return (
<>
<Tooltip tooltip={'View all attachments'}>
@@ -105,6 +121,7 @@ export function AttachmentsModal() {
<AttachmentItem
attachment={attachment}
onNavigate={navigateToItem}
+ senderId={messageSenderMap().get(attachment.message_id)}
/>
</Suspense>
)}
@@ -135,20 +152,11 @@ function makeAttachmentFromMention(
type AttachmentItemProps = {
attachment: Attachment;
onNavigate: (blockName: BlockName | BlockAlias, blockId: string) => void;
+ senderId: string | undefined;
};
function AttachmentItem(props: AttachmentItemProps) {
- const message = createMemo(() => {
- const channel = channelStore.get;
- const threads = threadsStore.get;
- const allMessages = [
- ...(channel.messages || []),
- ...Object.values(threads || {}).flat(),
- ];
- return allMessages.find((msg) => msg.id === props.attachment.message_id);
- });
-
- const senderId = () => message()?.sender_id || '';
+ const senderId = () => props.senderId ?? '';
const [userName] = useDisplayName(tryMacroId(senderId()));
const [preview] = useItemPreview(() => ({
@@ -185,7 +193,7 @@ function AttachmentItem(props: AttachmentItemProps) {
<span class="text-ink-extra-muted">attached</span>
<InlineItemPreview
itemId={props.attachment.entity_id}
- itemType={props.attachment.entity_type as any}
+ itemType={props.attachment.entity_type as ItemType}
/>
</span>
</button>
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/BaseInput.tsx
index 6cf820d898..1df3fc5bf1 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/BaseInput.tsx
@@ -13,7 +13,7 @@ import {
createTasksFromPotential,
replaceCheckboxesWithMentions,
} from '@block-channel/utils/taskModeConversion';
-import { useTaskMode } from '@block-channel/utils/useTaskMode';
+import { useTaskMode } from '@block-channel/hooks/taskmode';
import { isInBlock } from '@core/block';
import { LabelAndHotKey } from '@core/component/Tooltip';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
@@ -45,7 +45,6 @@ import { $getRoot } from 'lexical';
import { logger } from '@observability';
import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
import { staticFileClient } from '@service-static-files/client';
-import { createCallback } from '@solid-primitives/rootless';
import { leading, throttle } from '@solid-primitives/scheduled';
import { Button } from '@ui/components/Button';
import { activeElement } from 'app/signal/focus';
@@ -54,7 +53,6 @@ import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
type Accessor,
createEffect,
- createMemo,
createRenderEffect,
createSignal,
For,
@@ -140,11 +138,10 @@ export function BaseInput(props: BaseInputProps) {
? isDraggingOverChannelSignal
: createSignal(false);
- const attachments = createMemo(() => props.inputAttachments.store[key] ?? []);
+ const attachments = () => props.inputAttachments.store[key] ?? [];
- const hasPendingAttachments = createMemo(() =>
- attachments().some((item) => item.pending)
- );
+ const hasPendingAttachments = () =>
+ attachments().some((item) => item.pending);
const [typing, setTyping] = createSignal(false);
let remoteInactivityTimeout: ReturnType<typeof setTimeout> | undefined;
@@ -190,13 +187,13 @@ export function BaseInput(props: BaseInputProps) {
const startTyping = leading(
throttle,
- createCallback(() => {
+ () => {
if (!typing()) {
setTyping(true);
props.onStartTyping();
}
props.setLocalTyping?.(true);
- }),
+ },
1000
);
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index bc2ffaf22c..8d2e0d473e 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -1,6 +1,5 @@
import {
doesChannelRequireJoin,
- initializeChannelData,
isValidChannelData,
} from '@block-channel/signal/channel';
import { useBlockId } from '@core/block';
@@ -52,7 +51,6 @@ export default function BlockChannel(props: BlockChannelProps) {
if (!blockData_) return;
if (!isValidChannelData(blockData_)) return;
- initializeChannelData(blockData_);
setJoinState(
doesChannelRequireJoin(blockData_, userId_) ? 'REQUIRED' : 'NOT_REQUIRED'
);
diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsx
index c9a407bb5d..a35c47761e 100644
--- a/js/app/packages/block-channel/component/Channel.tsx
+++ b/js/app/packages/block-channel/component/Channel.tsx
@@ -2,19 +2,10 @@ import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';
import { URL_PARAMS } from '@block-channel/constants';
import type { ChannelData } from '@block-channel/definition';
-import {
- latestActivitySignal,
- updateActivityOnChannelClose,
- updateActivityOnChannelOpen,
-} from '@block-channel/signal/activity';
import {
isDraggingOverChannelSignal,
isValidChannelDragSignal,
} from '@block-channel/signal/attachment';
-import {
- channelStore,
- refetchChannelData,
-} from '@block-channel/signal/channel';
import { activeThreadIdSignal } from '@block-channel/signal/threads';
import { handleFileUpload } from '@block-channel/utils/inputAttachments';
import { withAnalytics } from '@coparse/analytics';
@@ -23,6 +14,7 @@ import { useBlockId } from '@core/block';
import type { EntityDragEvent } from '@macro-entity';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { useChannelActivity } from '@core/context/channels';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { TOKENS } from '@core/hotkey/tokens';
import {
@@ -39,10 +31,14 @@ import {
createEffectOnEntityTypeNotification,
useEntityHasUnreadNotifications,
} from '@notifications';
+import { useUpdateChannelsActivityMutation } from '@queries/channel/activity';
import { useChannelQuery } from '@queries/channel/channel';
+import {
+ getTopLevelMessages,
+ getThreadMessages,
+} from '@queries/channel/derived';
import type { Message } from '@service-comms/generated/models';
import { connectionGatewayClient } from '@service-connection/client';
-import { createCallback } from '@solid-primitives/rootless';
import { useBeforeLeave, useSearchParams } from '@solidjs/router';
import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
import { toast } from 'core/component/Toast/Toast';
@@ -69,23 +65,19 @@ import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
false && fileFolderDrop;
-/** 10 seconds threshold */
-const THRESHOLD = 10_000;
-
-export function createChannelRefetchEffect(channelId: string) {
- let lastTime = Date.now();
+/** Tracks channel entity when tab regains focus (throttled to 10s) */
+function createChannelTrackingEffect(channelId: string) {
+ let lastTrackTime = Date.now();
+ const TRACK_THROTTLE_MS = 10_000;
- /** Refetch channel data if the tab is focused */
createTabFocusEffect((isTabFocused) => {
- if (isTabFocused && Date.now() - lastTime > THRESHOLD) {
- console.log('tab focused, refetching channel data');
- refetchChannelData(channelId);
+ if (isTabFocused && Date.now() - lastTrackTime > TRACK_THROTTLE_MS) {
connectionGatewayClient.trackEntity({
entity_type: 'channel',
entity_id: channelId,
action: 'open',
});
- lastTime = Date.now();
+ lastTrackTime = Date.now();
}
});
}
@@ -94,14 +86,34 @@ export function Channel(props: {
data: Required<ChannelData>;
target?: TargetMessageInfo;
}) {
- const channelStoreData = channelStore.get;
- const channel = useChannelQuery(() => props.data.channel.id);
-
const [_activeThreadId, setActiveThreadId] = activeThreadIdSignal;
- const latestActivity = latestActivitySignal.get;
- const updateActivityOnOpen = createCallback(updateActivityOnChannelOpen);
- const updateActivityOnClose = createCallback(updateActivityOnChannelClose);
+ const channel = useChannelQuery(
+ () => props.data.channel.id,
+ () => ({ refetchOnWindowFocus: true })
+ );
+
+ // Derive messages and threads from query data
+ const messages = () => getTopLevelMessages(channel.data);
+ const threads = () => getThreadMessages(channel.data);
+ const reactions = () => channel.data?.reactions ?? {};
+ const attachments = () => channel.data?.attachments ?? [];
+
const channelId = useBlockId();
+
+ const latestActivity = useChannelActivity(channelId);
+
+ const [openedChannel, setOpenedChannel] = createSignal<Date>();
+
+ const updateActivityMutation = useUpdateChannelsActivityMutation();
+
+ const updateActivityOnOpen = () => {
+ setOpenedChannel(new Date());
+ updateActivityMutation.mutate({ channelId, activityType: 'view' });
+ };
+
+ const updateActivityOnClose = () =>
+ updateActivityMutation.mutate({ channelId, activityType: 'view' });
+
const { track } = withAnalytics();
let containerRef!: HTMLDivElement;
const [searchParams] = useSearchParams();
@@ -138,9 +150,9 @@ export function Channel(props: {
>(initialTargetMessage());
createMethodRegistration(blockHandle, {
- goToLocationFromParams: async (params: Record<string, any>) => {
- const threadId = params[URL_PARAMS.thread];
- const messageId = params[URL_PARAMS.message];
+ goToLocationFromParams: async (params: Record<string, unknown>) => {
+ const threadId = params[URL_PARAMS.thread] as string | undefined;
+ const messageId = params[URL_PARAMS.message] as string | undefined;
if (threadId) {
setActiveThreadId(threadId);
}
@@ -166,7 +178,7 @@ export function Channel(props: {
track(TrackingEvents.BLOCKCHANNEL.CHANNEL.OPEN);
});
- createChannelRefetchEffect(channelId);
+ createChannelTrackingEffect(channelId);
useBeforeLeave(() => {
updateActivityOnClose();
@@ -403,11 +415,16 @@ export function Channel(props: {
/>
<MessageList
channelId={channelId}
- messages={channelStoreData.messages}
+ messages={messages()}
+ threads={threads()}
+ reactions={reactions()}
+ attachments={attachments()}
+ participants={channel.data?.participants ?? []}
focusedMessageId={selectedMessageId}
setFocusedMessageId={setSelectedMessageId}
targetMessage={targetMessage}
latestActivity={latestActivity()}
+ openedChannel={openedChannel()}
orderedMessages={orderedMessages}
setOrderedMessages={setOrderedMessages}
onNavigationReady={setMessageListNav}
@@ -417,7 +434,9 @@ export function Channel(props: {
<div class="mx-auto -translate-x-1 w-full macro-message-width">
<Suspense>
<ChannelInput
+ channelId={channelId}
channelName={channel.data?.channel?.name ?? ''}
+ participants={channel.data?.participants ?? []}
inputAttachmentsStore={channelInputAttachmentsStore}
setInputAttachmentsStore={setChannelInputAttachmentsStore}
inputAttachmentsKey={channelId}
diff --git a/js/app/packages/block-channel/component/ChannelInput.tsx b/js/app/packages/block-channel/component/ChannelInput.tsx
index bf4016a8a5..20528318f9 100644
--- a/js/app/packages/block-channel/component/ChannelInput.tsx
+++ b/js/app/packages/block-channel/component/ChannelInput.tsx
@@ -1,63 +1,56 @@
-import {
- channelStore,
- useSendChannelMessageAction,
-} from '@block-channel/signal/channel';
-import { postTypingUpdate } from '@block-channel/signal/typing';
+import { useSendChannelMessageAction } from '@block-channel/signal/channel';
import {
clearDraftMessage,
loadDraftMessage,
saveDraftMessage,
} from '@block-channel/utils/draftMessages';
-import { useBlockId } from '@core/block';
import type {
DraftMessage,
InputAttachment,
} from '@core/store/cacheChannelInput';
import type { IUser } from '@core/user';
import { channelParticipantInfo } from '@core/user/util';
-import { createCallback } from '@solid-primitives/rootless';
+import { usePostTypingUpdateMutation } from '@queries/channel/typing';
+import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
import { createMemo, createSignal, onMount } from 'solid-js';
import type { SetStoreFunction } from 'solid-js/store';
import { BaseInput } from './BaseInput';
export type ChannelInputProps = {
+ channelId: string;
inputAttachmentsStore: Record<string, InputAttachment[]>;
setInputAttachmentsStore: SetStoreFunction<Record<string, InputAttachment[]>>;
inputAttachmentsKey: string;
channelName: string;
+ participants: ChannelParticipant[];
onFocusLeaveStart?: (e: KeyboardEvent) => void;
autoFocusOnMount?: boolean;
domRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
};
export function ChannelInput(props: ChannelInputProps) {
- const channelId = useBlockId();
-
- const sendMessage = useSendChannelMessageAction(() => channelId);
+ const sendMessage = useSendChannelMessageAction(() => props.channelId);
+ const typingMutation = usePostTypingUpdateMutation();
- const postTypingUpdate_ = createCallback(postTypingUpdate);
-
- const channel = channelStore.get;
const channelUsers = createMemo<IUser[]>(() => {
- const participants = channel.participants ?? [];
- return participants.map(channelParticipantInfo);
+ return props.participants.map(channelParticipantInfo);
});
- const handleChange = createCallback((content: string) => {
- if (!channelId) return;
- saveDraftMessage(channelId, {
+ const handleChange = (content: string) => {
+ if (!props.channelId) return;
+ saveDraftMessage(props.channelId, {
content,
attachments: props.inputAttachmentsStore[props.inputAttachmentsKey] ?? [],
});
- });
+ };
const [draftMessage, setDraftMessage] = createSignal<DraftMessage | null>(
null
);
onMount(() => {
- if (!channelId) return;
- const draft = loadDraftMessage(channelId);
+ if (!props.channelId) return;
+ const draft = loadDraftMessage(props.channelId);
if (draft) {
setDraftMessage(draft);
props.setInputAttachmentsStore(
@@ -70,10 +63,14 @@ export function ChannelInput(props: ChannelInputProps) {
return (
<BaseInput
placeholder={`Message ${props.channelName} — @mention to share`}
- onStartTyping={() => postTypingUpdate_('start')}
- onStopTyping={() => postTypingUpdate_('stop')}
+ onStartTyping={() =>
+ typingMutation.mutate({ channelId: props.channelId, action: 'start' })
+ }
+ onStopTyping={() =>
+ typingMutation.mutate({ channelId: props.channelId, action: 'stop' })
+ }
onSend={sendMessage}
- afterSend={() => clearDraftMessage(channelId)}
+ afterSend={() => clearDraftMessage(props.channelId)}
onChange={handleChange}
initialValue={() => draftMessage()?.content ?? ''}
inputAttachments={{
@@ -82,7 +79,7 @@ export function ChannelInput(props: ChannelInputProps) {
key: props.inputAttachmentsKey,
}}
onFocusLeaveStart={props.onFocusLeaveStart}
- closeDraft={() => clearDraftMessage(channelId)}
+ closeDraft={() => clearDraftMessage(props.channelId)}
channelUsers={channelUsers}
autoFocusOnMount={props.autoFocusOnMount}
domRef={props.domRef}
diff --git a/js/app/packages/block-channel/component/Message/ActionMenu.tsx b/js/app/packages/block-channel/component/Message/ActionMenu.tsx
index 35acd9865c..ebd227f362 100644
--- a/js/app/packages/block-channel/component/Message/ActionMenu.tsx
+++ b/js/app/packages/block-channel/component/Message/ActionMenu.tsx
@@ -1,8 +1,8 @@
-import { reactToMessage } from '@block-channel/signal/reactions';
+import { useReactToMessage } from '@block-channel/hooks/reactions';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import clickOutside from '@core/directive/clickOutside';
-import { createCallback } from '@solid-primitives/rootless';
-import { type Component, For, type Setter } from 'solid-js';
+import type { GetChannelResponseReactions } from '@service-comms/generated/models';
+import { type Accessor, type Component, For, type Setter } from 'solid-js';
import { ReactionSelector } from '../ReactionSelector';
import type { MessageAction } from './actions';
@@ -17,15 +17,16 @@ export type Action = {
export function ActionMenu(props: {
messageId: string;
+ channelId: Accessor<string>;
+ reactions: Accessor<GetChannelResponseReactions>;
actions: MessageAction[];
setReactionMenuActivated?: Setter<boolean>;
}) {
// default emojis
const defaultEmojis = ['❤️', '👍', '😂'];
- const react = createCallback((emoji: string) =>
- reactToMessage(emoji, props.messageId)
- );
+ const reactToMessage = useReactToMessage(props.channelId, props.reactions);
+ const react = (emoji: string) => reactToMessage(emoji, props.messageId);
return (
<div class="flex flex-row bg-menu items-center allow-css-brackets">
<For each={defaultEmojis}>
diff --git a/js/app/packages/block-channel/component/Message/MessageContainer.tsx b/js/app/packages/block-channel/component/Message/MessageContainer.tsx
index bf3cfc9a58..a0542de747 100644
--- a/js/app/packages/block-channel/component/Message/MessageContainer.tsx
+++ b/js/app/packages/block-channel/component/Message/MessageContainer.tsx
@@ -1,7 +1,10 @@
import { useMessageListContext } from '@block-channel/component/MessageList/MessageList';
import { COLLAPSED_THREAD_INDEX_CUTOFF } from '@block-channel/constants';
-import { messageAttachmentsStore } from '@block-channel/signal/attachment';
-import { reactToMessage } from '@block-channel/signal/reactions';
+import { useReactToMessage } from '@block-channel/hooks/reactions';
+import type {
+ Attachment,
+ GetChannelResponseReactions,
+} from '@service-comms/generated/models';
import type { MessageListContext } from '@block-channel/utils/listContext';
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { channelTheme } from '@core/component/LexicalMarkdown/theme';
@@ -27,7 +30,6 @@ import { ContextMenu } from '@kobalte/core/context-menu';
import { usePatchMessageMutation } from '@queries/channel/message';
import type { Message as MessageType } from '@service-comms/generated/models/message';
import { useUserId } from '@core/context/user';
-import { createCallback } from '@solid-primitives/rootless';
import { activeElement } from 'app/signal/focus';
import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
@@ -112,6 +114,9 @@ type MessageProps = {
listContext: MessageListContext;
setMessageContainerRef?: Setter<HTMLDivElement | undefined>;
isTarget: boolean;
+ channelId: Accessor<string>;
+ attachments: Attachment[];
+ reactions: GetChannelResponseReactions;
};
export function MessageContainer(props: MessageProps) {
@@ -139,8 +144,6 @@ export function MessageContainer(props: MessageProps) {
const userId = useUserId();
const [currentUserName] = useDisplayName(tryMacroId(userId() ?? ''));
- const attachmentStore = messageAttachmentsStore.get;
-
const [displayName] = useDisplayName(tryMacroId(message.sender_id));
let messageContainerRef!: HTMLDivElement;
@@ -177,20 +180,20 @@ export function MessageContainer(props: MessageProps) {
const isParentNewMessage = () =>
props.listContext?.isParentNewMessage ?? false;
- const previousMessage = createMemo(() => {
+ const previousMessage = () => {
return props.index() > 0
? props.orderedMessages()[props.index() - 1]
: undefined;
- });
+ };
- const newDayPreviousNonThreadMessage = createMemo(() => {
+ const newDayPreviousNonThreadMessage = () => {
const prev = props.listContext?.previousNonThreadedMessage;
if (!prev) return false;
return !isSameDay(new Date(message.created_at), new Date(prev.created_at));
- });
+ };
// We consider a message consecutive if it's from the same user and the same day and has the same thread id.
- const isConsecutive = createMemo(() => {
+ const isConsecutive = () => {
const prevMessage_ = previousMessage();
if (!prevMessage_) return false;
const prevSenderId = prevMessage_?.sender_id;
@@ -199,7 +202,7 @@ export function MessageContainer(props: MessageProps) {
prevSenderId === message.sender_id &&
isSameDay(new Date(prevMessage_.created_at), new Date(message.created_at))
);
- });
+ };
const threadState = createMemo(() => {
const threadID = message.thread_id;
@@ -294,22 +297,27 @@ export function MessageContainer(props: MessageProps) {
});
const attachments = createMemo(() =>
- message.id ? (attachmentStore[message.id] ?? []) : []
+ props.attachments.filter((a) => a.message_id === message.id)
);
const imageAttachments = createMemo(() =>
- attachments().filter((a) => a.entity_type === STATIC_IMAGE)
+ attachments().filter((a: Attachment) => a.entity_type === STATIC_IMAGE)
);
const videoAttachments = createMemo(() =>
- attachments().filter((a) => a.entity_type === STATIC_VIDEO)
+ attachments().filter((a: Attachment) => a.entity_type === STATIC_VIDEO)
);
const documentAttachments = createMemo(() =>
- attachments().filter((a) => !isStaticAttachmentType(a.entity_type))
+ attachments().filter(
+ (a: Attachment) => !isStaticAttachmentType(a.entity_type)
+ )
);
- const react = createCallback((emoji: string) =>
- reactToMessage(emoji, message.id)
+ const reactToMessage = useReactToMessage(
+ props.channelId,
+ () => props.reactions
);
+ const react = (emoji: string) => reactToMessage(emoji, message.id);
+
const onThreadAppend = () => {
const threadId = message.thread_id;
if (!threadId) return;
@@ -540,6 +548,8 @@ export function MessageContainer(props: MessageProps) {
hoverActions={
<ActionMenu
messageId={message.id}
+ channelId={props.channelId}
+ reactions={() => props.reactions}
actions={actions()}
setReactionMenuActivated={setTopBarEmojiMenuOpen}
/>
@@ -601,7 +611,11 @@ export function MessageContainer(props: MessageProps) {
content={message.content}
/>
<Show when={!message.deleted_at}>
- <MessageReactions messageId={props.message?.id ?? ''} />
+ <MessageReactions
+ messageId={props.message?.id ?? ''}
+ channelId={props.channelId}
+ reactions={() => props.reactions}
+ />
</Show>
</MessageComponent>
<Show when={isLastInCollapsedThread()}>
diff --git a/js/app/packages/block-channel/component/Message/MessageReactions.tsx b/js/app/packages/block-channel/component/Message/MessageReactions.tsx
index 36813fc207..597b37e828 100644
--- a/js/app/packages/block-channel/component/Message/MessageReactions.tsx
+++ b/js/app/packages/block-channel/component/Message/MessageReactions.tsx
@@ -1,17 +1,14 @@
-import {
- messageToReactionStore,
- reactToMessage,
-} from '@block-channel/signal/reactions';
+import { useReactToMessage } from '@block-channel/hooks/reactions';
import { EmojiButton } from '@core/component/Emoji/EmojiButton';
import { resolveEmojiFromUnicode } from '@core/component/Emoji/emojis';
import clickOutside from '@core/directive/clickOutside';
import { touchHandler } from '@core/directive/touchHandler';
import { idToDisplayName } from '@core/user';
import Tooltip from '@corvu/tooltip';
+import type { GetChannelResponseReactions } from '@service-comms/generated/models';
import { useUserId } from '@core/context/user';
-import { createCallback } from '@solid-primitives/rootless';
-import { createMemo, createSignal, For, Show } from 'solid-js';
+import { createMemo, createSignal, For, Show, type Accessor } from 'solid-js';
import { ReactionSelector } from '../ReactionSelector';
false && clickOutside;
@@ -19,23 +16,23 @@ false && touchHandler;
type MessageReactionsProps = {
messageId: string;
+ channelId: Accessor<string>;
+ reactions: Accessor<GetChannelResponseReactions>;
};
export function MessageReactions(props: MessageReactionsProps) {
const userId = useUserId();
- const messageToReaction = messageToReactionStore.get;
+ const reactionsForMessage = createMemo(() => {
+ return props.reactions()?.[props.messageId] ?? [];
+ });
- const reactionsForMessage = () => {
- return messageToReaction?.[props.messageId];
- };
+ const reactToMessage = useReactToMessage(props.channelId, props.reactions);
- const react = createCallback((emoji: string) =>
- reactToMessage(emoji, props.messageId)
- );
+ const react = (emoji: string) => reactToMessage(emoji, props.messageId);
return (
- <Show when={reactionsForMessage() && reactionsForMessage().length > 0}>
+ <Show when={reactionsForMessage().length > 0}>
<div class="flex flex-row flex-wrap items-center gap-2 mt-0.5 mb-1">
<For each={reactionsForMessage().slice(0, 10)}>
{(reaction) => {
@@ -72,7 +69,7 @@ export function MessageReactions(props: MessageReactionsProps) {
didCurrentUserReact
? 'text-accent-ink border border-accent'
: 'hover:bg-hover transition-transform border border-edge-muted transition-none hover:transition hover:scale-105'
- }
+ }
cursor-default h-8
`}
onClick={() => react(reaction.emoji)}
diff --git a/js/app/packages/block-channel/component/Message/actions.ts b/js/app/packages/block-channel/component/Message/actions.ts
index 2a84dd8e0b..29acd72860 100644
--- a/js/app/packages/block-channel/component/Message/actions.ts
+++ b/js/app/packages/block-channel/component/Message/actions.ts
@@ -1,4 +1,4 @@
-import { getUrlToMessage } from '@block-channel/state/link';
+import { getUrlToMessage } from '@block-channel/utils/link';
import { useBlockId } from '@core/block';
import { logger } from '@observability';
import ReplyIcon from '@phosphor-icons/core/regular/arrow-bend-up-left.svg?component-solid';
diff --git a/js/app/packages/block-channel/component/MessageList/MessageList.tsx b/js/app/packages/block-channel/component/MessageList/MessageList.tsx
index 718f0285df..ed4c228817 100644
--- a/js/app/packages/block-channel/component/MessageList/MessageList.tsx
+++ b/js/app/packages/block-channel/component/MessageList/MessageList.tsx
@@ -2,16 +2,12 @@ import {
COLLAPSED_THREAD_INDEX_CUTOFF,
TARGET_MESSAGE_ACTIVE_TIME,
} from '@block-channel/constants';
-import { openedChannelSignal } from '@block-channel/signal/activity';
-import { messageToReactionStore } from '@block-channel/signal/reactions';
-import {
- type ThreadStoreData,
- threadsStore,
-} from '@block-channel/signal/threads';
+import type { MessageWithThreadId } from '@block-channel/signal/threads';
import type {
ThreadView,
ThreadViewData,
} from '@block-channel/type/threadView';
+import type { GetChannelResponseReactions } from '@service-comms/generated/models';
import { loadDraftMessage } from '@block-channel/utils/draftMessages';
import {
createMessageListContextLookup,
@@ -26,6 +22,8 @@ import SunIcon from '@icon/duotone/sun-horizon-duotone.svg';
import ArrowDownIcon from '@icon/regular/arrow-down.svg';
import XIcon from '@icon/regular/x.svg';
import type { Activity as ChannelActivity } from '@service-comms/generated/models/activity';
+import type { Attachment } from '@service-comms/generated/models/attachment';
+import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
import type { Message } from '@service-comms/generated/models/message';
import { useUserId } from '@core/context/user';
import { debounce } from '@solid-primitives/scheduled';
@@ -101,10 +99,17 @@ export type MessageListNavigation = {
navigateToMessage: (messageId: string) => boolean;
};
+export type ThreadStoreData = Record<string, MessageWithThreadId[]>;
+
export type MessageListProps = {
channelId: string;
messages: Message[];
+ threads: ThreadStoreData;
+ reactions: GetChannelResponseReactions;
+ attachments: Attachment[];
+ participants: ChannelParticipant[];
latestActivity?: ChannelActivity;
+ openedChannel?: Date;
containerRef?: HTMLDivElement;
targetMessage: Accessor<TargetMessageInfo | undefined>;
focusedMessageId: Accessor<string | undefined>;
@@ -243,7 +248,6 @@ function MessageListImpl(props: MessageListProps) {
createStore<MessageListContextLookup>({});
const userId = useUserId();
- const threads = threadsStore.get;
const [viewThreads, setViewThreads] = createStore<ThreadStoreData>({});
const [threadInputAttachmentsStore, setThreadInputAttachmentsStore] =
@@ -252,8 +256,6 @@ function MessageListImpl(props: MessageListProps) {
const [isNearBottom, setIsNearBottom] = createSignal(true);
const [initialScrollComplete, setInitialScrollComplete] = createSignal(false);
- const openedChannel = openedChannelSignal.get;
-
const normalizeIndex = (index: number) => {
const length = props.orderedMessages().length;
@@ -324,13 +326,13 @@ function MessageListImpl(props: MessageListProps) {
const checkIfNewMessage = (message: Message) => {
const lastViewed_ = lastViewed();
- const openedChannel_ = openedChannel();
+ const openedChannel_ = props.openedChannel;
return (
!!lastViewed_ &&
!!openedChannel_ &&
new Date(message.created_at) > new Date(lastViewed_) &&
userId() !== message.sender_id &&
- new Date(message.created_at) < new Date(openedChannel_)
+ new Date(message.created_at) < openedChannel_
);
};
@@ -509,7 +511,7 @@ function MessageListImpl(props: MessageListProps) {
for (const message of baseMessages) {
const id = message.id;
- const threadArr = threads[id] ?? [];
+ const threadArr = props.threads[id] ?? [];
const currentView = viewThreads[id];
const isTypingThisThread = id === activeThreadId;
@@ -539,7 +541,7 @@ function MessageListImpl(props: MessageListProps) {
prevTypingId !== currentTypingId &&
dirtyTypingThreadId === prevTypingId
) {
- const threadArr = untrack(() => threads[prevTypingId] ?? []);
+ const threadArr = untrack(() => props.threads[prevTypingId] ?? []);
setViewThreads(prevTypingId, reconcile(threadArr));
dirtyTypingThreadId = undefined;
}
@@ -615,10 +617,9 @@ function MessageListImpl(props: MessageListProps) {
};
const lastMessageReaction = createMemo(() => {
- const messageToReaction = messageToReactionStore.get;
const list = props.orderedMessages();
const lastMessageId = list[list.length - 1]?.id;
- return messageToReaction[lastMessageId];
+ return props.reactions[lastMessageId];
});
const lastMessageThread = createMemo(() => {
@@ -868,6 +869,9 @@ function MessageListImpl(props: MessageListProps) {
container={containerRef()}
listContext={messageListContext[row.id]}
isTarget={isActiveTargetMessage(row.message.id)}
+ channelId={() => props.channelId}
+ attachments={props.attachments}
+ reactions={props.reactions}
/>
</Show>
);
@@ -922,6 +926,7 @@ function MessageListImpl(props: MessageListProps) {
threadInputAttachmentsStore={threadInputAttachmentsStore}
setThreadInputAttachmentsStore={setThreadInputAttachmentsStore}
setLocalTypingThreadId={setLocalTypingThreadId}
+ participants={props.participants}
/>
</div>
);
diff --git a/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx b/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx
index 3f7ab371e3..54eeb29526 100644
--- a/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx
+++ b/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx
@@ -1,6 +1,7 @@
-import { usersTypingSignal } from '@block-channel/signal/typing';
+import { useBlockId } from '@core/block';
import { Message } from '@core/component/Message';
import { idToDisplayName } from '@core/user';
+import { getTypingUsersForChannel } from '@queries/channel/typing';
import type { Message as MessageType } from '@service-comms/generated/models/message';
import { createMemo, Show } from 'solid-js';
@@ -10,9 +11,10 @@ type TypingIndicatorProps = {
};
export function TypingIndicator(props: TypingIndicatorProps) {
+ const channelId = useBlockId();
+
const typingUsers = createMemo(() => {
- const users =
- usersTypingSignal.get().get(props.threadId ?? null) ?? new Set();
+ const users = getTypingUsersForChannel(channelId, props.threadId ?? null);
return Array.from(users);
});
diff --git a/js/app/packages/block-channel/component/ParticipantManager.tsx b/js/app/packages/block-channel/component/ParticipantManager.tsx
index c96bfe6d03..e6626795aa 100644
--- a/js/app/packages/block-channel/component/ParticipantManager.tsx
+++ b/js/app/packages/block-channel/component/ParticipantManager.tsx
@@ -1,8 +1,7 @@
-import { channelStore } from '@block-channel/signal/channel';
import {
useAddParticipantsToChannel,
useRemoveParticipantsFromChannel,
-} from '@block-channel/signal/participants';
+} from '@block-channel/hooks/participants';
import { ClippedPanel } from '@core/component/ClippedPanel';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
@@ -29,9 +28,15 @@ import { VList } from 'virtua/solid';
import { beveledCorners } from '../../block-theme/signals/themeSignals';
import { UserItem } from './UserItem';
-export function ParticipantManager(props: { participantCount: number }) {
- const channel = channelStore.get;
- const channelType = () => channel?.channel?.channel_type ?? 'private';
+type ParticipantManagerProps = {
+ channelId: string;
+ channelType?: string;
+ participants: ChannelParticipant[];
+ participantCount: number;
+};
+
+export function ParticipantManager(props: ParticipantManagerProps) {
+ const channelType = () => props.channelType ?? 'private';
const users = useContacts();
const userId = useUserId();
const [usersToInvite, setUsersToInvite] = createSignal<
@@ -39,7 +44,9 @@ export function ParticipantManager(props: { participantCount: number }) {
>([]);
const canManageParticipants = () =>
channelType() !== ChannelType.organization;
- const addParticipantsToChannel = useAddParticipantsToChannel();
+ const addParticipantsToChannel = useAddParticipantsToChannel(
+ () => props.channelId
+ );
function handleAddParticipants() {
const destination = getDestinationFromOptions(usersToInvite());
@@ -56,7 +63,7 @@ export function ParticipantManager(props: { participantCount: number }) {
const options = () =>
users()
?.filter((user) => {
- return !channel?.participants.find(
+ return !props.participants.find(
(participant) => participant.user_id === user.id
);
})
@@ -128,8 +135,9 @@ export function ParticipantManager(props: { participantCount: number }) {
<div class="flex flex-col">
<ParticipantList
+ channelId={props.channelId}
editable={editable()}
- participants={channel.participants}
+ participants={props.participants}
userId={userId()!}
/>
</div>
@@ -155,6 +163,7 @@ function EmptyParticipantList(props: { query: string }) {
}
export function ParticipantList(props: {
+ channelId: string;
participants: ChannelParticipant[];
userId: string;
editable: boolean;
@@ -162,7 +171,9 @@ export function ParticipantList(props: {
let ref!: HTMLDivElement;
const [searchQuery, setSearchQuery] = createSignal('');
- const removeParticipants = useRemoveParticipantsFromChannel();
+ const removeParticipants = useRemoveParticipantsFromChannel(
+ () => props.channelId
+ );
const filteredParticipants = createMemo(() => {
if (searchQuery().trim().length === 0) return props.participants;
diff --git a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
index 9f8a96d495..fb8bcf4a55 100644
--- a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
+++ b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
@@ -1,11 +1,9 @@
import { useMessageListContext } from '@block-channel/component/MessageList/MessageList';
import {
- channelStore,
type SendMessageArgs,
useSendChannelMessageAction,
} from '@block-channel/signal/channel';
-import type { ThreadStoreData } from '@block-channel/signal/threads';
-import { postTypingUpdate } from '@block-channel/signal/typing';
+import type { MessageWithThreadId } from '@block-channel/signal/threads';
import {
clearDraftMessage,
loadDraftMessage,
@@ -14,7 +12,8 @@ import {
import { blockElementSignal } from '@core/signal/blockElement';
import type { InputAttachment } from '@core/store/cacheChannelInput';
import { channelParticipantInfo } from '@core/user/util';
-import { createCallback } from '@solid-primitives/rootless';
+import { usePostTypingUpdateMutation } from '@queries/channel/typing';
+import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
import {
createEffect,
createMemo,
@@ -26,6 +25,8 @@ import type { SetStoreFunction } from 'solid-js/store';
import { Portal } from 'solid-js/web';
import { BaseInput } from './BaseInput';
+export type ThreadStoreData = Record<string, MessageWithThreadId[]>;
+
export type ReplyInputsPortalerProps = {
channelId: string;
threads: ThreadStoreData;
@@ -34,20 +35,17 @@ export type ReplyInputsPortalerProps = {
Record<string, InputAttachment[]>
>;
setLocalTypingThreadId?: Setter<string | undefined>;
+ participants: ChannelParticipant[];
};
export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
const listContext = useMessageListContext();
const sendMessage = useSendChannelMessageAction(() => props.channelId);
+ const typingMutation = usePostTypingUpdateMutation();
- const postTypingUpdate_ = createCallback(postTypingUpdate);
const blockRef = blockElementSignal.get;
- const channel = channelStore.get;
- const channelUsers = createMemo(() => {
- const participants = channel.participants ?? [];
- return participants.map(channelParticipantInfo);
- });
+ const channelUsers = () => props.participants.map(channelParticipantInfo);
const [focusedReplyInputThreadId, setFocusedReplyInputThreadId] =
createSignal<string>();
@@ -152,8 +150,20 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
setFocusedReplyInputThreadId(undefined);
}, 100);
}}
- onStartTyping={() => postTypingUpdate_('start', threadId)}
- onStopTyping={() => postTypingUpdate_('stop', threadId)}
+ onStartTyping={() =>
+ typingMutation.mutate({
+ channelId: props.channelId,
+ action: 'start',
+ threadId,
+ })
+ }
+ onStopTyping={() =>
+ typingMutation.mutate({
+ channelId: props.channelId,
+ action: 'stop',
+ threadId,
+ })
+ }
inputAttachments={{
store: props.threadInputAttachmentsStore,
setStore: props.setThreadInputAttachmentsStore,
diff --git a/js/app/packages/block-channel/component/TaskPreviewPanel.tsx b/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
index 5e76f3d2fe..8b8f159a49 100644
--- a/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
+++ b/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
@@ -1,5 +1,5 @@
import type { PropertyApiValues } from '@core/component/Properties/types';
-import type { TaskWithProperties } from '@block-channel/utils/useTaskMode';
+import type { TaskWithProperties } from '@block-channel/hooks/taskmode';
import { For } from 'solid-js';
import { TaskPreviewRow } from './TaskPreviewRow';
diff --git a/js/app/packages/block-channel/component/TaskPreviewRow.tsx b/js/app/packages/block-channel/component/TaskPreviewRow.tsx
index 6ce966fba2..d9b53aa73e 100644
--- a/js/app/packages/block-channel/component/TaskPreviewRow.tsx
+++ b/js/app/packages/block-channel/component/TaskPreviewRow.tsx
@@ -1,4 +1,4 @@
-import type { TaskWithProperties } from '@block-channel/utils/useTaskMode';
+import type { TaskWithProperties } from '@block-channel/hooks/taskmode';
import { EntityIcon } from '@core/component/EntityIcon';
import { propertyApiValuesToNormalized } from '@core/component/Properties/api/converters';
import { Modals } from '@core/component/Properties/component/modal';
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index 5fc3975ed7..e382e5ef03 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -116,7 +116,12 @@ export function Top(props: { channelID: string }) {
/>
<AttachmentsModal />
<Show when={channelType() !== 'direct_message'}>
- <ParticipantManager participantCount={participantCount()} />
+ <ParticipantManager
+ channelId={props.channelID}
+ channelType={channelType()}
+ participants={participants()}
+ participantCount={participantCount()}
+ />
</Show>
</div>
</SplitToolbarRight>
diff --git a/js/app/packages/block-channel/hooks/message.tsx b/js/app/packages/block-channel/hooks/message.tsx
new file mode 100644
index 0000000000..6bbfcca5e4
--- /dev/null
+++ b/js/app/packages/block-channel/hooks/message.tsx
@@ -0,0 +1,100 @@
+import {
+ type InputAttachment,
+ isStaticAttachmentType,
+} from '@core/store/cacheChannelInput';
+import { getImageDimensions, getVideoDimensions } from '@core/util/media';
+import { useSendMessageMutation } from '@queries/channel/message';
+import { invalidateListChannels } from '@queries/channel/channels';
+import type { NewAttachment } from '@service-comms/generated/models';
+import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
+import { useUserId } from '@core/context/user';
+import { blockNameToItemType } from '@service-storage/client';
+import type { Accessor } from 'solid-js';
+
+function isMessageSendable(
+ content: string | undefined,
+ attachments: InputAttachment[]
+): boolean {
+ return (content && content.trim().length > 0) || attachments.length > 0;
+}
+
+export type SendMessageArgs = {
+ content: string | undefined;
+ attachments: InputAttachment[];
+ threadId?: string;
+ mentions?: SimpleMention[];
+};
+
+export function useSendChannelMessageAction(channelID: Accessor<string>) {
+ const userId = useUserId();
+
+ const mutation = useSendMessageMutation({
+ onSettled() {
+ invalidateListChannels();
+ },
+ });
+
+ return async ({
+ content,
+ attachments,
+ threadId,
+ mentions,
+ }: SendMessageArgs) => {
+ if (!userId) return;
+ if (!isMessageSendable(content, attachments)) return;
+
+ const channelId = channelID();
+ const senderId = userId()!;
+ const optimisticId = crypto.randomUUID();
+
+ const attachmentsToSend = await Promise.allSettled(
+ attachments.map(async (a) => {
+ const attachmentType = isStaticAttachmentType(a.blockName)
+ ? a.blockName
+ : blockNameToItemType(a.blockName);
+
+ if (!attachmentType) return;
+
+ let attachment: NewAttachment = {
+ entity_id: a.id,
+ entity_type: attachmentType,
+ };
+
+ if (!a.file) return attachment;
+
+ if (
+ attachmentType !== 'static/image' &&
+ attachmentType !== 'static/video'
+ ) {
+ return attachment;
+ }
+
+ const dimensions =
+ attachmentType === 'static/image'
+ ? await getImageDimensions(a.file)
+ : await getVideoDimensions(a.file);
+
+ attachment.width = dimensions.width;
+ attachment.height = dimensions.height;
+
+ return attachment;
+ })
+ );
+
+ const filteredAttachements = attachmentsToSend
+ .map((r) => (r.status === 'fulfilled' ? r.value : undefined))
+ .filter((r) => r !== undefined);
+
+ await mutation.mutateAsync({
+ channelID: channelId,
+ optimisticId,
+ senderId,
+ message: {
+ attachments: filteredAttachements,
+ content: content ?? '',
+ thread_id: threadId,
+ mentions: mentions ?? [],
+ },
+ });
+ };
+}
diff --git a/js/app/packages/block-channel/hooks/participants.tsx b/js/app/packages/block-channel/hooks/participants.tsx
new file mode 100644
index 0000000000..b4cea904ad
--- /dev/null
+++ b/js/app/packages/block-channel/hooks/participants.tsx
@@ -0,0 +1,50 @@
+import { withAnalytics } from '@coparse/analytics';
+import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
+import {
+ useAddParticipantsMutation,
+ useRemoveParticipantsMutation,
+} from '@queries/channel/participants';
+import type { Accessor } from 'solid-js';
+
+/**
+ * Hook to add participants to a channel with optimistic updates
+ */
+export function useAddParticipantsToChannel(channelId: Accessor<string>) {
+ const { track } = withAnalytics();
+ const mutation = useAddParticipantsMutation({
+ onSuccess: () => {
+ track(TrackingEvents.BLOCKCHANNEL.PARTICIPANT.ADD);
+ },
+ });
+
+ return (participants: string[]) => {
+ const id = channelId();
+ if (!id) {
+ console.error(
+ 'tried to add participants to a channel that does not exist'
+ );
+ return;
+ }
+
+ mutation.mutate({ channelId: id, participants });
+ };
+}
+
+/**
+ * Hook to remove participants from a channel with optimistic updates
+ */
+export function useRemoveParticipantsFromChannel(channelId: Accessor<string>) {
+ const mutation = useRemoveParticipantsMutation();
+
+ return (participants: string[]) => {
+ const id = channelId();
+ if (!id) {
+ console.error(
+ 'tried to remove participants from a channel that does not exist'
+ );
+ return;
+ }
+
+ mutation.mutate({ channelId: id, participants });
+ };
+}
diff --git a/js/app/packages/block-channel/hooks/reactions.tsx b/js/app/packages/block-channel/hooks/reactions.tsx
new file mode 100644
index 0000000000..0f4ae405fc
--- /dev/null
+++ b/js/app/packages/block-channel/hooks/reactions.tsx
@@ -0,0 +1,62 @@
+import { withAnalytics } from '@coparse/analytics';
+import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
+import { useUserId } from '@core/context/user';
+import {
+ useAddReactionMutation,
+ useRemoveReactionMutation,
+} from '@queries/channel/reaction';
+import type { Accessor } from 'solid-js';
+import type { GetChannelResponseReactions } from '@service-comms/generated/models';
+
+type CountedReaction = {
+ emoji: string;
+ users: string[];
+};
+
+/**
+ * Hook to react to a message. Uses the reaction mutations with optimistic updates.
+ */
+export function useReactToMessage(
+ channelId: Accessor<string>,
+ reactions: Accessor<GetChannelResponseReactions>
+) {
+ const { track } = withAnalytics();
+ const userId_ = useUserId();
+
+ const addReaction = useAddReactionMutation();
+ const removeReaction = useRemoveReactionMutation();
+
+ return async (emoji: string, messageId: string) => {
+ const userId = userId_();
+ const channelIdValue = channelId();
+ if (!channelIdValue || !userId) return;
+
+ const messageReactions = reactions()?.[messageId] ?? [];
+ const hasReacted = messageReactions.some(
+ (reaction: CountedReaction) =>
+ reaction.emoji === emoji && reaction.users.includes(userId)
+ );
+
+ if (hasReacted) {
+ await removeReaction.mutateAsync({
+ channelId: channelIdValue,
+ messageId,
+ emoji,
+ userId,
+ });
+ } else {
+ await addReaction.mutateAsync({
+ channelId: channelIdValue,
+ messageId,
+ emoji,
+ userId,
+ });
+ }
+
+ track(TrackingEvents.BLOCKCHANNEL.MESSAGE.REACTION, {
+ channelId: channelIdValue,
+ emoji,
+ action: hasReacted ? 'Remove' : 'Add',
+ });
+ };
+}
diff --git a/js/app/packages/block-channel/utils/useTaskMode.ts b/js/app/packages/block-channel/hooks/taskmode.tsx
similarity index 100%
rename from js/app/packages/block-channel/utils/useTaskMode.ts
rename to js/app/packages/block-channel/hooks/taskmode.tsx
diff --git a/js/app/packages/block-channel/signal/activity.ts b/js/app/packages/block-channel/signal/activity.ts
deleted file mode 100644
index 5ced77a8eb..0000000000
--- a/js/app/packages/block-channel/signal/activity.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { createBlockSignal } from '@core/block';
-import { useChannelActivity } from '@core/context/channels';
-import { invalidateChannelsActivity } from '@queries/channel/activity';
-import { commsServiceClient } from '@service-comms/client';
-import type { Activity as ChannelActivity } from '@service-comms/generated/models/activity';
-
-import { channelStore } from './channel';
-
-export const latestActivitySignal = createBlockSignal<ChannelActivity>();
-export const openedChannelSignal = createBlockSignal<Date>();
-
-export async function updateActivityOnChannelOpen() {
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId) return;
-
- const latestActivity = useChannelActivity(channelId);
-
- const setLatestActivity = latestActivitySignal.set;
- const setOpenedChannel = openedChannelSignal.set;
-
- const lastActivity = latestActivity();
-
- if (lastActivity) {
- setLatestActivity(lastActivity);
- }
-
- setOpenedChannel(new Date());
-
- await commsServiceClient.postActivity({
- activity_type: 'view',
- channel_id: channelId,
- });
-
- invalidateChannelsActivity();
-}
-
-export async function updateActivityOnChannelClose() {
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId) return;
-
- await commsServiceClient.postActivity({
- activity_type: 'view',
- channel_id: channelId,
- });
-}
-
-export async function updateActivityOnMessageReceived(
- incomingChannelId: string
-) {
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId || channelId === incomingChannelId) return;
- invalidateChannelsActivity();
-}
-
-export async function updateActivityOnMessageSend() {
- invalidateChannelsActivity();
-}
diff --git a/js/app/packages/block-channel/signal/attachment.ts b/js/app/packages/block-channel/signal/attachment.ts
index e8d345fd57..b53f0e7b27 100644
--- a/js/app/packages/block-channel/signal/attachment.ts
+++ b/js/app/packages/block-channel/signal/attachment.ts
@@ -1,68 +1,3 @@
-import { createBlockSignal, createBlockStore } from '@core/block';
-import { isStaticAttachmentType } from '@core/store/cacheChannelInput';
-import type { Attachment } from '@service-comms/generated/models/attachment';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
-import { useUserId } from '@core/context/user';
-import { isItemType } from '@service-storage/client';
-import { channelStore } from './channel';
-
+import { createBlockSignal } from '@core/block';
export const isDraggingOverChannelSignal = createBlockSignal(false);
export const isValidChannelDragSignal = createBlockSignal(true);
-
-export const messageAttachmentsStore = createBlockStore<
- Record<string, Attachment[]>
->({});
-
-// NOTE (seamus) : we briefly sent a few attachments on dev with block names
-// instead of itemTypes as the entity type. This breaks the item preview api
-// in a hard to predict way - just filter them here.
-function isSafeAttachment(attachment: Attachment) {
- if (isStaticAttachmentType(attachment.entity_type)) return true;
- if (isItemType(attachment.entity_type)) return true;
- return false;
-}
-
-export function initializeAttachments(attachments: Attachment[]) {
- const setAttachmentsStore = messageAttachmentsStore.set;
- const safeAttachments = attachments.filter(isSafeAttachment);
- setAttachmentsStore('all', safeAttachments);
- const grouped = safeAttachments.reduce(
- (acc, item) => {
- const id = item.message_id;
- if (!acc[id]) {
- acc[id] = [];
- }
- acc[id].push(item);
- return acc;
- },
- {} as Record<string, Attachment[]>
- );
- setAttachmentsStore(grouped);
-}
-
-export function addAttachmentToMessage(attachment: Attachment) {
- const setAttachmentsStore = messageAttachmentsStore.set;
- setAttachmentsStore(attachment.message_id, (prev) => [
- ...(prev ?? []),
- attachment,
- ]);
-}
-
-createConnectionBlockWebsocketEffect((msg) => {
- if (msg.type === 'comms_attachment') {
- const userId_ = useUserId();
- const userId = userId_();
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId || !userId) return;
- let value = JSON.parse(msg.data as any);
-
- const { channel_id: targetChannelId, attachments } = value;
-
- if (targetChannelId === channelId) {
- for (const attachment of attachments) {
- addAttachmentToMessage(attachment);
- }
- }
- }
-});
diff --git a/js/app/packages/block-channel/signal/channel.ts b/js/app/packages/block-channel/signal/channel.ts
index 81986944d7..2a2d5d9f44 100644
--- a/js/app/packages/block-channel/signal/channel.ts
+++ b/js/app/packages/block-channel/signal/channel.ts
@@ -1,66 +1,16 @@
import type { ChannelData } from '@block-channel/definition';
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
-import { createBlockMemo, createBlockStore } from '@core/block';
-import { invalidateListChannels } from '@queries/channel/channels';
import {
type InputAttachment,
isStaticAttachmentType,
} from '@core/store/cacheChannelInput';
-import { isErr } from '@core/util/maybeResult';
import { getImageDimensions, getVideoDimensions } from '@core/util/media';
import { useSendMessageMutation } from '@queries/channel/message';
-import { commsServiceClient } from '@service-comms/client';
+import { invalidateListChannels } from '@queries/channel/channels';
import type { NewAttachment } from '@service-comms/generated/models';
-import type { Attachment } from '@service-comms/generated/models/attachment';
-import type { Channel } from '@service-comms/generated/models/channel';
-import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
-import type { Message } from '@service-comms/generated/models/message';
-import type { ParticipantAccess } from '@service-comms/generated/models/participantAccess';
import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
import { useUserId } from '@core/context/user';
import { blockNameToItemType } from '@service-storage/client';
-import { createCallback } from '@solid-primitives/rootless';
-import { toast } from 'core/component/Toast/Toast';
import type { Accessor } from 'solid-js';
-import { updateActivityOnMessageReceived } from './activity';
-import { initializeAttachments, messageAttachmentsStore } from './attachment';
-import { messageToReactionStore } from './reactions';
-import {
- type MessageWithThreadId,
- type ThreadStoreData,
- threadsStore,
- upsertInThread,
-} from './threads';
-
-const { track } = withAnalytics();
-
-type ChannelStoreData = {
- messages: Message[];
- channel: Channel | undefined;
- participants: ChannelParticipant[];
- id: string | undefined;
- access: ParticipantAccess | undefined;
-};
-
-export const channelStore = createBlockStore<ChannelStoreData>({
- messages: [],
- channel: undefined,
- participants: [],
- id: undefined,
- access: undefined,
-});
-
-export const isChannelAdminOrOwnerMemo = createBlockMemo(() => {
- const channel = channelStore.get;
- if (!channel) return false;
- return (
- channel.access &&
- channel.access !== 'NoAccess' &&
- ['admin', 'owner'].includes(channel.access.Access.role)
- );
-});
export function isValidChannelData(
data: ChannelData
@@ -81,119 +31,6 @@ export function doesChannelRequireJoin(
);
}
-export async function refetchChannelData(channelId: string) {
- const initialize = createCallback(initializeChannelData);
-
- let res = await commsServiceClient.getChannel({
- channel_id: channelId,
- });
-
- const [_, data] = res;
-
- if (isErr(res) || !data || !isValidChannelData(data)) {
- toast.alert('Failed to refetch channel');
- return;
- }
-
- initialize(data);
-}
-
-/** Initializes all of the channel signals / stores
- * based on the block data passed in */
-export function initializeChannelData(data: Required<ChannelData>) {
- const setChannelStore = channelStore.set;
- const setThreadsStore = threadsStore.set;
- const setMessageToReaction = messageToReactionStore.set;
-
- setChannelStore('id', data.channel.id);
- setChannelStore('participants', data.participants ?? []);
- setChannelStore('channel', data.channel);
- setChannelStore('access', data.access);
-
- const initialMessages = data.messages ?? [];
-
- // messages that are not a part of a thread
- const messages = initialMessages.filter((m: Message) => !m.thread_id);
- // All of the messages that are a part of the thread
- let messagesInThreads: MessageWithThreadId[] = initialMessages.filter(
- (m: Message) => !!m.thread_id
- ) as MessageWithThreadId[];
-
- let threads: ThreadStoreData = {};
-
- // correlate each message to the thread it belongs to
- for (let message of messagesInThreads) {
- let prevChildren = threads[message.thread_id] ?? [];
- threads[message.thread_id] = [...prevChildren, message];
- }
-
- setChannelStore('messages', messages);
- // Initialize map of message id -> reactions
- setMessageToReaction(data.reactions ?? {});
- setThreadsStore(threads);
-
- initializeAttachments(data.attachments ?? []);
-
- commsServiceClient.postActivity({
- activity_type: 'view',
- channel_id: data.channel.id,
- });
-}
-
-function upsertMessage(message: Message) {
- let [channel, setChannel] = channelStore;
-
- let messages = channel.messages;
- let index = messages.findIndex((m) => m.id === message.id);
- if (index === -1) {
- setChannel('messages', (prev) => [...prev, message]);
- } else {
- setChannel('messages', index, message);
- }
-}
-
-function upsertAttachment(messageId: string, attachments: Attachment[]) {
- let attachmentStore = messageAttachmentsStore.get;
- let messageAttachments = attachmentStore[messageId];
- if (!messageAttachments) {
- console.error('message attachments not found', messageId);
- return;
- }
- messageAttachmentsStore.set(messageId, attachments);
-}
-
-function optimisticChannelMessage({
- channelId,
- messageId,
- content,
- threadId,
- senderId,
-}: {
- channelId: string;
- messageId: string;
- threadId?: string;
- content: string;
- senderId: string;
-}) {
- const now = new Date().toISOString();
-
- const message: Message = {
- id: messageId,
- channel_id: channelId,
- content,
- sender_id: senderId,
- created_at: now,
- updated_at: now,
- thread_id: threadId,
- };
-
- if (threadId) {
- upsertInThread(message as MessageWithThreadId);
- } else {
- upsertMessage(message);
- }
-}
-
function isMessageSendable(
content: string | undefined,
attachments: InputAttachment[]
@@ -209,22 +46,12 @@ export type SendMessageArgs = {
};
export function useSendChannelMessageAction(channelID: Accessor<string>) {
- const optimisticSend = createCallback(optimisticChannelMessage);
const userId = useUserId();
const mutation = useSendMessageMutation({
onSettled() {
invalidateListChannels();
},
- onSuccess(_, variables) {
- const message = variables.message;
- track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
- channelId: variables.channelID,
- contentLength: message.content?.length ?? 0,
- attachmentsLength: message.attachments.length,
- inThread: message.thread_id !== undefined,
- });
- },
});
return async ({
@@ -237,6 +64,8 @@ export function useSendChannelMessageAction(channelID: Accessor<string>) {
if (!isMessageSendable(content, attachments)) return;
const channelId = channelID();
+ const senderId = userId()!;
+ const optimisticId = crypto.randomUUID();
const attachmentsToSend = await Promise.allSettled(
attachments.map(async (a) => {
@@ -276,8 +105,10 @@ export function useSendChannelMessageAction(channelID: Accessor<string>) {
.map((r) => (r.status === 'fulfilled' ? r.value : undefined))
.filter((r) => r !== undefined);
- const data = await mutation.mutateAsync({
+ await mutation.mutateAsync({
channelID: channelId,
+ optimisticId,
+ senderId,
message: {
attachments: filteredAttachements,
content: content ?? '',
@@ -285,51 +116,5 @@ export function useSendChannelMessageAction(channelID: Accessor<string>) {
mentions: mentions ?? [],
},
});
-
- optimisticSend({
- channelId,
- messageId: data.id,
- content: content ?? '',
- threadId,
- senderId: userId()!,
- });
};
}
-
-createConnectionBlockWebsocketEffect((msg) => {
- const channel = channelStore.get;
- const upsert = createCallback(upsertMessage);
- const upsertThread = createCallback(upsertInThread);
- const updateActivity = createCallback(updateActivityOnMessageReceived);
- const channelId = channel?.channel?.id;
- if (!channelId) return;
- if (msg.type === 'comms_message') {
- //TODO: make this better, once things are more fleshed out
- let value = JSON.parse(msg.data as any);
- updateActivity(value.channel_id);
- if (value.channel_id !== channelId) {
- return;
- }
- if (!value.thread_id) {
- upsert(value);
- } else {
- upsertThread(value);
- }
- }
-});
-
-// Update on attachment deletion
-createConnectionBlockWebsocketEffect((msg) => {
- const channel = channelStore.get;
- const updateActivity = createCallback(updateActivityOnMessageReceived);
- const channelId = channel?.channel?.id;
- if (!channelId) return;
- if (msg.type === 'comms_attachment') {
- let value = JSON.parse(msg.data as any);
- updateActivity(value.channel_id);
- if (value.channel_id !== channelId) {
- return;
- }
- upsertAttachment(value.message_id, value.attachments);
- }
-});
diff --git a/js/app/packages/block-channel/signal/participants.ts b/js/app/packages/block-channel/signal/participants.ts
deleted file mode 100644
index b056d63c91..0000000000
--- a/js/app/packages/block-channel/signal/participants.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
-import { isErr } from '@core/util/maybeResult';
-import { commsServiceClient } from '@service-comms/client';
-import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
-import { toast } from 'core/component/Toast/Toast';
-import { channelStore } from './channel';
-
-export function useAddParticipantsToChannel() {
- const [channel, setChannel] = channelStore;
- const { track } = withAnalytics();
-
- return async (participants: string[]) => {
- const channelId = channel.channel?.id;
- if (!channelId) {
- console.error(
- 'tried to add participants to a channel that does not exist'
- );
- return;
- }
-
- let newParticipants: ChannelParticipant[] = participants.map((p) => ({
- user_id: p,
- role: 'member',
- left_at: null,
- joined_at: new Date().toISOString(),
- channel_id: channelId,
- }));
-
- setChannel('participants', (prev) => [...prev, ...newParticipants]);
-
- const res = await commsServiceClient.addParticipantsToChanenl({
- channel_id: channelId,
- participants: participants,
- });
-
- if (isErr(res)) {
- toast.failure('Failed to add participants to channel');
- console.error(res);
- return;
- }
-
- track(TrackingEvents.BLOCKCHANNEL.PARTICIPANT.ADD);
- };
-}
-
-export function useRemoveParticipantsFromChannel() {
- const [channel, setChannel] = channelStore;
-
- return async (participants: string[]) => {
- const channelId = channel.channel?.id;
- if (!channelId) {
- console.error(
- 'tried to remove participants from a channel that does not exist'
- );
- return;
- }
-
- setChannel('participants', (prev) =>
- prev.filter((p) => !participants.includes(p.user_id))
- );
-
- const res = await commsServiceClient.removeParticipantsFromChannel({
- channel_id: channelId,
- participants: participants,
- });
-
- if (isErr(res)) {
- toast.failure('Failed to remove participants from channel');
- console.error(res);
- return;
- }
- };
-}
diff --git a/js/app/packages/block-channel/signal/pendingLocationParams.ts b/js/app/packages/block-channel/signal/pendingLocationParams.ts
deleted file mode 100644
index 23bbf1318d..0000000000
--- a/js/app/packages/block-channel/signal/pendingLocationParams.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { createBlockSignal } from '@core/block';
-
-export const pendingLocationParamsSignal = createBlockSignal<
- Record<string, string> | undefined
->();
diff --git a/js/app/packages/block-channel/signal/reactions.ts b/js/app/packages/block-channel/signal/reactions.ts
deleted file mode 100644
index f4bb026106..0000000000
--- a/js/app/packages/block-channel/signal/reactions.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
-import { createBlockStore } from '@core/block';
-import { commsServiceClient } from '@service-comms/client';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
-import { useUserId } from '@core/context/user';
-import { channelStore } from './channel';
-
-type CountedReaction = {
- emoji: string;
- users: string[];
-};
-
-export const messageToReactionStore = createBlockStore<
- Record<string, CountedReaction[]>
->({});
-
-export async function reactToMessage(emoji: string, messageId: string) {
- const { track } = withAnalytics();
- const channel = channelStore.get;
- const channelId = channel?.id;
- const userId_ = useUserId();
- const userId = userId_();
- if (!channelId || !userId) return;
-
- const messageToReaction = messageToReactionStore.get;
- const setMessageToReaction = messageToReactionStore.set;
- let action: 'Add' | 'Remove' = 'Add';
-
- let prev = messageToReaction?.[messageId] ?? [];
-
- if (
- prev.some(
- (reaction) => reaction.emoji === emoji && reaction.users.includes(userId)
- )
- ) {
- action = 'Remove';
- }
-
- // Optimistically update the UI
- const optimisticReactions = prev.slice();
- const existingReactionIndex = optimisticReactions.findIndex(
- (r) => r.emoji === emoji
- );
-
- if (action === 'Add') {
- if (existingReactionIndex >= 0) {
- // Add user to existing reaction
- optimisticReactions[existingReactionIndex] = {
- ...optimisticReactions[existingReactionIndex],
- users: [...optimisticReactions[existingReactionIndex].users, userId],
- };
- } else {
- // Create new reaction
- optimisticReactions.push({
- emoji,
- users: [userId],
- });
- }
- } else {
- // Remove user from reaction
- if (existingReactionIndex >= 0) {
- const updatedUsers = optimisticReactions[
- existingReactionIndex
- ].users.filter((id) => id !== userId);
-
- if (updatedUsers.length === 0) {
- // Remove reaction entirely if no users left
- optimisticReactions.splice(existingReactionIndex, 1);
- } else {
- optimisticReactions[existingReactionIndex] = {
- ...optimisticReactions[existingReactionIndex],
- users: updatedUsers,
- };
- }
- }
- }
-
- setMessageToReaction(messageId, optimisticReactions);
-
- try {
- await commsServiceClient.postReaction({
- channel_id: channelId,
- action,
- emoji: emoji,
- message_id: messageId,
- });
- } catch (e) {
- console.error(e);
- // Revert optimistic update on error
- setMessageToReaction(messageId, prev);
- }
-
- track(TrackingEvents.BLOCKCHANNEL.MESSAGE.REACTION, {
- channelId,
- emoji,
- action,
- });
-}
-
-createConnectionBlockWebsocketEffect((msg) => {
- if (msg.type === 'comms_reaction') {
- const userId_ = useUserId();
- const userId = userId_();
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- const setMessageToReaction = messageToReactionStore.set;
- if (!channelId || !userId) return;
- //TODO: make this better, once things are more fleshed out
- let value = JSON.parse(msg.data as any);
- const { channel_id: targetChannelId, reactions } = value;
-
- if (targetChannelId === channelId) {
- setMessageToReaction(value.message_id, reactions);
- }
- }
-});
diff --git a/js/app/packages/block-channel/signal/threads.ts b/js/app/packages/block-channel/signal/threads.ts
index a8bc546e76..02c2492c52 100644
--- a/js/app/packages/block-channel/signal/threads.ts
+++ b/js/app/packages/block-channel/signal/threads.ts
@@ -1,40 +1,14 @@
-import { createBlockSignal, createBlockStore } from '@core/block';
+import { createBlockSignal } from '@core/block';
import type { Message } from '@service-comms/generated/models/message';
import { useSearchParams } from '@solidjs/router';
-// message/thread id -> thread
-export type ThreadStoreData = Record<string, MessageWithThreadId[]>;
-
export type MessageWithThreadId = Message & {
thread_id: NonNullable<Message['thread_id']>;
};
-/** stores all of the threads in the channel parent_message_id -> messages */
-export const threadsStore = createBlockStore<ThreadStoreData>({});
/** stores the id of the thread currently being viewed */
export const activeThreadIdSignal = createBlockSignal<string>();
-/** Updates a message in a thread
- * if the message is not in a thread, it will be added */
-export function upsertInThread(message: MessageWithThreadId) {
- const threadId = message.thread_id;
- const [threads, setThreads] = threadsStore;
-
- const thread = threads[threadId] ?? [];
- const index = thread.findIndex((m) => m.id === message.id);
-
- if (thread && index !== -1) {
- setThreads(threadId, index, message);
- } else {
- setThreads(threadId, (prev) => {
- if (!prev) {
- return [message];
- }
- return [...prev, message];
- });
- }
-}
-
/** Toggle the active thread by id
* if the thread is already active, it will be closed */
export function toggleThread(threadId?: string) {
diff --git a/js/app/packages/block-channel/signal/typing.ts b/js/app/packages/block-channel/signal/typing.ts
deleted file mode 100644
index 06f5e2d363..0000000000
--- a/js/app/packages/block-channel/signal/typing.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { createBlockSignal } from '@core/block';
-import { commsServiceClient } from '@service-comms/client';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
-import { useUserId } from '@core/context/user';
-import { channelStore } from './channel';
-
-export const usersTypingSignal = createBlockSignal<
- Map<string | null, Set<string>>
->(new Map([[null, new Set()]]));
-
-function addTypingUser(user_id: string, thread_id: string | null = null) {
- usersTypingSignal.set((prev) => {
- const newMap = new Map(prev);
- const threadUsers = newMap.get(thread_id) || new Set();
- newMap.set(thread_id, new Set([...threadUsers, user_id]));
- return newMap;
- });
-}
-
-function removeTypingUser(user_id: string, thread_id: string | null = null) {
- usersTypingSignal.set((prev) => {
- const newMap = new Map(prev);
- const threadUsers = newMap.get(thread_id);
- if (threadUsers) {
- newMap.set(
- thread_id,
- new Set(Array.from(threadUsers).filter((id) => id !== user_id))
- );
- }
- return newMap;
- });
-}
-
-export async function postTypingUpdate(
- action: 'start' | 'stop',
- threadId?: string
-) {
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId || !channel) return;
-
- try {
- await commsServiceClient.postTypingUpdate({
- channel_id: channelId,
- action,
- thread_id: threadId,
- });
- } catch (e) {
- console.error(`failed to post typing update ${e}`);
- // TODO: handle error
- }
-}
-
-createConnectionBlockWebsocketEffect((msg) => {
- if (msg.type === 'comms_typing') {
- const userId_ = useUserId();
- const userId = userId_();
- const channel = channelStore.get;
- const channelId = channel?.channel?.id;
- if (!channelId || !userId) return;
- //TODO: make this better, once things are more fleshed out
- let value = JSON.parse(msg.data as any);
-
- const { channel_id: targetChannelId, user_id, action, thread_id } = value;
-
- // don't care about updates for the current user
- if (user_id === userId) return;
-
- if (targetChannelId === channelId) {
- if (action === 'start') {
- addTypingUser(user_id, thread_id);
- } else {
- removeTypingUser(user_id, thread_id);
- }
- }
- }
-});
diff --git a/js/app/packages/block-channel/utils/attachments.ts b/js/app/packages/block-channel/utils/attachments.ts
new file mode 100644
index 0000000000..1a4c951902
--- /dev/null
+++ b/js/app/packages/block-channel/utils/attachments.ts
@@ -0,0 +1,20 @@
+import { isStaticAttachmentType } from '@core/store/cacheChannelInput';
+import type { Attachment } from '@service-comms/generated/models/attachment';
+import { isItemType } from '@service-storage/client';
+
+/**
+ * Filter out unsafe attachments that might have been sent with block names
+ * instead of itemTypes as the entity type.
+ */
+export function isSafeAttachment(attachment: Attachment) {
+ if (isStaticAttachmentType(attachment.entity_type)) return true;
+ if (isItemType(attachment.entity_type)) return true;
+ return false;
+}
+
+/**
+ * Filter attachments to only safe ones
+ */
+export function filterSafeAttachments(attachments: Attachment[]): Attachment[] {
+ return attachments.filter(isSafeAttachment);
+}
diff --git a/js/app/packages/block-channel/state/link.ts b/js/app/packages/block-channel/utils/link.ts
similarity index 100%
rename from js/app/packages/block-channel/state/link.ts
rename to js/app/packages/block-channel/utils/link.ts
diff --git a/js/app/packages/block-channel/utils/taskModeConversion.ts b/js/app/packages/block-channel/utils/taskModeConversion.ts
index 9558477f3b..ffd92e2f02 100644
--- a/js/app/packages/block-channel/utils/taskModeConversion.ts
+++ b/js/app/packages/block-channel/utils/taskModeConversion.ts
@@ -1,4 +1,4 @@
-import type { TaskWithProperties } from './useTaskMode';
+import type { TaskWithProperties } from '../hooks/taskmode';
import { propertyValueToApi } from '@core/component/Properties/api/converters';
import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
import { createTask } from '@core/util/create';
diff --git a/js/app/packages/macro-entity/src/components/Provider.tsx b/js/app/packages/macro-entity/src/components/Provider.tsx
index cff10c646f..6ba58ff86f 100644
--- a/js/app/packages/macro-entity/src/components/Provider.tsx
+++ b/js/app/packages/macro-entity/src/components/Provider.tsx
@@ -9,7 +9,6 @@ import { fetchApiToken } from '../queries/auth';
import { queryClient } from '../queries/client';
import { queryKeys } from '../queries/key';
import type { EntityData } from '../types/entity';
-import { QuerySyncProvider } from '@queries/sync/SyncProvider';
// NOTE: leaving this in as reference for now.
// Turning this off due to [M-5344]. This is likely unnecessary.
@@ -59,7 +58,7 @@ export function Provider(props: ParentProps) {
return (
<QueryClientProvider client={queryClient}>
- <QuerySyncProvider>{props.children}</QuerySyncProvider>
+ {props.children}
</QueryClientProvider>
);
}
diff --git a/js/app/packages/queries/channel/activity.ts b/js/app/packages/queries/channel/activity.ts
index c65e383edc..b89e1ba8f3 100644
--- a/js/app/packages/queries/channel/activity.ts
+++ b/js/app/packages/queries/channel/activity.ts
@@ -29,6 +29,7 @@ export function useUpdateChannelsActivityMutation(
>
) {
return useMutation(() => ({
+ gcTime: 0,
mutationFn: async (vars: UpdateChannelActivityMutationVars) =>
await throwOnErr(
async () =>
diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.ts
index 8da726f5cb..ecdc7efea6 100644
--- a/js/app/packages/queries/channel/channel.ts
+++ b/js/app/packages/queries/channel/channel.ts
@@ -72,28 +72,71 @@ export function useChannelQuery(
}, queryClient);
}
+type WithChannelId<T> = T & { channelId: string };
+
+export type UpdateChannelNameContext = {
+ previousName: string | null | undefined;
+ previousUpdatedAt: string;
+};
+
+/**
+ * Optimistically update the channel name.
+ * Returns minimal context: only the previous name and timestamp.
+ */
export function optimisticUpdateChannelName(
- channelID: string,
- newName: string
-) {
- const queryKey = channelKeys.withID(channelID).queryKey;
+ vars: WithChannelId<{ name: string }>
+): UpdateChannelNameContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
queryClient.cancelQueries({ queryKey });
+ let context: UpdateChannelNameContext | undefined;
+
queryClient.setQueriesData(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
- if (!prev) return;
+ if (!prev) return prev;
- const next = {
+ context = {
+ previousName: prev.channel.name,
+ previousUpdatedAt: prev.channel.updated_at,
+ };
+
+ return {
...prev,
channel: {
...prev.channel,
- name: newName,
- updatedAt: new Date().toISOString(),
+ name: vars.name,
+ updated_at: new Date().toISOString(),
},
};
+ }
+ );
+
+ return context;
+}
- return { ...next };
+/**
+ * Rollback an optimistic channel name update.
+ */
+export function rollbackUpdateChannelName(
+ channelId: string,
+ context: UpdateChannelNameContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ return {
+ ...prev,
+ channel: {
+ ...prev.channel,
+ name: context.previousName,
+ updated_at: context.previousUpdatedAt,
+ },
+ };
}
);
}
@@ -104,6 +147,18 @@ export function invalidateChannelWithID(channelID: string) {
});
}
+/**
+ * Marks the channel query as stale without triggering an immediate refetch.
+ * Uses `refetchType: 'inactive'` so queries only refetch when they become active again.
+ * Use this after WebSocket updates to ensure eventual consistency without redundant fetches.
+ */
+export function softInvalidateChannelWithID(channelID: string) {
+ queryClient.invalidateQueries({
+ queryKey: channelKeys.withID(channelID).queryKey,
+ refetchType: 'inactive',
+ });
+}
+
export function optimisticUpdateChannelViewedAt(channelId: string) {
const now = new Date().toISOString();
diff --git a/js/app/packages/queries/channel/derived.ts b/js/app/packages/queries/channel/derived.ts
new file mode 100644
index 0000000000..43a61e8118
--- /dev/null
+++ b/js/app/packages/queries/channel/derived.ts
@@ -0,0 +1,111 @@
+import type {
+ Attachment,
+ GetChannelResponse,
+ GetChannelResponseReactions,
+ Message,
+} from '@service-comms/generated/models';
+
+export type MessageWithThreadId = Message & {
+ thread_id: NonNullable<Message['thread_id']>;
+};
+
+/**
+ * Get top-level messages (messages that are not replies in a thread)
+ */
+export function getTopLevelMessages(data: GetChannelResponse): Message[] {
+ return data.messages.filter((m) => !m.thread_id);
+}
+
+/**
+ * Get thread messages grouped by parent message ID
+ */
+export function getThreadMessages(
+ data: GetChannelResponse
+): Record<string, MessageWithThreadId[]> {
+ const threads: Record<string, MessageWithThreadId[]> = {};
+
+ for (const message of data.messages) {
+ if (message.thread_id) {
+ const threadId = message.thread_id;
+ if (!threads[threadId]) {
+ threads[threadId] = [];
+ }
+ threads[threadId].push(message as MessageWithThreadId);
+ }
+ }
+
+ return threads;
+}
+
+/**
+ * Check if the current user is an admin or owner of the channel
+ */
+export function isChannelAdminOrOwner(data: GetChannelResponse): boolean {
+ const access = data.access;
+ if (!access || access === 'NoAccess') return false;
+ return ['admin', 'owner'].includes(access.Access.role);
+}
+
+export function getReactionsForMessage(
+ reactions: GetChannelResponseReactions,
+ messageId: string
+) {
+ return reactions[messageId] ?? [];
+}
+
+export function getAttachmentsByMessageId(
+ attachments: Attachment[]
+): Record<string, Attachment[]> {
+ return attachments.reduce(
+ (acc, attachment) => {
+ const id = attachment.message_id;
+ if (!acc[id]) {
+ acc[id] = [];
+ }
+ acc[id].push(attachment);
+ return acc;
+ },
+ {} as Record<string, Attachment[]>
+ );
+}
+
+/**
+ * Get a message by ID from the channel data
+ */
+export function getMessageById(
+ data: GetChannelResponse,
+ messageId: string
+): Message | undefined {
+ return data.messages.find((m) => m.id === messageId);
+}
+
+/**
+ * Get attachments for a specific message
+ */
+export function getAttachmentsForMessage(
+ attachments: Attachment[],
+ messageId: string
+): Attachment[] {
+ return attachments.filter((a) => a.message_id === messageId);
+}
+
+/**
+ * Get a participant by user ID
+ */
+export function getParticipantById(data: GetChannelResponse, userId: string) {
+ return data.participants.find((p) => p.user_id === userId);
+}
+
+/**
+ * Check if a user has reacted to a message with a specific emoji
+ */
+export function hasUserReacted(
+ reactions: GetChannelResponseReactions,
+ messageId: string,
+ userId: string,
+ emoji: string
+): boolean {
+ const messageReactions = reactions[messageId] ?? [];
+ const reaction = messageReactions.find((r) => r.emoji === emoji);
+ return reaction?.users.includes(userId) ?? false;
+}
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
index 99bc63fcc5..5ca75fb21d 100644
--- a/js/app/packages/queries/channel/keys.ts
+++ b/js/app/packages/queries/channel/keys.ts
@@ -7,3 +7,10 @@ export const channelKeys = createQueryKeys('channel', {
activity: null,
listChannels: null,
});
+
+export const ChannelNonceKeys = {
+ MESSAGE: 'comms_message',
+ REACTION: 'comms_reaction',
+ TYPING: 'comms_typing',
+ ATTACHMENT: 'comms_attachment',
+} as const;
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index c45ddc2700..e91e113458 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -1,45 +1,356 @@
import { TrackingEvents, withAnalytics } from '@coparse/analytics';
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/maybeResult';
-import { invalidateChannelWithID } from '@queries/channel/channel';
+import { softInvalidateChannelWithID } from '@queries/channel/channel';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
type IdResponse,
type MessageResponse,
} from '@service-comms/client';
-import type { PostMessageRequest } from '@service-comms/generated/models';
+import type {
+ Attachment,
+ ChannelMessage,
+ CountedReaction,
+ GetChannelResponse,
+ Message,
+ PostMessageRequest,
+} from '@service-comms/generated/models';
import { useMutation } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { channelKeys, ChannelNonceKeys } from './keys';
+import { createMutationNonce, registerNonce } from '../nonce';
+
+type WithChannelId<T> = T & { channelId: string };
+type WithOptimisticId<T> = T & { optimisticId: string };
+type WithSenderId<T> = T & { senderId: string };
+
+export type InsertMessageContext = {
+ optimisticId: string;
+};
+
+export type DeleteMessageContext = {
+ deletedMessage: Message;
+ deletedReactions: CountedReaction[];
+ deletedAttachments: Attachment[];
+};
+
+export type UpdateMessageContext = {
+ messageId: string;
+ previousContent: string;
+ previousEditedAt: string | null | undefined;
+ previousUpdatedAt: string;
+};
+
+/**
+ * Optimistically insert a new message into the channel cache.
+ * Returns minimal context for rollback (just the optimistic ID).
+ */
+export function optimisticInsertChannelMessage(
+ vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>
+): InsertMessageContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: InsertMessageContext | undefined;
+
+ 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,
+ sender_id: vars.senderId,
+ content: vars.content,
+ thread_id: vars.thread_id ?? undefined,
+ created_at: now,
+ updated_at: now,
+ deleted_at: undefined,
+ edited_at: undefined,
+ };
+
+ return {
+ ...prev,
+ messages: [...prev.messages, newMessage],
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic message insert by removing the optimistic message.
+ */
+export function rollbackInsertChannelMessage(
+ channelId: string,
+ context: InsertMessageContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ return {
+ ...prev,
+ messages: prev.messages.filter((m) => m.id !== context.optimisticId),
+ };
+ }
+ );
+}
+
+/**
+ * Replace an optimistic message ID with the real server-assigned ID.
+ * Called in mutation onSuccess after server returns the real message.
+ */
+export function replaceOptimisticMessage(
+ vars: WithChannelId<{ optimisticId: string; realId: string }>
+): void {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const messageIndex = prev.messages.findIndex(
+ (m) => m.id === vars.optimisticId
+ );
+
+ if (messageIndex === -1) return prev;
+
+ const updatedMessages = [...prev.messages];
+ updatedMessages[messageIndex] = {
+ ...updatedMessages[messageIndex],
+ id: vars.realId,
+ };
+
+ return {
+ ...prev,
+ messages: updatedMessages,
+ };
+ }
+ );
+}
+
+/**
+ * Optimistically delete a message from the channel cache.
+ * Returns minimal context: only the deleted message, reactions, and attachments.
+ */
+export function optimisticDeleteChannelMessage(
+ vars: WithChannelId<Pick<ChannelMessage, 'message_id'>>
+): DeleteMessageContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: DeleteMessageContext | undefined;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const deletedMessage = prev.messages.find(
+ (m) => m.id === vars.message_id
+ );
+ if (!deletedMessage) return prev;
+
+ context = {
+ deletedMessage,
+ deletedReactions: prev.reactions[vars.message_id] ?? [],
+ deletedAttachments: prev.attachments.filter(
+ (a) => a.message_id === vars.message_id
+ ),
+ };
+
+ const filteredMessages = prev.messages.filter(
+ (m) => m.id !== vars.message_id
+ );
+
+ // Remove reactions for the deleted message
+ const { [vars.message_id]: _removedReactions, ...remainingReactions } =
+ prev.reactions;
+
+ // Remove attachments linked to the deleted message
+ const filteredAttachments = prev.attachments.filter(
+ (a) => a.message_id !== vars.message_id
+ );
+
+ return {
+ ...prev,
+ messages: filteredMessages,
+ reactions: remainingReactions,
+ attachments: filteredAttachments,
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic message delete by restoring the deleted data.
+ */
+export function rollbackDeleteChannelMessage(
+ channelId: string,
+ context: DeleteMessageContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ return {
+ ...prev,
+ messages: [...prev.messages, context.deletedMessage],
+ reactions: {
+ ...prev.reactions,
+ ...(context.deletedReactions.length > 0 && {
+ [context.deletedMessage.id]: context.deletedReactions,
+ }),
+ },
+ attachments: [...prev.attachments, ...context.deletedAttachments],
+ };
+ }
+ );
+}
+
+/**
+ * Optimistically update a message's content in the channel cache.
+ * Returns minimal context: only the previous content and timestamps.
+ */
+export function optimisticUpdateChannelMessage(
+ vars: WithChannelId<Pick<ChannelMessage, 'message_id' | 'content'>>
+): UpdateMessageContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: UpdateMessageContext | undefined;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const message = prev.messages.find((m) => m.id === vars.message_id);
+ if (!message) return prev;
+
+ context = {
+ messageId: vars.message_id,
+ previousContent: message.content,
+ previousEditedAt: message.edited_at,
+ previousUpdatedAt: message.updated_at,
+ };
+
+ const now = new Date().toISOString();
+
+ return {
+ ...prev,
+ messages: prev.messages.map((m) =>
+ m.id === vars.message_id
+ ? { ...m, content: vars.content, edited_at: now, updated_at: now }
+ : m
+ ),
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic message update by restoring previous content.
+ */
+export function rollbackUpdateChannelMessage(
+ channelId: string,
+ context: UpdateMessageContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ return {
+ ...prev,
+ messages: prev.messages.map((m) =>
+ m.id === context.messageId
+ ? {
+ ...m,
+ content: context.previousContent,
+ edited_at: context.previousEditedAt,
+ updated_at: context.previousUpdatedAt,
+ }
+ : m
+ ),
+ };
+ }
+ );
+}
const { track } = withAnalytics();
-type WithChannelID<T> = T & { channelID: string };
+type SendMessageParams = {
+ channelID: string;
+ message: PostMessageRequest;
+ optimisticId: string;
+ senderId: string;
+};
-type SendMessageParams = WithChannelID<{ message: PostMessageRequest }>;
+type SendMessageContext = InsertMessageContext | undefined;
/**
* Mutation to send an channel message.
*/
export function useSendMessageMutation(
- callbacks?: MutationCallbacks<IdResponse, Error, SendMessageParams>
+ callbacks?: MutationCallbacks<
+ IdResponse,
+ Error,
+ SendMessageParams,
+ SendMessageContext
+ >
) {
return useMutation(() => ({
+ gcTime: 0,
mutationFn: async (vars: SendMessageParams) => {
+ // Use optimisticId as nonce - allows server to echo it back for correlation
return await throwOnErr(
async () =>
await commsServiceClient.postMessage({
channel_id: vars.channelID,
message: vars.message,
+ nonce: vars.optimisticId,
})
);
},
- ...withCallbacks<IdResponse, Error, SendMessageParams>(
+ ...withCallbacks<IdResponse, Error, SendMessageParams, SendMessageContext>(
{
- onError(error) {
- console.error('failed to send message', error);
- toast.failure('Failed to send message');
+ onMutate: (vars) => {
+ // Register nonce for deduplication when WebSocket event arrives
+ registerNonce(ChannelNonceKeys.MESSAGE, vars.optimisticId);
+ return optimisticInsertChannelMessage({
+ channelId: vars.channelID,
+ optimisticId: vars.optimisticId,
+ senderId: vars.senderId,
+ ...vars.message,
+ });
},
- onSuccess(_data, variables) {
+ onSuccess(data, variables) {
+ replaceOptimisticMessage({
+ channelId: variables.channelID,
+ optimisticId: variables.optimisticId,
+ realId: data.id,
+ });
track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
channelId: variables.channelID,
contentLength: variables.message.content?.length ?? 0,
@@ -47,8 +358,15 @@ export function useSendMessageMutation(
inThread: variables.message.thread_id !== undefined,
});
},
+ onError(error, vars, context) {
+ console.error('failed to send message', error);
+ toast.failure('Failed to send message');
+ if (context) {
+ rollbackInsertChannelMessage(vars.channelID, context);
+ }
+ },
onSettled: (_data, _error, variables) => {
- invalidateChannelWithID(variables.channelID);
+ softInvalidateChannelWithID(variables.channelID);
},
},
callbacks
@@ -58,30 +376,55 @@ export function useSendMessageMutation(
type DeleteMessageParams = { channelID: string; messageID: string };
+type DeleteMutationContext = DeleteMessageContext | undefined;
+
+const deleteNonce = createMutationNonce<DeleteMessageParams>(
+ ChannelNonceKeys.MESSAGE,
+ (v) => `delete:${v.channelID}:${v.messageID}`
+);
+
/**
* Mutation to delete a channel message
*/
export function useDeleteMessageMutation(
- callbacks?: MutationCallbacks<void, Error, DeleteMessageParams>
+ callbacks?: MutationCallbacks<
+ void,
+ Error,
+ DeleteMessageParams,
+ DeleteMutationContext
+ >
) {
return useMutation(() => ({
+ gcTime: 0,
mutationFn: async (vars: DeleteMessageParams) => {
await throwOnErr(
async () =>
await commsServiceClient.deleteMessage({
channel_id: vars.channelID,
message_id: vars.messageID,
+ nonce: deleteNonce.use(vars),
})
);
},
- ...withCallbacks<void, Error, DeleteMessageParams>(
+ ...withCallbacks<void, Error, DeleteMessageParams, DeleteMutationContext>(
{
- onError(error) {
+ onMutate: (vars) => {
+ deleteNonce.prepare(vars);
+ return optimisticDeleteChannelMessage({
+ channelId: vars.channelID,
+ message_id: vars.messageID,
+ });
+ },
+ onError(error, vars, context) {
console.error('failed to delete message', error);
toast.failure('Failed to delete message');
+ if (context) {
+ rollbackDeleteChannelMessage(vars.channelID, context);
+ }
},
- onSettled: (_data, _error, variables) => {
- invalidateChannelWithID(variables.channelID);
+ onSettled: (_data, _error, vars) => {
+ deleteNonce.cleanup(vars);
+ softInvalidateChannelWithID(vars.channelID);
},
},
callbacks
@@ -95,13 +438,26 @@ type PatchMessageParams = {
content: string;
};
+type PatchMutationContext = UpdateMessageContext | undefined;
+
+const patchNonce = createMutationNonce<PatchMessageParams>(
+ ChannelNonceKeys.MESSAGE,
+ (v) => `patch:${v.channelID}:${v.messageID}`
+);
+
/**
* Mutation to patch a channel message
*/
export function usePatchMessageMutation(
- callbacks?: MutationCallbacks<MessageResponse, Error, PatchMessageParams>
+ callbacks?: MutationCallbacks<
+ MessageResponse,
+ Error,
+ PatchMessageParams,
+ PatchMutationContext
+ >
) {
return useMutation(() => ({
+ gcTime: 0,
mutationFn: async (vars: PatchMessageParams) => {
return await throwOnErr(
async () =>
@@ -109,17 +465,35 @@ export function usePatchMessageMutation(
channel_id: vars.channelID,
message_id: vars.messageID,
content: vars.content,
+ nonce: patchNonce.use(vars),
})
);
},
- ...withCallbacks<MessageResponse, Error, PatchMessageParams>(
+ ...withCallbacks<
+ MessageResponse,
+ Error,
+ PatchMessageParams,
+ PatchMutationContext
+ >(
{
- onError(error) {
+ onMutate: (vars) => {
+ patchNonce.prepare(vars);
+ return optimisticUpdateChannelMessage({
+ channelId: vars.channelID,
+ message_id: vars.messageID,
+ content: vars.content,
+ });
+ },
+ onError(error, vars, context) {
console.error('failed to update message', error);
toast.failure('Failed to update message');
+ if (context) {
+ rollbackUpdateChannelMessage(vars.channelID, context);
+ }
},
- onSettled: (_data, _error, variables) => {
- invalidateChannelWithID(variables.channelID);
+ onSettled: (_data, _error, vars) => {
+ patchNonce.cleanup(vars);
+ softInvalidateChannelWithID(vars.channelID);
},
},
callbacks
diff --git a/js/app/packages/queries/channel/participants.ts b/js/app/packages/queries/channel/participants.ts
new file mode 100644
index 0000000000..d53006f35a
--- /dev/null
+++ b/js/app/packages/queries/channel/participants.ts
@@ -0,0 +1,263 @@
+import { toast } from '@core/component/Toast/Toast';
+import { throwOnErr } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import {
+ commsServiceClient,
+ type MessageResponse,
+} from '@service-comms/client';
+import type {
+ ChannelParticipant,
+ GetChannelResponse,
+} from '@service-comms/generated/models';
+import { useMutation } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { softInvalidateChannelWithID } from './channel';
+import { channelKeys } from './keys';
+
+type WithChannelId<T> = T & { channelId: string };
+
+export type AddParticipantsContext = {
+ addedUserIds: string[];
+};
+
+export type RemoveParticipantsContext = {
+ removedParticipants: ChannelParticipant[];
+};
+
+/**
+ * Optimistically add participants to a channel.
+ * Returns minimal context for rollback.
+ */
+export function optimisticAddParticipants(
+ vars: WithChannelId<{ participants: string[] }>
+): AddParticipantsContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: AddParticipantsContext | undefined;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const existingUserIds = new Set(prev.participants.map((p) => p.user_id));
+ const newUserIds = vars.participants.filter(
+ (id) => !existingUserIds.has(id)
+ );
+
+ if (newUserIds.length === 0) return prev;
+
+ context = { addedUserIds: newUserIds };
+
+ const newParticipants: ChannelParticipant[] = newUserIds.map(
+ (userId) => ({
+ user_id: userId,
+ role: 'member',
+ left_at: null,
+ joined_at: new Date().toISOString(),
+ channel_id: vars.channelId,
+ })
+ );
+
+ return {
+ ...prev,
+ participants: [...prev.participants, ...newParticipants],
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic add participants by removing them.
+ */
+export function rollbackAddParticipants(
+ channelId: string,
+ context: AddParticipantsContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const addedSet = new Set(context.addedUserIds);
+ return {
+ ...prev,
+ participants: prev.participants.filter((p) => !addedSet.has(p.user_id)),
+ };
+ }
+ );
+}
+
+/**
+ * Optimistically remove participants from a channel.
+ * Returns minimal context for rollback.
+ */
+export function optimisticRemoveParticipants(
+ vars: WithChannelId<{ participants: string[] }>
+): RemoveParticipantsContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: RemoveParticipantsContext | undefined;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ const toRemoveSet = new Set(vars.participants);
+ const removedParticipants = prev.participants.filter((p) =>
+ toRemoveSet.has(p.user_id)
+ );
+
+ if (removedParticipants.length === 0) return prev;
+
+ context = { removedParticipants };
+
+ return {
+ ...prev,
+ participants: prev.participants.filter(
+ (p) => !toRemoveSet.has(p.user_id)
+ ),
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic remove participants by re-adding them.
+ */
+export function rollbackRemoveParticipants(
+ channelId: string,
+ context: RemoveParticipantsContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return prev;
+
+ return {
+ ...prev,
+ participants: [...prev.participants, ...context.removedParticipants],
+ };
+ }
+ );
+}
+
+type AddParticipantsParams = {
+ channelId: string;
+ participants: string[];
+};
+
+type RemoveParticipantsParams = {
+ channelId: string;
+ participants: string[];
+};
+
+type AddParticipantsMutationContext = AddParticipantsContext | undefined;
+type RemoveParticipantsMutationContext = RemoveParticipantsContext | undefined;
+
+/**
+ * Mutation to add participants to a channel.
+ */
+export function useAddParticipantsMutation(
+ callbacks?: MutationCallbacks<
+ MessageResponse,
+ Error,
+ AddParticipantsParams,
+ AddParticipantsMutationContext
+ >
+) {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: AddParticipantsParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.addParticipantsToChanenl({
+ channel_id: vars.channelId,
+ participants: vars.participants,
+ })
+ );
+ },
+ ...withCallbacks<
+ MessageResponse,
+ Error,
+ AddParticipantsParams,
+ AddParticipantsMutationContext
+ >(
+ {
+ onMutate: (vars) =>
+ optimisticAddParticipants({
+ channelId: vars.channelId,
+ participants: vars.participants,
+ }),
+ onError(error, vars, context) {
+ console.error('failed to add participants', error);
+ toast.failure('Failed to add participants to channel');
+ if (context) {
+ rollbackAddParticipants(vars.channelId, context);
+ }
+ },
+ onSettled: (_, __, vars) => softInvalidateChannelWithID(vars.channelId),
+ },
+ callbacks
+ ),
+ }));
+}
+
+/**
+ * Mutation to remove participants from a channel.
+ */
+export function useRemoveParticipantsMutation(
+ callbacks?: MutationCallbacks<
+ MessageResponse,
+ Error,
+ RemoveParticipantsParams,
+ RemoveParticipantsMutationContext
+ >
+) {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: RemoveParticipantsParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.removeParticipantsFromChannel({
+ channel_id: vars.channelId,
+ participants: vars.participants,
+ })
+ );
+ },
+ ...withCallbacks<
+ MessageResponse,
+ Error,
+ RemoveParticipantsParams,
+ RemoveParticipantsMutationContext
+ >(
+ {
+ onMutate: (vars) =>
+ optimisticRemoveParticipants({
+ channelId: vars.channelId,
+ participants: vars.participants,
+ }),
+ onError(error, vars, context) {
+ console.error('failed to remove participants', error);
+ toast.failure('Failed to remove participants from channel');
+ if (context) {
+ rollbackRemoveParticipants(vars.channelId, context);
+ }
+ },
+ onSettled: (_, __, vars) => softInvalidateChannelWithID(vars.channelId),
+ },
+ callbacks
+ ),
+ }));
+}
diff --git a/js/app/packages/queries/channel/reaction.ts b/js/app/packages/queries/channel/reaction.ts
new file mode 100644
index 0000000000..1d163f6028
--- /dev/null
+++ b/js/app/packages/queries/channel/reaction.ts
@@ -0,0 +1,362 @@
+import { toast } from '@core/component/Toast/Toast';
+import { throwOnErr } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import {
+ commsServiceClient,
+ type MessageResponse,
+} from '@service-comms/client';
+import type {
+ GetChannelResponse,
+ PostReactionRequest,
+} from '@service-comms/generated/models';
+import { useMutation } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { softInvalidateChannelWithID } from './channel';
+import { channelKeys, ChannelNonceKeys } from './keys';
+import { createMutationNonce } from '../nonce';
+
+type WithChannelId<T> = T & { channelId: string };
+type WithUserId<T> = T & { userId: string };
+
+export type AddReactionContext = {
+ messageId: string;
+ emoji: string;
+ userId: string;
+ wasNewReaction: boolean;
+};
+
+export type RemoveReactionContext = {
+ messageId: string;
+ emoji: string;
+ userId: string;
+ wasLastUser: boolean;
+};
+
+/**
+ * Optimistically add a reaction to a message.
+ * Returns minimal context for rollback.
+ */
+export function optimisticAddReaction(
+ vars: WithChannelId<
+ WithUserId<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ >
+): AddReactionContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: AddReactionContext | undefined;
+
+ 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,
+ },
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic add reaction by removing the user's reaction.
+ */
+export function rollbackAddReaction(
+ channelId: string,
+ context: AddReactionContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { 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 },
+ };
+ }
+ }
+ );
+}
+
+/**
+ * Optimistically remove a reaction from a message.
+ * Returns minimal context for rollback.
+ */
+export function optimisticRemoveReaction(
+ vars: WithChannelId<
+ WithUserId<Pick<PostReactionRequest, 'emoji' | 'message_id'>>
+ >
+): RemoveReactionContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ let context: RemoveReactionContext | undefined;
+
+ 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) {
+ const { [vars.message_id]: _, ...rest } = prev.reactions;
+ return { ...prev, reactions: rest };
+ }
+
+ return {
+ ...prev,
+ reactions: { ...prev.reactions, [vars.message_id]: updated },
+ };
+ }
+ );
+
+ return context;
+}
+
+/**
+ * Rollback an optimistic remove reaction by re-adding the user's reaction.
+ */
+export function rollbackRemoveReaction(
+ channelId: string,
+ context: RemoveReactionContext
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+
+ queryClient.setQueriesData(
+ { 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] },
+ ],
+ },
+ };
+ }
+ );
+}
+
+type ReactionParams = {
+ channelId: string;
+ messageId: string;
+ emoji: string;
+ userId: string;
+};
+
+type AddReactionMutationContext = AddReactionContext | undefined;
+type RemoveReactionMutationContext = RemoveReactionContext | undefined;
+
+const addReactionNonce = createMutationNonce<ReactionParams>(
+ ChannelNonceKeys.REACTION,
+ (v) => `add:${v.channelId}:${v.messageId}:${v.emoji}`
+);
+
+const removeReactionNonce = createMutationNonce<ReactionParams>(
+ ChannelNonceKeys.REACTION,
+ (v) => `remove:${v.channelId}:${v.messageId}:${v.emoji}`
+);
+
+/**
+ * Mutation to add a reaction to a channel message.
+ */
+export function useAddReactionMutation(
+ callbacks?: MutationCallbacks<
+ MessageResponse,
+ Error,
+ ReactionParams,
+ AddReactionMutationContext
+ >
+) {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: ReactionParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.postReaction({
+ channel_id: vars.channelId,
+ message_id: vars.messageId,
+ emoji: vars.emoji,
+ action: 'Add',
+ nonce: addReactionNonce.use(vars),
+ })
+ );
+ },
+ ...withCallbacks<
+ MessageResponse,
+ Error,
+ ReactionParams,
+ AddReactionMutationContext
+ >(
+ {
+ onMutate: (vars) => {
+ addReactionNonce.prepare(vars);
+ return optimisticAddReaction({
+ channelId: vars.channelId,
+ message_id: vars.messageId,
+ emoji: vars.emoji,
+ userId: vars.userId,
+ });
+ },
+ onError(error, vars, context) {
+ console.error('failed to add reaction', error);
+ toast.failure('Failed to add reaction');
+ if (context) {
+ rollbackAddReaction(vars.channelId, context);
+ }
+ },
+ onSettled: (_, __, vars) => {
+ addReactionNonce.cleanup(vars);
+ softInvalidateChannelWithID(vars.channelId);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+/**
+ * Mutation to remove a reaction from a channel message.
+ */
+export function useRemoveReactionMutation(
+ callbacks?: MutationCallbacks<
+ MessageResponse,
+ Error,
+ ReactionParams,
+ RemoveReactionMutationContext
+ >
+) {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: ReactionParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.postReaction({
+ channel_id: vars.channelId,
+ message_id: vars.messageId,
+ emoji: vars.emoji,
+ action: 'Remove',
+ nonce: removeReactionNonce.use(vars),
+ })
+ );
+ },
+ ...withCallbacks<
+ MessageResponse,
+ Error,
+ ReactionParams,
+ RemoveReactionMutationContext
+ >(
+ {
+ onMutate: (vars) => {
+ removeReactionNonce.prepare(vars);
+ return optimisticRemoveReaction({
+ channelId: vars.channelId,
+ message_id: vars.messageId,
+ emoji: vars.emoji,
+ userId: vars.userId,
+ });
+ },
+ onError(error, vars, context) {
+ console.error('failed to remove reaction', error);
+ toast.failure('Failed to remove reaction');
+ if (context) {
+ rollbackRemoveReaction(vars.channelId, context);
+ }
+ },
+ onSettled: (_, __, vars) => {
+ removeReactionNonce.cleanup(vars);
+ softInvalidateChannelWithID(vars.channelId);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
diff --git a/js/app/packages/queries/channel/sync.ts b/js/app/packages/queries/channel/sync.ts
new file mode 100644
index 0000000000..71252c7128
--- /dev/null
+++ b/js/app/packages/queries/channel/sync.ts
@@ -0,0 +1,139 @@
+import type {
+ Attachment,
+ CountedReaction,
+ GetChannelResponse,
+ Message,
+} from '@service-comms/generated/models';
+import { queryClient } from '../client';
+import { softInvalidateChannelWithID } from './channel';
+import { channelKeys, ChannelNonceKeys } from './keys';
+import { consumeNonce } from '../nonce';
+
+/**
+ * Websocket payload types
+ */
+type CommsMessagePayload = Message & { channel_id: string; nonce: string };
+
+type CommsReactionPayload = {
+ channel_id: string;
+ message_id: string;
+ reactions: CountedReaction[];
+ nonce: string;
+};
+
+type CommsAttachmentPayload = {
+ channel_id: string;
+ message_id: string;
+ attachments: Attachment[];
+ nonce: string;
+};
+
+/**
+ * Handle incoming message from websocket.
+ *
+ * If the nonce was registered by this client (optimistic update), we skip the cache
+ * update since it was already applied. Otherwise, this is an external update
+ * (other user, other tab, or server-initiated) and we apply it to the cache.
+ *
+ * We always call softInvalidateChannelWithID to ensure eventual consistency:
+ * - Marks query as stale for background refetch when component remounts
+ * - Handles cross-tab sync where optimistic state may differ
+ * - Catches edge cases like server-side message modifications
+ */
+export function handleCommsMessage(payload: CommsMessagePayload): void {
+ const isExternalUpdate = !consumeNonce(
+ ChannelNonceKeys.MESSAGE,
+ payload.nonce
+ );
+
+ if (isExternalUpdate) {
+ try {
+ const queryKey = channelKeys.withID(payload.channel_id).queryKey;
+ queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
+ if (!prev) return prev;
+
+ if (prev.messages.some((m) => m.id === payload.id)) {
+ return prev;
+ }
+
+ return {
+ ...prev,
+ messages: [...prev.messages, payload],
+ };
+ });
+ } catch (error) {
+ console.error('Failed to update message cache from websocket:', error);
+ }
+ }
+
+ softInvalidateChannelWithID(payload.channel_id);
+}
+
+/**
+ * Handle reaction update from websocket.
+ * Updates the cache directly with the new reaction state.
+ *
+ * Soft invalidation ensures eventual consistency across tabs/devices.
+ */
+export function handleCommsReaction(payload: CommsReactionPayload): void {
+ const isExternalUpdate = !consumeNonce(
+ ChannelNonceKeys.REACTION,
+ payload.nonce
+ );
+
+ if (isExternalUpdate) {
+ try {
+ const queryKey = channelKeys.withID(payload.channel_id).queryKey;
+ queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ reactions: {
+ ...prev.reactions,
+ [payload.message_id]: payload.reactions,
+ },
+ };
+ });
+ } catch (error) {
+ console.error('Failed to update reaction cache from websocket:', error);
+ }
+ }
+
+ softInvalidateChannelWithID(payload.channel_id);
+}
+
+/**
+ * Handle attachment update from websocket.
+ * Updates the cache directly with the new attachments.
+ *
+ * Soft invalidation ensures eventual consistency across tabs/devices.
+ */
+export function handleCommsAttachment(payload: CommsAttachmentPayload): void {
+ const isExternalUpdate = !consumeNonce(
+ 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);
+ }
+ }
+
+ softInvalidateChannelWithID(payload.channel_id);
+}
diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
new file mode 100644
index 0000000000..19b386d5e2
--- /dev/null
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -0,0 +1,790 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type {
+ Attachment,
+ CountedReaction,
+ GetChannelResponse,
+ Message,
+} from '@service-comms/generated/models';
+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;
+ },
+}));
+
+vi.mock('@coparse/analytics', () => ({
+ TrackingEvents: { BLOCKCHANNEL: { MESSAGE: { SEND: 'test' } } },
+ withAnalytics: () => ({ track: vi.fn() }),
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@service-comms/client', () => ({
+ commsServiceClient: {},
+}));
+
+vi.mock('@macro-entity', () => ({
+ queryKeys: { all: { channel: ['channel'] } },
+}));
+
+// Import after mocks are set up
+import {
+ optimisticUpdateChannelName,
+ rollbackUpdateChannelName,
+} from '../channel';
+import { channelKeys } from '../keys';
+import {
+ optimisticDeleteChannelMessage,
+ optimisticInsertChannelMessage,
+ optimisticUpdateChannelMessage,
+ replaceOptimisticMessage,
+ rollbackDeleteChannelMessage,
+ rollbackInsertChannelMessage,
+ rollbackUpdateChannelMessage,
+} from '../message';
+import {
+ optimisticAddReaction,
+ optimisticRemoveReaction,
+ rollbackAddReaction,
+ rollbackRemoveReaction,
+} from '../reaction';
+
+function createMockMessage(overrides: Partial<Message> = {}): Message {
+ return {
+ id: `msg-${Math.random().toString(36).slice(2)}`,
+ 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',
+ deleted_at: undefined,
+ edited_at: undefined,
+ thread_id: undefined,
+ ...overrides,
+ };
+}
+
+function createMockAttachment(overrides: Partial<Attachment> = {}): Attachment {
+ 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',
+ ...overrides,
+ } as Attachment;
+}
+
+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;
+}
+
+function seedQueryCache(
+ channelId: string,
+ data: GetChannelResponse
+): readonly unknown[] {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+ testQueryClient.setQueryData(queryKey, data);
+ return queryKey;
+}
+
+function getChannelFromCache(
+ channelId: string
+): GetChannelResponse | undefined {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+ return testQueryClient.getQueryData<GetChannelResponse>(queryKey);
+}
+
+describe('optimisticInsertChannelMessage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ afterEach(() => {
+ testQueryClient.clear();
+ });
+
+ it('should insert a new message at the end of the messages array', () => {
+ const existingMessage = createMockMessage({ id: 'existing-msg' });
+ seedQueryCache(
+ 'channel-1',
+ createMockChannelResponse({ messages: [existingMessage] })
+ );
+
+ const context = optimisticInsertChannelMessage({
+ channelId: 'channel-1',
+ optimisticId: 'optimistic-msg-1',
+ 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',
+ attachments: [],
+ mentions: [],
+ thread_id: 'parent-msg-id',
+ });
+
+ const cached = getChannelFromCache('channel-1');
+ expect(cached?.messages[0].thread_id).toBe('parent-msg-id');
+ });
+
+ 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: [],
+ });
+
+ expect(context).toBeUndefined();
+ });
+
+ it('should rollback correctly using returned context', () => {
+ const existingMessage = createMockMessage({ id: 'existing-msg' });
+ seedQueryCache(
+ 'channel-1',
+ createMockChannelResponse({ messages: [existingMessage] })
+ );
+
+ const context = optimisticInsertChannelMessage({
+ channelId: 'channel-1',
+ optimisticId: 'optimistic-msg-1',
+ senderId: 'user-2',
+ content: 'New message content',
+ attachments: [],
+ mentions: [],
+ });
+
+ // Verify insert happened
+ expect(getChannelFromCache('channel-1')?.messages).toHaveLength(2);
+
+ // 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');
+ });
+
+ 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(
+ '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'
+ );
+
+ // 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());
+
+ const context = optimisticAddReaction({
+ 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('👍');
+ 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({});
+ });
+
+ it('should rollback correctly using returned context', () => {
+ const reactions: Record<string, CountedReaction[]> = {
+ 'msg-1': [{ emoji: '👍', users: ['user-1'] }],
+ };
+ seedQueryCache('channel-1', createMockChannelResponse({ reactions }));
+
+ const context = optimisticRemoveReaction({
+ channelId: 'channel-1',
+ userId: 'user-1',
+ emoji: '👍',
+ message_id: 'msg-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.toBe(originalUpdatedAt);
+ // Context should contain previous name for rollback
+ expect(context?.previousName).toBe('Test Channel');
+ });
+
+ it('should rollback correctly using returned context', () => {
+ const originalUpdatedAt = '2024-01-01T00:00:00.000Z';
+ 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'
+ );
+
+ // 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).toBe(originalUpdatedAt);
+ });
+});
diff --git a/js/app/packages/queries/channel/typing.ts b/js/app/packages/queries/channel/typing.ts
new file mode 100644
index 0000000000..307dde26f1
--- /dev/null
+++ b/js/app/packages/queries/channel/typing.ts
@@ -0,0 +1,137 @@
+import { commsServiceClient } from '@service-comms/client';
+import { useMutation } from '@tanstack/solid-query';
+import { createSignal } from 'solid-js';
+import { createMutationNonce } from '../nonce';
+import { ChannelNonceKeys } from './keys';
+
+/**
+ * Websocket payload type for typing events
+ */
+type CommsTypingPayload = {
+ channel_id: string;
+ user_id: string;
+ action: 'start' | 'stop';
+ thread_id?: string | null;
+};
+
+/**
+ * Ephemeral store for typing indicators.
+ * Map<channelId, Map<threadId | null, Set<userId>>>
+ *
+ * Uses null key for main channel, string key for threads.
+ */
+const [typingUsers, setTypingUsers] = createSignal<
+ Map<string, Map<string | null, Set<string>>>
+>(new Map());
+
+function addTypingUser(
+ channelId: string,
+ userId: string,
+ threadId: string | null = null
+) {
+ setTypingUsers((prev) => {
+ const newMap = new Map(prev);
+ const channelMap =
+ newMap.get(channelId) ?? new Map<string | null, Set<string>>();
+ const threadUsers = channelMap.get(threadId) ?? new Set<string>();
+ channelMap.set(threadId, new Set([...threadUsers, userId]));
+ newMap.set(channelId, channelMap);
+ return newMap;
+ });
+}
+
+function removeTypingUser(
+ channelId: string,
+ userId: string,
+ threadId: string | null = null
+) {
+ setTypingUsers((prev) => {
+ const newMap = new Map(prev);
+ const channelMap = newMap.get(channelId);
+ if (!channelMap) return prev;
+
+ const threadUsers = channelMap.get(threadId);
+ if (!threadUsers) return prev;
+
+ const newThreadUsers = new Set(
+ [...threadUsers].filter((id) => id !== userId)
+ );
+ channelMap.set(threadId, newThreadUsers);
+ newMap.set(channelId, channelMap);
+ return newMap;
+ });
+}
+
+/**
+ * Get the set of user IDs currently typing in a channel/thread.
+ */
+export function getTypingUsersForChannel(
+ channelId: string,
+ threadId: string | null = null
+): Set<string> {
+ return typingUsers().get(channelId)?.get(threadId) ?? new Set();
+}
+
+/**
+ * Handle typing indicator from websocket.
+ * Ignores typing events from the current user.
+ */
+export function handleCommsTyping(
+ payload: CommsTypingPayload,
+ currentUserId: string
+): void {
+ // Ignore own typing indicators
+ if (payload.user_id === currentUserId) return;
+
+ if (payload.action === 'start') {
+ addTypingUser(
+ payload.channel_id,
+ payload.user_id,
+ payload.thread_id ?? null
+ );
+ } else {
+ removeTypingUser(
+ payload.channel_id,
+ payload.user_id,
+ payload.thread_id ?? null
+ );
+ }
+}
+
+type PostTypingUpdateVars = {
+ channelId: string;
+ action: 'start' | 'stop';
+ threadId?: string;
+};
+
+const typingNonce = createMutationNonce<PostTypingUpdateVars>(
+ ChannelNonceKeys.TYPING,
+ (v) => `${v.channelId}:${v.action}:${v.threadId ?? 'main'}`
+);
+
+export function usePostTypingUpdateMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: PostTypingUpdateVars) => {
+ await commsServiceClient.postTypingUpdate({
+ channel_id: vars.channelId,
+ action: vars.action,
+ thread_id: vars.threadId,
+ nonce: typingNonce.use(vars),
+ });
+ },
+ onMutate: (vars: PostTypingUpdateVars) => {
+ typingNonce.prepare(vars);
+ },
+ onSettled: (
+ _data: unknown,
+ _error: Error | null,
+ vars: PostTypingUpdateVars
+ ) => {
+ typingNonce.cleanup(vars);
+ },
+ onError: (error: Error) => {
+ console.error('failed to post typing update', error);
+ },
+ }));
+}
diff --git a/js/app/packages/queries/nonce.ts b/js/app/packages/queries/nonce.ts
new file mode 100644
index 0000000000..037f459cf8
--- /dev/null
+++ b/js/app/packages/queries/nonce.ts
@@ -0,0 +1,178 @@
+/**
+ * Nonce storage for optimistic update deduplication.
+ *
+ * ## Problem
+ * When a user performs an action (e.g., sends a message), we:
+ * 1. Apply the change optimistically to the UI
+ * 2. Send the request to the server
+ * 3. Receive a WebSocket event when the server broadcasts the change
+ *
+ * Without deduplication, step 3 would re-apply the change, causing duplicates.
+ *
+ * ## Solution: Nonce-based deduplication
+ * 1. In `onMutate`: Generate a unique nonce, register it, apply optimistic update
+ * 2. In `mutationFn`: Send the nonce with the request to the server
+ * 3. Server echoes the nonce back in the WebSocket broadcast
+ * 4. In WebSocket handler: Check if nonce is registered (our own action) → skip update
+ * If not registered (external action from another user/tab) → apply update
+ *
+ * ## Lifecycle
+ * ```
+ * prepare() → registers nonce, stores for later retrieval
+ * ↓
+ * use() → retrieves the nonce for the API request
+ * ↓
+ * [WebSocket arrives] → consumeNonce() returns true, skip cache update
+ * ↓
+ * cleanup() → removes from pending map (in onSettled)
+ * ```
+ *
+ * Nonces auto-expire after TTL to handle cases where WebSocket events are lost.
+ */
+
+const NONCE_TTL_MS = 60_000; // 60 seconds - allows for slow networks
+
+type NonceEntry = {
+ nonce: string;
+ expiresAt: number;
+ timerId: ReturnType<typeof setTimeout>;
+};
+
+const noncesByKey = new Map<string, Map<string, NonceEntry>>();
+
+function isNonceValid(
+ nonceMap: Map<string, NonceEntry>,
+ nonce: string
+): boolean {
+ const entry = nonceMap.get(nonce);
+ if (!entry) return false;
+
+ if (Date.now() > entry.expiresAt) {
+ clearTimeout(entry.timerId);
+ nonceMap.delete(nonce);
+ cleanupEmptyMap(nonceMap);
+ return false;
+ }
+
+ return true;
+}
+
+function cleanupEmptyMap(nonceMap: Map<string, NonceEntry>): void {
+ if (nonceMap.size === 0) {
+ for (const [key, map] of noncesByKey.entries()) {
+ if (map === nonceMap) {
+ noncesByKey.delete(key);
+ break;
+ }
+ }
+ }
+}
+
+/**
+ * Register a nonce for a given event type.
+ * The nonce will auto-expire after TTL to prevent memory leaks.
+ * Must be called in onMutate (synchronously before request) to avoid race conditions.
+ */
+export function registerNonce(key: string, nonce: string): void {
+ let nonceMap = noncesByKey.get(key);
+ if (!nonceMap) {
+ nonceMap = new Map();
+ noncesByKey.set(key, nonceMap);
+ }
+
+ const existing = nonceMap.get(nonce);
+ if (existing) {
+ clearTimeout(existing.timerId);
+ }
+
+ const currentNonceMap = nonceMap;
+
+ const timerId = setTimeout(() => {
+ if (noncesByKey.get(key) === currentNonceMap) {
+ currentNonceMap.delete(nonce);
+ cleanupEmptyMap(currentNonceMap);
+ }
+ }, NONCE_TTL_MS);
+
+ nonceMap.set(nonce, {
+ nonce,
+ expiresAt: Date.now() + NONCE_TTL_MS,
+ timerId,
+ });
+}
+
+/**
+ * Check if a nonce exists and consume it (remove from storage).
+ * Returns true if the nonce was found and consumed.
+ */
+export function consumeNonce(
+ key: string,
+ nonce: string | undefined | null
+): boolean {
+ if (!nonce) return false;
+
+ const nonceMap = noncesByKey.get(key);
+ if (!nonceMap) return false;
+
+ if (!isNonceValid(nonceMap, nonce)) return false;
+
+ const entry = nonceMap.get(nonce);
+ if (entry) {
+ clearTimeout(entry.timerId);
+ nonceMap.delete(nonce);
+ cleanupEmptyMap(nonceMap);
+ }
+
+ return true;
+}
+
+/**
+ * Creates a nonce coordinator for mutations.
+ * Handles the pattern of generating nonce in onMutate and retrieving in mutationFn.
+ *
+ * @example
+ * const nonce = createMutationNonce('my_key', (v) => `${v.id}`);
+ *
+ * // In mutation:
+ * onMutate: (vars) => { nonce.prepare(vars); ... },
+ * mutationFn: (vars) => { nonce: nonce.use(vars), ... },
+ * onSettled: (_, __, vars) => { nonce.cleanup(vars); ... }
+ */
+export function createMutationNonce<TVars>(
+ nonceKey: string,
+ makeKey: (vars: TVars) => string
+) {
+ const pending = new Map<string, string>();
+
+ return {
+ /** Generate nonce, register for deduplication, store for later retrieval. Call in onMutate. */
+ prepare: (vars: TVars): string => {
+ const key = makeKey(vars);
+ const nonce = crypto.randomUUID();
+ pending.set(key, nonce);
+ registerNonce(nonceKey, nonce);
+ return nonce;
+ },
+
+ /**
+ * Retrieve the prepared nonce for this mutation. Call in mutationFn.
+ * @throws Error if prepare() was not called first (indicates a bug in mutation setup)
+ */
+ use: (vars: TVars): string => {
+ const key = makeKey(vars);
+ const nonce = pending.get(key);
+ if (!nonce) {
+ throw new Error(
+ `Nonce not found for key "${key}". Ensure prepare() is called in onMutate before use() is called in mutationFn.`
+ );
+ }
+ return nonce;
+ },
+
+ /** Remove stored nonce. Call in onSettled. */
+ cleanup: (vars: TVars): void => {
+ const key = makeKey(vars);
+ pending.delete(key);
+ },
+ };
+}
diff --git a/js/app/packages/queries/sync/SyncProvider.tsx b/js/app/packages/queries/sync/SyncProvider.tsx
index 2b7abec8a6..babaa0cd91 100644
--- a/js/app/packages/queries/sync/SyncProvider.tsx
+++ b/js/app/packages/queries/sync/SyncProvider.tsx
@@ -1,16 +1,42 @@
import { invalidateContacts } from '@queries/contacts/contacts';
+import {
+ handleCommsAttachment,
+ handleCommsMessage,
+ handleCommsReaction,
+} from '@queries/channel/sync';
+import { handleCommsTyping } from '@queries/channel/typing';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
-import type { ParentProps } from 'solid-js';
+import type { Accessor, ParentProps } from 'solid-js';
import { match } from 'ts-pattern';
-// NOTE: This is a POC.
-// Needs to be fleshed out more. Also ideally the Provider from macto-entity should be
-// moved into the queries package first.
-export function QuerySyncProvider(props: ParentProps) {
+type SyncProviderProps = ParentProps<{
+ userId: Accessor<string | undefined>;
+}>;
+
+export function QuerySyncProvider(props: SyncProviderProps) {
createConnectionWebsocketEffect((data) => {
- match(data).with({ type: 'contacts_invalidation' }, () => {
- invalidateContacts();
- });
+ const payload =
+ typeof data.data === 'string' ? JSON.parse(data.data) : data.data;
+
+ match(data)
+ .with({ type: 'contacts_invalidation' }, () => {
+ invalidateContacts();
+ })
+ .with({ type: 'comms_message' }, () => {
+ handleCommsMessage(payload);
+ })
+ .with({ type: 'comms_reaction' }, () => {
+ handleCommsReaction(payload);
+ })
+ .with({ type: 'comms_attachment' }, () => {
+ handleCommsAttachment(payload);
+ })
+ .with({ type: 'comms_typing' }, () => {
+ const userId = props.userId();
+ if (!userId) return;
+ handleCommsTyping(payload, userId);
+ })
+ .otherwise(() => {});
});
return props.children;
diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.ts
index d94f77b359..61ae562123 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -84,15 +84,20 @@ export const commsServiceClient = {
(result) => result
);
},
- async postMessage(args: WithChannelId & { message: PostMessageRequest }) {
- const { channel_id, message } = args;
+ async postMessage(
+ args: WithChannelId & { message: PostMessageRequest; nonce?: string }
+ ) {
+ const { channel_id, message, nonce } = args;
const uniqueMentions = Array.from(new Set(message.mentions));
- const sendMessage = { ...message, mentions: uniqueMentions };
+ const sendMessage = { ...message, mentions: uniqueMentions, nonce };
return mapOk(
- await commsFetch<IdResponse>(`/channels/${channel_id}/message`, {
- method: 'POST',
- body: JSON.stringify(sendMessage),
- }),
+ await commsFetch<IdResponse & { nonce?: string }>(
+ `/channels/${channel_id}/message`,
+ {
+ method: 'POST',
+ body: JSON.stringify(sendMessage),
+ }
+ ),
(result) => result ?? {}
);
},
@@ -105,50 +110,59 @@ export const commsServiceClient = {
(result) => result
);
},
- async postTypingUpdate(args: PostTypingRequest & WithChannelId) {
- const { channel_id, action, thread_id } = args;
+ async postTypingUpdate(
+ args: PostTypingRequest & WithChannelId & { nonce?: string }
+ ) {
+ const { channel_id, action, thread_id, nonce } = args;
return mapOk(
await commsFetch<MessageResponse>(`/channels/${channel_id}/typing`, {
method: 'POST',
- body: JSON.stringify({ action, thread_id }),
+ body: JSON.stringify({ action, thread_id, nonce }),
}),
(result) => result
);
},
- async postReaction(args: PostReactionRequest & WithChannelId) {
- const { channel_id, action, emoji, message_id } = args;
+ async postReaction(
+ args: PostReactionRequest & WithChannelId & { nonce?: string }
+ ) {
+ const { channel_id, action, emoji, message_id, nonce } = args;
return mapOk(
await commsFetch<MessageResponse>(`/channels/${channel_id}/reaction`, {
method: 'POST',
- body: JSON.stringify({ action, emoji, message_id }),
+ body: JSON.stringify({ action, emoji, message_id, nonce }),
}),
(result) => result
);
},
async patchMessage(
- args: PatchMessageRequest & WithChannelId & WithMessageId
+ args: PatchMessageRequest &
+ WithChannelId &
+ WithMessageId & { nonce?: string }
) {
- const { channel_id, content, message_id, attachment_ids_to_delete } = args;
+ const { channel_id, content, message_id, attachment_ids_to_delete, nonce } =
+ args;
return mapOk(
await commsFetch<MessageResponse>(
`/channels/${channel_id}/message/${message_id}`,
{
method: 'PATCH',
- body: JSON.stringify({ content, attachment_ids_to_delete }),
+ body: JSON.stringify({ content, attachment_ids_to_delete, nonce }),
}
),
(result) => result
);
},
- async deleteMessage(args: WithChannelId & WithMessageId) {
- const { channel_id, message_id } = args;
+ async deleteMessage(
+ args: WithChannelId & WithMessageId & { nonce?: string }
+ ) {
+ const { channel_id, message_id, nonce } = args;
+ const url = nonce
+ ? `/channels/${channel_id}/message/${message_id}?nonce=${encodeURIComponent(nonce)}`
+ : `/channels/${channel_id}/message/${message_id}`;
return mapOk(
- await commsFetch<MessageResponse>(
- `/channels/${channel_id}/message/${message_id}`,
- {
- method: 'DELETE',
- }
- ),
+ await commsFetch<MessageResponse>(url, {
+ method: 'DELETE',
+ }),
(result) => result
);
},
diff --git a/js/app/packages/service-clients/service-comms/generated/models/index.ts b/js/app/packages/service-clients/service-comms/generated/models/index.ts
index abc1414c4a..3c94e2b932 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/index.ts
@@ -105,12 +105,17 @@ export * from './patchMessageParams';
export * from './patchMessageRequest';
export * from './patchMessageRequestAttachmentIdsToDelete';
export * from './patchMessageRequestContent';
+export * from './patchMessageRequestNonce';
export * from './postActivityRequest';
export * from './postMessageRequest';
+export * from './postMessageRequestNonce';
export * from './postMessageRequestThreadId';
export * from './postMessageResponse';
+export * from './postMessageResponseNonce';
export * from './postReactionRequest';
+export * from './postReactionRequestNonce';
export * from './postTypingRequest';
+export * from './postTypingRequestNonce';
export * from './postTypingRequestThreadId';
export * from './reaction';
export * from './reactionAction';
diff --git a/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequest.ts b/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequest.ts
index 30a04f3d5c..e27e8b277f 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequest.ts
@@ -6,8 +6,10 @@
*/
import type { PatchMessageRequestAttachmentIdsToDelete } from './patchMessageRequestAttachmentIdsToDelete';
import type { PatchMessageRequestContent } from './patchMessageRequestContent';
+import type { PatchMessageRequestNonce } from './patchMessageRequestNonce';
export interface PatchMessageRequest {
attachment_ids_to_delete?: PatchMessageRequestAttachmentIdsToDelete;
content?: PatchMessageRequestContent;
+ nonce?: PatchMessageRequestNonce;
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequestNonce.ts b/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequestNonce.ts
new file mode 100644
index 0000000000..ef0a8cefb0
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/patchMessageRequestNonce.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PatchMessageRequestNonce = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postMessageRequest.ts b/js/app/packages/service-clients/service-comms/generated/models/postMessageRequest.ts
index e2fce060b4..ba33ed29cf 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/postMessageRequest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/postMessageRequest.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { NewAttachment } from './newAttachment';
+import type { PostMessageRequestNonce } from './postMessageRequestNonce';
import type { PostMessageRequestThreadId } from './postMessageRequestThreadId';
import type { SimpleMention } from './simpleMention';
@@ -12,5 +13,6 @@ export interface PostMessageRequest {
attachments: NewAttachment[];
content: string;
mentions: SimpleMention[];
+ nonce?: PostMessageRequestNonce;
thread_id?: PostMessageRequestThreadId;
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postMessageRequestNonce.ts b/js/app/packages/service-clients/service-comms/generated/models/postMessageRequestNonce.ts
new file mode 100644
index 0000000000..bc97d6c105
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/postMessageRequestNonce.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostMessageRequestNonce = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postMessageResponse.ts b/js/app/packages/service-clients/service-comms/generated/models/postMessageResponse.ts
index 1bb5972e50..a225362cd9 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/postMessageResponse.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/postMessageResponse.ts
@@ -4,7 +4,9 @@
* comms_service
* OpenAPI spec version: 0.1.0
*/
+import type { PostMessageResponseNonce } from './postMessageResponseNonce';
export interface PostMessageResponse {
id: string;
+ nonce?: PostMessageResponseNonce;
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postMessageResponseNonce.ts b/js/app/packages/service-clients/service-comms/generated/models/postMessageResponseNonce.ts
new file mode 100644
index 0000000000..aa312ee151
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/postMessageResponseNonce.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostMessageResponseNonce = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postReactionRequest.ts b/js/app/packages/service-clients/service-comms/generated/models/postReactionRequest.ts
index 18af8c2826..a5013009ad 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/postReactionRequest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/postReactionRequest.ts
@@ -4,10 +4,13 @@
* comms_service
* OpenAPI spec version: 0.1.0
*/
+
+import type { PostReactionRequestNonce } from './postReactionRequestNonce';
import type { ReactionAction } from './reactionAction';
export interface PostReactionRequest {
action: ReactionAction;
emoji: string;
message_id: string;
+ nonce?: PostReactionRequestNonce;
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postReactionRequestNonce.ts b/js/app/packages/service-clients/service-comms/generated/models/postReactionRequestNonce.ts
new file mode 100644
index 0000000000..819e8dbfd2
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/postReactionRequestNonce.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostReactionRequestNonce = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postTypingRequest.ts b/js/app/packages/service-clients/service-comms/generated/models/postTypingRequest.ts
index 0e893a81fd..b77de77c25 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/postTypingRequest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/postTypingRequest.ts
@@ -5,10 +5,12 @@
* OpenAPI spec version: 0.1.0
*/
+import type { PostTypingRequestNonce } from './postTypingRequestNonce';
import type { PostTypingRequestThreadId } from './postTypingRequestThreadId';
import type { TypingAction } from './typingAction';
export interface PostTypingRequest {
action: TypingAction;
+ nonce?: PostTypingRequestNonce;
thread_id?: PostTypingRequestThreadId;
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/postTypingRequestNonce.ts b/js/app/packages/service-clients/service-comms/generated/models/postTypingRequestNonce.ts
new file mode 100644
index 0000000000..4a665f200b
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/postTypingRequestNonce.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostTypingRequestNonce = string | null;
diff --git a/js/app/packages/service-clients/service-comms/openapi.json b/js/app/packages/service-clients/service-comms/openapi.json
index 7288d1fcd2..9c99f171a6 100644
--- a/js/app/packages/service-clients/service-comms/openapi.json
+++ b/js/app/packages/service-clients/service-comms/openapi.json
@@ -2515,6 +2515,9 @@
},
"content": {
"type": ["string", "null"]
+ },
+ "nonce": {
+ "type": ["string", "null"]
}
}
},
@@ -2549,6 +2552,9 @@
"$ref": "#/components/schemas/SimpleMention"
}
},
+ "nonce": {
+ "type": ["string", "null"]
+ },
"thread_id": {
"type": ["string", "null"],
"format": "uuid"
@@ -2561,6 +2567,9 @@
"properties": {
"id": {
"type": "string"
+ },
+ "nonce": {
+ "type": ["string", "null"]
}
}
},
@@ -2576,6 +2585,9 @@
},
"message_id": {
"type": "string"
+ },
+ "nonce": {
+ "type": ["string", "null"]
}
}
},
@@ -2586,6 +2598,9 @@
"action": {
"$ref": "#/components/schemas/TypingAction"
},
+ "nonce": {
+ "type": ["string", "null"]
+ },
"thread_id": {
"type": ["string", "null"]
}
diff --git a/rust/cloud-storage/comms_service/src/api/channels/delete_message.rs b/rust/cloud-storage/comms_service/src/api/channels/delete_message.rs
index 21ab63b86b..a8c2db04a4 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/delete_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/delete_message.rs
@@ -3,11 +3,14 @@ use crate::{
context::AppState,
extractors::{ChannelParticipants, MessageId, MessageSenderOrAdmin},
},
- service::{self, sender::notify::notify_message},
+ service::{
+ self,
+ sender::notify::{WithNonce, notify_message},
+ },
};
use anyhow::Result;
use axum::{
- extract::{Path, State},
+ extract::{Path, Query, State},
http::StatusCode,
};
use comms_db_client::messages::delete_message::delete_message;
@@ -20,6 +23,11 @@ pub struct DeleteMessageParams {
pub message_id: String,
}
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct DeleteMessageQuery {
+ pub nonce: Option<String>,
+}
+
#[utoipa::path(
delete,
tag = "channels",
@@ -43,31 +51,35 @@ pub async fn delete_message_handler(
ChannelParticipants(participants): ChannelParticipants,
MessageId(message_id): MessageId,
Path(params): Path<DeleteMessageParams>,
+ Query(query): Query<DeleteMessageQuery>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
tracing::info!("delete_message");
let message = delete_message(&ctx.db, message_id).await.map_err(|e| {
- tracing::error!(error=?e, "unable to patch message");
+ tracing::error!(error=?e, "unable to delete message");
(
StatusCode::INTERNAL_SERVER_ERROR,
- "unable to patch message".to_string(),
+ "unable to delete message".to_string(),
)
})?;
- let participants: Vec<_> = participants
- .clone()
- .iter()
- .map(|p| p.user_id.clone())
- .collect();
+ let participants: Vec<_> = participants.iter().map(|p| p.user_id.clone()).collect();
- notify_message(&ctx, message, &participants)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to notify message");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to deliver message".to_string(),
- )
- })?;
+ notify_message(
+ &ctx,
+ WithNonce {
+ data: &message,
+ nonce: query.nonce.as_deref(),
+ },
+ &participants,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to notify message");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to deliver message".to_string(),
+ )
+ })?;
service::search::send_remove_channel_message_to_search_extractor_queue(
&ctx.sqs_client,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs b/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
index c4795670fb..7669831ee5 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
@@ -3,7 +3,10 @@ use crate::{
context::AppState,
extractors::{ChannelId, ChannelParticipants, MessageId, MessageSender},
},
- service::{self, sender::notify},
+ service::{
+ self,
+ sender::notify::{self, AttachmentData, WithNonce},
+ },
};
use anyhow::Result;
use axum::{
@@ -25,6 +28,7 @@ use uuid::Uuid;
pub struct PatchMessageRequest {
pub content: Option<String>,
pub attachment_ids_to_delete: Option<Vec<String>>,
+ pub nonce: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
@@ -64,8 +68,14 @@ pub async fn patch_message_handler(
if let Some(attachment_ids) = &req.attachment_ids_to_delete
&& !attachment_ids.is_empty()
{
- delete_message_attachments(&app_state, attachment_ids.clone(), message_id, channel_id)
- .await?;
+ delete_message_attachments(
+ &app_state,
+ attachment_ids.clone(),
+ message_id,
+ channel_id,
+ req.nonce.as_deref(),
+ )
+ .await?;
}
if let Some(content) = &req.content {
@@ -96,15 +106,22 @@ pub async fn patch_message_handler(
} else {
participants.iter().map(|p| p.user_id.copied()).collect()
};
- notify::notify_message(&app_state, message, &participants)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to notify message");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to deliver message".to_string(),
- )
- })?;
+ notify::notify_message(
+ &app_state,
+ WithNonce {
+ data: &message,
+ nonce: req.nonce.as_deref(),
+ },
+ &participants,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to notify message");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to deliver message".to_string(),
+ )
+ })?;
upsert_activity(
&app_state.db,
@@ -134,6 +151,7 @@ async fn delete_message_attachments(
attachment_ids: Vec<String>,
message_id: Uuid,
channel_id: Uuid,
+ nonce: Option<&str>,
) -> Result<(), (StatusCode, String)> {
// Parse string IDs into UUIDs
let attachment_uuids = attachment_ids
@@ -206,17 +224,22 @@ async fn delete_message_attachments(
// TODO: delete from sfs it's a static file attachment (image)
// Notify about the remaining attachments
- let attachment_update = notify::AttachmentUpdate {
- channel_id,
- message_id,
- attachments: remaining_attachments.clone(),
- };
- notify::notify_attachments(ctx, attachment_update)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to notify attachments");
- (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
- })?;
+ notify::notify_attachments(
+ ctx,
+ WithNonce {
+ data: AttachmentData {
+ channel_id: &channel_id,
+ message_id: &message_id,
+ attachments: &remaining_attachments,
+ },
+ nonce,
+ },
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to notify attachments");
+ (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
+ })?;
patch_message_attachments(&ctx.db, message_id, remaining_attachments)
.await
diff --git a/rust/cloud-storage/comms_service/src/api/channels/post_message.rs b/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
index d7d371f450..c1c25dea2e 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
@@ -2,11 +2,12 @@ use crate::api::context::ChannelImpl;
use crate::api::{context::AppState, extractors::ChannelName};
use crate::channel_permissions;
use crate::notification as comms_notification;
+use crate::service::sender::notify::WithNonce;
use crate::{
api::extractors::{ChannelId, ChannelMember, ChannelParticipants, ChannelTypeExtractor},
service::{
self,
- sender::notify::{self, AttachmentUpdate},
+ sender::notify::{self, AttachmentData},
},
};
use anyhow::Result;
@@ -39,11 +40,13 @@ pub struct PostMessageRequest {
pub mentions: Vec<SimpleMention>,
pub thread_id: Option<Uuid>,
pub attachments: Vec<NewAttachment>,
+ pub nonce: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct PostMessageResponse {
pub id: String,
+ pub nonce: Option<String>,
}
#[utoipa::path(
@@ -156,15 +159,22 @@ pub async fn post_message_handler(
.collect();
let start_time = Instant::now();
- notify::notify_message(&ctx, message.clone(), &participants)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to notify message");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to deliver message".to_string(),
- )
- })?;
+ notify::notify_message(
+ &ctx,
+ WithNonce {
+ data: &message,
+ nonce: req.nonce.as_deref(),
+ },
+ &participants,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to notify message");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to deliver message".to_string(),
+ )
+ })?;
tracing::debug!("message notification took {:?}ms", start_time.elapsed());
let start_time = Instant::now();
@@ -203,10 +213,13 @@ pub async fn post_message_handler(
let start_time = Instant::now();
notify::notify_attachments(
&ctx,
- AttachmentUpdate {
- channel_id,
- message_id: message.id,
- attachments,
+ WithNonce {
+ data: AttachmentData {
+ channel_id: &channel_id,
+ message_id: &message.id,
+ attachments: &attachments,
+ },
+ nonce: req.nonce.as_deref(),
},
)
.await
@@ -242,6 +255,7 @@ pub async fn post_message_handler(
StatusCode::OK,
Json(PostMessageResponse {
id: message.id.to_string(),
+ nonce: req.nonce.clone(),
}),
))
}
diff --git a/rust/cloud-storage/comms_service/src/api/channels/post_reaction.rs b/rust/cloud-storage/comms_service/src/api/channels/post_reaction.rs
index a7bef91ec7..4a524c8e41 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/post_reaction.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/post_reaction.rs
@@ -11,7 +11,7 @@ use crate::{
context::AppState,
extractors::{ChannelId, ChannelMember},
},
- service::sender::notify::{ReactionUpdate, notify_reactions},
+ service::sender::notify::{ReactionData, WithNonce, notify_reactions},
};
use comms_db_client::{
@@ -37,6 +37,9 @@ pub struct PostReactionRequest {
pub message_id: String,
// wether we are adding or removing the reaction
pub action: ReactionAction,
+
+ // nonce to help optimistic updating on the frontend
+ pub nonce: Option<String>,
}
#[utoipa::path(
@@ -48,7 +51,7 @@ pub struct PostReactionRequest {
("channel_id" = String, Path, description = "id of the channel")
),
responses(
- (status = 201, body=String),
+ (status = 201, body=String),
(status = 401, body=String),
(status = 404, body=String),
(status = 500, body=String),
@@ -66,7 +69,7 @@ pub async fn post_reaction_handler(
(StatusCode::BAD_REQUEST, err.to_string())
})?;
- let req = match req.action {
+ let req_action = match req.action {
ReactionAction::Add => {
add_reaction(
&ctx.db,
@@ -96,17 +99,20 @@ pub async fn post_reaction_handler(
let counted_reactions = group_reactions(reactions);
- req.map_err(|err| {
- tracing::error!(error=?err, "unable to add reaction");
+ req_action.map_err(|err| {
+ tracing::error!(error=?err, "unable to process reaction");
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
})?;
notify_reactions(
&ctx,
- ReactionUpdate {
- channel_id,
- message_id,
- reactions: counted_reactions,
+ WithNonce {
+ data: ReactionData {
+ channel_id: &channel_id,
+ message_id: &message_id,
+ reactions: &counted_reactions,
+ },
+ nonce: req.nonce.as_deref(),
},
)
.await
diff --git a/rust/cloud-storage/comms_service/src/api/channels/post_typing.rs b/rust/cloud-storage/comms_service/src/api/channels/post_typing.rs
index dcfdcc9d0c..96c8eb0966 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/post_typing.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/post_typing.rs
@@ -3,7 +3,7 @@ use crate::{
context::AppState,
extractors::{ChannelId, ChannelMember},
},
- service::sender::notify::{TypingUpdate, notify_typing},
+ service::sender::notify::{TypingData, WithNonce, notify_typing},
};
use anyhow::Result;
@@ -18,6 +18,7 @@ use uuid::Uuid;
pub struct PostTypingRequest {
pub action: TypingAction,
pub thread_id: Option<String>,
+ pub nonce: Option<String>,
}
#[utoipa::path(
@@ -54,11 +55,14 @@ pub async fn post_typing_handler(
notify_typing(
&app_state,
- TypingUpdate {
- channel_id,
- user_id: channel_member.context.user_id.clone(),
- action: req.action,
- thread_id,
+ WithNonce {
+ data: TypingData {
+ channel_id: &channel_id,
+ user_id: &channel_member.context.user_id,
+ action: req.action,
+ thread_id: thread_id.as_ref(),
+ },
+ nonce: req.nonce.as_deref(),
},
)
.await
diff --git a/rust/cloud-storage/comms_service/src/service/sender/notify.rs b/rust/cloud-storage/comms_service/src/service/sender/notify.rs
index 786e1c6ba2..6db68908d2 100644
--- a/rust/cloud-storage/comms_service/src/service/sender/notify.rs
+++ b/rust/cloud-storage/comms_service/src/service/sender/notify.rs
@@ -3,15 +3,25 @@ use comms_db_client::model::{Attachment, CountedReaction, Message, TypingAction}
use comms_db_client::participants::get_participants::get_participants;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
-use serde::{Deserialize, Serialize};
+use serde::Serialize;
use utoipa::ToSchema;
use uuid::Uuid;
use crate::api::context::AppState;
+/// Generic wrapper that adds an optional nonce to any serializable payload.
+/// Used for optimistic update correlation - the nonce is echoed back to the client.
+#[derive(Serialize, ToSchema)]
+pub struct WithNonce<'a, T: Serialize> {
+ #[serde(flatten)]
+ pub data: T,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub nonce: Option<&'a str>,
+}
+
pub async fn notify_message(
ctx: &AppState,
- message: Message,
+ message: WithNonce<'_, &Message>,
participants: &[MacroUserIdStr<'_>],
) -> Result<()> {
if participants.is_empty() {
@@ -31,16 +41,16 @@ pub async fn notify_message(
Ok(())
}
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
-pub struct TypingUpdate {
- pub channel_id: Uuid,
- pub user_id: String,
+#[derive(Debug, Serialize, ToSchema)]
+pub struct TypingData<'a> {
+ pub channel_id: &'a Uuid,
+ pub user_id: &'a str,
pub action: TypingAction,
- pub thread_id: Option<Uuid>,
+ pub thread_id: Option<&'a Uuid>,
}
-pub async fn notify_typing(ctx: &AppState, update: TypingUpdate) -> Result<()> {
- let participants = get_participants(&ctx.db, &update.channel_id).await?;
+pub async fn notify_typing(ctx: &AppState, update: WithNonce<'_, TypingData<'_>>) -> Result<()> {
+ let participants = get_participants(&ctx.db, update.data.channel_id).await?;
ctx.connection_gateway_client
.batch_send_message(
@@ -56,15 +66,18 @@ pub async fn notify_typing(ctx: &AppState, update: TypingUpdate) -> Result<()> {
Ok(())
}
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
-pub struct ReactionUpdate {
- pub channel_id: Uuid,
- pub message_id: Uuid,
- pub reactions: Vec<CountedReaction>,
+#[derive(Debug, Serialize, ToSchema)]
+pub struct ReactionData<'a> {
+ pub channel_id: &'a Uuid,
+ pub message_id: &'a Uuid,
+ pub reactions: &'a [CountedReaction],
}
-pub async fn notify_reactions(ctx: &AppState, update: ReactionUpdate) -> Result<()> {
- let participants = get_participants(&ctx.db, &update.channel_id).await?;
+pub async fn notify_reactions(
+ ctx: &AppState,
+ update: WithNonce<'_, ReactionData<'_>>,
+) -> Result<()> {
+ let participants = get_participants(&ctx.db, update.data.channel_id).await?;
ctx.connection_gateway_client
.batch_send_message(
@@ -80,15 +93,18 @@ pub async fn notify_reactions(ctx: &AppState, update: ReactionUpdate) -> Result<
Ok(())
}
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
-pub struct AttachmentUpdate {
- pub channel_id: Uuid,
- pub message_id: Uuid,
- pub attachments: Vec<Attachment>,
+#[derive(Debug, Serialize, ToSchema)]
+pub struct AttachmentData<'a> {
+ pub channel_id: &'a Uuid,
+ pub message_id: &'a Uuid,
+ pub attachments: &'a [Attachment],
}
-pub async fn notify_attachments(ctx: &AppState, update: AttachmentUpdate) -> Result<()> {
- let participants = get_participants(&ctx.db, &update.channel_id).await?;
+pub async fn notify_attachments(
+ ctx: &AppState,
+ update: WithNonce<'_, AttachmentData<'_>>,
+) -> Result<()> {
+ let participants = get_participants(&ctx.db, update.data.channel_id).await?;
ctx.connection_gateway_client
.batch_send_message(