Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): ack per-cursor tolerance — one bad cursor no longer wedges the batch

Simoneebb8772e681d
diff --git a/src/web/src/app/api/community/agent/ack/route.test.ts b/src/web/src/app/api/community/agent/ack/route.test.ts
index 34271d4f5..185a874c5 100644
--- a/src/web/src/app/api/community/agent/ack/route.test.ts
+++ b/src/web/src/app/api/community/agent/ack/route.test.ts
@@ -91,39 +91,111 @@ describe("POST /api/community/agent/ack", () => {
const res = await POST(
req({ cursors: [{ channel: "/studio/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" })
)
- expect(res.status).toBe(404)
+ // Best-effort: an unresolvable cursor is reported in `failed`, not a
+ // request-level error. Still never bumps (nothing resolved).
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(false)
+ expect(body.applied).toEqual([])
+ expect(body.failed).toEqual([
+ { channel: "/studio/general", seq: 3, code: "unresolvable", error: expect.any(String) },
+ ])
expect(mockBumpReadCursor).not.toHaveBeenCalled()
})
- it("404 when bumpReadCursor can't find that seq in the channel", async () => {
+ it("reports no_such_seq in failed[] (not a request error) when bumpReadCursor can't find that seq", async () => {
mockBumpReadCursor.mockResolvedValue(null)
const res = await POST(
req({ cursors: [{ channel: "/studio/general", seq: 99 }] }, { Authorization: "Bearer crk_abc" })
)
- expect(res.status).toBe(404)
- expect((await res.json()).error).toMatch(/no message with seq #99/)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(false)
+ expect(body.applied).toEqual([])
+ expect(body.failed[0]).toMatchObject({ channel: "/studio/general", seq: 99, code: "no_such_seq" })
+ expect(body.failed[0].error).toMatch(/no message with seq #99/)
})
- it("fails fast on the first bad cursor, never processing the rest", async () => {
+ it("REGRESSION (the wedge): a bad cursor never stalls the good cursors behind it — good ones still apply and advance", async () => {
+ // First cursor is a good top-level channel; SECOND resolves fine but its
+ // channel doesn't resolve back (forum_post-style poison ref); THIRD is a
+ // good DM. Under the old fail-fast this returned 404 and the DM after the
+ // poison cursor never bumped — the exact mechanism that muted the bot.
mockResolveChannelByNameForMember
- .mockResolvedValueOnce([{ id: "ch_1" }])
- .mockResolvedValueOnce([]) // second cursor's channel doesn't resolve
- mockBumpReadCursor.mockResolvedValue({ id: "m_1", createdAt: "t", seq: 3 })
+ .mockResolvedValueOnce([{ id: "ch_1" }]) // /studio/general → ok
+ .mockResolvedValueOnce([]) // /studio/badpost → unresolvable
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
+ mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>
+ Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })
+ )
+ mockGetDMBetween.mockResolvedValue({ id: "dm_1" })
+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })
+ mockIsBlocked.mockResolvedValue(false)
+ mockBumpReadCursor.mockResolvedValue({ id: "m_1", createdAt: "t", seq: 1 })
const res = await POST(
req(
{
cursors: [
{ channel: "/studio/general", seq: 3 },
- { channel: "/studio/missing", seq: 1 },
+ { channel: "/studio/badpost", seq: 5 },
+ { channel: "/.dm/peer#0001", seq: 1 },
],
},
{ Authorization: "Bearer crk_abc" }
)
)
- expect(res.status).toBe(404)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(false)
+ // Both good cursors applied AND bumped — despite the poison cursor between them.
+ expect(body.applied).toEqual([
+ { channel: "/studio/general", seq: 3 },
+ { channel: "/.dm/peer#0001", seq: 1 },
+ ])
+ expect(body.failed).toEqual([
+ { channel: "/studio/badpost", seq: 5, code: "unresolvable", error: expect.any(String) },
+ ])
+ expect(mockBumpReadCursor).toHaveBeenCalledTimes(2)
+ expect(mockBumpReadCursor).toHaveBeenNthCalledWith(1, expect.anything(), "bot_1", { channelId: "ch_1" }, 3)
+ expect(mockBumpReadCursor).toHaveBeenNthCalledWith(2, expect.anything(), "bot_1", { channelId: "dm_1" }, 1)
+ })
+
+ it("reports a forbidden cursor in failed[] while a sibling good cursor still applies", async () => {
+ // First cursor resolves to a channel the bot isn't a member of; second is fine.
+ mockResolveChannelByNameForMember
+ .mockResolvedValueOnce([{ id: "ch_forbidden" }])
+ .mockResolvedValueOnce([{ id: "ch_1" }])
+ mockGetChannelForMember
+ .mockResolvedValueOnce(null) // not a member of ch_forbidden → requireChannelMember fails
+ .mockResolvedValueOnce({ id: "ch_1", serverId: "srv_1", parentChannelId: null })
+ mockBumpReadCursor.mockResolvedValue({ id: "m_1", createdAt: "t", seq: 2 })
+ const res = await POST(
+ req(
+ {
+ cursors: [
+ { channel: "/studio/secret", seq: 7 },
+ { channel: "/studio/general", seq: 2 },
+ ],
+ },
+ { Authorization: "Bearer crk_abc" }
+ )
+ )
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(false)
+ expect(body.applied).toEqual([{ channel: "/studio/general", seq: 2 }])
+ expect(body.failed[0]).toMatchObject({ channel: "/studio/secret", seq: 7, code: "forbidden" })
expect(mockBumpReadCursor).toHaveBeenCalledTimes(1)
})
+ it("propagates a genuine D1 exception as a 500 (never swallowed into failed[])", async () => {
+ mockBumpReadCursor.mockRejectedValue(new Error("D1_ERROR: something non-retryable"))
+ await expect(
+ POST(req({ cursors: [{ channel: "/studio/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" }))
+ ).rejects.toThrow()
+ })
+
it("200 { ok: true } advances the cursor for every scope in the request, channel and DM alike", async () => {
mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>
@@ -146,17 +218,27 @@ describe("POST /api/community/agent/ack", () => {
)
)
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ ok: true })
+ expect(await res.json()).toEqual({
+ ok: true,
+ applied: [
+ { channel: "/studio/general", seq: 3 },
+ { channel: "/.dm/peer#0001", seq: 1 },
+ ],
+ failed: [],
+ })
expect(mockBumpReadCursor).toHaveBeenCalledTimes(2)
expect(mockBumpReadCursor).toHaveBeenNthCalledWith(1, expect.anything(), "bot_1", { channelId: "ch_1" }, 3)
expect(mockBumpReadCursor).toHaveBeenNthCalledWith(2, expect.anything(), "bot_1", { channelId: "dm_1" }, 1)
})
- it("400 invalid DM handle when a cursor's channel segment has no #0042 tag", async () => {
+ it("reports an invalid DM handle in failed[] as unresolvable (not a request error)", async () => {
const res = await POST(
req({ cursors: [{ channel: "/.dm/peer_1", seq: 1 }] }, { Authorization: "Bearer crk_abc" })
)
- expect(res.status).toBe(400)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(false)
+ expect(body.failed[0]).toMatchObject({ channel: "/.dm/peer_1", seq: 1, code: "unresolvable" })
expect(mockBumpReadCursor).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/agent/ack/route.ts b/src/web/src/app/api/community/agent/ack/route.ts
index b7d301b0b..bed6c061c 100644
--- a/src/web/src/app/api/community/agent/ack/route.ts
+++ b/src/web/src/app/api/community/agent/ack/route.ts
@@ -2,7 +2,7 @@ import { NextResponse, type NextRequest } from "next/server"
import { queries, withD1Retry, CommunityAgentAckRequestSchema } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"
-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"
+import { resolveTargetForMember } from "@/lib/community/resolve-ref"
import { isDmTarget } from "@/lib/community/message-handler"
import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
@@ -11,9 +11,17 @@ import { requireChannelMember, requireDMAccess } from "@/lib/community/permissio
* `lastReadSeq` (`inboxPull` never mutates read state — debt #2 correction).
* Each cursor's `channel` ref is resolved read-only (no DM/thread
* auto-create — a stale ref must never materialize a row as a side effect
- * of an ack) and membership-gated before `bumpReadCursor`. Fails fast on
- * the first bad cursor; earlier cursors in the same request have already
- * been durably applied (`bumpReadCursor` is independently atomic per call).
+ * of an ack) and membership-gated before `bumpReadCursor`.
+ *
+ * Best-effort per cursor, NOT fail-fast: every good cursor is applied and its
+ * waterline advanced regardless of any sibling cursor failing. A single
+ * unresolvable cursor (e.g. a forum_post whose ref can't parse back) must
+ * never stall the healthy cursors behind it — that regressed their waterlines
+ * and muted the bot in every channel with unread. Bad cursors are collected
+ * into `failed[]` with a coarse `code`; the response is ALWAYS 200 (partial
+ * success is not a request-level error — the good cursors DID apply, and the
+ * daemon must not treat the whole call as failed). Only a genuine D1 exception
+ * escaping `withD1Retry` propagates as a 500 so the daemon retries the batch.
*/
export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
@@ -29,38 +37,57 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })
}
+ const applied: Array<{ channel: string; seq: number }> = []
+ const failed: Array<{ channel: string; seq: number; code: "unresolvable" | "forbidden" | "no_such_seq"; error: string }> = []
+
for (const cursor of parsed.data.cursors) {
const resolved = await resolveTargetForMember(db, ctx.botUserId, cursor.channel, {
createDmIfMissing: false,
createThreadIfMissing: false,
callerKind: "bot",
})
- if ("error" in resolved) return resolveErrorResponse(resolved)
+ if ("error" in resolved) {
+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "unresolvable", error: resolved.message })
+ continue
+ }
const scopeTarget = { channelId: resolved.channelId }
if (isDmTarget(resolved)) {
const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)
- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
+ if (!gate.ok) {
+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "forbidden", error: gate.error })
+ continue
+ }
} else {
const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)
- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
+ if (!gate.ok) {
+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "forbidden", error: gate.error })
+ continue
+ }
}
// Idempotent write — safe to retry a transient D1 blip (same treatment as
- // the human-facing routes). A real "no such seq" is a structured `false`
- // return below, not a thrown error, so it is never retried.
+ // the human-facing routes). A real "no such seq" is a structured `null`
+ // return below, not a thrown error, so it is never retried. A genuine D1
+ // exception escaping withD1Retry is NOT caught here — it propagates as a
+ // 500 so the daemon retries the whole batch (never swallow infra failures
+ // into `failed`).
const bumped = await withD1Retry(
() => queries.communityReadState.bumpReadCursor(db, ctx.botUserId, scopeTarget, cursor.seq),
{ route: "community/agent/ack:bump" },
)
if (!bumped) {
- return NextResponse.json(
- { error: `no message with seq #${cursor.seq} in ${cursor.channel}` },
- { status: 404 }
- )
+ failed.push({
+ channel: cursor.channel,
+ seq: cursor.seq,
+ code: "no_such_seq",
+ error: `no message with seq #${cursor.seq} in ${cursor.channel}`,
+ })
+ continue
}
+ applied.push({ channel: cursor.channel, seq: cursor.seq })
}
- return NextResponse.json({ ok: true })
+ return NextResponse.json({ ok: failed.length === 0, applied, failed })
})