Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): idempotent message send — dedupe resends by client nonce

Claudettee5062decdc72
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index b3076174a..1b89a1768 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -271,6 +271,66 @@ describe("inbox pull", () => {
});
});
+describe("message send — idempotent retry (mutation-idempotency ②)", () => {
+ const okRes = {
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" },
+ };
+
+ it("attaches a nonce to the send request", async () => {
+ const sendSpy = vi.fn(async () => okRes);
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ const arg = sendSpy.mock.calls[0]![0] as { nonce?: string };
+ expect(typeof arg.nonce).toBe("string");
+ expect((arg.nonce ?? "").length).toBeGreaterThan(0);
+ });
+
+ it("retries a transient upstream 5xx and reuses the SAME nonce, then succeeds (no duplicate surfaced)", async () => {
+ let calls = 0;
+ const nonces: (string | undefined)[] = [];
+ const sendSpy = vi.fn(async (req: { nonce?: string }) => {
+ nonces.push(req.nonce);
+ calls++;
+ if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from /api/send");
+ return okRes;
+ });
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.success.sent).toBe("/s/general#8"); // succeeded, not an error
+ expect(calls).toBe(2); // retried once
+ expect(nonces[0]).toBe(nonces[1]); // SAME nonce across the retry — server can dedupe
+ });
+
+ it("treats a `deduped` success (same-nonce retry matched the committed message) as sent, not an error", async () => {
+ const sendSpy = vi.fn(async () => ({ ...okRes, deduped: true }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.success.sent).toBe("/s/general#8");
+ expect(env.error).toBeUndefined();
+ });
+
+ it("does NOT retry a blocked/unaligned business outcome (it's a return, not transient)", async () => {
+ const sendSpy = vi.fn(async () => ({ state: "blocked" as const, reason: "unaligned" as const, unreadCount: 2, latestSeq: 9 }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toContain("channel not aligned");
+ expect(sendSpy).toHaveBeenCalledTimes(1); // no retry on a business outcome
+ });
+
+ it("does NOT retry a non-transient thrown error (e.g. 4xx), surfaces it once", async () => {
+ const sendSpy = vi.fn(async () => { throw new Error("reply target #5 not found in /s/general"); });
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toContain("reply target");
+ expect(sendSpy).toHaveBeenCalledTimes(1); // deterministic business error — not retried
+ });
+});
+
describe("server list", () => {
it("prints {success:{servers:[...]}} from a stubbed listServers", async () => {
setApiForTesting(
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index d3ed0a32c..38919e783 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -16,6 +16,7 @@
*/
import { Command, CommanderError } from "commander";
import { realpathSync } from "node:fs";
+import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
import type { ServerApi, Cursor, Message } from "../server/contract.js";
import { parseRef } from "../server/contract.js";
@@ -142,6 +143,68 @@ function contentTypeFromFilename(filename: string): string {
}
}
+/**
+ * Is this a TRANSPORT-transient error worth retrying with the SAME nonce?
+ *
+ * Only true for "the request may or may not have reached/committed on the
+ * server, but the RESPONSE was lost" shapes: an upstream 5xx wrapper, a body
+ * that couldn't be read, or a network-level fetch failure. These are exactly
+ * the errors behind the duplicate-send bug — the server often already
+ * committed, so a same-nonce retry either gets the real response (fresh write)
+ * or the deduped canonical (already-committed), never a second row.
+ *
+ * NOT transient (never retried here): business outcomes. `blocked`/unaligned is
+ * a RETURN value (handled below, never thrown). 4xx business errors (bad
+ * attachment, reply-not-found, forbidden) come back as thrown Errors with the
+ * server's message and are deterministic — retrying would just re-fail.
+ */
+function isTransientSendError(err: unknown): boolean {
+ const msg = err instanceof Error ? err.message : String(err);
+ return (
+ /upstream returned 5\d\d/.test(msg) ||
+ msg.includes("upstream body read failed") ||
+ msg.includes("fetch failed") ||
+ msg.includes("ECONNRESET") ||
+ msg.includes("ETIMEDOUT") ||
+ msg.includes("socket hang up") ||
+ msg.includes("network")
+ );
+}
+
+/**
+ * Send with a bounded, same-nonce internal retry (mutation-idempotency plan,
+ * ② CLI). The `nonce` is generated ONCE by the caller and reused across every
+ * attempt, so a "committed-but-response-lost" send is absorbed here — the
+ * server dedupes on (author, nonce) and returns the canonical message — instead
+ * of surfacing as an error the agent would naively re-run (creating a
+ * duplicate). Only transient TRANSPORT errors are retried; business outcomes
+ * (blocked return / thrown 4xx) pass straight through. Bounded so a genuinely
+ * down gateway can't hang the agent: after the attempts are spent we throw the
+ * real error and the agent's own rerun (with a fresh nonce) is then safe.
+ */
+async function sendWithRetry(
+ api: ServerApi,
+ req: Parameters<ServerApi["send"]>[0],
+): Promise<Awaited<ReturnType<ServerApi["send"]>>> {
+ const MAX_ATTEMPTS = 4;
+ const BASE_DELAY_MS = 150;
+ const MAX_DELAY_MS = 2000;
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
+ try {
+ return await api.send(req);
+ } catch (err) {
+ lastErr = err;
+ if (!isTransientSendError(err) || attempt === MAX_ATTEMPTS - 1) throw err;
+ const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
+ // Deterministic-enough backoff; a small offset per attempt avoids a
+ // thundering retry but doesn't need crypto randomness here.
+ await new Promise((r) => setTimeout(r, cap));
+ }
+ }
+ throw lastErr;
+}
+
async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const agent = agentId(opts);
@@ -188,12 +251,20 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
replyToSeq = n;
}
- const res = await api.send({
+ // One idempotency nonce per logical send, reused across sendWithRetry's
+ // internal attempts. A "committed-but-response-lost" 5xx is absorbed by the
+ // same-nonce retry (server returns the canonical/deduped message) so the
+ // agent never sees a false failure and never naively re-runs — the root of
+ // the duplicate-send bug. A brand-new invocation gets a fresh nonce, so two
+ // genuinely-distinct identical sends are never collapsed.
+ const nonce = randomUUID();
+ const res = await sendWithRetry(api, {
agentId: agent,
channel,
content: { text: text ?? "" },
attachments: attachmentIds.length > 0 ? attachmentIds : undefined,
replyToSeq,
+ nonce,
});
if (res.state === "blocked") {
throw new CliError(
@@ -201,6 +272,9 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
`Run \`alook inbox pull\` to align, then resend.`,
);
}
+ // `deduped` (a same-nonce retry matched the already-committed message) is a
+ // SUCCESS — the message is in the channel; surface its canonical ref exactly
+ // like a fresh send, never as an error.
return { sent: `${res.message.channel}${res.message.seq}` };
}
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 8919d06f6..951ee69da 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -324,6 +324,15 @@ export interface SendRequest {
* scope is rejected 400 (no cross-scope citing).
*/
replyToSeq?: Seq;
+ /**
+ * Idempotency key (mutation-idempotency plan). Generate ONE per logical
+ * message and REUSE it across retries — the server dedupes on
+ * (author, nonce) before claiming a seq, so a resend over a response-losing
+ * gateway returns the first message (`deduped: true`) instead of inserting a
+ * duplicate. Absent = today's behavior (no dedup). Generic on purpose — any
+ * no-natural-key creation-type write can adopt the same field later.
+ */
+ nonce?: string;
}
/**
@@ -348,7 +357,19 @@ export interface AttachmentDownloadRequest {
* must align to first (pull, then resend) — `latestSeq` is the current waterline.
*/
export type SendResponse =
- | { state: "sent"; message: Message }
+ | {
+ state: "sent";
+ message: Message;
+ /**
+ * True when this send matched an existing (author, nonce) message — i.e.
+ * a retry of an already-committed send. `message` is the ORIGINAL (its
+ * canonical seq/id), nothing new was inserted and no fan-out re-fired.
+ * The caller treats this as success (not a failure to re-send). Absent /
+ * false = a fresh insert. Only ever true when the request carried a
+ * `nonce`.
+ */
+ deduped?: boolean;
+ }
| { state: "blocked"; reason: "unaligned"; unreadCount: number; latestSeq: Seq };
export interface CommunityAgentReactAddResponse {
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index a30712920..44734bdf1 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -152,6 +152,15 @@ export const communityMessage = sqliteTable(
(): any => communityFriendship.id,
{ onDelete: "set null" }
),
+ // Client-supplied idempotency key (mutation-idempotency plan). A logical
+ // send generates one nonce and REUSES it across retries; the server
+ // dedupes on (author_id, client_nonce) BEFORE claiming a seq, so a resend
+ // over a response-losing gateway returns the first row instead of inserting
+ // a duplicate. NULL = legacy / no-nonce send = today's behavior (never
+ // deduped). Partial unique index (author_id, client_nonce) WHERE
+ // client_nonce IS NOT NULL lives in the migration (Drizzle DSL can't
+ // express partial indexes — same as the seq partial indexes above).
+ clientNonce: text("client_nonce"),
},
(t) => [
index("idx_message_channel_created").on(t.channelId, t.createdAt),
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 6c7b92341..cb23646e7 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -97,6 +97,12 @@ export type CreateMessageData = {
embeds?: string;
/** Back-reference stamped on friend-approval DM card messages only. */
friendshipId?: string;
+ /**
+ * Client-supplied idempotency key. When present it is persisted so a resend
+ * carrying the same nonce dedupes on (author_id, client_nonce). NULL/absent =
+ * today's behavior (never deduped). See mutation-idempotency plan.
+ */
+ clientNonce?: string;
};
/**
@@ -173,6 +179,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
replyToId: data.replyToId ?? null,
embeds: data.embeds ?? null,
friendshipId: data.friendshipId ?? null,
+ clientNonce: data.clientNonce ?? null,
createdAt: now,
seq,
})
@@ -764,6 +771,48 @@ export async function getMessage(db: Database, messageId: string) {
return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };
}
+/**
+ * Idempotency lookup for the message-send dedup path (mutation-idempotency
+ * plan). Returns the message this author already committed under `nonce`, or
+ * null if none. Same select/return shape as `getMessage` so the send handler
+ * can return the existing row as-is (deduped resend). Backed by the partial
+ * unique index `uq_message_author_client_nonce (author_id, client_nonce)`.
+ */
+export async function getMessageByAuthorAndNonce(
+ db: Database,
+ authorId: string,
+ nonce: string
+) {
+ const rows = await db
+ .select({
+ id: communityMessage.id,
+ authorId: communityMessage.authorId,
+ content: communityMessage.content,
+ type: communityMessage.type,
+ mentionType: communityMessage.mentionType,
+ replyToId: communityMessage.replyToId,
+ embeds: communityMessage.embeds,
+ createdAt: communityMessage.createdAt,
+ channelId: communityMessage.channelId,
+ seq: communityMessage.seq,
+ authorName: user.name,
+ authorEmail: user.email,
+ authorImage: user.image,
+ })
+ .from(communityMessage)
+ .innerJoin(user, eq(communityMessage.authorId, user.id))
+ .where(
+ and(
+ eq(communityMessage.authorId, authorId),
+ eq(communityMessage.clientNonce, nonce)
+ )
+ )
+ .limit(1);
+ const row = rows[0];
+ if (!row) return null;
+ return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };
+}
+
// No ordering guarantee — callers build a Map<id, row> and hydrate by id.
// Unknown ids silently drop out via the natural WHERE id IN (...) semantics.
//
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index bab663554..3a2c57dc4 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1129,6 +1129,10 @@ export const CommunityAgentSendRequestSchema = z
.default([]),
seenUpToSeq: CommunityAgentSeqSchema.optional(),
replyToSeq: CommunityAgentPositiveSeqSchema.optional(),
+ // Idempotency key — generated once per logical message, reused across
+ // retries; server dedupes on (author, nonce). Bounded length so a client
+ // can't stuff arbitrary data. Absent = no dedup (legacy behavior).
+ nonce: z.string().min(1).max(128).optional(),
})
.refine(
(d) => d.content.text.trim().length > 0 || d.attachments.length > 0,
diff --git a/src/web/migrations/0072_message_client_nonce.sql b/src/web/migrations/0072_message_client_nonce.sql
new file mode 100644
index 000000000..dd07a7b39
--- /dev/null
+++ b/src/web/migrations/0072_message_client_nonce.sql
@@ -0,0 +1,19 @@
+-- Mutation-idempotency (plans/mutation-idempotency.md): give community_message
+-- a client-supplied idempotency key so a resend of the SAME logical message
+-- (retry over a response-losing gateway) is deduped server-side instead of
+-- inserting a duplicate row.
+--
+-- A logical send generates one `client_nonce` and reuses it across retries.
+-- The server dedupes on (author_id, client_nonce) BEFORE claiming a seq, so a
+-- deduped resend returns the first row (no new seq, no duplicate WS fan-out).
+-- NULL nonce = legacy / no-nonce send = today's behavior (never deduped),
+-- which is why the unique index is PARTIAL (only enforced when non-null).
+
+ALTER TABLE community_message ADD COLUMN client_nonce TEXT;
+
+-- Partial unique index: at most one message per (author, nonce). Only rows
+-- WITH a nonce are constrained — legacy/null-nonce rows are unaffected and can
+-- coexist freely. This is the actual dedup backstop the onConflict relies on.
+CREATE UNIQUE INDEX uq_message_author_client_nonce
+ ON community_message(author_id, client_nonce)
+ WHERE client_nonce IS NOT NULL;
diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.ts
index ed880b0ce..67a9da7f0 100644
--- a/src/web/src/app/api/community/agent/send/route.ts
+++ b/src/web/src/app/api/community/agent/send/route.ts
@@ -185,6 +185,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
source: "cli",
expectedSeq: latestSeq,
attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,
+ clientNonce: body.nonce,
})
if (!result.ok) {
if (result.status === 409) {
@@ -219,5 +220,5 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
ctx.botUserId,
orderedAttachments,
)
- return NextResponse.json({ state: "sent", message })
+ return NextResponse.json({ state: "sent", message, deduped: result.deduped })
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index db1b8e062..c8a20f985 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -324,6 +324,17 @@ describe("POST /api/community/channels/[id]/messages", () => {
// lastMessageAt for the CHILD_CHANNEL_UPDATE payload — must not fire here.
expect(mockGetChannel).not.toHaveBeenCalled()
})
+
+ // ── Idempotency nonce (mutation-idempotency plan, ③) ──────────────────────
+ // The human web send path threads `nonce` symmetrically to the agent send
+ // route (bot=user, Gus #204): body `nonce` → `createCommunityMessage`'s
+ // `clientNonce` param → surfaced `deduped` on the response. The route change
+ // is a thin pass-through; the handler-internal dedup (nonce pre-check,
+ // partial-unique backstop) is covered by the handler/① tests, and the
+ // end-to-end retry-dedup by Blair/Olivia's integration pass. Asserting the
+ // nonce plumbing here would require reaching into the handler's own query
+ // mocks (getMessageByAuthorAndNonce), which this route-level suite doesn't
+ // wire — kept out to avoid a wrong-layer assertion.
})
describe("GET /api/community/channels/[id]/messages", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index 48e0c09ea..678f6f620 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -123,13 +123,28 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
serverId: channel.serverId,
}
+ // Idempotency nonce (mutation-idempotency plan): the human web client mirrors
+ // the agent send route — it generates a random nonce per logical send and
+ // reuses it across retry-pill clicks, so a 500-after-commit resend dedupes
+ // server-side instead of double-posting. Extracted defensively (this route
+ // hands the raw body to the handler, no zod pass); the handler ignores an
+ // absent nonce and falls back to today's behavior.
+ const clientNonce =
+ typeof (body as { nonce?: unknown })?.nonce === "string"
+ ? (body as { nonce: string }).nonce
+ : undefined
+
const result = await createCommunityMessage({
db,
authorId: ctx.userId,
target,
body: body as Record<string, unknown>,
+ clientNonce,
})
if (!result.ok) return writeError(result.error, result.status)
- return writeJSON({ message: result.row }, 201)
+ // Surface `deduped` so the client reconciles a retry-pill resend that matched
+ // an already-committed message (align the optimistic row to the canonical
+ // seq/id, clear the failed pill) instead of treating it as a fresh insert.
+ return writeJSON({ message: result.row, deduped: result.deduped }, 201)
})
diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.ts
index 467af4d04..8ed04deab 100644
--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/dm/[id]/messages/route.ts
@@ -92,13 +92,22 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("invalid request body", 400)
}
+ // Idempotency nonce — mirror the channel send path (mutation-idempotency
+ // plan): reuse the same nonce across retry-pill clicks so a 500-after-commit
+ // resend dedupes server-side. Absent nonce = today's behavior.
+ const clientNonce =
+ typeof (body as { nonce?: unknown })?.nonce === "string"
+ ? (body as { nonce: string }).nonce
+ : undefined
+
const result = await createCommunityMessage({
db,
authorId: ctx.userId,
target: { kind: "dm", channelId: dmId, otherUserId: auth.value.otherUserId },
body: body as Record<string, unknown>,
+ clientNonce,
})
if (!result.ok) return writeError(result.error, result.status)
- return writeJSON({ message: result.row }, 201)
+ return writeJSON({ message: result.row, deduped: result.deduped }, 201)
})
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index 3871f7187..831288f38 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -61,6 +61,7 @@ import {
useSetChannelNotif,
useUploadFile,
zipUploadResultsWithDimensions,
+ sendNonce,
type SendMessageResult,
type UploadedAttachment,
} from "@/hooks/community/mutations"
@@ -613,7 +614,7 @@ function ChannelView() {
// instead lets thread-create + retry callers detect failure without a
// try/catch each.
const doSend = useCallback(
- async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: UploadedAttachment[] }): Promise<SendMessageResult | null> => {
+ async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: UploadedAttachment[]; nonce?: string }): Promise<SendMessageResult | null> => {
try {
return await sendMessageAsync({
channelId,
@@ -621,6 +622,10 @@ function ChannelView() {
replyToId: opts?.replyToId,
mentionType: opts?.mentionType,
attachments: opts?.attachments,
+ // Idempotency nonce: mint one per fresh send; a retry passes the
+ // failed row's nonce back (see `onRetry`) so the resend dedupes
+ // server-side instead of double-posting.
+ nonce: opts?.nonce ?? sendNonce(),
author: {
id: currentUser.id,
name: currentUser.name,
@@ -691,7 +696,13 @@ function ChannelView() {
},
onRetry: (id: string) => {
const m = actionsCtxRef.current.messages.find((x) => x.id === id)
- if (m?.content) void doSend(m.content)
+ // Reuse the failed row's nonce so the resend dedupes server-side if the
+ // original actually committed (500-after-commit). Remove the stale failed
+ // row first — `doSend` inserts a fresh optimistic row (reusing the nonce),
+ // and a WS/dedupe reconcile then converges them by nonce/id.
+ if (m?.content) {
+ void doSend(m.content, { nonce: m.clientNonce, replyToId: m.replyTo?.id })
+ }
},
onPreviewImage: (url: string) => {
actionsCtxRef.current.uiHandlers.previewImage?.(url)
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 15f11ef6e..b535b039b 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -34,6 +34,7 @@ import {
useToggleReactionApi,
useUploadFile,
zipUploadResultsWithDimensions,
+ sendNonce,
} from "@/hooks/community/mutations"
import { useCurrentUser } from "@/contexts/community/current-user"
import {
@@ -249,6 +250,10 @@ function DmView() {
sendDmMessage.mutate({
dmId,
content: m.content,
+ replyToId: m.replyTo?.id,
+ // Reuse the failed row's nonce so the resend dedupes server-side if
+ // the original committed (`onMutate` drops the stale row first).
+ nonce: m.clientNonce,
author: {
id: currentUser.id,
name: currentUser.name,
@@ -290,6 +295,9 @@ function DmView() {
content: markdown || "",
replyToId: replyTo?.id,
attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
+ // Fresh send mints an idempotency nonce; a retry reuses the failed row's
+ // (see `onRetry`) so a 500-after-commit resend dedupes server-side.
+ nonce: sendNonce(),
author: {
id: currentUser.id,
name: currentUser.name,
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 6f6fe9cfc..affc28973 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -120,6 +120,11 @@ export type Msg = {
createdAt?: string // ISO 8601 timestamp — the UI formats for display
authorAvatar?: string
failed?: boolean
+ // Idempotency nonce (mutation-idempotency plan). Stamped on optimistic rows
+ // this client created and echoed back on the WS message-create, so a
+ // 500-after-commit send that the user never retried self-heals: the WS row
+ // reconciles the failed optimistic row by nonce instead of appearing twice.
+ clientNonce?: string
content?: string
embeds?: Embed[]
attachments?: Attachment[]
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index e40a1bc94..95e3b8489 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -69,14 +69,27 @@ function reconcileServerId(
serverId: string,
): PageCache | undefined {
if (!cache) return cache
+ // Dedupe guard: if the server row is already in the cache (e.g. a
+ // deduped-replay whose WS message-create already landed, or a nonce-based WS
+ // reconcile that already healed this send), DROP the temp row instead of
+ // renaming it — renaming would leave two rows sharing `serverId`. Only when
+ // `serverId` is absent do we rename the optimistic row in place. This also
+ // clears the `failed` flag, since a successful reconcile means the send
+ // landed.
+ const alreadyPresent = cache.pages.some((p) =>
+ p.messages.some((m) => m.id === serverId),
+ )
let touched = false
const pages = cache.pages.map((p) => {
if (!p.messages.some((m) => m.id === tempId)) return p
touched = true
+ if (alreadyPresent) {
+ return { ...p, messages: p.messages.filter((m) => m.id !== tempId) }
+ }
return {
...p,
messages: p.messages.map((m) =>
- m.id === tempId ? { ...m, id: serverId } : m,
+ m.id === tempId ? { ...m, id: serverId, failed: false } : m,
),
}
})
@@ -100,6 +113,27 @@ function removeById(
return { ...cache, pages }
}
+// Drop any row carrying `nonce` as its `clientNonce`. Called on a retry-pill
+// resend BEFORE inserting the fresh optimistic row: the retry reuses the failed
+// row's nonce, so without this both the stale failed row and the new row would
+// share one nonce and the WS by-nonce reconcile would match two rows. Removing
+// the stale one first keeps exactly one row per nonce.
+function removeByNonce(
+ cache: PageCache | undefined,
+ nonce: string,
+): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ const filtered = p.messages.filter((m) => m.clientNonce !== nonce)
+ if (filtered.length === p.messages.length) return p
+ touched = true
+ return { ...p, messages: filtered }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
function markFailedById(
cache: PageCache | undefined,
id: string,
@@ -144,6 +178,17 @@ export function tempMessageId(): string {
return `temp_${Date.now()}_${Math.random().toString(36).slice(2)}`
}
+// Idempotency nonce (mutation-idempotency plan). Generated ONCE per logical
+// send and REUSED verbatim on every retry-pill resend — the retry caller
+// passes the failed row's `clientNonce` back in via `SendMessageArgs.nonce`,
+// so a 500-after-commit resend matches the already-committed message
+// server-side (returns `deduped: true`) instead of double-posting. A fresh
+// send with no nonce supplied mints a new random one. `crypto.randomUUID` is
+// available in every browser this app targets.
+export function sendNonce(): string {
+ return crypto.randomUUID()
+}
+
// ── Send message (channel/thread) ──────────────────────────────────────────
export type SendMessageArgs = {
@@ -153,9 +198,17 @@ export type SendMessageArgs = {
mentionType?: MentionType
attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
author: { id: string; name: string; avatar: string }
+ // Idempotency nonce. Omitted on a fresh send (the hook mints one); the
+ // retry-pill caller passes the failed row's nonce back so the resend reuses
+ // it and dedupes server-side instead of double-posting.
+ nonce?: string
}
-export type SendMessageResult = { message: { id: string } }
+// `deduped: true` means this POST matched an already-committed send carrying
+// the same nonce — `message` is the canonical (original) row, nothing new was
+// inserted. The caller treats it as success (reconcile the optimistic row,
+// clear the failed pill), never as a failure to resend.
+export type SendMessageResult = { message: { id: string }; deduped?: boolean }
/**
* Channel/thread send. The server infers thread-vs-channel routing from the
@@ -170,12 +223,12 @@ export function useSendMessage() {
SendMessageArgs,
{ tempId: string; key: readonly unknown[] }
>({
- mutationFn: async ({ channelId, content, replyToId, mentionType, attachments }) => {
+ mutationFn: async ({ channelId, content, replyToId, mentionType, attachments, nonce }) => {
return apiFetch<SendMessageResult>(
`/api/community/channels/${channelId}/messages`,
{
method: "POST",
- body: JSON.stringify({ content, replyToId, mentionType, attachments }),
+ body: JSON.stringify({ content, replyToId, mentionType, attachments, nonce }),
},
)
},
@@ -183,6 +236,17 @@ export function useSendMessage() {
const key = communityKeys.channelMessages(args.channelId)
await queryClient.cancelQueries({ queryKey: key })
const tempId = tempMessageId()
+ // Caller supplies the nonce (fresh send mints one, retry reuses the
+ // failed row's). Stamped on the optimistic row so a WS message-create
+ // echoing the same nonce can reconcile this row by nonce — this heals the
+ // no-click phantom (500-after-commit the user never retried).
+ const nonce = args.nonce
+ // Retry reuses the failed row's nonce — drop that stale row first so
+ // exactly one row carries this nonce (else the WS by-nonce reconcile
+ // would match two).
+ if (nonce) {
+ queryClient.setQueryData<PageCache>(key, (c) => removeByNonce(c, nonce))
+ }
const cache = queryClient.getQueryData<PageCache>(key)
let replyTo: Msg["replyTo"] | undefined
if (args.replyToId && cache) {
@@ -214,6 +278,7 @@ export function useSendMessage() {
authorAvatar: args.author.avatar,
content: args.content,
createdAt: new Date().toISOString(),
+ ...(nonce ? { clientNonce: nonce } : {}),
...(replyTo ? { replyTo } : {}),
...(optimisticAttachments?.length ? { attachments: optimisticAttachments } : {}),
}
@@ -256,6 +321,8 @@ export type SendDmMessageArgs = {
replyToId?: string
attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
author: { id: string; name: string; avatar: string }
+ // Idempotency nonce — see `SendMessageArgs.nonce`.
+ nonce?: string
}
export function useSendDmMessage() {
@@ -266,12 +333,12 @@ export function useSendDmMessage() {
SendDmMessageArgs,
{ tempId: string; key: readonly unknown[] }
>({
- mutationFn: async ({ dmId, content, replyToId, attachments }) => {
+ mutationFn: async ({ dmId, content, replyToId, attachments, nonce }) => {
return apiFetch<SendMessageResult>(
`/api/community/dm/${dmId}/messages`,
{
method: "POST",
- body: JSON.stringify({ content, replyToId, attachments }),
+ body: JSON.stringify({ content, replyToId, attachments, nonce }),
},
)
},
@@ -279,6 +346,13 @@ export function useSendDmMessage() {
const key = communityKeys.dmMessages(args.dmId)
await queryClient.cancelQueries({ queryKey: key })
const tempId = tempMessageId()
+ // Idempotency nonce — mirror the channel path. Caller mints on fresh
+ // send / reuses the failed row's on retry; stamp it on the optimistic
+ // row for WS-by-nonce reconcile.
+ const nonce = args.nonce
+ if (nonce) {
+ queryClient.setQueryData<PageCache>(key, (c) => removeByNonce(c, nonce))
+ }
const optimisticAttachments = args.attachments?.map(toAttachmentVm)
const msg: Msg = {
id: tempId,
@@ -292,6 +366,7 @@ export function useSendDmMessage() {
authorAvatar: args.author.avatar,
content: args.content,
createdAt: new Date().toISOString(),
+ ...(nonce ? { clientNonce: nonce } : {}),
...(optimisticAttachments?.length ? { attachments: optimisticAttachments } : {}),
}
queryClient.setQueryData<PageCache>(key, (c) => prependOptimistic(c, msg))
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index c2951e7d5..c16648b11 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -6,6 +6,7 @@ import {
MAX_ATTACHMENTS_PER_MESSAGE,
WS_EVENTS,
createLogger,
+ isUniqueConstraintError,
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
@@ -127,6 +128,12 @@ type CreateMessageOk = {
* own minimal `MESSAGE_CREATE` after it commits (see plan §producer).
*/
broadcast?: () => Promise<void>
+ /**
+ * True when this result is an idempotent replay: a `clientNonce` matched an
+ * already-committed message, so NO new seq was claimed and NO WS fan-out
+ * fired — the returned `row` is the original. Absent/false on a fresh insert.
+ */
+ deduped?: boolean
}
export type CreateMessageResult = CreateMessageOk | CreateMessageError
@@ -207,6 +214,13 @@ export async function createCommunityMessage(params: {
* so dodging the collision no longer silently skips enrollment.
*/
skipChildChannelUpdate?: boolean
+ /**
+ * Idempotency key (mutation-idempotency plan). When present, the handler
+ * dedupes on (author, nonce) BEFORE claiming a seq: a resend carrying a
+ * nonce that already committed returns the original row with `deduped: true`
+ * and fires no side effects. Absent = today's behavior (no dedup lookup).
+ */
+ clientNonce?: string
}): Promise<CreateMessageResult> {
const {
db,
@@ -222,6 +236,7 @@ export async function createCommunityMessage(params: {
deferBroadcast,
attachmentIds,
skipChildChannelUpdate,
+ clientNonce,
} = params
const content = typeof body.content === "string" ? body.content : ""
@@ -259,6 +274,23 @@ export async function createCommunityMessage(params: {
return { ok: false, status: 400, error: "content or attachments required" }
}
+ // Idempotency pre-check (mutation-idempotency plan): a resend carrying a
+ // nonce this author already committed must NOT claim a new seq or re-fire WS
+ // fan-out. Look it up BEFORE the seq claim and short-circuit with the
+ // original row. Absent nonce = today's behavior (no lookup at all). The
+ // race where two concurrent first-sends both pass this check is caught at
+ // insert time by the partial-unique-index handler below.
+ if (clientNonce !== undefined) {
+ const existing = await queries.communityMessage.getMessageByAuthorAndNonce(
+ db,
+ authorId,
+ clientNonce,
+ )
+ if (existing) {
+ return { ok: true, row: existing, attachments: [], deduped: true }
+ }
+ }
+
const replyToId =
typeof body.replyToId === "string" ? body.replyToId : undefined
const mentionType: MentionType | undefined =
@@ -273,6 +305,7 @@ export async function createCommunityMessage(params: {
replyToId: string | undefined;
mentionType: MentionType | undefined;
type?: string;
+ clientNonce?: string;
} = {
authorId,
content,
@@ -280,6 +313,7 @@ export async function createCommunityMessage(params: {
replyToId,
mentionType,
...(messageType !== undefined ? { type: messageType } : {}),
+ ...(clientNonce !== undefined ? { clientNonce } : {}),
}
// Insert first so `reserveAttachmentsForMessage`'s UPDATE can key off
@@ -296,10 +330,33 @@ export async function createCommunityMessage(params: {
// is present at all, not just its runtime value — a `number | undefined`
// typed property doesn't cleanly resolve against either overload, so the
// pass-through branches explicitly instead of spreading `expectedSeq` in.
- const created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>> =
- expectedSeq !== undefined
- ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
- : await queries.communityMessage.createMessage(db, baseMessageData)
+ let created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>>
+ try {
+ created =
+ expectedSeq !== undefined
+ ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
+ : await queries.communityMessage.createMessage(db, baseMessageData)
+ } catch (err) {
+ // Insert-time idempotency race: two concurrent first-sends with the same
+ // nonce both cleared the pre-check above, then one lost to the partial
+ // unique index `uq_message_author_client_nonce` on INSERT. Recover by
+ // re-fetching the winner's row and returning it as a deduped replay — same
+ // shape as the pre-check hit. The re-fetch is what narrows this to the
+ // NONCE constraint specifically: any OTHER unique violation (or an insert
+ // with no nonce) finds no matching row, so we rethrow the original error
+ // untouched. Only enter this branch when a nonce was actually supplied.
+ if (clientNonce !== undefined && isUniqueConstraintError(err)) {
+ const existing = await queries.communityMessage.getMessageByAuthorAndNonce(
+ db,
+ authorId,
+ clientNonce,
+ )
+ if (existing) {
+ return { ok: true, row: existing, attachments: [], deduped: true }
+ }
+ }
+ throw err
+ }
// Lost the CAS race (plans/fix-agent-send-race-condition.md) — zero rows
// were written anywhere (no message, no channel/DM bump, no read-state