Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve accepted sends across community navigation (#902)

Generc4e51095a1f4
diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
new file mode 100644
index 000000000..9c1130772
--- /dev/null
+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
@@ -0,0 +1,69 @@
+import React, { type PropsWithChildren } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render, screen, waitFor } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { DmView } from "./dm-view"
+
+const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), failed: true }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api, toastApiError: vi.fn() }))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "mobile" }))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "u_me", name: "Me", avatar: "M" }) }))
+vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => ({ dms: ["dm_1", "dm_2"].map(id => ({ id, userId: "peer", name: "Peer", avatar: "P" })), isLoading: false, isFetching: false }) }))
+vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], blocked: [] }) }))
+vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], isLoading: false, isPending: false, isError: false, latestSeq: 0 }) }))
+vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => ({ canRead: true, status: "readable" }) }))
+vi.mock("@/hooks/community/use-dm-read-state", () => ({ useDmReadStateSnapshot: () => ({ snapshot: { lastReadMessageId: null, lastReadSeq: 0 }, isFetching: false }) }))
+vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))
+vi.mock("@/hooks/community/use-channel-ref-directory", () => ({ useChannelRefDirectory: () => ({ directory: [], isResolved: true }) }))
+vi.mock("@/hooks/community/use-native-system-notifications", () => ({ useNativeSystemNotificationConversationDismissal: vi.fn() }))
+vi.mock("./use-dm-seq-context", () => ({ useDmSeqContext: vi.fn() }))
+vi.mock("@/lib/community/conversation-navigation-proof", async importOriginal => ({ ...await importOriginal<typeof import("@/lib/community/conversation-navigation-proof")>(), useConversationNavigationGate: () => ({ allowed: true, failed: false }) }))
+vi.mock("@/lib/community/last-community-route", () => ({ commitCommunityChannelRoute: vi.fn() }))
+vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings: () => ({ channel: {} }) }))
+vi.mock("@/hooks/community/use-community-ws", () => ({ communityWsSubscribe: vi.fn(), communityWsUnsubscribe: vi.fn(), communityWsSendTyping: vi.fn(), communityWsEndTyping: vi.fn() }))
+vi.mock("@/lib/community-onboarding", () => ({ readCommunityOnboardingState: () => ({ status: "active", stage: "dm", dmId: "dm_1" }), advanceCommunityOnboarding: mocks.advance }))
+vi.mock("@/hooks/community/mutations", async importOriginal => ({ ...await importOriginal<typeof import("@/hooks/community/mutations")>(), useAddReactionApi: () => vi.fn(), useToggleReactionApi: () => vi.fn(), useToggleMark: () => vi.fn(), useSetChannelNotif: () => ({ mutate: vi.fn() }) }))
+vi.mock("./dm-header", () => ({ DmHeader: () => null }))
+vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))
+vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))
+vi.mock("@/components/community/messages/conversation-footer-shell", () => ({ ConversationFooterSlotProvider: ({ children }: PropsWithChildren) => children, ConversationFooterShell: ({ children }: PropsWithChildren) => children }))
+vi.mock("@/components/community/messages/composer", () => ({ ComposerSkeleton: () => null, Composer: ({ onAcceptSend }: { onAcceptSend: (text: string) => boolean }) => React.createElement("button", { onClick: () => onAcceptSend("hello") }, "Send") }))
+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: ({ onRetry }: { onRetry: (id: string) => void }) => React.createElement("button", { onClick: () => onRetry("failed") }, "Retry") }))
+
+beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.failed = true })
+
+describe("real DmView accepted send UI lifecycle", () => {
+ it.each(["send", "retry"] as const)("continues %s after target view retires without advancing old onboarding", async action => {
+ const owner = await createCommunityQueryOwner("u_me")
+ owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })
+ owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })
+ let finish!: (value: unknown) => void
+ mocks.api.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })
+ await act(async () => screen.getByRole("button", { name: action === "send" ? "Send" : "Retry" }).click())
+ await waitFor(() => expect(mocks.api).toHaveBeenCalledOnce())
+ const [, options] = mocks.api.mock.calls[0]
+ const body = JSON.parse(options.body)
+ expect(mocks.api.mock.calls[0][0]).toBe("/api/community/channels/dm_1/messages")
+ view.rerender(React.createElement(DmView, { dmId: "dm_2" }))
+ expect(options.signal.aborted).toBe(false)
+ await act(async () => finish({ message: { id: "confirmed", seq: 9, type: "chat", content: body.content, authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T00:00:00Z", embeds: [] } }))
+ await waitFor(() => expect(owner.registry.collections.messages.get("confirmed")?.channelId).toBe("dm_1"))
+ expect(mocks.advance).not.toHaveBeenCalled()
+ expect(mocks.api).toHaveBeenCalledOnce()
+ view.unmount()
+ })
+ it.each(["send", "retry"] as const)("allows a current %s callback after real confirmation", async action => {
+ const owner = await createCommunityQueryOwner("u_me")
+ owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })
+ owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })
+ mocks.api.mockResolvedValueOnce({ message: { id: "confirmed", seq: 9, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T00:00:00Z", embeds: [] } })
+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })
+ await act(async () => screen.getByRole("button", { name: action === "send" ? "Send" : "Retry" }).click())
+ await waitFor(() => expect(mocks.advance).toHaveBeenCalledOnce())
+ view.unmount()
+ })
+})
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 9d2076036..2ed8729f0 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -1,5 +1,6 @@
"use client"
+import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useAtom, useCreateAtom } from "@tanstack/react-store"
import { useCommunityRuntime } from "@/stores/community/runtime"
@@ -87,6 +88,7 @@ function resolveDmLoadingOwnership({
export function DmView({ dmId }: { dmId: string }) {
const communityRuntime = useCommunityRuntime()
+ const sendView = useCommunityViewSource(`dm-send:${dmId}`)
const bp = useBreakpoint()
const currentUser = useCurrentUser()
const queryClient = useQueryClient()
@@ -365,7 +367,9 @@ export function DmView({ dmId }: { dmId: string }) {
onRetry: (id: string) => {
const m = messages.find((x) => x.id === id)
if (!m?.clientNonce) return
- void retryDmMessage(dmId, m.clientNonce).then((result) => {
+ const assertActive = sendView.capture()
+ void retryDmMessage(dmId, m.clientNonce, assertActive).then((result) => {
+ try { assertActive() } catch { return }
if (result.ok) advanceOnboardingAfterSend()
})
},
@@ -383,12 +387,14 @@ export function DmView({ dmId }: { dmId: string }) {
onPreviewAttachment: (attachment: FileAttachment) => {
uiHandlers.previewAttachment?.(attachment)
},
- }), [toggleReaction, dmId, currentUser.id, addReaction, messages, setReplyTo, toggleMark, retryDmMessage, advanceOnboardingAfterSend, communityRuntime.messageStream.actions, uiHandlers])
+ }), [toggleReaction, dmId, currentUser.id, addReaction, messages, setReplyTo, toggleMark, retryDmMessage, sendView, advanceOnboardingAfterSend, communityRuntime.messageStream.actions, uiHandlers])
// DM endpoint ignores mentionType. Replies are supported — the backend
// persists replyToId for DMs too.
const acceptDmSend = (markdown: string, attachments?: SendAttachment[]): boolean => {
+ const assertActive = sendView.capture()
const receipt = acceptDmMessage({
+ assertActive,
dmId,
content: markdown,
replyTo: replyTo ?? undefined,
@@ -401,6 +407,7 @@ export function DmView({ dmId }: { dmId: string }) {
})
if (!receipt.accepted) return false
void receipt.committed.then((result) => {
+ try { assertActive() } catch { return }
if (result.ok) advanceOnboardingAfterSend()
})
communityWsEndTyping(communityRuntime, { channelId: dmId })
diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
index db9151f80..1098762f5 100644
--- a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
+++ b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
@@ -216,7 +216,7 @@ describe("Composer committed send lifecycle", () => {
const upload = vi.fn()
const post = vi.fn()
const clearReply = vi.fn()
- const runner = vi.fn((nonce: string) => runAcceptedMessageIntent({
+ const runner = vi.fn((nonce: string) => runAcceptedMessageIntent({ assertCommand: () => {},
runtime, messageScope, nonce, uploadFileAsync: upload, sendMessageAsync: post,
channelId: messageScope.id, serverId: messageScope.serverId, viewer,
}))
diff --git a/src/web/src/components/community/messages/message-channel-controller-send.test.ts b/src/web/src/components/community/messages/message-channel-controller-send.test.ts
index ab6cc645f..e82ad593f 100644
--- a/src/web/src/components/community/messages/message-channel-controller-send.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-send.test.ts
@@ -225,7 +225,7 @@ describe("message channel send helpers", () => {
},
mentionType: "user",
})
- await runAcceptedMessageIntent({
+ await runAcceptedMessageIntent({ assertCommand: () => {},
runtime,
messageScope: scope, nonce: "nonce_1", uploadFileAsync, sendMessageAsync,
channelId: "channel_1", serverId: "server_1", viewer,
@@ -247,7 +247,7 @@ describe("message channel send helpers", () => {
id: "ok", filename: "a.png", contentType: "image/png", size: 3,
}).mockRejectedValueOnce(new Error("failed"))
sendMessageAsync.mockClear()
- await runAcceptedMessageIntent({
+ await runAcceptedMessageIntent({ assertCommand: () => {},
runtime,
messageScope: scope, nonce: "nonce_2", uploadFileAsync, sendMessageAsync,
channelId: "channel_1", serverId: "server_1", viewer,
@@ -305,7 +305,7 @@ describe("message channel send helpers", () => {
mocks.dispatch.mockImplementation(() => { order.push("dispatch") })
const sendMessageAsync = vi.fn(async () => { order.push("send") })
- await runAcceptedMessageIntent({
+ await runAcceptedMessageIntent({ assertCommand: () => {},
runtime,
messageScope: scope,
nonce: "nonce_upload",
@@ -320,6 +320,7 @@ describe("message channel send helpers", () => {
expect(uploadFileAsync).toHaveBeenCalledTimes(2)
expect(uploadFileAsync).toHaveBeenNthCalledWith(1, {
assertActive: undefined,
+ assertCommand: expect.any(Function),
target: { channelId: "channel_1" },
file: uploads[0].file,
thumbnailBlob: uploads[0].thumbnailBlob,
@@ -328,6 +329,7 @@ describe("message channel send helpers", () => {
})
expect(uploadFileAsync).toHaveBeenNthCalledWith(2, {
assertActive: undefined,
+ assertCommand: expect.any(Function),
target: { channelId: "channel_1" },
file: uploads[1].file,
thumbnailBlob: undefined,
@@ -344,6 +346,7 @@ describe("message channel send helpers", () => {
})
expect(sendMessageAsync).toHaveBeenCalledWith({
assertActive: undefined,
+ assertCommand: expect.any(Function),
serverId: "server_1",
channelId: "channel_1",
forumParentChannelId: "forum_1",
@@ -363,7 +366,7 @@ describe("message channel send helpers", () => {
const uploadFileAsync = vi.fn()
const sendMessageAsync = vi.fn()
mocks.getRetryPayload.mockReturnValueOnce(undefined)
- await runAcceptedMessageIntent({
+ await runAcceptedMessageIntent({ assertCommand: () => {},
runtime,
messageScope: scope, nonce: "missing", uploadFileAsync, sendMessageAsync,
channelId: "channel_1", serverId: "server_1", viewer,
@@ -379,7 +382,7 @@ describe("message channel send helpers", () => {
message: { content: "keep optimistic" },
})
sendMessageAsync.mockRejectedValueOnce(failure)
- await expect(runAcceptedMessageIntent({
+ await expect(runAcceptedMessageIntent({ assertCommand: () => {},
runtime,
messageScope: scope, nonce: "nonce_failed", uploadFileAsync, sendMessageAsync,
channelId: "channel_1", serverId: "server_1", viewer,
@@ -404,6 +407,7 @@ describe("message channel send helpers", () => {
})
const sendMessageAsync = vi.fn(async () => ({}))
const args = {
+ assertCommand: () => {},
runtime,
messageScope: scope,
nonce: "nonce_retry",
diff --git a/src/web/src/components/community/messages/message-channel-controller-send.ts b/src/web/src/components/community/messages/message-channel-controller-send.ts
index fe3eec6d2..4764d688e 100644
--- a/src/web/src/components/community/messages/message-channel-controller-send.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-send.ts
@@ -16,6 +16,7 @@ type SendMessage = (input: SendMessageArgs & { nonce: string }) => Promise<unkno
export async function runAcceptedMessageIntent({
runtime,
assertActive,
+ assertCommand,
messageScope,
nonce,
uploadFileAsync,
@@ -27,6 +28,7 @@ export async function runAcceptedMessageIntent({
}: {
runtime: CommunityRuntime
assertActive?: (() => void) & { signal: AbortSignal }
+ assertCommand: () => void
messageScope: ChannelMessageScope
nonce: string
uploadFileAsync: UploadFile
@@ -38,11 +40,12 @@ export async function runAcceptedMessageIntent({
}) {
const generation = runtime.lifecycle.get().generation
const assertOwner = () => {
+ assertCommand()
const state = runtime.lifecycle.get()
if (!state.active || state.generation !== generation) throw new DOMException("Retired send owner", "AbortError")
}
- const assert = () => { assertOwner(); assertActive?.() }
- const prepared = await prepareMessageIntent({ runtime, scope: messageScope, nonce, assertOwner, assertActive, uploadFileAsync, target: { channelId } })
+ const assert = assertOwner
+ const prepared = await prepareMessageIntent({ runtime, scope: messageScope, nonce, assertOwner, assertActive, assertCommand, uploadFileAsync, target: { channelId } })
if (!prepared.ok) return
const { payload, attachments: uploadedAttachments } = prepared
@@ -55,6 +58,7 @@ export async function runAcceptedMessageIntent({
try {
await sendMessageAsync({
assertActive,
+ assertCommand,
serverId,
channelId,
forumParentChannelId,
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index 064588be4..da421f142 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -303,6 +303,7 @@ describe("useMessageChannelController", () => {
await act(async () => input.runAcceptedIntent("nonce_1"))
expect(mocks.run).toHaveBeenCalledWith({
assertActive: expect.any(Function),
+ assertCommand: expect.any(Function),
runtime: fixtureOwner.registry.runtime,
messageScope: { kind: "channel", id: "channel_1", serverId: "server_1" },
nonce: "nonce_1",
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index a5860a7e8..7767791fc 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -5,7 +5,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"
import { useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
-import { captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"
+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { useCommunityRuntime } from "@/stores/community/runtime"
@@ -240,11 +240,21 @@ export function useMessageChannelController({
[channelId, serverId],
)
- const runAcceptedIntent = useCallback(async (nonce: string) => {
+ const captureSendCommand = useCallback(() => {
const assertActive = source.capture()
+ assertActive()
+ const token = captureCommunityLiveSnapshotToken(profileQueryClient, channelId)
+ const assertCommand = () => assertCommunityLiveSnapshotTokenCurrent(profileQueryClient, token, undefined)
+ assertCommand()
+ return { assertActive, assertCommand }
+ }, [source, profileQueryClient, channelId])
+
+ const runAcceptedIntent = useCallback(async (nonce: string, command = captureSendCommand()) => {
+ const { assertActive, assertCommand } = command
await runAcceptedMessageIntent({
runtime: communityRuntime,
assertActive,
+ assertCommand,
messageScope,
nonce,
uploadFileAsync,
@@ -254,7 +264,7 @@ export function useMessageChannelController({
serverId,
viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },
})
- }, [source, communityRuntime, messageScope, uploadFileAsync, sendMessageAsync, channelId, forumParentChannelId, serverId, viewer.id, viewer.name, viewer.avatar])
+ }, [captureSendCommand, communityRuntime, messageScope, uploadFileAsync, sendMessageAsync, channelId, forumParentChannelId, serverId, viewer.id, viewer.name, viewer.avatar])
const messageActions = useMemo(() => createMessageActions({
runtime: communityRuntime,
@@ -280,7 +290,9 @@ export function useMessageChannelController({
markdown: string,
attachments?: SendAttachment[],
mentionType?: MentionType,
- ): boolean => acceptChannelMessage({
+ ): boolean => {
+ const command = captureSendCommand()
+ return acceptChannelMessage({
runtime: communityRuntime,
markdown,
attachments,
@@ -288,10 +300,11 @@ export function useMessageChannelController({
messageScope,
viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },
replyTo,
- runAcceptedIntent,
+ runAcceptedIntent: (nonce) => runAcceptedIntent(nonce, command),
channelId,
clearReply: () => setReplyTo(null),
- }), [channelId, communityRuntime, messageScope, replyTo, runAcceptedIntent, setReplyTo, viewer.avatar, viewer.id, viewer.name])
+ })
+ }, [captureSendCommand, channelId, communityRuntime, messageScope, replyTo, runAcceptedIntent, setReplyTo, viewer.avatar, viewer.id, viewer.name])
return useMemo<MessageChannelControllerValue>(() => ({
feed,
diff --git a/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
new file mode 100644
index 000000000..3a91b2c6d
--- /dev/null
+++ b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
@@ -0,0 +1,97 @@
+import { createElement, type PropsWithChildren } from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner, canonicalMessageReader, getMessageStreamState } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { useDmMessageSender, type DmSendReceipt } from "./use-dm-message-sender"
+import { useCommunityViewSource } from "./use-community-view-source"
+import { useSendMessage } from "./mutations/messages"
+import { useUploadFile } from "./mutations/uploads"
+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
+import { runAcceptedMessageIntent } from "@/components/community/messages/message-channel-controller-send"
+import { Message } from "@/components/community/messages/message"
+import { materializeMessageStream } from "@/lib/community/message-stream"
+
+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
+const author = { id: "u_me", name: "Me", avatar: "M" }
+const posted = { message: { id: "confirmed", seq: 12, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } }
+afterEach(() => vi.unstubAllGlobals())
+
+describe("accepted IO survives real view retirement", () => {
+ it.each(["channel", "dm"] as const)("%s: original target completes through all four leave phases", async kind => {
+ for (const phase of ["preparation", "upload", "post", "decode"] as const) {
+ const owner = await createCommunityQueryOwner("u_me")
+ owner.runtime.ws.actions.rememberChannelAccess(kind === "dm" ? null : "server", "scope", kind === "dm" ? null : "parent")
+ const scope = kind === "dm" ? { kind, id: "scope" } : { kind, id: "scope", serverId: "server" }
+ const gate = deferred<Response>(), decode = deferred<void>()
+ const response = new Response(JSON.stringify(posted), { status: 201 })
+ const json = vi.spyOn(response, "json").mockImplementation(async () => { await decode.promise; return posted })
+ const fetchMock = vi.fn(async (path: string) => {
+ if (path.endsWith("/attachments")) return gate.promise
+ if (phase === "post") return gate.promise
+ return response
+ })
+ vi.stubGlobal("fetch", fetchMock)
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
+ const view = renderHook(() => ({ dm: useDmMessageSender(), source: useCommunityViewSource("channel-send"), send: useSendMessage(), upload: useUploadFile() }), { wrapper })
+ let committed!: Promise<unknown>
+ act(() => {
+ const attachments = phase === "upload" ? [{ file: new File(["x"], "x.txt"), previewObjectUrl: "blob:x" }] : undefined
+ if (kind === "dm") {
+ const receipt: DmSendReceipt = view.result.current.dm.accept({ dmId: scope.id, author, content: "hello", nonce: "nonce", attachments })
+ if (!receipt.accepted) throw new Error("Intent rejected")
+ committed = receipt.committed
+ } else {
+ const assertActive = view.result.current.source.capture(), token = captureCommunityLiveSnapshotToken(owner.client, scope.id)
+ const assertCommand = () => assertCommunityLiveSnapshotTokenCurrent(owner.client, token, undefined)
+ assertActive(); assertCommand()
+ owner.runtime.messageStream.actions.accept(scope, { nonce: "nonce", tempId: "temp", message: { type: "chat", content: "hello", authorId: author.id }, localUploads: attachments?.map(a => ({ ...a })) ?? [] })
+ committed = runAcceptedMessageIntent({ runtime: owner.runtime, messageScope: { kind: "channel", id: "scope", serverId: "server" }, nonce: "nonce", assertActive, assertCommand, uploadFileAsync: view.result.current.upload.mutateAsync, sendMessageAsync: view.result.current.send.mutateAsync, channelId: "scope", serverId: "server", viewer: author })
+ }
+ if (phase === "preparation") view.unmount()
+ })
+ if (phase === "decode") await waitFor(() => expect(json).toHaveBeenCalledOnce())
+ else if (phase !== "preparation") await waitFor(() => expect(fetchMock).toHaveBeenCalledOnce())
+ if (phase !== "preparation") view.unmount()
+ owner.runtime.ws.actions.beginChannelMembershipChange("other-server", "other-channel")
+ await act(async () => {
+ gate.resolve(phase === "upload" ? new Response(JSON.stringify({ id: "attachment", filename: "x.txt", contentType: "text/plain", size: 1 }), { status: 201 }) : new Response(JSON.stringify(posted), { status: 201 }))
+ decode.resolve()
+ await committed
+ })
+ expect(owner.registry.collections.messages.get("confirmed")).toMatchObject({ channelId: "scope", authorId: "u_me", clientNonce: "nonce" })
+ for (const [, options] of fetchMock.mock.calls as unknown as [string, RequestInit][]) expect(options.signal?.aborted).toBe(false)
+ const base = [{ id: "confirmed", seq: 12, clientNonce: "nonce", authorId: "u_me", type: "chat" as const, content: "hello" }]
+ owner.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: base })
+ const rows = materializeMessageStream(base, getMessageStreamState(owner.client, scope), canonicalMessageReader(owner.client))
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({ id: "confirmed" })
+ expect(rows[0].failed).not.toBe(true)
+ const returned = render(createElement(Message, { m: { ...rows[0], grouped: false }, onOpenThread: () => {}, onCopy: () => {} }), { wrapper })
+ expect(returned.container.textContent).not.toContain("Message failed to send. Click to retry.")
+ returned.unmount()
+ await owner.registry.cleanup(); owner.client.clear()
+ }
+ })
+ it.each(["owner", "permission"] as const)("DM upload cannot POST after original %s retires", async retirement => {
+ const owner = await createCommunityQueryOwner("u_me"), upload = deferred<Response>()
+ owner.runtime.ws.actions.rememberChannelAccess(null, "scope", null)
+ const fetchMock = vi.fn(() => upload.promise)
+ vi.stubGlobal("fetch", fetchMock)
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
+ const view = renderHook(() => useDmMessageSender(), { wrapper })
+ let receipt!: DmSendReceipt
+ act(() => { receipt = view.result.current.accept({ dmId: "scope", author, content: "hello", attachments: [{ file: new File(["x"], "x.txt"), previewObjectUrl: "blob:x" }] }) })
+ if (!receipt.accepted) throw new Error("Intent rejected")
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledOnce())
+ act(() => {
+ if (retirement === "owner") owner.runtime.lifecycle.setState(state => ({ ...state, active: false, generation: state.generation + 1 }))
+ else owner.runtime.ws.actions.revokeChannelAccess(null, "scope")
+ })
+ await act(async () => { upload.resolve(new Response(JSON.stringify({ id: "attachment", filename: "x.txt", contentType: "text/plain", size: 1 }), { status: 201 })); if (receipt.accepted) await receipt.committed })
+ expect(await receipt.committed).toMatchObject({ ok: false, error: expect.any(Error) })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(owner.registry.collections.messages.get("confirmed")).toBeUndefined()
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.ts
index 2c603c644..0a724fecb 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -1,4 +1,4 @@
-import { canonicalMessageReader } from "@/test/community-query-owner"
+import { getMessageStreamState, canonicalMessageReader } from "@/test/community-query-owner"
import { materializeMessageStream } from "@/lib/community/message-stream"
import { createElement, type PropsWithChildren } from "react"
import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
@@ -547,7 +547,7 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
const mod = await loadMod()
const mutation = mountHook(() => mod.useSendMessage())
const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")
- await act(async () => { await expect(runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "runner_failure",
+ await act(async () => { await expect(runAcceptedMessageIntent({ assertCommand: () => {}, runtime, messageScope: scope, nonce: "runner_failure",
uploadFileAsync: vi.fn(), sendMessageAsync: mutation.mutateAsync,
channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" },
})).resolves.toBeUndefined() })
@@ -575,7 +575,8 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
)
})
- it("fails the upload intent when its view retires after upload succeeds, before native POST", async () => {
+ it("continues the upload intent when its view retires after upload succeeds, before native POST", async () => {
+ apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }, runtime = canonicalRegistry.runtime
const file = new File(["x"], "x.txt", { type: "text/plain" })
runtime.messageStream.actions.accept(scope, { nonce: "upload-view", tempId: "temp-upload-view", message: { type: "chat", content: "file", authorId: "u_me" }, localUploads: [{ file, previewObjectUrl: "blob:view" }] })
@@ -585,20 +586,21 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
const assertActive = Object.assign(() => { if (!current) throw new DOMException("Retired view", "AbortError") }, { signal: new AbortController().signal })
const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")
await act(async () => {
- const pending = runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "upload-view", assertActive, uploadFileAsync, sendMessageAsync: mutation.mutateAsync,
+ const pending = runAcceptedMessageIntent({ assertCommand: () => {}, runtime, messageScope: scope, nonce: "upload-view", assertActive, uploadFileAsync, sendMessageAsync: mutation.mutateAsync,
channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" } })
current = false
finish({ id: "uploaded", filename: "x.txt", contentType: "text/plain", size: 1 })
await pending
})
expect(uploadFileAsync).toHaveBeenCalledOnce()
- expect(apiFetchMock).not.toHaveBeenCalled()
- expect(dispatch.mock.calls).toEqual([[scope, { type: "uploadFailed", nonce: "upload-view" }]])
- expect(runtime.messageStream.actions.getRetryPayload(scope, "upload-view")?.message.failed).toBe(true)
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(dispatch.mock.calls.some(([, event]) => event.type === "uploadFailed")).toBe(false)
+ expect(dispatch.mock.calls.some(([, event]) => event.type === "postAck")).toBe(true)
expect(toastMock).not.toHaveBeenCalled()
})
- it("fails the accepted channel intent once when its view retires before native POST starts", async () => {
+ it("continues the accepted channel intent when its view retires before native POST starts", async () => {
+ apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
const runtime = canonicalRegistry.runtime
runtime.messageStream.actions.accept(scope, { nonce: "retired_view", tempId: "temp_retired_view",
@@ -610,16 +612,16 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
const assertActive = Object.assign(() => { if (!current) throw new DOMException("Retired view", "AbortError") }, { signal: new AbortController().signal })
const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")
await act(async () => {
- const pending = runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "retired_view", assertActive,
+ const pending = runAcceptedMessageIntent({ assertCommand: () => {}, runtime, messageScope: scope, nonce: "retired_view", assertActive,
uploadFileAsync: vi.fn(), sendMessageAsync: mutation.mutateAsync,
channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" },
})
current = false
await expect(pending).resolves.toBeUndefined()
})
- expect(apiFetchMock).not.toHaveBeenCalled()
- expect(dispatch.mock.calls).toEqual([[scope, { type: "postFail", nonce: "retired_view" }]])
- expect(runtime.messageStream.actions.getRetryPayload(scope, "retired_view")?.message).toMatchObject({ content: "keep optimistic", failed: true })
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(dispatch.mock.calls.some(([, event]) => event.type === "postFail")).toBe(false)
+ expect(dispatch.mock.calls.some(([, event]) => event.type === "postAck")).toBe(true)
expect(toastMock).not.toHaveBeenCalled()
})
})
@@ -1366,3 +1368,107 @@ describe("useDeleteMention — rollback", () => {
expect(serversInvalidates).toHaveLength(1)
})
})
+
+
+describe("confirmed send failures", () => {
+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
+ const args = { serverId: "s1", channelId: "ch_1", content: "hi", nonce: "n1", author: { id: "u_me", name: "me", avatar: "M" } }
+ const confirmed = { id: "server_confirmed", seq: 7, type: "chat" as const, content: "hi", authorId: "u_me", clientNonce: "n1" }
+ it.each(["ordinary", "network", "500", "503"].flatMap(kind => ["canonical", "ws", "base"].map(stage => [kind, stage])))("settles the existing intent when %s failure follows %s confirmation", async (kind, stage) => {
+ const { ApiError } = await import("@/lib/errors")
+ const error = kind === "ordinary" ? new Error("late failure") : new ApiError("late failure", kind === "network" ? 0 : Number(kind))
+ canonicalRegistry.runtime.messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi", authorId: "u_me" }, localUploads: [] })
+ canonicalRegistry.runtime.ui.actions.setCurrentServerId(scope.serverId)
+ canonicalRegistry.runtime.ui.actions.subscribe({ channelId: scope.id })
+ apiFetchMock.mockImplementationOnce(async () => {
+ if (stage === "ws") {
+ const { dispatchCommunityWsEvent } = await import("@/hooks/community/community-ws/registry")
+ dispatchCommunityWsEvent({ type: "community:message.create", serverId: scope.serverId, channelId: scope.id,
+ message: { ...confirmed, authorName: "Me", authorAvatar: "M", authorAvatarVersion: 0, createdAt: "2026-08-07T10:00:00.000Z" } }, {
+ deliveryMode: "single", queryClient: capturedQc, communityStore: canonicalRegistry.runtime.ui, wsStore: canonicalRegistry.runtime.ws,
+ sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" }, matchesFocus: event => event.channelId === scope.id, scheduleInboxInvalidate: vi.fn(),
+ })
+ } else {
+ ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ if (stage === "base") canonicalRegistry.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: [confirmed] })
+ }
+ throw error
+ })
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await expect(runMutation(args)).rejects.toBe(error)
+ expect(toastMock).not.toHaveBeenCalled()
+ expect(getMessageStreamState(capturedQc, scope).outboxByNonce.size).toBe(0)
+ expect(materializeMessageStream([], getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc)).map(({ id }) => id)).toEqual(["server_confirmed"])
+ })
+ it.each([400, 401, 403, 429])("retains explicit %s despite matching canonical confirmation", async (status) => {
+ const { ApiError } = await import("@/lib/errors")
+ const error = new ApiError("explicit rejection", status)
+ ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ apiFetchMock.mockRejectedValueOnce(error)
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await expect(runMutation(args)).rejects.toBe(error)
+ expect(toastMock).toHaveBeenCalledOnce()
+ })
+ it.each([
+ { authorId: "other" }, { clientNonce: "other" }, { seq: undefined }, { seq: 0 },
+ ])("does not accept an invalid confirmation %j", async (change) => {
+ ingestMessages(canonicalRegistry, scope.id, [{ ...confirmed, ...change }])
+ apiFetchMock.mockRejectedValueOnce(new Error("not confirmed"))
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await runMutation(args).catch(() => {})
+ expect(toastMock).toHaveBeenCalledWith("not confirmed")
+ })
+ it.each(["owner", "view", "abort", "synthetic nonce"])("does not confirm after %s loses eligibility", async (mode) => {
+ ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ const { useCommunityMutationOrigin } = await import("../community-origin")
+ const origin = mountHook(() => useCommunityMutationOrigin()), original = origin.begin().token
+ const mod = await loadMod()
+ let error: Error = new Error("late failure")
+ if (mode === "owner") canonicalRegistry.runtime.lifecycle.setState(state => ({ ...state, active: false, generation: state.generation + 1 }))
+ if (mode === "abort") error = new DOMException("cancelled", "AbortError")
+ const assertActive = mode === "view" ? Object.assign(() => { throw new DOMException("retired view", "AbortError") }, { signal: new AbortController().signal }) : undefined
+ expect(mod.getConfirmedSentMessage(error, origin, original, scope.id, mode === "synthetic nonce" ? "srv:n1" : "n1", assertActive)).toBeUndefined()
+ })
+ it("releases accepted previews once through reducer settlement and keeps confirmed remote data", async () => {
+ const revoke = vi.fn(), originalRevoke = URL.revokeObjectURL
+ URL.revokeObjectURL = revoke
+ try {
+ canonicalRegistry.runtime.messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi", authorId: "u_me" }, localUploads: [{ file: new File(["x"], "x.txt"), previewObjectUrl: "blob:confirmed" }] })
+ apiFetchMock.mockImplementationOnce(async () => { ingestMessages(canonicalRegistry, scope.id, [confirmed]); throw new Error("late failure") })
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await runMutation(args).catch(() => {})
+ expect(toastMock).not.toHaveBeenCalled()
+ canonicalRegistry.runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: confirmed })
+ canonicalRegistry.runtime.messageStream.actions.removeScope(scope)
+ expect(revoke).toHaveBeenCalledExactlyOnceWith("blob:confirmed")
+ expect(canonicalRegistry.collections.messages.get(confirmed.id)).toMatchObject(confirmed)
+ } finally { URL.revokeObjectURL = originalRevoke }
+ })
+ it.each([{ id: "" }, { seq: -1 }, { seq: 1.5 }, { seq: Number.MAX_SAFE_INTEGER + 1 }])("rejects invalid server id/seq at canonical ingestion %j", (change) => {
+ expect(() => ingestMessages(canonicalRegistry, scope.id, [{ ...confirmed, ...change }])).toThrow()
+ })
+ it("does not accept another target or an absent outbox as confirmation", async () => {
+ ingestMessages(canonicalRegistry, "other_channel", [confirmed])
+ apiFetchMock.mockRejectedValueOnce(new Error("not confirmed"))
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await runMutation(args).catch(() => {})
+ expect(toastMock).toHaveBeenCalledWith("not confirmed")
+ })
+ it("retains failure before a later WS confirmation then reconciles through the existing reducer", async () => {
+ canonicalRegistry.runtime.messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi", authorId: "u_me" }, localUploads: [] })
+ apiFetchMock.mockRejectedValueOnce(new Error("not confirmed yet"))
+ const mod = await loadMod()
+ mountHook(() => mod.useSendMessage())
+ await runMutation(args).catch(() => {})
+ expect(toastMock).toHaveBeenCalledWith("not confirmed yet")
+ expect(getMessageStreamState(capturedQc, scope).outboxByNonce.get("n1")?.status).toBe("failed")
+ ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ canonicalRegistry.runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: confirmed })
+ expect(getMessageStreamState(capturedQc, scope).outboxByNonce.size).toBe(0)
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 3c8dd2123..81926693e 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -15,7 +15,7 @@ import { apiFetch, toastApiError } from "@/lib/api/client"
import { ApiError, isAbortError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
-import { publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel } from "@/lib/community-db/sync"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
import {
@@ -25,7 +25,7 @@ import {
-import type { MessageScope } from "@/lib/community/message-stream"
+import type { CanonicalMessage, MessageScope } from "@/lib/community/message-stream"
import type { Attachment, Msg } from "@/lib/community/models/message"
import type { UploadFileResult } from "./uploads"
@@ -158,6 +158,7 @@ export function sendNonce(): string {
export type SendMessageArgs = {
assertActive?: OriginalView
+ assertCommand?: () => void
serverId: string
channelId: string
forumParentChannelId?: string
@@ -188,7 +189,7 @@ export type SendMessageResult = { message: PostedMessage; deduped?: boolean }
* channel row's `parentChannelId` (per #14), so the client always POSTs to
* `/channels/:id/messages`.
*/
-export type SendDmMessageArgs = Pick<SendMessageArgs, "assertActive" | "content" | "replyToId" | "replyTo" | "attachments"> & {
+export type SendDmMessageArgs = Pick<SendMessageArgs, "assertActive" | "assertCommand" | "content" | "replyToId" | "replyTo" | "attachments"> & {
dmId: string
nonce: string
}
@@ -197,6 +198,25 @@ function sendMessageScope(input: SendMessageArgs | SendDmMessageArgs): MessageSc
return "dmId" in input ? { kind: "dm", id: input.dmId } : { kind: "channel", id: input.channelId, serverId: input.serverId }
}
+export function getConfirmedSentMessage(
+ error: unknown,
+ origin: ReturnType<typeof useCommunityMutationOrigin>,
+ original: ReturnType<ReturnType<typeof useCommunityMutationOrigin>["begin"]>["token"],
+ channelId: string,
+ nonce: string,
+ assertActive?: OriginalView,
+ assertCommand?: () => void,
+): CanonicalMessage | undefined {
+ if (isAbortError(error) || (error instanceof ApiError && error.status !== 0 && (error.status < 500 || error.status >= 600))) return
+ try { origin.assert(original); (assertCommand ?? assertActive)?.() } catch { return }
+ if (!original.viewerId || !nonce || nonce.startsWith("srv:")) return
+ for (const message of origin.registry!.collections.messages.values()) {
+ if (message.channelId === channelId && message.authorId === original.viewerId && message.clientNonce === nonce
+ && typeof message.id === "string" && message.id.length > 0
+ && typeof message.seq === "number" && Number.isSafeInteger(message.seq) && message.seq > 0) return message as CanonicalMessage
+ }
+}
+
function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(kind: MessageScope["kind"]) {
const origin = useCommunityMutationOrigin()
const queryClient = useQueryClient()
@@ -204,26 +224,26 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
const native = useMutation<SendMessageResult, Error, Intent>({
meta: { observabilityAction: `${kind}.message.send` },
mutationFn: async (args) => {
- const { content, replyToId, replyTo, attachments, nonce, original: token, assertActive } = args
- origin.assert(token); assertActive?.()
+ const { content, replyToId, replyTo, attachments, nonce, original: token, assertActive, assertCommand } = args
+ origin.assert(token); (assertCommand ?? assertActive)?.()
const scope = sendMessageScope(args)
const acceptedReply = replyTo ?? getCommunityRuntime(queryClient).messageStream.actions.getRetryPayload(scope, nonce ?? "")?.message.replyTo
const result = await origin.request<SendMessageResult>(token, `/api/community/channels/${scope.id}/messages`, {
- method: "POST", signal: assertActive?.signal, assertActive,
+ method: "POST", signal: assertCommand ? undefined : assertActive?.signal, assertActive: assertCommand ?? assertActive,
body: JSON.stringify({ content, replyToId: replyTo?.id ?? replyToId,
mentionType: "serverId" in args ? args.mentionType : undefined,
attachments: attachments?.map((attachment) => attachment.id), nonce }),
})
await origin.registry!.collections.messages.preload()
- origin.assert(token); assertActive?.()
+ origin.assert(token); (assertCommand ?? assertActive)?.()
const message = projectPostedMessage(result.message, nonce ?? "", scope.id)
publishCommunityMessages(queryClient, { channelId: scope.id,
messages: [{ ...message, ...(attachments?.length ? { attachments: attachments.map((attachment) => toAttachmentVm(scope.id, attachment)) } : {}), ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],
- proof: { token, ...(scope.kind === "channel" ? { signal: assertActive?.signal } : {}) } })
+ proof: { token, ...(scope.kind === "channel" && !assertCommand ? { signal: assertActive?.signal } : {}) } })
return result
},
onError: (error, args) => {
- try { origin.assert(args.original) } catch { return }
+ try { origin.assert(args.original); args.assertCommand?.() } catch { return }
const scope = sendMessageScope(args)
const stream = getCommunityRuntime(queryClient).messageStream.actions
const nonce = args.nonce ?? ""
@@ -233,14 +253,19 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
toast("You cannot send messages to this user")
return
}
+ const confirmed = getConfirmedSentMessage(error, origin, args.original, scope.id, nonce, args.assertActive, args.assertCommand)
+ if (confirmed) {
+ stream.dispatch(scope, { type: "wsMessage", message: confirmed })
+ return
+ }
if (scope.kind === "dm" || args.nonce) stream.dispatch(scope, { type: "postFail", nonce })
try { args.assertActive?.() } catch { return }
if (isAbortError(error)) return
if (error instanceof ApiError && error.status === 429) toast.error("Rate limited — please wait a moment before trying again")
- else toastApiError(error, "Failed to send message")
+ else toastApiError(error, "Failed to send message", () => { origin.assert(args.original); args.assertActive?.() })
},
onSuccess: (data, args) => {
- try { origin.assert(args.original) } catch { return }
+ try { origin.assert(args.original); args.assertCommand?.() } catch { return }
if (
"serverId" in args && args.forumParentChannelId &&
isForumSidebarParent(queryClient, args.serverId, args.forumParentChannelId)
@@ -267,7 +292,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
})
},
})
- const capture = useCallback((input: Args): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])
+ const capture = useCallback((input: Args): Intent => { (input.assertCommand ?? input.assertActive)?.(); return { ...input, original: input.assertCommand ? captureCommunityLiveSnapshotToken(queryClient, sendMessageScope(input).id) : origin.begin().token } }, [origin, queryClient])
const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.assertActive?.() }, [origin])
return useNativeMutationFacade(native, capture, assertCurrent)
}
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index 43b576348..33bab165f 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -6,7 +6,8 @@ import { useCallback } from "react"
import { useCommunityMutationOrigin } from "../community-origin"
-import { useMutation } from "@tanstack/react-query"
+import { useMutation, useQueryClient } from "@tanstack/react-query"
+import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared"
import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
@@ -27,6 +28,7 @@ export type UploadTarget = {
export type UploadFileArgs = {
receiptScope?: string
assertActive?: (() => void) & { signal: AbortSignal }
+ assertCommand?: () => void
target: UploadTarget
file: File
thumbnailBlob?: Blob
@@ -121,18 +123,19 @@ function uploadPath(target: UploadTarget): string | null {
export function useUploadFile(options: { gcTime?: number } = {}) {
const origin = useCommunityMutationOrigin()
+ const queryClient = useQueryClient()
type Intent = UploadFileArgs & { original: ReturnType<typeof origin.begin>["token"] }
const native = useMutation<UploadFileResult, Error, Intent>({ meta: { observabilityAction: "attachment.upload" },
mutationKey: ["community", "file-upload"], gcTime: options.gcTime ?? 0,
- mutationFn: async ({ target, file, thumbnailBlob, width, height, original, assertActive }) => {
- origin.assert(original); assertActive?.()
+ mutationFn: async ({ target, file, thumbnailBlob, width, height, original, assertActive, assertCommand }) => {
+ origin.assert(original); (assertCommand ?? assertActive)?.()
const path = uploadPath(target)
if (!path) throw new Error("Upload target requires channelId, dmId, or threadId")
const formData = buildAttachmentUploadFormData({ file, thumbnailBlob, width, height })
- return origin.request<UploadFileResult>(original, path, { method: "POST", body: formData, signal: assertActive?.signal, assertActive })
+ return origin.request<UploadFileResult>(original, path, { method: "POST", body: formData, signal: assertCommand ? undefined : assertActive?.signal, assertActive: assertCommand ?? assertActive })
},
})
- const capture = useCallback((input: UploadFileArgs): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])
+ const capture = useCallback((input: UploadFileArgs): Intent => { (input.assertCommand ?? input.assertActive)?.(); return { ...input, original: input.assertCommand ? captureCommunityLiveSnapshotToken(queryClient, input.target.threadId ?? input.target.dmId ?? input.target.channelId) : origin.begin().token } }, [origin, queryClient])
const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.assertActive?.() }, [origin])
return useNativeMutationFacade(native, capture, assertCurrent)
}
diff --git a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts b/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
index ac75a0f65..78a8e9790 100644
--- a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
+++ b/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
@@ -6,6 +6,8 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { getMessageStreamState } from "@/test/community-query-owner"
import { materializeMessageStream } from "@/lib/community/message-stream"
+import { ingestMessages } from "@/lib/community-db/sync"
+import { ApiError } from "@/lib/errors"
import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"
import { useDmMessageSender, type AcceptDmMessageArgs, type DmSendReceipt } from "./use-dm-message-sender"
@@ -146,3 +148,45 @@ describe("Native DM sender", () => {
expect(materializeMessageStream(base, owner.overlay(), canonicalMessageReader(owner.client)).map(({ id }) => id)).toEqual(["server_1"])
})
})
+
+
+describe("confirmed native DM receipt", () => {
+ const confirmed = { id: "server_confirmed", seq: 17, type: "chat" as const, content: "hello", authorId: "u_me", clientNonce: "fresh_nonce" }
+ it.each(["ordinary", 0, 500, 503])("returns the canonical receipt after a late %s while Native POST stays rejected", async (status) => {
+ const owner = await setup()
+ mocks.post.mockImplementationOnce(async () => { ingestMessages(owner.registry, scope.id, [confirmed]); throw status === "ordinary" ? new Error("late failure") : new ApiError("late failure", Number(status)) })
+ const receipt = owner.accept({ content: "hello" })
+ expect(await owner.settle(receipt)).toEqual({ ok: true, message: { id: "server_confirmed", seq: 17 } })
+ expect(owner.overlay().outboxByNonce.size).toBe(0)
+ const { awaitCommittedInvite } = await import("@/components/community/social/invite-dialog")
+ const onCommitted = vi.fn()
+ await awaitCommittedInvite(receipt, onCommitted)
+ expect(onCommitted).toHaveBeenCalledOnce()
+ })
+ it.each([403, 429])("keeps explicit %s as a failed receipt with a matching canonical row", async (status) => {
+ const owner = await setup()
+ ingestMessages(owner.registry, scope.id, [confirmed])
+ mocks.post.mockRejectedValueOnce(new ApiError("rejected", status))
+ expect(await owner.settle(owner.accept({ content: "hello" }))).toMatchObject({ ok: false, error: expect.any(Error) })
+ })
+ it.each(["abort", "view", "owner"])("keeps the DM receipt failed after %s with matching confirmation", async (mode) => {
+ const owner = await setup()
+ let current = true
+ const assertActive = Object.assign(() => { if (!current) throw new DOMException("retired view", "AbortError") }, { signal: new AbortController().signal })
+ mocks.post.mockImplementationOnce(async () => {
+ ingestMessages(owner.registry, scope.id, [confirmed])
+ if (mode === "view") current = false
+ if (mode === "owner") owner.runtime.lifecycle.setState(state => ({ ...state, active: false, generation: state.generation + 1 }))
+ throw mode === "abort" ? new DOMException("cancelled", "AbortError") : new Error("late failure")
+ })
+ expect(await owner.settle(owner.accept({ content: "hello", assertActive }))).toMatchObject(mode === "view" ? { ok: true, message: { id: "server_confirmed", seq: 17 } } : { ok: false, error: expect.any(Error) })
+ })
+ it("does not recover an upload failure from a matching canonical row", async () => {
+ const owner = await setup()
+ ingestMessages(owner.registry, scope.id, [confirmed])
+ mocks.upload.mockRejectedValueOnce(new ApiError("upload 503", 503))
+ const receipt = owner.accept({ content: "hello", attachments: [{ file: new File(["x"], "x.txt"), previewObjectUrl: "blob:x" }] })
+ expect(await owner.settle(receipt)).toMatchObject({ ok: false, error: expect.any(Error) })
+ expect(mocks.post).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.ts
index 874514bf2..6d81407b2 100644
--- a/src/web/src/hooks/community/use-dm-message-sender.ts
+++ b/src/web/src/hooks/community/use-dm-message-sender.ts
@@ -3,9 +3,11 @@ import { useCommunityRuntime } from "@/stores/community/runtime"
import { useCallback } from "react"
+import { useQueryClient } from "@tanstack/react-query"
+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
import { useCommunityViewSource } from "./use-community-view-source"
import { useCommunityMutationOrigin } from "./community-origin"
-import type { SendMessageArgs, SendMessageResult } from "./mutations/messages"
+import { getConfirmedSentMessage, type SendMessageArgs, type SendMessageResult } from "./mutations/messages"
import type { SendAttachment } from "@/lib/community/models/message"
import { acceptMessageIntent, prepareMessageIntent, messageSendError } from "@/lib/community/message-send-intent"
import {
@@ -28,6 +30,7 @@ export type AcceptDmMessageArgs = Pick<SendMessageArgs, "assertActive" | "conten
export function useDmMessageSender() {
const communityRuntime = useCommunityRuntime()
+ const queryClient = useQueryClient()
const source = useCommunityViewSource("dm-message-sender")
const origin = useCommunityMutationOrigin()
const { mutateAsync: uploadFileAsync } = useUploadFile()
@@ -36,25 +39,34 @@ export function useDmMessageSender() {
const runAcceptedIntent = useCallback(async (
dmId: string,
nonce: string,
+ original: ReturnType<typeof origin.begin>["token"],
+ assertCommand: () => void,
assertActive?: AcceptDmMessageArgs["assertActive"],
): Promise<DmSendCommit> => {
- const original = origin.begin().token
- const assert = () => { origin.assert(original); assertActive?.() }
+ const assert = () => { origin.assert(original); assertCommand() }
const scope = { kind: "dm" as const, id: dmId }
try {
const prepared = await prepareMessageIntent({ runtime: communityRuntime, scope, nonce,
- assertOwner: () => origin.assert(original), assertActive, uploadFileAsync, target: { dmId } })
+ assertOwner: assert, assertActive, assertCommand, uploadFileAsync, target: { dmId } })
if (!prepared.ok) return prepared
const { payload, attachments: uploadedAttachments } = prepared
assert()
- const result = await sendDmMessageAsync({
- dmId,
- content: payload.message.content ?? "",
- replyToId: payload.message.replyTo?.id,
- attachments: uploadedAttachments,
- nonce,
- assertActive,
- })
+ let result: SendMessageResult
+ try {
+ result = await sendDmMessageAsync({
+ dmId,
+ content: payload.message.content ?? "",
+ replyToId: payload.message.replyTo?.id,
+ attachments: uploadedAttachments,
+ nonce,
+ assertActive,
+ assertCommand,
+ })
+ } catch (error) {
+ const confirmed = getConfirmedSentMessage(error, origin, original, dmId, nonce, assertActive, assertCommand)
+ if (confirmed) return { ok: true, message: { id: confirmed.id, seq: confirmed.seq } }
+ throw error
+ }
return { ok: true, message: result.message }
} catch (error) {
return { ok: false, error: messageSendError(error) }
@@ -64,24 +76,30 @@ export function useDmMessageSender() {
const accept = useCallback((args: AcceptDmMessageArgs): DmSendReceipt => {
const assertActive = args.assertActive ?? source.capture()
assertActive()
+ const original = captureCommunityLiveSnapshotToken(queryClient, args.dmId)
+ const assertCommand = () => { origin.assert(original); assertCommunityLiveSnapshotTokenCurrent(queryClient, original, undefined) }
+ assertCommand()
const nonce = acceptMessageIntent(communityRuntime, { kind: "dm", id: args.dmId }, args)
if (nonce === undefined) return { accepted: false }
return {
accepted: true,
nonce,
- committed: runAcceptedIntent(args.dmId, nonce, assertActive),
+ committed: runAcceptedIntent(args.dmId, nonce, original, assertCommand, assertActive),
}
- }, [communityRuntime, runAcceptedIntent, source])
+ }, [communityRuntime, origin, queryClient, runAcceptedIntent, source])
- const retry = useCallback((dmId: string, nonce: string): Promise<DmSendCommit> => {
- const assertActive = source.capture()
+ const retry = useCallback((dmId: string, nonce: string, view?: AcceptDmMessageArgs["assertActive"]): Promise<DmSendCommit> => {
+ const assertActive = view ?? source.capture()
assertActive()
+ const original = captureCommunityLiveSnapshotToken(queryClient, dmId)
+ const assertCommand = () => { origin.assert(original); assertCommunityLiveSnapshotTokenCurrent(queryClient, original, undefined) }
+ assertCommand()
communityRuntime.messageStream.actions.dispatch(
{ kind: "dm", id: dmId },
{ type: "retry", nonce },
)
- return runAcceptedIntent(dmId, nonce, assertActive)
- }, [communityRuntime, runAcceptedIntent, source])
+ return runAcceptedIntent(dmId, nonce, original, assertCommand, assertActive)
+ }, [communityRuntime, origin, queryClient, runAcceptedIntent, source])
return { accept, retry }
}
diff --git a/src/web/src/lib/community/message-send-intent.ts b/src/web/src/lib/community/message-send-intent.ts
index 3b3375367..5922b0f69 100644
--- a/src/web/src/lib/community/message-send-intent.ts
+++ b/src/web/src/lib/community/message-send-intent.ts
@@ -51,17 +51,19 @@ export function acceptMessageIntent(runtime: CommunityRuntime, scope: MessageSco
}
export async function prepareMessageIntent<Target extends UploadFileArgs["target"]>({
- runtime, scope, nonce, assertOwner, assertActive, uploadFileAsync, target,
+ runtime, scope, nonce, assertOwner, assertActive, assertCommand, uploadFileAsync, target,
}: {
runtime: CommunityRuntime
scope: MessageScope
nonce: string
assertOwner: () => void
assertActive?: UploadFileArgs["assertActive"]
+ assertCommand?: () => void
target: Target
uploadFileAsync: (input: Omit<UploadFileArgs, "target"> & { target: Target }) => Promise<UploadFileResult>
}) {
- const assert = () => { assertOwner(); assertActive?.() }
+ const assert = () => { assertOwner(); (assertCommand ?? assertActive)?.() }
+ const assertUi = () => { assertOwner(); assertActive?.() }
assert()
const streamStore = runtime.messageStream.actions
const payload = streamStore.getRetryPayload(scope, nonce)
@@ -91,13 +93,14 @@ export async function prepareMessageIntent<Target extends UploadFileArgs["target
payload.localUploads.map((upload) =>
uploadFileAsync({
assertActive,
+ assertCommand,
target,
file: upload.file,
thumbnailBlob: upload.thumbnailBlob,
width: upload.width,
height: upload.height,
}).catch((error) => {
- toastApiError(error, "Failed to attach file", assert)
+ toastApiError(error, "Failed to attach file", assertUi)
return null
}),
),