Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(messages): keep the client-minted id as the message id (#6886)
gbirman1e0281884426
diff --git a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.mdindex 1283da8a54..80d1aab43d 100644--- a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md+++ b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md@@ -154,8 +154,8 @@ Signals are the interface; no factory imports another factory's file — Channelat the bottom of every cached variant — but **only if the newest page has no`previous_cursor`** (i.e. we're actually at the bottom of the conversation, channel-messages.ts:278).Returns rollback context.-2. **mutationFn**: `postMessage({ ..., nonce: optimisticId })` — server echoes the nonce in the WS broadcast.-3. **onSuccess**: `replaceOptimisticMessage` swaps `optimisticId → data.id` in place (no refetch);+2. **mutationFn**: `postMessage({ ..., id: optimisticId, nonce: optimisticId })` — the server keeps the id and echoes the nonce in the WS broadcast.+3. **onSuccess**: no id swap, since the optimistic message already carries its final id (`newMessageId`);refresh soup entity so channel lists re-sort.4. **onError**: toast + `rollbackInsertChannelMessage` (remove the optimistic row).5. **onSettled**: `softInvalidateTargetCaches` — `invalidateQueries({ refetchType: 'inactive' })`,@@ -236,7 +236,7 @@ and each `*InTargetCaches` helper applies the change to all three cache familiesChannel stores both `onChange`-mirrored snapshot and `onReady` handle in signals (Channel.tsx:204–207).- **Send** (Channel.tsx:623–648): `buildPostMessageSendPayload({ snapshot, participantIds })`(`Input/message-payload.ts:96`) expands mentions (`@here` fan-out, bot re-tagging) and maps- attachments; then `sendMessageMutation.mutate({ channelID, senderId, optimisticId: crypto.randomUUID(), ...payload }, { onError })`.+ attachments; then `sendMessageMutation.mutate({ channelID, senderId, optimisticId: newMessageId(), ...payload }, { onError })`.- **Restore-on-error**: the input cleared itself on send; `onError` restores the failedsnapshot via `handle.restoreSnapshot(snapshot)` — but only if the user hasn't typed newsendable content meanwhile (`hasSendableInputContent(current)` check, :643).diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex 8a4c3c7c73..401b2db6d3 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -52,6 +52,7 @@ import {import { queryClient } from '@queries/client';import { queryReadyGate } from '@queries/gate';import {+ newMessageId,useDeleteMessageMutation,usePatchMessageMutation,useSendMessageMutation,@@ -636,7 +637,7 @@ export function Channel(props: ChannelProps) {{parent: { type: 'channel', id: props.channelId },senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),...payload,},{diff --git a/apps/web/src/features/channel/Thread/ThreadReplyChannelInput.tsx b/apps/web/src/features/channel/Thread/ThreadReplyChannelInput.tsxindex a0aef080e0..b55d4dcf4a 100644--- a/apps/web/src/features/channel/Thread/ThreadReplyChannelInput.tsx+++ b/apps/web/src/features/channel/Thread/ThreadReplyChannelInput.tsx@@ -1,5 +1,8 @@import { useUserId } from '@core/context/user';-import { useSendMessageMutation } from '@queries/messages/mutations';+import {+ newMessageId,+ useSendMessageMutation,+} from '@queries/messages/mutations';import { usePostTypingUpdateMutation } from '@queries/messages/typing';import type { MessageParent } from '@service-storage/messages';import {@@ -145,7 +148,7 @@ export function ThreadReplyChannelInput(props: ThreadReplyChannelInputProps) {{parent: props.parent,senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),...payload,},{diff --git a/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsx b/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsxindex 3ab3552869..37b27afa44 100644--- a/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsx+++ b/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsx@@ -43,7 +43,10 @@ import {useGetOrCreateDirectMessageMutation,useGetOrCreatePrivateChannelMutation,} from '@queries/channel/get-or-create-dm';-import { useSendMessageMutation } from '@queries/messages/mutations';+import {+ newMessageId,+ useSendMessageMutation,+} from '@queries/messages/mutations';import { staticFileClient } from '@service-static-files/client';import { isIOS } from '@solid-primitives/platform';import { Button } from '@ui';@@ -316,7 +319,7 @@ function IosShareSheetComposer(props: {parent: { type: 'channel', id: channelId },message,senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),});invalidateListChannels();diff --git a/apps/web/src/lib/core/messages/DocumentConversation.tsx b/apps/web/src/lib/core/messages/DocumentConversation.tsxindex 286b9f34fe..65d6d53f7d 100644--- a/apps/web/src/lib/core/messages/DocumentConversation.tsx+++ b/apps/web/src/lib/core/messages/DocumentConversation.tsx@@ -4,7 +4,10 @@ import { useMessageBotMentionUsers } from '@channel/use-channel-bot-mention-userimport { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { useUserId } from '@core/context/user';import { useMessageLink } from '@queries/messages/document-messages';-import { useSendMessageMutation } from '@queries/messages/mutations';+import {+ newMessageId,+ useSendMessageMutation,+} from '@queries/messages/mutations';import { useMessageTimelineQuery } from '@queries/messages/timeline';import type { MessageParent } from '@service-storage/messages';import { createMemo, createSignal, For, Show } from 'solid-js';@@ -36,7 +39,7 @@ export function DocumentConversationComposer(props: {await send.mutateAsync({parent: props.parent,senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),...buildPostMessageSendPayload({ snapshot }),});input?.clear();diff --git a/apps/web/src/lib/core/util/channels.ts b/apps/web/src/lib/core/util/channels.tsindex ce6f0b715c..281db80d3c 100644--- a/apps/web/src/lib/core/util/channels.ts+++ b/apps/web/src/lib/core/util/channels.ts@@ -9,7 +9,10 @@ import {useGetOrCreateDirectMessageMutation,useGetOrCreatePrivateChannelMutation,} from '@queries/channel/get-or-create-dm';-import { useSendMessageMutation } from '@queries/messages/mutations';+import {+ newMessageId,+ useSendMessageMutation,+} from '@queries/messages/mutations';import type { NewAttachment } from '@service-storage/generated/schemas/newAttachment';import type { SimpleMention } from '@service-storage/generated/schemas/simpleMention';import { createCallback } from '@solid-primitives/rootless';@@ -58,7 +61,7 @@ export function useSendMessageToPeople() {parent: { type: 'channel', id: channelId },message: { content, attachments, mentions },senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),}).catch(() => null);if (!messageResponse) return;diff --git a/apps/web/src/lib/queries/messages/document-messages.ts b/apps/web/src/lib/queries/messages/document-messages.tsindex d445304358..1e07cf0a02 100644--- a/apps/web/src/lib/queries/messages/document-messages.ts+++ b/apps/web/src/lib/queries/messages/document-messages.ts@@ -9,6 +9,7 @@ import {import { useQuery } from '@tanstack/solid-query';import { type Accessor, createEffect } from 'solid-js';import {+ newMessageId,useDeleteMessageMutation,useDeleteThreadMutation,usePatchThreadMutation,@@ -82,7 +83,7 @@ export function useMessageActions(parent: Accessor<MessageParent>) {parent: parent(),message,senderId,- optimisticId: crypto.randomUUID(),+ optimisticId: newMessageId(),});},delete: (id: string) =>diff --git a/apps/web/src/lib/queries/messages/mutations.ts b/apps/web/src/lib/queries/messages/mutations.tsindex 4b4ddbb240..e8b43f7baa 100644--- a/apps/web/src/lib/queries/messages/mutations.ts+++ b/apps/web/src/lib/queries/messages/mutations.ts@@ -26,6 +26,7 @@ import {type PostMessage,} from '@service-storage/messages';import { useMutation } from '@tanstack/solid-query';+import { v7 as uuidv7 } from 'uuid';import { queryClient } from '../client';import { createMutationNonce, registerNonce } from '../nonce';import { MessageNonceKeys } from './keys';@@ -40,7 +41,6 @@ import {markTopLevelMessageDeletedInTargetCaches,patchTargetMessage,removeMessageFromTargetCaches,- replaceTargetMessageId,resolveMessageTarget,restoreMessageInTargetCaches,softInvalidateTargetCaches,@@ -232,28 +232,6 @@ export function rollbackInsertChannelMessage(removeMessageFromTargetCaches(parent, context.target);}-/**- * Replace an optimistic message ID with the real server-assigned ID.- * Called in mutation onSuccess after server returns the real message.- */-function replaceOptimisticMessage(- vars: WithParent<{- optimisticId: string;- realId: string;- threadId?: string;- }>-): void {- replaceTargetMessageId(- vars.parent,- resolveMessageTarget({- parent: vars.parent,- messageId: vars.optimisticId,- threadId: vars.threadId,- }),- vars.realId- );-}-/*** Optimistically delete a message from the channel cache.*@@ -403,10 +381,19 @@ export function rollbackUpdateMessage(});}+/**+ * Mint the id of a message about to be sent. The server stores it as the+ * message id, so it must be a UUIDv7 stamped with the current time.+ */+export function newMessageId(): string {+ return uuidv7();+}+type SendMessageParams = {parent: MessageParent;message: PostMessage;optimisticAttachments?: readonly OptimisticPostMessageAttachment[];+ /** From `newMessageId`; the message's final id, not a placeholder. */optimisticId: string;senderId: string;};@@ -432,9 +419,11 @@ export function useSendMessageMutation(return useMutation(() => ({gcTime: 0,mutationFn: async (vars: SendMessageParams) => {- // Use optimisticId as nonce - allows server to echo it back for correlation+ // The server keeps optimisticId as the message id, so the optimistic+ // message never changes id; it is also the nonce the server echoes.return entityMessagesClient.post(vars.parent, {...vars.message,+ id: vars.optimisticId,nonce: vars.optimisticId,});},@@ -468,14 +457,22 @@ export function useSendMessageMutation(return { insert, updatedAt };},- onSuccess(data, variables) {+ onSuccess(data, variables, context) {const threadId = variables.message.thread_id ?? undefined;- replaceOptimisticMessage({- parent: variables.parent,- optimisticId: variables.optimisticId,- realId: data.id,- threadId,- });+ // A server predating client-minted ids ignores `id` and mints its+ // own. Rebuild the optimistic row under the server id so it keeps+ // its thread state (including the anchor) and never holds a dead id;+ // `applyMessage` below then settles it on the server's fields.+ if (data.id !== variables.optimisticId && context?.insert) {+ rollbackInsertChannelMessage(variables.parent, context.insert);+ optimisticInsertMessage({+ parent: variables.parent,+ optimisticId: data.id,+ senderId: variables.senderId,+ optimisticAttachments: variables.optimisticAttachments,+ ...variables.message,+ });+ }// Sending is a `messaged` activity server-side; stamp the touch now// so the Recent order moves the channel up without waiting on thediff --git a/apps/web/src/lib/queries/messages/reconcile.ts b/apps/web/src/lib/queries/messages/reconcile.tsindex e0de3efaf9..33f4413005 100644--- a/apps/web/src/lib/queries/messages/reconcile.ts+++ b/apps/web/src/lib/queries/messages/reconcile.ts@@ -12,7 +12,6 @@ import {getThreadReplySnapshot,insertThreadReply,removeThreadReply,- replaceThreadReplyId,restoreThreadReply,setThreadRepliesData,softInvalidateThreadReplies,@@ -27,8 +26,6 @@ import {insertTopLevelMessageIntoMessageTimeline,removeThreadReplyFromMessageTimeline,removeTopLevelMessageFromMessageTimeline,- replaceThreadReplyIdInMessageTimeline,- replaceTopLevelMessageIdInMessageTimeline,restoreThreadPreviewReplyInMessageTimeline,restoreTopLevelMessageInMessageTimeline,setMessageTimelineData,@@ -265,32 +262,6 @@ export function restoreMessageInTargetCaches();}-/** Replaces a target message id across all rendered caches. */-export function replaceTargetMessageId(- parent: MessageParent,- target: MessageTarget,- realId: string-) {- if (target.kind === 'thread_reply') {- setThreadRepliesData(parent, target.threadId, (prev) =>- replaceThreadReplyId(prev, target.messageId, realId)- );- setMessageTimelineData(parent, (prev) =>- replaceThreadReplyIdInMessageTimeline(- prev,- target.threadId,- target.messageId,- realId- )- );- return;- }-- setMessageTimelineData(parent, (prev) =>- replaceTopLevelMessageIdInMessageTimeline(prev, target.messageId, realId)- );-}-/** Find a root's cached thread state without inventing a partial one. */export function getCachedThreadState(parent: MessageParent,diff --git a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx b/apps/web/src/lib/queries/messages/tests/mutations.test.tsxindex 3360f7b20d..56fa716c18 100644--- a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx@@ -9,7 +9,11 @@ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';let testQueryClient: QueryClient;-const mocks = vi.hoisted(() => ({ delete: vi.fn(), patchThread: vi.fn() }));+const mocks = vi.hoisted(() => ({+ delete: vi.fn(),+ patchThread: vi.fn(),+ post: vi.fn(),+}));vi.mock('../../client', () => ({get queryClient() {return testQueryClient;@@ -20,9 +24,17 @@ vi.mock('@core/component/Toast/Toast', () => ({}));vi.mock('@service-storage/messages', () => ({ entityMessagesClient: mocks }));vi.mock('../subscription', () => ({ useMessageSubscription: () => {} }));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => ({ track: vi.fn() }),+}));import { messageKeys } from '../keys';-import { useDeleteMessageMutation, usePatchThreadMutation } from '../mutations';+import {+ newMessageId,+ useDeleteMessageMutation,+ usePatchThreadMutation,+ useSendMessageMutation,+} from '../mutations';import { handleMessageEvent, onThreadStateUpdated } from '../sync';import { getThreadRepliesQueryKey } from '../thread-replies';import {@@ -53,6 +65,7 @@ function message(beforeEach(() => {mocks.delete.mockReset();mocks.patchThread.mockReset();+ mocks.post.mockReset();testQueryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },});@@ -367,3 +380,91 @@ describe('thread resolution', () => {expect(cachedResolved()).toEqual({ timeline: false, thread: false });});});++describe('sending', () => {+ it('posts the optimistic id as the message id, so it never changes', async () => {+ const parent: MessageParent = { type: 'document', id: 'doc' };+ const timelineKey = getMessageTimelineQueryKey(parent);+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {+ pageParams: [null],+ pages: [{ items: [], next_cursor: null, previous_cursor: null }],+ });+ const rootIds = () =>+ testQueryClient+ .getQueryData<MessageTimelineData>(timelineKey)!+ .pages[0].items.map((item) => [item.id, item.state.root_id]);+ let respond!: () => void;+ mocks.post.mockImplementation(+ (_parent, input) =>+ new Promise((resolve) => {+ respond = () => resolve(message(parent, input.id));+ })+ );+ let mutation!: ReturnType<typeof useSendMessageMutation>;+ function Harness() {+ mutation = useSendMessageMutation();+ return null;+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Harness />+ </QueryClientProvider>+ ));++ const id = newMessageId();+ expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7/);+ const pending = mutation.mutateAsync({+ parent,+ message: { content: '2+2=?' },+ senderId: 'macro|[email protected]',+ optimisticId: id,+ });+ await vi.waitFor(() => expect(rootIds()).toEqual([[id, id]]));+ expect(mocks.post).toHaveBeenCalledWith(+ parent,+ expect.objectContaining({ id, nonce: id })+ );+ respond();+ await pending;+ expect(rootIds()).toEqual([[id, id]]);+ });++ it('adopts the server id when the server ignores the client id', async () => {+ const parent: MessageParent = { type: 'document', id: 'doc' };+ const timelineKey = getMessageTimelineQueryKey(parent);+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {+ pageParams: [null],+ pages: [{ items: [], next_cursor: null, previous_cursor: null }],+ });+ mocks.post.mockResolvedValue(message(parent, 'server-id'));+ let mutation!: ReturnType<typeof useSendMessageMutation>;+ function Harness() {+ mutation = useSendMessageMutation();+ return null;+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Harness />+ </QueryClientProvider>+ ));++ await mutation.mutateAsync({+ parent,+ message: { content: '2+2=?' },+ senderId: 'macro|[email protected]',+ optimisticId: newMessageId(),+ });+ // The row keeps its thread state, so a document discussion (which shows+ // roots with a null anchor) still renders it.+ expect(+ testQueryClient+ .getQueryData<MessageTimelineData>(timelineKey)!+ .pages[0].items.map((item) => [item.id, item.state])+ ).toEqual([+ [+ 'server-id',+ expect.objectContaining({ root_id: 'server-id', anchor: null }),+ ],+ ]);+ });+});diff --git a/apps/web/src/lib/queries/messages/tests/sync.test.ts b/apps/web/src/lib/queries/messages/tests/sync.test.tsindex e038771fca..04eb254458 100644--- a/apps/web/src/lib/queries/messages/tests/sync.test.ts+++ b/apps/web/src/lib/queries/messages/tests/sync.test.ts@@ -27,7 +27,6 @@ vi.mock('@service-storage/messages', async (importOriginal) => ({import { registerNonce } from '../../nonce';import { MessageNonceKeys, messageKeys } from '../keys';-import { replaceTargetMessageId } from '../reconcile';import { applyMessage, applyThreadState, handleMessageEvent } from '../sync';import {getThreadRepliesQueryKey,@@ -558,27 +557,6 @@ describe.each(['channel', 'document'] as const)(expect(threadReplies()).toEqual([]);unsubscribe();});- it('keeps an own reply whose id is remapped while the fetch is in flight', async () => {- const { settleEmpty, threadReplies, unsubscribe } =- await expandThreadWithPendingFetch();-- // An own reply is inserted optimistically, then its id is remapped to the- // server id (as the send mutation does) before the fetch settles.- applyMessage(message(parent, 'optimistic', 'root'), 'posted');- replaceTargetMessageId(- parent,- { kind: 'thread_reply', messageId: 'optimistic', threadId: 'root' },- 'server-id'- );- await settleEmpty();-- // The deferred re-apply matches the reply by its current preview id, so it- // lands under the server id rather than being lost to the remap.- expect(threadReplies()).toEqual([- expect.objectContaining({ id: 'server-id' }),- ]);- unsubscribe();- });it('skips the sender nonce and scopes ephemeral typing to the parent and root', () => {seed();registerNonce(MessageNonceKeys.MESSAGE, 'own-send');diff --git a/apps/web/src/lib/queries/messages/thread-preview.ts b/apps/web/src/lib/queries/messages/thread-preview.tsindex 48003d1b28..f48f64a05d 100644--- a/apps/web/src/lib/queries/messages/thread-preview.ts+++ b/apps/web/src/lib/queries/messages/thread-preview.ts@@ -64,21 +64,6 @@ export function replaceReplyCreatedAtInThreadPreview(return didChange ? { ...thread, preview } : thread;}-export function replaceReplyIdInThreadPreview(- thread: ThreadPreviewState,- optimisticId: string,- realId: string-): ThreadPreviewState {- let didChange = false;- const preview = thread.preview.map((reply) => {- if (reply.id !== optimisticId) return reply;- didChange = true;- return { ...reply, id: realId };- });-- return didChange ? { ...thread, preview } : thread;-}-export function captureThreadPreviewReplySnapshot(thread: ThreadPreviewState,replyId: stringdiff --git a/apps/web/src/lib/queries/messages/thread-replies.ts b/apps/web/src/lib/queries/messages/thread-replies.tsindex 00bf28322c..d07eda8ce3 100644--- a/apps/web/src/lib/queries/messages/thread-replies.ts+++ b/apps/web/src/lib/queries/messages/thread-replies.ts@@ -112,23 +112,6 @@ export function removeThreadReply(return nextReplies.length === data.length ? data : nextReplies;}-export function replaceThreadReplyId(- data: Array<EntityMessage> | undefined,- optimisticId: string,- realId: string-): Array<EntityMessage> | undefined {- if (!data) return data;-- let didChange = false;- const nextReplies = data.map((reply) => {- if (reply.id !== optimisticId) return reply;- didChange = true;- return { ...reply, id: realId };- });-- return didChange ? nextReplies : data;-}-export function getThreadReplySnapshot(data: Array<EntityMessage> | undefined,replyId: stringdiff --git a/apps/web/src/lib/queries/messages/timeline.ts b/apps/web/src/lib/queries/messages/timeline.tsindex 31e0051540..ca1be3b587 100644--- a/apps/web/src/lib/queries/messages/timeline.ts+++ b/apps/web/src/lib/queries/messages/timeline.ts@@ -30,7 +30,6 @@ import {captureThreadPreviewReplySnapshot,insertReplyIntoThreadPreview,removeReplyFromThreadPreview,- replaceReplyIdInThreadPreview,restoreReplyToThreadPreview,} from './thread-preview';@@ -533,20 +532,6 @@ export function removeTopLevelMessageFromMessageTimeline();}-export function replaceTopLevelMessageIdInMessageTimeline(- data: MessageTimelineData | undefined,- optimisticId: string,- realId: string-): MessageTimelineData | undefined {- if (!data) return data;-- return mapMessageTimelineItems(data, (message) =>- message.id === optimisticId- ? { ...message, id: realId, state: { ...message.state, root_id: realId } }- : message- );-}-function getTopLevelMessageSnapshot(data: MessageTimelineData | undefined,messageId: string@@ -625,25 +610,6 @@ export function removeThreadReplyFromMessageTimeline(});}-export function replaceThreadReplyIdInMessageTimeline(- data: MessageTimelineData | undefined,- threadId: string,- optimisticId: string,- realId: string-): MessageTimelineData | undefined {- if (!data) return data;-- return mapMessageTimelineItems(data, (message) => {- if (message.id !== threadId) return message;- const thread = replaceReplyIdInThreadPreview(- message.thread,- optimisticId,- realId- );- return thread === message.thread ? message : { ...message, thread };- });-}-function getThreadPreviewReplySnapshot(data: MessageTimelineData | undefined,threadId: string,diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex c08acfdad7..d2cadaa4a9 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -1065,6 +1065,7 @@ export * from './postItemsSoupAstParams';export * from './postItemsSoupParams';export * from './postMessage';export * from './postMessageAnchor';+export * from './postMessageId';export * from './postMessageNonce';export * from './postMessageNotificationPolicy';export * from './postMessageRequest';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessage.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessage.tsindex 8b663b1f86..c1d0be281e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessage.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessage.ts@@ -7,6 +7,7 @@import type { NewAttachment } from './newAttachment';import type { PostMessageAnchor } from './postMessageAnchor';+import type { PostMessageId } from './postMessageId';import type { PostMessageNonce } from './postMessageNonce';import type { PostMessageThreadId } from './postMessageThreadId';import type { SimpleMention } from './simpleMention';@@ -20,6 +21,9 @@ export interface PostMessage {attachments?: NewAttachment[];/** Macro Markdown body. */content: string;+ /** Client-minted UUIDv7 for the new message, so an optimistic message+already carries its final id; the server mints one when absent. */+ id?: PostMessageId;/** Mentions tracked by the editor. */mentions?: SimpleMention[];/** Client nonce for optimistic reconciliation. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessageId.tsnew file mode 100644index 0000000000..7f6d35df41--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/postMessageId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Client-minted UUIDv7 for the new message, so an optimistic message+already carries its final id; the server mints one when absent.+ */+export type PostMessageId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 0aaad4c161..b758183135 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -28998,6 +28998,12 @@ export const entityMessageCreateBody = zod.optional().describe('Initial attachments.'),content: zod.string().describe('Macro Markdown body.'),+ id: zod+ .uuid()+ .nullish()+ .describe(+ 'Client-minted UUIDv7 for the new message, so an optimistic message\nalready carries its final id; the server mints one when absent.'+ ),mentions: zod.array(zoddiff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 45712139cf..bb8918277b 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -26668,6 +26668,11 @@"type": "string","description": "Macro Markdown body."},+ "id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Client-minted UUIDv7 for the new message, so an optimistic message\nalready carries its final id; the server mints one when absent."+ },"mentions": {"type": "array","items": {diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rsindex 18ce360f66..47f34ba8f1 100644--- a/crates/agent_harness/src/outbound/channel_announcer.rs+++ b/crates/agent_harness/src/outbound/channel_announcer.rs@@ -133,6 +133,7 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>.post(access,PostMessage {+ id: None,attribution: MessageAttribution::ActingUser,// The chip is a pointer, not news: the thread hears// about the session when it finishes or asks, through@@ -173,6 +174,7 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>.post(access,PostMessage {+ id: None,attribution: MessageAttribution::ActingUser,anchor: None,content,diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex c199314d48..c1bcfd5000 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -2180,6 +2180,7 @@ async fn a_document_session_preserves_its_origin_and_inherits_live_document_acceactor: OWNER.to_owned().try_into().unwrap(),triggered_by: None,input: PostMessage {+ id: None,attribution: Default::default(),notification_policy: Default::default(),content: "@agent investigate".into(),diff --git a/crates/bots/src/inbound/channel_webhook_router.rs b/crates/bots/src/inbound/channel_webhook_router.rsindex ec08348d07..54f28e76ee 100644--- a/crates/bots/src/inbound/channel_webhook_router.rs+++ b/crates/bots/src/inbound/channel_webhook_router.rs@@ -284,6 +284,7 @@ where.post(access,PostMessage {+ id: None,// External webhook bot posting on its own; no triggering user.attribution: MessageAttribution::Unprompted,notification_policy: Default::default(),@@ -392,6 +393,7 @@ impl IntoResponse for ChannelBotWebhookHandlerErr {Self::BadRequest(_)| Self::Bot(BotError::BadRequest(_))| Self::Message(MessageError::Invalid(_)) => StatusCode::BAD_REQUEST,+ Self::Message(MessageError::Conflict) => StatusCode::CONFLICT,Self::Bot(BotError::Unauthorized) => StatusCode::UNAUTHORIZED,Self::Message(MessageError::Forbidden) => StatusCode::FORBIDDEN,Self::Bot(BotError::NotFound(_)) | Self::Message(MessageError::NotFound) => {diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rsindex d569acf77e..c6a500a9ae 100644--- a/crates/channel_bots/src/domain/service.rs+++ b/crates/channel_bots/src/domain/service.rs@@ -450,6 +450,7 @@ where.post(access,PostMessage {+ id: None,attribution: MessageAttribution::ActingUser,notification_policy: PostMessageNotificationPolicy::Silent,content: THINKING_MESSAGE.to_string(),diff --git a/crates/channels/src/domain/message_commands.rs b/crates/channels/src/domain/message_commands.rsindex 69927fe184..019c30bd26 100644--- a/crates/channels/src/domain/message_commands.rs+++ b/crates/channels/src/domain/message_commands.rs@@ -58,6 +58,7 @@ impl ChannelMessageCommands for ChannelMessageAdapter {.post(access,PostMessage {+ id: None,attribution: if req.triggered_by.is_some() {MessageAttribution::ActingUser} else {@@ -198,6 +199,9 @@ fn shared_message_error(error: MessageError) -> ChannelMutationErr {MessageError::NotFound => ChannelMutationErr::NotFound("message not found".into()),MessageError::Forbidden => ChannelMutationErr::Unauthorized("message access denied".into()),MessageError::Invalid(message) => ChannelMutationErr::BadRequest(message.into()),+ MessageError::Conflict => {+ ChannelMutationErr::BadRequest("message id already exists".into())+ }MessageError::Repository(report) => {ChannelMutationErr::Repo(anyhow::anyhow!(report.to_string()))}diff --git a/crates/channels/src/inbound/toolset/send_channel_message.rs b/crates/channels/src/inbound/toolset/send_channel_message.rsindex 3de6d99423..b24132935a 100644--- a/crates/channels/src/inbound/toolset/send_channel_message.rs+++ b/crates/channels/src/inbound/toolset/send_channel_message.rs@@ -72,6 +72,7 @@ where.post(access,PostMessage {+ id: None,attribution: MessageAttribution::ActingUser,notification_policy: PostMessageNotificationPolicy::Default,content: self.content.clone(),diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex 2461085c62..92945a75a6 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -266,6 +266,7 @@ fn comment_error(description: &'static str) -> impl FnOnce(MessageError) -> Tool"you need comment access to the document to comment on it".to_string()}MessageError::Invalid(reason) => format!("{description}: {reason}"),+ MessageError::Conflict => format!("{description}: message id already exists"),MessageError::Repository(_) => description.to_string(),};ToolCallError {diff --git a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs b/crates/documents/src/inbound/toolset/reply_to_document_comment.rsindex 4e7809777c..560a60a16a 100644--- a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs+++ b/crates/documents/src/inbound/toolset/reply_to_document_comment.rs@@ -74,6 +74,7 @@ where.post(access,PostMessage {+ id: None,attribution: MessageAttribution::ActingUser,notification_policy: PostMessageNotificationPolicy::Default,content: self.content.clone(),diff --git a/crates/messages/src/domain/models.rs b/crates/messages/src/domain/models.rsindex 3838c8d80c..bf01193792 100644--- a/crates/messages/src/domain/models.rs+++ b/crates/messages/src/domain/models.rs@@ -433,6 +433,10 @@ pub struct PostMessage {#[serde(skip)]#[cfg_attr(feature = "schema", schema(ignore))]pub notification_policy: PostMessageNotificationPolicy,+ /// Client-minted UUIDv7 for the new message, so an optimistic message+ /// already carries its final id; the server mints one when absent.+ #[serde(default)]+ pub id: Option<Uuid>,/// Macro Markdown body.pub content: String,/// Root to reply to, if this is a reply.diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rsindex 1a67566beb..54de02a8b4 100644--- a/crates/messages/src/domain/ports.rs+++ b/crates/messages/src/domain/ports.rs@@ -16,6 +16,9 @@ pub enum MessageError {/// Invalid thread relation or anchor.#[error("{0}")]Invalid(&'static str),+ /// A client-supplied message id is already taken.+ #[error("message id already exists")]+ Conflict,/// Persistence or delivery failed.#[error("message operation failed: {0}")]Repository(rootcause::Report),diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rsindex 7825283da0..e304ccb4c3 100644--- a/crates/messages/src/domain/service.rs+++ b/crates/messages/src/domain/service.rs@@ -751,5 +751,32 @@ fn validate_post(parent: &MessageParent, input: &PostMessage) -> Result<(), Mess{return Err(MessageError::Invalid("invalid PDF comment geometry"));}+ if let Some(id) = input.id {+ validate_client_id(id, chrono::Utc::now())?;+ }+ Ok(())+}++/// How far a client-minted id's timestamp may drift from the server clock.+/// Ordering uses the server's `created_at`, so this only needs to catch forged+/// ids; it is wide so a device with a wrong clock can still post.+const CLIENT_ID_MAX_SKEW: chrono::TimeDelta = chrono::TimeDelta::days(1);++/// A client-minted id must be a UUIDv7 stamped near now, so its embedded time+/// stays roughly the message's creation time.+fn validate_client_id(id: Uuid, now: chrono::DateTime<chrono::Utc>) -> Result<(), MessageError> {+ let minted_at = id+ .get_timestamp()+ .filter(|_| id.get_version_num() == 7)+ .and_then(|timestamp| {+ let (seconds, nanos) = timestamp.to_unix();+ chrono::DateTime::from_timestamp(i64::try_from(seconds).ok()?, nanos)+ })+ .ok_or(MessageError::Invalid("message id must be a UUIDv7"))?;+ if (now - minted_at).abs() > CLIENT_ID_MAX_SKEW {+ return Err(MessageError::Invalid(+ "message id timestamp is too far from the server clock",+ ));+ }Ok(())}diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rsindex 0f6f64dc0b..2cc4579374 100644--- a/crates/messages/src/domain/service/test.rs+++ b/crates/messages/src/domain/service/test.rs@@ -530,6 +530,7 @@ fn view_access_cannot_mint_a_write_receipt() {#[test]fn only_root_document_messages_can_have_anchors() {let mut input = PostMessage {+ id: None,attribution: Default::default(),notification_policy: Default::default(),content: "test".into(),@@ -559,6 +560,7 @@ async fn inaccessible_references_are_rejected_before_persistence() {height: None,};let input = PostMessage {+ id: None,attribution: Default::default(),notification_policy: Default::default(),content: "Look here".into(),@@ -630,6 +632,7 @@ async fn user_mentions_do_not_require_or_grant_parent_sharing() {fn post_input() -> PostMessage {PostMessage {+ id: None,attribution: Default::default(),notification_policy: Default::default(),content: "@agent please help".into(),@@ -1335,3 +1338,30 @@ async fn display_only_mention_kinds_are_stored_without_authorization() {vec![(EntityType::AgentSession, Uuid::from_u128(10).to_string())]);}++#[test]+fn client_ids_must_be_recent_uuid_v7() {+ let now = Utc::now();+ let v7_at = |at: chrono::DateTime<Utc>| {+ Uuid::new_v7(uuid::Timestamp::from_unix(+ uuid::NoContext,+ at.timestamp() as u64,+ at.timestamp_subsec_nanos(),+ ))+ };+ assert!(validate_client_id(v7_at(now), now).is_ok());+ assert!(validate_client_id(v7_at(now - chrono::TimeDelta::hours(23)), now).is_ok());+ assert!(validate_client_id(v7_at(now + chrono::TimeDelta::hours(23)), now).is_ok());+ assert!(matches!(+ validate_client_id(v7_at(now - chrono::TimeDelta::hours(25)), now),+ Err(MessageError::Invalid(_))+ ));+ assert!(matches!(+ validate_client_id(v7_at(now + chrono::TimeDelta::days(30)), now),+ Err(MessageError::Invalid(_))+ ));+ assert!(matches!(+ validate_client_id(Uuid::new_v4(), now),+ Err(MessageError::Invalid(_))+ ));+}diff --git a/crates/messages/src/inbound/axum_router.rs b/crates/messages/src/inbound/axum_router.rsindex 5502a8ec47..ce92cadaf5 100644--- a/crates/messages/src/inbound/axum_router.rs+++ b/crates/messages/src/inbound/axum_router.rs@@ -135,6 +135,7 @@ impl IntoResponse for MessageHttpError {MessageError::NotFound => (StatusCode::NOT_FOUND, "message or parent not found"),MessageError::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),MessageError::Invalid(message) => (StatusCode::BAD_REQUEST, message),+ MessageError::Conflict => (StatusCode::CONFLICT, "message id already exists"),MessageError::Repository(error) => {tracing::error!(error=?error, "message request failed");(diff --git a/crates/messages/src/outbound/pg_message_repo.rs b/crates/messages/src/outbound/pg_message_repo.rsindex b011247a93..fc23b6ff4f 100644--- a/crates/messages/src/outbound/pg_message_repo.rs+++ b/crates/messages/src/outbound/pg_message_repo.rs@@ -36,6 +36,9 @@ fn database_error(error: sqlx::Error) -> MessageError {if let sqlx::Error::Database(ref error) = error {match error.code().as_deref() {Some("23503") => return MessageError::NotFound,+ Some("23505") if error.constraint() == Some("comms_messages_pkey") => {+ return MessageError::Conflict;+ }Some("23505") => {return MessageError::Invalid("a live discussion already uses this anchor");}@@ -551,7 +554,10 @@ impl MessageRepository for PgMessageRepository {}async fn create(&self, command: CreateMessage) -> Result<Message, MessageError> {- let id = macro_uuid::generate_uuid_v7();+ let id = command+ .input+ .id+ .unwrap_or_else(macro_uuid::generate_uuid_v7);let mut tx = self.pool.begin().await.map_err(database_error)?;if let Some(root_id) = command.input.thread_id {// Replies attach to a live root of the same parent. The composite FKdiff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rsindex e851225264..9bbe405eea 100644--- a/crates/messages/src/outbound/pg_message_repo/test.rs+++ b/crates/messages/src/outbound/pg_message_repo/test.rs@@ -33,6 +33,7 @@ fn command(document: &str, root: Option<Uuid>, content: &str) -> CreateMessage {actor: USER.to_owned().try_into().unwrap(),triggered_by: None,input: PostMessage {+ id: None,attribution: Default::default(),notification_policy: Default::default(),content: content.into(),@@ -1125,3 +1126,26 @@ async fn legacy_ids_resolve_through_the_import_mapping_tables(pool: PgPool) {Some("23503"));}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn client_supplied_ids_are_kept_and_never_reused(pool: PgPool) {+ setup(&pool).await;+ let repo = PgMessageRepository::new(pool);+ let id = macro_uuid::generate_uuid_v7();+ let mut first = command("message-doc-a", None, "first");+ first.input.id = Some(id);+ assert_eq!(repo.create(first).await.unwrap().id, id);++ // A reused id conflicts even on another parent, and never overwrites.+ let mut second = command("message-doc-b", None, "second");+ second.input.id = Some(id);+ assert!(matches!(+ repo.create(second).await,+ Err(MessageError::Conflict)+ ));+ let parent = MessageParent::parse("document", "message-doc-a").unwrap();+ assert_eq!(+ repo.get(&parent, id).await.unwrap().unwrap().content,+ "first"+ );+}diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex bfd0f00755..934e136e72 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -7570,6 +7570,11 @@ export type PostMessage = {* Macro Markdown body.*/content: string;+ /**+ * Client-minted UUIDv7 for the new message, so an optimistic message+ * already carries its final id; the server mints one when absent.+ */+ id?: string | null;/*** Mentions tracked by the editor.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 45712139cf..bb8918277b 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -26668,6 +26668,11 @@"type": "string","description": "Macro Markdown body."},+ "id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Client-minted UUIDv7 for the new message, so an optimistic message\nalready carries its final id; the server mints one when absent."+ },"mentions": {"type": "array","items": {diff --git a/services/authentication_service/src/service/user/support_channel_welcome.rs b/services/authentication_service/src/service/user/support_channel_welcome.rsindex d69c1eeddb..d8c593e94e 100644--- a/services/authentication_service/src/service/user/support_channel_welcome.rs+++ b/services/authentication_service/src/service/user/support_channel_welcome.rs@@ -112,6 +112,7 @@ If you have any feedback or find any bugs let us know here.",Sender::new_from_user(julia),channel_id,PostMessage {+ id: None,attribution: MessageAttribution::Unprompted,notification_policy: PostMessageNotificationPolicy::MentionsOnly,content: welcome,