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): align concurrent forum openers (#633)
Gustavo Yeedf3763ac304
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.tsindex 084964a3c..101ec6926 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts@@ -10,6 +10,11 @@ vi.mock("@/lib/db", () => ({const mockCreateMessageWithThread = vi.fn()const mockResolveTargetForMember = vi.fn()const mockRequireMessageSurfaceAccess = vi.fn()+const mockGetLatestSeqForScope = vi.fn()+const mockHasDeliverableUnreadForAgentScope = vi.fn()+const mockGetReadState = vi.fn()+const mockFindPendingAttachmentsForSender = vi.fn()+const mockGetCommunityMessageReplay = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -19,14 +24,28 @@ vi.mock("@alook/shared", async () => {...actual.queries,communityAgentInbox: {...actual.queries.communityAgentInbox,+ getLatestSeqForScope: (...args: unknown[]) => mockGetLatestSeqForScope(...args),+ hasDeliverableUnreadForAgentScope: (...args: unknown[]) => mockHasDeliverableUnreadForAgentScope(...args),toAgentMessage: vi.fn(async (_db, row) => ({ id: row.id, content: row.content, seq: row.seq ?? 1 })),},+ communityReadState: {+ ...actual.queries.communityReadState,+ getReadState: (...args: unknown[]) => mockGetReadState(...args),+ },+ communityAttachment: {+ ...actual.queries.communityAttachment,+ findPendingAttachmentsForSender: (...args: unknown[]) => mockFindPendingAttachmentsForSender(...args),+ },},}})vi.mock("@/lib/community/resolve-ref", () => ({ resolveTargetForMember: (...args: unknown[]) => mockResolveTargetForMember(...args) }))vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))vi.mock("@/lib/community/create-channels", () => ({ createMessageWithThread: (...args: unknown[]) => mockCreateMessageWithThread(...args) }))+vi.mock("@/lib/community/message-handler", () => ({+ createCommunityMessage: vi.fn(),+ getCommunityMessageReplay: (...args: unknown[]) => mockGetCommunityMessageReplay(...args),+}))vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(async () => ({ allowed: true })) }))vi.mock("@/lib/middleware/community-actor", () => ({withCommunityActor: (handler: any) => async (req: any, ctx?: any) => handler(req, {@@ -66,6 +85,11 @@ describe("forum sends open a thread through the canonical message route", () =>attachments: [],thread: { id: "thread_1" },})+ mockGetCommunityMessageReplay.mockResolvedValue(null)+ mockGetLatestSeqForScope.mockResolvedValue(4)+ mockGetReadState.mockResolvedValue({ lastReadSeq: 4 })+ mockHasDeliverableUnreadForAgentScope.mockResolvedValue(false)+ mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "attachment_1" }])})it("creates only the opener and structural child thread", async () => {@@ -79,6 +103,7 @@ describe("forum sends open a thread through the canonical message route", () =>body: { content: "Title" },pendingAttachmentIdsToRebind: [],clientNonce: "command:opener",+ expectedSeq: 4,}))expect(await response.json()).toEqual(expect.objectContaining({ state: "sent", threadId: "thread_1" }))})@@ -88,11 +113,14 @@ describe("forum sends open a thread through the canonical message route", () =>expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({pendingAttachmentIdsToRebind: ["attachment_1"],- attachmentIds: undefined,}))})it("accepts a deduped opener replay without a pending-attachment precheck", async () => {+ mockGetCommunityMessageReplay.mockResolvedValueOnce({+ row: { id: "message_1", content: "Title", seq: 5 },+ attachments: [],+ })mockCreateMessageWithThread.mockResolvedValueOnce({ok: true,deduped: true,@@ -105,6 +133,51 @@ describe("forum sends open a thread through the canonical message route", () =>expect(response.status).toBe(200)expect(await response.json()).toEqual(expect.objectContaining({ deduped: true, threadId: "thread_1" }))+ expect(mockGetLatestSeqForScope).not.toHaveBeenCalled()+ expect(mockHasDeliverableUnreadForAgentScope).not.toHaveBeenCalled()+ expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()+ })++ it("blocks an unread forum parent before opener or attachment side effects", async () => {+ mockGetLatestSeqForScope.mockResolvedValueOnce(5)+ mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 4 })+ mockHasDeliverableUnreadForAgentScope.mockResolvedValueOnce(true)++ const response = await POST(request({+ channel: "/demo/forum",+ content: { text: "Blind post" },+ attachments: ["attachment_1"],+ }), ctx)++ expect(await response.json()).toEqual({+ state: "blocked",+ reason: "unaligned",+ unreadCount: 1,+ latestSeq: 5,+ })+ expect(mockCreateMessageWithThread).not.toHaveBeenCalled()+ expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()+ })++ it("returns the fresh forum waterline when the opener loses the seq CAS", async () => {+ mockGetLatestSeqForScope+ .mockResolvedValueOnce(4)+ .mockResolvedValueOnce(5)+ mockCreateMessageWithThread.mockResolvedValueOnce({+ ok: false,+ status: 409,+ error: "seq_conflict",+ })++ const response = await POST(request({ channel: "/demo/forum", content: { text: "Lost race" } }), ctx)++ expect(await response.json()).toEqual({+ state: "blocked",+ reason: "unaligned",+ unreadCount: 1,+ latestSeq: 5,+ })+ expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({ expectedSeq: 4 }))})it("does not open a nested thread for an ordinary thread target", async () => {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.tsindex e263366dd..6c68a1fd9 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@@ -343,43 +343,19 @@ async function handleBotSend(}const target = resolved.value.targetconst channelId = target.channelId-- // Sending into a forum's top level always opens a thread on the opener- // message — a forum is a browsable topic list, so every message landing- // there needs its own thread the same way a post always did. This branches- // on the TARGET's resolved kind (set by resolveMessageTarget from the- // channel's own stored type), never on a body field's presence — a forum- // message always gets this treatment regardless of what fields the client- // happened to send, and a plain channel/thread/DM never does regardless of- // what fields it sends either. A thread can't nest another thread and a DM- // has no thread axis, which is- // exactly why this path is only reachable when the target's kind is- // "forum". No alignment/hasUnread gate on this branch — opening a- // brand-new thread is a fresh scope with no seq contention to align- // against.- if (target.kind === "forum") {- const created = await createMessageWithThread({+ const createForumOpener = (serverId: string, expectedSeq?: number) =>+ createMessageWithThread({db,authorId: botUserId,authorKind: "bot",parentChannelId: channelId,- serverId: target.serverId,+ serverId,body: { content: body.content.text },- attachmentIds: undefined,pendingAttachmentIdsToRebind: body.attachments,clientNonce: body.nonce,+ ...(expectedSeq !== undefined ? { expectedSeq } : {}),source: "cli",})- if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })- const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)- return NextResponse.json({- state: "sent",- message,- threadId: created.thread.id,- deduped: created.deduped,- })- }-const replay = await getCommunityMessageReplay({db,@@ -388,6 +364,17 @@ async function handleBotSend(clientNonce: body.nonce,})if (replay) {+ if (target.kind === "forum") {+ const created = await createForumOpener(target.serverId)+ if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })+ const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)+ return NextResponse.json({+ state: "sent",+ message,+ threadId: created.thread.id,+ deduped: created.deduped,+ })+ }const orderedAttachments = replay.attachments.map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))const message = await queries.communityAgentInbox.toAgentMessage(db, replay.row, botUserId, orderedAttachments)return NextResponse.json({ state: "sent", message, deduped: true })@@ -440,6 +427,32 @@ async function handleBotSend(}}+ if (target.kind === "forum") {+ const created = await createForumOpener(target.serverId, latestSeq)+ if (!created.ok) {+ if (created.status === 409) {+ const freshLatestSeq = await withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),+ { route: "community/messages:forum-fresh-latest-seq" },+ )+ return NextResponse.json({+ state: "blocked",+ reason: "unaligned",+ unreadCount: Math.max(0, freshLatestSeq - seen),+ latestSeq: freshLatestSeq,+ })+ }+ return NextResponse.json({ error: created.error }, { status: created.status })+ }+ const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)+ return NextResponse.json({+ state: "sent",+ message,+ threadId: created.thread.id,+ deduped: created.deduped,+ })+ }+let replyToId: string | undefinedif (body.replyToSeq !== undefined) {const replyTarget = await withD1Retry(diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.tsindex 2ce4197e6..949d1a1e9 100644--- a/src/web/src/lib/community/create-channels.test.ts+++ b/src/web/src/lib/community/create-channels.test.ts@@ -321,6 +321,26 @@ describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensatexpect(mockCreateChannel).not.toHaveBeenCalled()})+ it("forwards the parent expectedSeq and leaves no thread side effects when the opener loses the CAS", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 409, error: "seq_conflict" })++ const res = await createMessageWithThread({+ db: {} as any,+ authorId: "bot_1",+ authorKind: "bot",+ parentChannelId: "forum_1",+ serverId: "s1",+ body: { content: "lost race" },+ expectedSeq: 9,+ })++ expect(res).toEqual({ ok: false, status: 409, error: "seq_conflict" })+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(expect.objectContaining({ expectedSeq: 9 }))+ expect(mockCreateChannel).not.toHaveBeenCalled()+ expect(mockAddThreadParticipants).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })+it("compensates with hardDeleteMessage when the thread-open throws unrecoverably (no orphan message left behind)", async () => {mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })mockCreateChannel.mockRejectedValue(new Error("D1 outage"))diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.tsindex 59d1cfd7c..cf06f41a8 100644--- a/src/web/src/lib/community/create-channels.ts+++ b/src/web/src/lib/community/create-channels.ts@@ -327,6 +327,7 @@ export async function createMessageWithThread(params: {attachmentIds?: string[]pendingAttachmentIdsToRebind?: string[]clientNonce?: string+ expectedSeq?: numbersource?: "cli" | "daemon-http" | "web"}): Promise<CreateMessageWithThreadResult> {const { db, authorId, parentChannelId, serverId } = params@@ -340,6 +341,7 @@ export async function createMessageWithThread(params: {source: params.source,attachmentIds: params.attachmentIds,clientNonce: params.clientNonce,+ expectedSeq: params.expectedSeq,suppressBroadcast: params.suppressBroadcast,deferBroadcast: true,})