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(shared): cap agent inbox unread query binds (#602)
Generd3430b28b4c4
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 86462982e..f387532f7 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -453,29 +453,52 @@ describe("message send --reply", () => {});describe("inbox pull", () => {- it("never acks a rejected pull and only advances the returned cursor after repair", async () => {+ it("never partially acks a non-JSON 500 and advances the rich batch once after repair", async () => {const ackSpy = vi.fn(async (req: { cursors: Array<{ channel: string; seq: number }> }) => ({ok: true, applied: req.cursors, failed: [],}));const pullSpy = vi.fn()- .mockRejectedValueOnce(new Error("DM peer identity unavailable"))+ .mockRejectedValueOnce(new Error("upstream returned 500 with non-JSON body during inboxPull")).mockResolvedValueOnce({- messages: [{ seq: "#7", channel: "/.dm/Bob#0042", sender: "@Alice#1234", content: { text: "still owed" }, time: "" }],+ messages: [+ {+ seq: "#152",+ channel: "/.dm/Alice#0042",+ sender: "@Alice#0042",+ content: {+ text: "see attached",+ replyTo: { seq: "#147", sender: "@Alice#0042" },+ attachments: [{ id: "att_1", filename: "proof.png", contentType: "image/png", size: 12544 }],+ },+ time: "",+ },+ { seq: "#3", channel: "/Demo#1234/support/#29", sender: "@Bob#0043", content: { text: "thread update" }, time: "" },+ { seq: "#29", channel: "/Demo#1234/support", sender: "@Bob#0043", content: { text: "forum title" }, time: "" },+ ],hasMore: false,markedCount: 0,});setApiForTesting(stubApi({ inboxPull: pullSpy, ack: ackSpy }));await main(["inbox", "pull"]);- expect(parseEnvelope(cap.lines()).error).toContain("DM peer identity unavailable");+ expect(parseEnvelope(cap.lines()).error).toContain("upstream returned 500 with non-JSON body during inboxPull");expect(ackSpy).not.toHaveBeenCalled();cap.lines().length = 0;await main(["inbox", "pull"]);+ const repaired = parseEnvelope(cap.lines()) as { success: { messages: Array<{ content: Record<string, unknown> }> } };+ expect(repaired.success.messages[0]!.content).toMatchObject({+ replyTo: { seq: "#147", sender: "@Alice#0042" },+ attachments: [{ id: "att_1", filename: "proof.png" }],+ });expect(ackSpy).toHaveBeenCalledOnce();expect(ackSpy).toHaveBeenCalledWith({agentId: expect.any(String),- cursors: [{ channel: "/.dm/Bob#0042", seq: 7 }],+ cursors: [+ { channel: "/.dm/Alice#0042", seq: 152 },+ { channel: "/Demo#1234/support/#29", seq: 3 },+ { channel: "/Demo#1234/support", seq: 29 },+ ],});});diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex b475a1fff..83fbbc4a3 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -431,6 +431,16 @@ describe("createProxyServerApi — inbox trinity pull/snapshot/ack (retargeted texpect(body.agentId).toBeUndefined();});+ it("inboxPull surfaces an upstream empty 500 as the stable non-JSON error", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });++ await expect(api.inboxPull({ agentId: "a1" as never, max: 1 })).rejects.toThrow(+ "upstream returned 500 with non-JSON body during inboxPull",+ );+ expect(fetchImpl).toHaveBeenCalledOnce();+ });+it("inboxSnapshot GETs users/me/inbox/snapshot (pure peek, no body)", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex d9c491b31..3119d97b9 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -37,7 +37,7 @@ import { listDmChannelIdsForUser } from "./dm";import { listParticipatingThreadIds } from "./thread";import { getMessagesByIdsInScope, type MessageScope } from "./message";import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";-import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { chunk, D1_MAX_IN_PARAMS, maxInParams } from "../_chunk";import { withD1Retry } from "../../resilience";import { hasDirectMentionSql, notificationEligibleSql } from "./notification-eligibility";@@ -572,6 +572,13 @@ export async function listUnreadMessagesForAgent();if (allowedChannelIds.length === 0) return [];+ // Besides the dynamic channel ids, the unread statement emits 13 fixed+ // bindings (viewer predicates, notification-policy literals, and LIMIT).+ // The generic 90-id cap therefore produces 103 bindings exactly when an+ // agent reaches 90 allowed scopes. Give this query its own exact budget so+ // every chunk stays within D1's hard 100-parameter ceiling.+ const unreadChannelChunkSize = maxInParams(13);+// D1 caps a statement at 100 bound params, and `allowedChannelIds` is// unbounded (a bot allowed into >100 channels). Chunk the `inArray` and merge:// each chunk runs the SAME order+limit; since chunks partition channel ids,@@ -631,7 +638,7 @@ export async function listUnreadMessagesForAgent(.limit(opts.max);const merged = (- await Promise.all(chunk(allowedChannelIds, D1_MAX_IN_PARAMS).map(runChunk))+ await Promise.all(chunk(allowedChannelIds, unreadChannelChunkSize).map(runChunk))).flat();merged.sort((a, b) =>a.channelId === b.channelIddiff --git a/src/shared/test/queries/param-limit.test.ts b/src/shared/test/queries/param-limit.test.tsindex 06429aed6..8eaa3eb7b 100644--- a/src/shared/test/queries/param-limit.test.ts+++ b/src/shared/test/queries/param-limit.test.ts@@ -9,6 +9,7 @@ import {import * as mentionQueries from "../../src/db/queries/community/mention";import * as attachmentQueries from "../../src/db/queries/community/attachment";import * as inboxQueries from "../../src/db/queries/community/inbox";+import * as agentInboxQueries from "../../src/db/queries/community/agent-inbox";import * as readStateQueries from "../../src/db/queries/community/read-state";import * as channelQueries from "../../src/db/queries/community/channel";import * as categoryQueries from "../../src/db/queries/community/category";@@ -215,6 +216,29 @@ describe("listEligibleUnreadChannels bound parameters", () => {});});+describe("listUnreadMessagesForAgent bound parameters", () => {+ it("90 allowed channels split at the query's 13-fixed-bind budget", async () => {+ const channelIds = Array.from({ length: 90 }, (_, index) => `channel_${index}`);+ const typeRows = channelIds.map((id) => [id, "text"]);+ const { db, statements } = makeD1Capture([typeRows, [], []]);++ await expect(+ agentInboxQueries.listUnreadMessagesForAgent(db as never, "user_1", {+ max: 2,+ visibleChannelIds: channelIds,+ }),+ ).resolves.toEqual([]);++ expect(statements.map(({ params }) => params.filter(+ (value) => typeof value === "string" && value.startsWith("channel_"),+ ).length)).toEqual([90, 87, 3]);+ expect(statements.map(({ params }) => params.length)).toEqual([90, 100, 16]);+ for (const { params } of statements) {+ expect(params.length).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);+ }+ });+});+describe("mark-all-read revision guard bound parameters", () => {function buildGuard(targetCount: number) {const targets = Array.from({ length: targetCount }, (_, index) => ({diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.test.tsindex b3a97f705..d135bb09d 100644--- a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts@@ -104,6 +104,63 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"expect(body.messages).toHaveLength(2)})+ it("preserves a rich cross-surface batch with DM replyTo and attachments", async () => {+ const rows = [+ { id: "m_dm", channelId: "dm_1", seq: 152, replyToId: "m_dm_earlier" },+ { id: "m_thread", channelId: "thread_1", seq: 3, replyToId: null },+ { id: "m_forum", channelId: "forum_1", seq: 29, replyToId: null },+ ]+ const messages = [+ {+ seq: "#152",+ channel: "/.dm/Alice#0042",+ sender: "@Alice#0042",+ content: {+ text: "see attached",+ replyTo: { seq: "#147", sender: "@Alice#0042" },+ attachments: [{ id: "att_1", filename: "proof.png", contentType: "image/png", size: 12544 }],+ },+ time: "2026-08-28T09:34:14.873Z",+ },+ {+ seq: "#3",+ channel: "/Demo#1234/support/#29",+ sender: "@Bob#0043",+ content: { text: "thread update" },+ time: "2026-08-28T09:47:02.247Z",+ },+ {+ seq: "#29",+ channel: "/Demo#1234/support",+ sender: "@Bob#0043",+ content: { text: "forum title" },+ hint: "This is a forum post, please reply in /Demo#1234/support/#29.",+ time: "2026-08-28T09:47:45.404Z",+ },+ ]+ mockListUnreadMessagesForAgent.mockResolvedValue(rows)+ mockListByMessageIds.mockResolvedValue([{+ id: "att_1",+ messageId: "m_dm",+ filename: "proof.png",+ contentType: "image/png",+ size: 12544,+ }])+ mockToAgentMessages.mockResolvedValue(messages)++ const res = await POST(req(JSON.stringify({ max: 3 }), { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toEqual({ messages, hasMore: false, markedCount: 0 })+ expect(mockListByMessageIds).toHaveBeenCalledWith(expect.anything(), ["m_dm", "m_thread", "m_forum"])+ const attachments = mockToAgentMessages.mock.calls[0]![3] as Map<string, unknown>+ expect([...attachments.entries()]).toEqual([["m_dm", [{+ id: "att_1",+ filename: "proof.png",+ contentType: "image/png",+ size: 12544,+ }]]])+ })+it("returns the numeric markedCount in the HTTP response unchanged", async () => {mockListUnreadMessagesForAgent.mockResolvedValue([])mockCountMarksForUser.mockResolvedValue(3)