Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): return stored nonce in message confirmations (#1104)
Generd3823535a281
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex f8ea522c9..0f72b2701 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -1084,8 +1084,7 @@ export async function getMessageClientNonceForDelivery(/*** 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+ * null if none. Backed by the partial* unique index `uq_message_author_client_nonce (author_id, client_nonce)`.*/export async function getMessageByAuthorAndNonce(@@ -1097,6 +1096,7 @@ export async function getMessageByAuthorAndNonce(.select({...messageProjection,seq: communityMessage.seq,+ clientNonce: communityMessage.clientNonce,authorEmail: user.email,}).from(communityMessage)diff --git a/src/shared/test/queries/community-forum-message-pagination.test.ts b/src/shared/test/queries/community-forum-message-pagination.test.tsindex f62bf515f..27967f49d 100644--- a/src/shared/test/queries/community-forum-message-pagination.test.ts+++ b/src/shared/test/queries/community-forum-message-pagination.test.ts@@ -67,7 +67,7 @@ describe("forum opener message pagination against real SQLite", () => {.run('[{"title":"Native"}]', "nonce", "friendship", "m1")const reads = [{ row: await messageQueries.getMessage(db as never, "m1"), extra: ["seq", "authorEmail"] },- { row: await messageQueries.getMessageByAuthorAndNonce(db as never, "u1", "nonce"), extra: ["seq", "authorEmail"] },+ { row: await messageQueries.getMessageByAuthorAndNonce(db as never, "u1", "nonce"), extra: ["seq", "clientNonce", "authorEmail"] },{ row: (await messageQueries.getMessagesByIds(db as never, ["m1"]))[0], extra: ["seq", "authorEmail"] },{ row: await messageQueries.getMessageInScope(db as never, "m1", { channelId: "c1" }), extra: ["authorEmail"] },{ row: (await messageQueries.getMessagesByIdsInChannels(db as never, ["m1"], ["c1"]))[0], extra: ["seq", "clientNonce", "discriminator", "authorEmail"] },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.tsindex 4551b4c69..3db10a1ce 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@@ -257,7 +257,7 @@ describe("POST /api/community/channels/[id]/messages", () => {// The door's single mask (requireMessageSurfaceAccess) probes getChannel// first to dispatch by surface; default = the same text channel.mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })- mockCreateMessage.mockResolvedValue({ id: "m1" })+ mockCreateMessage.mockImplementation(async (_db: unknown, data: { clientNonce?: string }) => ({ id: "m1", clientNonce: data.clientNonce ?? null }))// Human author by default.mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })mockGetMessage.mockResolvedValue({@@ -505,7 +505,6 @@ describe("POST /api/community/channels/[id]/messages", () => {mockGetMessage.mockResolvedValue({id: "m1",seq: 12,- clientNonce: "n1",authorId: "u1",authorName: "Alice",authorImage: null,diff --git a/src/web/src/lib/community/message-confirmation.sql.test.ts b/src/web/src/lib/community/message-confirmation.sql.test.tsnew file mode 100644index 000000000..dc1f00302--- /dev/null+++ b/src/web/src/lib/community/message-confirmation.sql.test.ts@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityMessagePostedSchema, queries } from "@alook/shared"+import type { CommunityActorHandler } from "@/lib/middleware/community-actor"+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"+import { projectPostedMessage } from "./message-wire"++const state = vi.hoisted(() => ({ db: null as unknown, dispatch: vi.fn() }))+vi.mock("@/lib/db", () => ({ getDb: () => state.db, getPrimaryDb: () => state.db }))+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: CommunityActorHandler) => (request: NextRequest, context: { params: Record<string, string> }) => handler(request, {+ env: { DB: {} } as Env,+ actor: { kind: "human", userId: "sender", email: "[email protected]" },+ params: context.params,+ }),+}))+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: async () => ({ allowed: true }) }))+vi.mock("@/lib/community/message-dispatcher", () => ({ dispatchCommittedMessage: state.dispatch }))+vi.mock("@/lib/community/fanout", () => ({ fanOutToChannel: vi.fn(), fanOutToServerMembers: vi.fn(), broadcastToUserSafe: vi.fn() }))++import { POST } from "@/app/api/community/channels/[id]/messages/route"++const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []+const stamp = "2026-10-30T00:00:00.000Z"+const kinds = ["text", "dm", "thread", "forum"] as const++beforeEach(() => { state.dispatch.mockReset().mockResolvedValue(undefined) })+afterEach(() => { for (const fixture of fixtures) fixture.sqlite.close(); fixtures.length = 0 })++function fixture(kind: typeof kinds[number]) {+ const store = createCommunitySqliteDb()+ fixtures.push(store)+ state.db = store.db+ for (const id of ["sender", "peer"]) store.sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt","isBot") VALUES (?,?,?,?,0,?,?,0)')+ .run(id, `${id}@example.test`, id, id === "sender" ? "0001" : "0002", stamp, stamp)+ store.sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0003','','sender',?)").run(stamp)+ store.sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('member','server','sender','owner')")+ store.sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at) VALUES ('scope',?,'Scope',?,'',0,0,0,?)")+ .run(kind === "dm" ? null : "server", kind, stamp)+ if (kind === "dm") {+ for (const id of ["sender", "peer"]) store.sqlite.prepare("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source,added_by,added_at) VALUES (?,'scope',?,'access','added','sender',?)").run(`scope:${id}`, id, stamp)+ store.sqlite.prepare("INSERT INTO community_friendship (id,requester_id,addressee_id,status,created_at,updated_at) VALUES ('friendship','sender','peer','accepted',?,?)").run(stamp, stamp)+ }+ if (kind === "thread") {+ store.sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at) VALUES ('parent','server','Parent','text','',0,0,1,?)").run(stamp)+ store.sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at) VALUES ('anchor','peer','Anchor','default','parent',1,?)").run(stamp)+ store.sqlite.exec("UPDATE community_channel SET parent_channel_id='parent',parent_message_id='anchor' WHERE id='scope'")+ }+ return store+}++async function post(channelId: string, nonce: string) {+ const response = await POST(new NextRequest(`http://localhost/api/community/channels/${channelId}/messages`, {+ method: "POST",+ headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },+ body: JSON.stringify({ content: "A manual send", nonce }),+ }), { params: { id: channelId } })+ return { response, body: CommunityMessagePostedSchema.parse(await response.json()) }+}++describe("human POST confirmation with actual persisted SQL projections", () => {+ it.each(kinds)("confirms a fresh %s send without exposing its nonce through general reads", async kind => {+ const store = fixture(kind)+ const { response, body } = await post("scope", "fresh-nonce")+ expect(response.status).toBe(201)+ expect(store.sqlite.prepare("SELECT client_nonce AS nonce FROM community_message WHERE id=?").get(body.message.id)).toEqual({ nonce: "fresh-nonce" })+ expect(await queries.communityMessage.getMessage(store.db, body.message.id)).not.toHaveProperty("clientNonce")+ expect(projectPostedMessage(body.message, "fresh-nonce", "scope")).toMatchObject({ id: body.message.id, seq: 1, clientNonce: "fresh-nonce" })+ expect(() => projectPostedMessage(body.message, "wrong-nonce", "scope")).toThrow("Posted message confirmation mismatch")+ expect(() => projectPostedMessage(body.message, "fresh-nonce", "foreign-scope")).toThrow("Posted message confirmation mismatch")+ if (kind === "forum") expect(body.threadId).toEqual(expect.any(String))+ })++ it.each(kinds)("confirms a same-nonce %s retry as the original single committed send", async kind => {+ const store = fixture(kind)+ const first = await post("scope", "retry-nonce")+ expect(first.response.status).toBe(201)+ const batches = store.record.batches.length+ const deliveries = state.dispatch.mock.calls.length+ const replay = await post("scope", "retry-nonce")+ expect(replay.response.status).toBe(200)+ expect(replay.body.deduped).toBe(true)+ expect(replay.body.message.id).toBe(first.body.message.id)+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM community_message WHERE channel_id='scope'").get()).toEqual({ count: 1 })+ expect(store.sqlite.prepare("SELECT next_seq AS seq FROM community_message_seq WHERE channel_id='scope'").get()).toEqual({ seq: 1 })+ expect(store.record.batches).toHaveLength(batches)+ expect(state.dispatch).toHaveBeenCalledTimes(deliveries)+ expect(projectPostedMessage(replay.body.message, "retry-nonce", "scope")).toMatchObject({ id: first.body.message.id, seq: 1, clientNonce: "retry-nonce" })+ expect(await queries.communityMessage.getMessageByAuthorAndNonce(store.db, "peer", "retry-nonce")).toBeNull()+ if (kind === "forum") expect(replay.body.threadId).toBe(first.body.threadId)+ })+})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 7bd702e13..98261a0bf 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -115,7 +115,7 @@ export async function getCommunityMessageReplay(params: {}type FullMessageRow = NonNullable<- Awaited<ReturnType<typeof queries.communityMessage.getMessage>>+ Awaited<ReturnType<typeof queries.communityMessage.getMessageByAuthorAndNonce>>>type CreateMessageError = {@@ -596,8 +596,9 @@ export async function createCommunityMessage(params: {throw new Error("message not found after insert")}+ const postedRow = { ...row, clientNonce: created.clientNonce }if (!suppressBroadcast && deferBroadcast) {- return { ok: true, row, attachments, broadcast: doBroadcast }+ return { ok: true, row: postedRow, attachments, broadcast: doBroadcast }}- return { ok: true, row, attachments }+ return { ok: true, row: postedRow, attachments }}