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(c): harden attachment pipeline — empty-body 500s, rollback correctness, capability wiring
Gus6ed796aef8ee
diff --git a/.gitignore b/.gitignoreindex 825a3d731..885a0830e 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,4 @@+.alook-qa-scratch/node_modules/.pnpm-store/dist/diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsnew file mode 100644index 000000000..064c40623--- /dev/null+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -0,0 +1,158 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import * as fs from "fs";+import * as os from "os";+import * as path from "path";+import { createProxyServerApi } from "./proxyServerApi";++// Helpers for the mocked fetch — build a Response-shaped object that only+// implements what parseJsonResponse touches. Using the real Response class+// makes it hard to simulate an empty body distinct from JSON `"null"`, so a+// hand-rolled stub matches the code path more faithfully.+type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;+function jsonBody(body: string, init: { status?: number; ok?: boolean; headers?: Record<string, string> } = {}): Response {+ const status = init.status ?? 200;+ const ok = init.ok ?? (status >= 200 && status < 300);+ return {+ ok,+ status,+ headers: new Headers(init.headers ?? {}),+ text: async () => body,+ arrayBuffer: async () => new TextEncoder().encode(body).buffer,+ } as unknown as Response;+}+function textThrowingResponse(status: number, cause: string): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: new Headers(),+ text: async () => {+ throw new TypeError(cause);+ },+ } as unknown as Response;+}+function bufferResponse(bytes: Uint8Array, headers: Record<string, string> = {}): Response {+ return {+ ok: true,+ status: 200,+ headers: new Headers(headers),+ arrayBuffer: async () => bytes.buffer,+ text: async () => "",+ } as unknown as Response;+}++const cfg = { proxyUrl: "http://proxy.test", voucher: "vch_test" };++describe("createProxyServerApi — parseJsonResponse via call<T>", () => {+ it("throws structured 'non-JSON body' on empty 500", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(+ /upstream returned 500 with non-JSON body from \/api\/listServers/,+ );+ });++ it("returns undefined on empty 200 (void endpoint like ack)", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 200 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.ack({ agentId: "a1", messageIds: [] } as never);+ expect(out).toBeUndefined();+ });++ it("returns undefined on 204 (empty successful body)", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 204 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.ack({ agentId: "a1", messageIds: [] } as never);+ expect(out).toBeUndefined();+ });++ it("throws 'non-JSON body' on truncated HTML 502", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("<html>bad gateway", { status: 502 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(+ /upstream returned 502 with non-JSON body from \/api\/listServers/,+ );+ });++ it("throws 'body read failed' when res.text() rejects mid-read", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => textThrowingResponse(500, "terminated"));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(+ /upstream body read failed from \/api\/listServers \(500\): terminated/,+ );+ });++ it("preserves .code and .hint from a structured error body on non-2xx", async () => {+ const fetchImpl: FetchLike = vi.fn(async () =>+ jsonBody(JSON.stringify({ error: "not allowed", code: "forbidden", hint: "check owner" }), { status: 403 }),+ );+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ try {+ await api.listServers({ agentId: "a1" as never });+ throw new Error("should have thrown");+ } catch (err) {+ expect((err as Error).message).toBe("not allowed");+ expect((err as { code?: string }).code).toBe("forbidden");+ expect((err as { hint?: string }).hint).toBe("check owner");+ }+ });++ it("returns parsed JSON on 2xx", async () => {+ const fetchImpl: FetchLike = vi.fn(async () =>+ jsonBody(JSON.stringify({ servers: [{ id: "srv_1" }] }), { status: 200 }),+ );+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.listServers({ agentId: "a1" as never });+ expect(out).toEqual({ servers: [{ id: "srv_1" }] });+ });+});++describe("createProxyServerApi — callUpload via parseJsonResponse", () => {+ it("throws 'non-JSON body' on empty 500", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await expect(+ api.attachmentUpload({+ agentId: "a1",+ target: "/c/s/g",+ file: { data: new Uint8Array([1, 2, 3]), filename: "x.png", contentType: "image/png" },+ } as never),+ ).rejects.toThrow(/upstream returned 500 with non-JSON body from \/api\/attachmentUpload/);+ });+});++describe("createProxyServerApi — callDownload", () => {+ let tmp: string;+ beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pxdl-"));+ });+ afterEach(() => {+ fs.rmSync(tmp, { recursive: true, force: true });+ });++ it("routes empty-500 error branch through parseJsonResponse", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await expect(+ api.attachmentDownload({ agentId: "a1", id: "att_1", destPath: path.join(tmp, "out.bin") } as never),+ ).rejects.toThrow(/upstream returned 500 with non-JSON body from \/api\/attachmentDownload/);+ });++ it("happy path writes the binary body to destPath", async () => {+ const bytes = new Uint8Array([1, 2, 3, 4]);+ const fetchImpl: FetchLike = vi.fn(async () =>+ bufferResponse(bytes, {+ "content-type": "image/png",+ "content-length": String(bytes.length),+ "x-alook-filename": encodeURIComponent("hi.png"),+ }),+ );+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const dest = path.join(tmp, "out.png");+ const out = await api.attachmentDownload({ agentId: "a1", id: "att_1", destPath: dest } as never);+ expect(out.path).toBe(dest);+ expect(out.filename).toBe("hi.png");+ expect(out.contentType).toBe("image/png");+ expect(out.size).toBe(bytes.length);+ expect(fs.readFileSync(dest)).toEqual(Buffer.from(bytes));+ });+});diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 6c7c053a6..c56c9ba4e 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -68,6 +68,46 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {const fetchImpl = config.fetchImpl ?? fetch;const base = config.proxyUrl.replace(/\/+$/, "");+ // Empty body + res.ok → undefined (204 / empty-200 like `ack`).+ // Empty body + !res.ok → structured "upstream ... non-JSON body" (the empty-500 class).+ // Non-empty non-JSON → same non-JSON message (truncated HTML 502 is "upstream broken", not client bug).+ // JSON parse: res.ok → parsed T; !res.ok → Error with .code/.hint from the structured error body.+ // res.text() throwing (RST after headers, TypeError: terminated) → surfaces as+ // "upstream body read failed" so callers see a meaningful message instead of+ // the bare TypeError.+ async function parseJsonResponse<T>(res: Response, method: string): Promise<T> {+ let text: string;+ try {+ text = await res.text();+ } catch (err) {+ const cause = err instanceof Error ? err.message : String(err);+ throw new Error(`upstream body read failed from /api/${method} (${res.status}): ${cause}`);+ }+ if (text.length === 0) {+ if (res.ok) return undefined as T;+ throw new Error(`upstream returned ${res.status} with non-JSON body from /api/${method}`);+ }+ let json: (T & { error?: string; code?: string; hint?: string }) | undefined;+ try {+ json = JSON.parse(text) as T & { error?: string; code?: string; hint?: string };+ } catch {+ throw new Error(`upstream returned ${res.status} with non-JSON body from /api/${method}`);+ }+ if (!res.ok) {+ const e = new Error(json?.error ?? `proxy api/${method} failed (${res.status})`);+ // Only attach when present — assigning `undefined` would leave an own+ // property that trips `"code" in err` / `hasOwnProperty` checks in+ // callers that use those as feature-tests.+ if (json?.code !== undefined) (e as { code?: string }).code = json.code;+ // Copy `hint` onto the thrown Error the same way `.code` is copied —+ // without this the owner-mismatch hint never leaves this file (see+ // plan's "Hint propagation" note).+ if (json?.hint !== undefined) (e as { hint?: string }).hint = json.hint;+ throw e;+ }+ return json as T;+ }+async function call<T>(method: string, body: unknown): Promise<T> {// Strip any agentId from the wire body: identity travels ONLY as the voucher,// which the proxy turns into a trusted X-Agent-Id the bridge injects. Sending@@ -82,17 +122,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {},body: JSON.stringify(wire),});- const json = (await res.json()) as T & { error?: string; code?: string; hint?: string };- if (!res.ok) {- const e = new Error(json?.error ?? `proxy api/${method} failed (${res.status})`);- (e as { code?: string }).code = json?.code;- // Copy `hint` onto the thrown Error the same way `.code` is copied —- // without this the owner-mismatch hint never leaves this file (see- // plan's "Hint propagation" note).- (e as { hint?: string }).hint = json?.hint;- throw e;- }- return json;+ return parseJsonResponse<T>(res, method);}async function callUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult> {@@ -111,13 +141,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {headers: { authorization: `Bearer ${config.voucher}` },body: form,});- const json = (await res.json()) as AgentAttachmentUploadResult & { error?: string; code?: string };- if (!res.ok) {- const e = new Error(json?.error ?? `proxy api/attachmentUpload failed (${res.status})`);- (e as { code?: string }).code = json?.code;- throw e;- }- return json;+ return parseJsonResponse<AgentAttachmentUploadResult>(res, "attachmentUpload");}async function callDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult> {@@ -131,10 +155,12 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {});if (!res.ok) {// Error responses ARE JSON. Streaming success responses are binary.- const body = (await res.json().catch(() => ({}))) as { error?: string; code?: string };- const e = new Error(body?.error ?? `proxy api/attachmentDownload failed (${res.status})`);- (e as { code?: string }).code = body?.code;- throw e;+ // Route through the shared helper so empty/HTML-502/read-fail all+ // surface as the same "upstream ..." message the other calls use.+ // parseJsonResponse ALWAYS throws when `!res.ok` (empty→non-JSON msg,+ // parse-fail→non-JSON msg, structured JSON→Error carrying .code/.hint).+ await parseJsonResponse<never>(res, "attachmentDownload");+ throw new Error("unreachable: parseJsonResponse must throw on !res.ok");}const encoded = res.headers.get("x-alook-filename");const filename = encoded ? decodeURIComponent(encoded) : path.basename(req.destPath);diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.tsindex 40f17510e..45cc219c6 100644--- a/src/daemon/src/drivers/cliTransport.test.ts+++ b/src/daemon/src/drivers/cliTransport.test.ts@@ -44,6 +44,57 @@ describe("prepareCliTransport — layered spawn env", () => {await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(/credentialProxy is required/);});+ it("throws a legible error when credentialProxy.capabilities is undefined (wiring bug)", async () => {+ const ctx = baseCtx(mkTmp(), {+ credentialProxy: {+ broker: broker(),+ proxyUrl: "http://127.0.0.1:9/proxy",+ runnerKey: "sk_agent_test",+ } as unknown as LaunchContext["credentialProxy"],+ });+ await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(+ /credentialProxy\.capabilities is required/,+ );+ });++ it("throws when a capability entry contains a comma (would silently widen scope)", async () => {+ const ctx = baseCtx(mkTmp(), {+ credentialProxy: {+ broker: broker(),+ proxyUrl: "http://127.0.0.1:9/proxy",+ runnerKey: "sk_agent_test",+ capabilities: ["send,read"],+ },+ });+ await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(+ /contains a comma/,+ );+ });++ it("accepts an empty capabilities array (legitimate zero-capability launch)", async () => {+ const cred = broker();+ const { spawnEnv, tokenFile } = await prepareCliTransport(+ baseCtx(mkTmp(), {+ credentialProxy: {+ broker: cred,+ proxyUrl: "http://127.0.0.1:9/proxy",+ runnerKey: "sk_agent_test",+ capabilities: [],+ },+ }),+ {},+ undefined,+ "linux",+ );+ // capabilities.join(",") on an empty array = "" → the env var is present+ // but empty, and the proxy reads that as "no capabilities granted".+ expect(spawnEnv.ALOOK_ACTIVE_CAPABILITIES).toBe("");+ // The minted voucher must reject every capability check (the Set is empty).+ const voucher = fs.readFileSync(tokenFile, "utf8");+ expect(cred.check(`Bearer ${voucher}`, "send").ok).toBe(false);+ expect(cred.check(`Bearer ${voucher}`, "attach").ok).toBe(false);+ });+it("prepends the per-launch bin dir to PATH", async () => {const wd = mkTmp();const { spawnEnv, stateDir } = await prepareCliTransport(baseCtx(wd), {}, undefined, "linux");diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.tsindex 0e881c3af..6b90dd660 100644--- a/src/daemon/src/drivers/cliTransport.ts+++ b/src/daemon/src/drivers/cliTransport.ts@@ -154,6 +154,29 @@ export async function prepareCliTransport();}const capabilities = ctx.credentialProxy.capabilities;+ // Guard: `capabilities` must be a real array. `undefined` is a caller wiring+ // bug (typically `{} as CredentialProxyHandoff` in a test) — surface it at+ // spawn time instead of crashing later inside `spawnEnv`'s `capabilities.join(",")`+ // with an opaque "Cannot read properties of undefined (reading 'join')". An+ // empty array IS allowed — that's a legitimate zero-capability launch.+ if (!Array.isArray(capabilities)) {+ throw new Error(+ "prepareCliTransport: credentialProxy.capabilities is required " ++ "(empty array is allowed for zero-capability launches; undefined is a wiring bug)",+ );+ }+ // The proxy uses `,` as the sole separator between capabilities on the wire+ // (`spawnEnv.ts` joins with "," and the proxy re-splits on ","). A capability+ // entry containing a comma would silently widen the enforced scope — reject+ // at wiring time so nobody smuggles in "send,attach" as a single token.+ for (const c of capabilities) {+ if (typeof c !== "string" || c.includes(",")) {+ throw new Error(+ `prepareCliTransport: capability entry ${JSON.stringify(c)} contains a comma ` ++ `(each capability must be a single token; use ["send","read"] instead of ["send,read"])`,+ );+ }+ }// Revoke this agent's previous voucher(s) before minting a new one — an// agent has at most one live launch at a time, so this bounds the broker's// registration map to "one live entry per active agent" regardless of howdiff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 8b6d1118b..bd6a7ec00 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -93,13 +93,6 @@ function safeParseEmbeds(raw: string | null, messageId: string): unknown | undef}export type CreateMessageData = {- /**- * Optional pre-minted id — the agent-attachment path (plan- * agent-attachment-pipeline.md §Send) pre-mints this in application code so- * `reserveAttachmentsForMessage` can point at it BEFORE the message row is- * inserted. When absent, the schema's `$defaultFn` fires nanoid at insert- * time, matching the existing human-composer behavior.- */id?: string;authorId: string;content: string;@@ -259,13 +252,115 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb}/**- * Hard-delete a message row by id. Reserved for rollback of a message that- * was written moments before but its dependent row (approval-request, etc.)- * failed to persist. Do NOT use this for user-facing message deletion — that- * path should soft-delete or set a tombstone.+ * Cascading rollback of a message row. Reserved for compensating a message+ * that was written moments before but a follow-up dependency failed to+ * persist (approval-request, attachment reserve, etc.). Do NOT use for+ * user-facing message deletion — that path should soft-delete / tombstone.+ *+ * Reverts everything `insertMessageRow` wrote:+ * 1. DELETE the message row itself.+ * 2. Channel/DM lastMessageAt (recomputed via `MAX(createdAt)` subquery so+ * concurrent inserts keep their timestamps) + `messageCount -= 1` on+ * channel (DM has no counter).+ * 3. Author's `communityReadState` row: if a prior message in scope exists,+ * revert the watermark to it (guarded by `lastReadMessageId = messageId`+ * so a concurrent same-author send that already advanced past our seq+ * keeps its newer state); if this was the first-ever message in scope,+ * DELETE the read-state row entirely so the schema's+ * "materialized ⇒ lastReadMessageId IS NOT NULL" invariant holds — the+ * next send re-inserts through `.onConflictDoUpdate`, and the DELETE+ * completes inside the same batch so no partial-UNIQUE-index collision.+ *+ * Idempotent — if the message is already gone (double-rollback race), the+ * initial SELECT returns nothing and the whole cascade is skipped.*/export async function hardDeleteMessage(db: Database, messageId: string) {- await db.delete(communityMessage).where(eq(communityMessage.id, messageId));+ const msgRows = await db+ .select({+ id: communityMessage.id,+ channelId: communityMessage.channelId,+ dmConversationId: communityMessage.dmConversationId,+ authorId: communityMessage.authorId,+ seq: communityMessage.seq,+ createdAt: communityMessage.createdAt,+ })+ .from(communityMessage)+ .where(eq(communityMessage.id, messageId))+ .limit(1);+ const msg = msgRows[0];+ if (!msg) return;++ // Prior-in-scope message for the read-state revert. Pre-fetched because+ // Drizzle's D1 batch driver serializes each statement independently and+ // cannot pipe one statement's result into another. Safe: the read-state+ // UPDATE in the batch is guarded by `lastReadMessageId = messageId`, so a+ // concurrent same-author advance past our seq keeps its own newer state+ // regardless of what this prior lookup returns.+ const scopeMatch = msg.channelId+ ? eq(communityMessage.channelId, msg.channelId)+ : eq(communityMessage.dmConversationId, msg.dmConversationId!);+ const priorRows = await db+ .select({+ id: communityMessage.id,+ seq: communityMessage.seq,+ createdAt: communityMessage.createdAt,+ })+ .from(communityMessage)+ .where(and(scopeMatch, lt(communityMessage.seq, msg.seq)))+ .orderBy(desc(communityMessage.seq))+ .limit(1);+ const prior = priorRows[0];++ const deleteMsg = db.delete(communityMessage).where(eq(communityMessage.id, messageId));++ // `lastMessageAt` is an INLINE `MAX(createdAt)` subquery — never pre-fetched.+ // A concurrent writer inserting a newer message between our SELECT above and+ // this UPDATE would otherwise get its timestamp clobbered. Same rule for+ // `messageCount - 1`: a JS-side `oldCount - 1` would clobber any concurrent+ // insert that landed between the pre-batch SELECT and this UPDATE.+ const scopeUpdate = msg.channelId+ ? db+ .update(communityChannel)+ .set({+ messageCount: sql`${communityChannel.messageCount} - 1`,+ lastMessageAt: sql<+ string | null+ >`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.channelId} = ${msg.channelId} AND ${communityMessage.id} != ${messageId})`,+ })+ .where(eq(communityChannel.id, msg.channelId))+ : db+ .update(communityDmConversation)+ .set({+ lastMessageAt: sql<+ string | null+ >`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.dmConversationId} = ${msg.dmConversationId} AND ${communityMessage.id} != ${messageId})`,+ })+ .where(eq(communityDmConversation.id, msg.dmConversationId!));++ const readStateWhere = msg.channelId+ ? and(+ eq(communityReadState.userId, msg.authorId),+ eq(communityReadState.channelId, msg.channelId),+ eq(communityReadState.lastReadMessageId, messageId)+ )+ : and(+ eq(communityReadState.userId, msg.authorId),+ eq(communityReadState.dmConversationId, msg.dmConversationId!),+ eq(communityReadState.lastReadMessageId, messageId)+ );++ const readStateStmt = prior+ ? db+ .update(communityReadState)+ .set({+ lastReadMessageId: prior.id,+ lastReadSeq: prior.seq,+ lastReadAt: prior.createdAt,+ })+ .where(readStateWhere)+ : db.delete(communityReadState).where(readStateWhere);++ await db.batch([deleteMsg, scopeUpdate, readStateStmt] as any);}// Shared select projection for the three list-messages paths (`listMessages`,diff --git a/src/shared/test/community-message-hardDelete.test.ts b/src/shared/test/community-message-hardDelete.test.tsnew file mode 100644index 000000000..f48da0035--- /dev/null+++ b/src/shared/test/community-message-hardDelete.test.ts@@ -0,0 +1,195 @@+import { describe, it, expect } from "vitest";+import { getTableName } from "drizzle-orm";+import { queries } from "../src/index";+import type { Database } from "../src/index";++/**+ * Tests for the cascading `hardDeleteMessage`. It:+ * 1. SELECTs the message row (channelId/dmConversationId/authorId/seq/createdAt).+ * 2. SELECTs the prior message in scope (id, seq, createdAt) for the read-state revert.+ * 3. Runs one `db.batch([delete-msg, update-scope, update-or-delete-readstate])`.+ * The batch composition varies by whether the target is a channel/DM and whether+ * a prior message exists.+ */++type SelectShape = "message" | "prior";+type Tag =+ | { kind: "delete-msg" }+ | { kind: "update-channel"; setValues?: Record<string, unknown> }+ | { kind: "update-dm"; setValues?: Record<string, unknown> }+ | { kind: "update-readstate"; setValues?: Record<string, unknown> }+ | { kind: "delete-readstate" };++interface MockState {+ batchCalls: Tag[][];+ selectQueue: Array<{ shape: SelectShape; rows: unknown[] }>;+}++function makeDb(state: MockState): Database {+ const mkBuilder = (tag: Tag) => {+ const b: any = { __tag: tag };+ b.set = (values: Record<string, unknown>) => {+ // Capture the set(...) payload so tests can assert on messageCount /+ // lastMessageAt / lastReadMessageId values, not just batch shape.+ (tag as { setValues?: Record<string, unknown> }).setValues = values;+ return b;+ };+ b.where = () => b;+ b.limit = () => b;+ b.orderBy = () => b;+ return b;+ };++ const db: any = {+ select: () => {+ const b: any = {};+ b.from = () => b;+ b.where = () => b;+ b.orderBy = () => b;+ b.limit = () => {+ const next = state.selectQueue.shift();+ if (!next) throw new Error("unexpected select — selectQueue empty");+ return Promise.resolve(next.rows);+ };+ return b;+ },+ delete: (table: any) => {+ const name = getTableName(table);+ const tag: Tag = name.includes("read_state")+ ? { kind: "delete-readstate" }+ : { kind: "delete-msg" };+ return mkBuilder(tag);+ },+ update: (table: any) => {+ const name = getTableName(table);+ const tag: Tag = name.includes("read_state")+ ? { kind: "update-readstate" }+ : name.includes("dm_conversation")+ ? { kind: "update-dm" }+ : { kind: "update-channel" };+ return mkBuilder(tag);+ },+ batch: (stmts: any[]) => {+ state.batchCalls.push(stmts.map((s) => s.__tag as Tag));+ return Promise.resolve(stmts.map(() => undefined));+ },+ };+ return db as Database;+}++describe("hardDeleteMessage — cascading rollback", () => {+ it("channel + prior message exists → batch(delete-msg, update-channel, update-readstate)", async () => {+ const state: MockState = {+ batchCalls: [],+ selectQueue: [+ {+ shape: "message",+ rows: [+ {+ id: "msg_1",+ channelId: "chan_1",+ dmConversationId: null,+ authorId: "user_1",+ seq: 5,+ createdAt: "2026-01-01T00:00:05Z",+ },+ ],+ },+ {+ shape: "prior",+ rows: [{ id: "msg_0", seq: 4, createdAt: "2026-01-01T00:00:04Z" }],+ },+ ],+ };+ await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");+ expect(state.batchCalls).toHaveLength(1);+ const [del, upChan, upRs] = state.batchCalls[0]!;+ expect(del.kind).toBe("delete-msg");+ expect(upChan.kind).toBe("update-channel");+ expect(upRs.kind).toBe("update-readstate");+ // Regression guard for the plan's "CRITICAL" rule: messageCount must be a+ // SQL fragment / decrement expression, NOT a JS literal like `oldCount - 1`+ // (a concurrent inbound insert between the SELECT and this UPDATE would+ // otherwise get clobbered). Same story for lastMessageAt — must be an+ // inline MAX(createdAt) subquery, never a pre-fetched JS value.+ const chanSet = (upChan as { setValues?: Record<string, unknown> }).setValues!;+ expect(typeof chanSet.messageCount).toBe("object"); // Drizzle SQL fragment+ expect(typeof chanSet.lastMessageAt).toBe("object");+ expect(chanSet.messageCount).not.toBe(0); // not a pre-fetched literal+ // Read-state UPDATE must revert to the prior message's id/seq/createdAt.+ const rsSet = (upRs as { setValues?: Record<string, unknown> }).setValues!;+ expect(rsSet.lastReadMessageId).toBe("msg_0");+ expect(rsSet.lastReadSeq).toBe(4);+ expect(rsSet.lastReadAt).toBe("2026-01-01T00:00:04Z");+ });++ it("channel + NO prior message (first-ever sender) → batch(delete-msg, update-channel, DELETE-readstate)", async () => {+ const state: MockState = {+ batchCalls: [],+ selectQueue: [+ {+ shape: "message",+ rows: [+ {+ id: "msg_1",+ channelId: "chan_1",+ dmConversationId: null,+ authorId: "user_1",+ seq: 1,+ createdAt: "2026-01-01T00:00:01Z",+ },+ ],+ },+ { shape: "prior", rows: [] },+ ],+ };+ await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");+ const kinds = state.batchCalls[0]!.map((t) => t.kind);+ expect(kinds).toEqual(["delete-msg", "update-channel", "delete-readstate"]);+ });++ it("DM + prior message → batch(delete-msg, update-dm, update-readstate) — no messageCount column touched", async () => {+ const state: MockState = {+ batchCalls: [],+ selectQueue: [+ {+ shape: "message",+ rows: [+ {+ id: "msg_1",+ channelId: null,+ dmConversationId: "dm_1",+ authorId: "user_1",+ seq: 3,+ createdAt: "2026-01-01T00:00:03Z",+ },+ ],+ },+ {+ shape: "prior",+ rows: [{ id: "msg_0", seq: 2, createdAt: "2026-01-01T00:00:02Z" }],+ },+ ],+ };+ await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");+ const [, upDm, upRs] = state.batchCalls[0]!;+ const kinds = state.batchCalls[0]!.map((t) => t.kind);+ expect(kinds).toEqual(["delete-msg", "update-dm", "update-readstate"]);+ // DM update must NOT touch messageCount (the DM schema has none).+ const dmSet = (upDm as { setValues?: Record<string, unknown> }).setValues!;+ expect(dmSet).not.toHaveProperty("messageCount");+ expect(typeof dmSet.lastMessageAt).toBe("object"); // inline SQL subquery+ const rsSet = (upRs as { setValues?: Record<string, unknown> }).setValues!;+ expect(rsSet.lastReadMessageId).toBe("msg_0");+ expect(rsSet.lastReadSeq).toBe(2);+ });++ it("idempotent — SELECT returns no rows → no batch call, no throw", async () => {+ const state: MockState = {+ batchCalls: [],+ selectQueue: [{ shape: "message", rows: [] }],+ };+ await queries.communityMessage.hardDeleteMessage(makeDb(state), "missing");+ expect(state.batchCalls).toHaveLength(0);+ });+});diff --git a/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.test.tsindex 5e79cc127..9673a8492 100644--- a/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts@@ -101,7 +101,12 @@ describe("POST /api/community/agent/attachmentDownload", () => {contentType: "image/png",size: 10,})- mockR2Get.mockResolvedValue({ body: new ReadableStream(), size: 10, httpMetadata: {} })+ mockR2Get.mockResolvedValue({+ body: new ReadableStream(),+ size: 10,+ httpMetadata: {},+ arrayBuffer: async () => new ArrayBuffer(10),+ })const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(res.headers.get("Content-Type")).toBe("image/png")@@ -120,7 +125,12 @@ describe("POST /api/community/agent/attachmentDownload", () => {contentType: "image/png",size: 5,})- mockR2Get.mockResolvedValue({ body: new ReadableStream(), size: 5, httpMetadata: {} })+ mockR2Get.mockResolvedValue({+ body: new ReadableStream(),+ size: 5,+ httpMetadata: {},+ arrayBuffer: async () => new ArrayBuffer(5),+ })const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)const encoded = res.headers.get("X-Alook-Filename")@@ -143,6 +153,52 @@ describe("POST /api/community/agent/attachmentDownload", () => {expect(res.status).toBe(502)})+ it("getAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {+ mockGetAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })++ it("COMMUNITY_MEDIA.get throws → 500 JSON envelope", async () => {+ mockGetAttachmentById.mockResolvedValue({+ id: "att_1",+ messageId: null,+ uploaderId: "bot_1",+ r2Key: "channel/c1/uuid/a.png",+ filename: "a.png",+ contentType: "image/png",+ size: 10,+ })+ mockR2Get.mockRejectedValueOnce(new Error("r2_boom"))+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })++ it("obj.arrayBuffer() throws (R2 stream mid-read) → 500 JSON envelope, NOT a truncated 200", async () => {+ mockGetAttachmentById.mockResolvedValue({+ id: "att_1",+ messageId: null,+ uploaderId: "bot_1",+ r2Key: "channel/c1/uuid/a.png",+ filename: "a.png",+ contentType: "image/png",+ size: 10,+ })+ mockR2Get.mockResolvedValue({+ body: new ReadableStream(),+ size: 10,+ httpMetadata: {},+ arrayBuffer: async () => {+ throw new Error("stream_error")+ },+ })+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })+it("404 when a persisted row's channel-member gate fails — same shape as genuine 404", async () => {mockGetAttachmentById.mockResolvedValue({id: "att_1",diff --git a/src/web/src/app/api/community/agent/attachmentDownload/route.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.tsindex 4a40cb286..d6b700c07 100644--- a/src/web/src/app/api/community/agent/attachmentDownload/route.ts+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.ts@@ -1,9 +1,11 @@import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"+import { queries, createLogger, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+const log = createLogger({ service: "community-agent-attachment-download" })+/*** RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes* everything outside the RFC 5987 attr-char set. The daemon-side client@@ -20,7 +22,7 @@ function encodeRfc5987(value: string): string {* POST /api/community/agent/attachmentDownload** Body: `{ id }`.- * Response: raw binary stream + `Content-Type`, `Content-Length`,+ * Response: raw binary body + `Content-Type`, `Content-Length`,* `X-Alook-Filename` (RFC 5987 percent-encoded).** Enumeration-safe: every "you can't have this" path returns the same 404@@ -28,63 +30,81 @@ function encodeRfc5987(value: string): string {* genuine 404 are indistinguishable to a prober. A distinct 502 fires only* when the DB row exists but R2 has drifted (infra fault, not user-facing* gate).+ *+ * The body is buffered (`arrayBuffer`) inside the top-level try/catch so an+ * R2 stream error becomes a structured 500 instead of a truncated 200 the+ * daemon-side helper can't parse. The daemon `callDownload` already+ * buffers via `res.arrayBuffer()` (attachments are capped at 25 MB), so no+ * streaming behavior is lost.*/export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- let raw: unknowntry {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentAttachmentDownloadRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload" }, { status: 400 })- }-- const db = getDb(ctx.env.DB)- const row = await queries.communityAttachment.getAttachmentById(db, parsed.data.id)- if (!row) {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })- }-- if (row.messageId === null) {- // Pending row — only the uploading bot may see it (round-trip verify).- if (row.uploaderId !== ctx.botUserId) {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentAttachmentDownloadRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload" }, { status: 400 })}- } else {- // Persisted row — resolve target scope, then run the standard membership- // gate. Rewrite any non-2xx to a generic 404 so a prober can't tell- // "not a member" from "row doesn't exist".- const message = await queries.communityMessage.getMessage(db, row.messageId)- if (!message) {++ const db = getDb(ctx.env.DB)+ const row = await queries.communityAttachment.getAttachmentById(db, parsed.data.id)+ if (!row) {return NextResponse.json({ error: "attachment not found" }, { status: 404 })}- if (message.channelId) {- const gate = await requireChannelMember(db, message.channelId, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })- } else if (message.dmConversationId) {- const gate = await requireDMParticipant(db, message.dmConversationId, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })++ if (row.messageId === null) {+ // Pending row — only the uploading bot may see it (round-trip verify).+ if (row.uploaderId !== ctx.botUserId) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }} else {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ // Persisted row — resolve target scope, then run the standard membership+ // gate. Rewrite any non-2xx to a generic 404 so a prober can't tell+ // "not a member" from "row doesn't exist".+ const message = await queries.communityMessage.getMessage(db, row.messageId)+ if (!message) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }+ if (message.channelId) {+ const gate = await requireChannelMember(db, message.channelId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ } else if (message.dmConversationId) {+ const gate = await requireDMParticipant(db, message.dmConversationId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ } else {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }}- }- const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)- if (!obj) {- // Row exists but R2 has no object — infra fault, distinct from the- // enumeration-safe 404 above.- return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })- }+ const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)+ if (!obj) {+ // Row exists but R2 has no object — infra fault, distinct from the+ // enumeration-safe 404 above.+ return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })+ }- const contentType = row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"- const size = row.size ?? obj.size- const headers: Record<string, string> = {- "Content-Type": contentType,- "X-Alook-Filename": encodeRfc5987(row.filename),- }- if (typeof size === "number") headers["Content-Length"] = String(size)+ const contentType = row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"+ const size = row.size ?? obj.size+ const headers: Record<string, string> = {+ "Content-Type": contentType,+ "X-Alook-Filename": encodeRfc5987(row.filename),+ }+ if (typeof size === "number") headers["Content-Length"] = String(size)- return new Response(obj.body, { headers })+ // Buffer here (inside try/catch) so an R2 stream mid-read error surfaces+ // as a structured 500 rather than a truncated 200 the client can't parse.+ const buffer = await obj.arrayBuffer()+ return new Response(buffer, { headers })+ } catch (err) {+ log.error("attachment_route_failure", {+ route: "attachmentDownload",+ botUserId: ctx.botUserId,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })+ }})diff --git a/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.test.tsindex 01728719a..f6a939564 100644--- a/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts@@ -1,8 +1,11 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+const mockR2Delete = vi.fn(async () => undefined)vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {}, COMMUNITY_MEDIA: { put: vi.fn() } } })),+ getCloudflareContext: vi.fn(async () => ({+ env: { DB: {}, COMMUNITY_MEDIA: { put: vi.fn(), delete: (...a: unknown[]) => mockR2Delete(...(a as [])) } },+ })),}))vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -123,6 +126,44 @@ describe("POST /api/community/agent/attachmentUpload", () => {}))})+ it("createPendingAttachment throws → 500 JSON envelope, R2 delete fired with r2Key", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([+ { id: "c1", serverId: "srv_1", parentChannelId: null },+ ])+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1_transient"))++ const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ const body = await res.json()+ expect(body).toEqual({ error: "internal error", code: "internal" })+ expect(mockR2Delete).toHaveBeenCalledWith("channel/c1/uuid/hi.png")+ })++ it("createPendingAttachment throws AND R2 delete also throws → still 500 JSON, no rethrow", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([+ { id: "c1", serverId: "srv_1", parentChannelId: null },+ ])+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1_transient"))+ mockR2Delete.mockRejectedValueOnce(new Error("r2_boom"))++ const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })++ it("pre-R2 throw (resolveTargetForMember errors) → 500 JSON, R2 delete NOT called", async () => {+ mockResolveServerByNameForMember.mockRejectedValueOnce(new Error("d1_outage"))++ const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ expect(mockR2Delete).not.toHaveBeenCalled()+ })+it("propagates handler failure response verbatim", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([diff --git a/src/web/src/app/api/community/agent/attachmentUpload/route.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.tsindex db79ca72c..a60ad57a0 100644--- a/src/web/src/app/api/community/agent/attachmentUpload/route.ts+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.ts@@ -1,11 +1,13 @@import { NextResponse, type NextRequest } from "next/server"-import { queries } from "@alook/shared"+import { queries, createLogger } 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 { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"import { handleAttachmentUpload } from "@/lib/community/upload"+const log = createLogger({ service: "community-agent-attachment-upload" })+/*** POST /api/community/agent/attachmentUpload?target=<ref>*@@ -17,50 +19,82 @@ import { handleAttachmentUpload } from "@/lib/community/upload"* membership + write-permission gate is identical to `send`.*/export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- const target = req.nextUrl.searchParams.get("target")- if (!target) {- return NextResponse.json({ error: "missing target query param" }, { status: 400 })- }+ // Track any R2 blob written before the D1 insert throws so the catch below+ // can best-effort delete it. Hoisted here so the try/catch can see it.+ let r2KeyToCleanUp: string | null = null- const db = getDb(ctx.env.DB)+ try {+ const target = req.nextUrl.searchParams.get("target")+ if (!target) {+ return NextResponse.json({ error: "missing target query param" }, { status: 400 })+ }- const resolved = await resolveTargetForMember(db, ctx.botUserId, target)- if ("error" in resolved) return resolveErrorResponse(resolved)+ const db = getDb(ctx.env.DB)- let kind: "channel" | "dm"- let targetId: string- if (resolved.kind === "dm") {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- kind = "dm"- targetId = resolved.dmConversationId- } else {- const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- kind = "channel"- targetId = resolved.channelId- }+ const resolved = await resolveTargetForMember(db, ctx.botUserId, target)+ if ("error" in resolved) return resolveErrorResponse(resolved)- const result = await handleAttachmentUpload(req, ctx.env, kind, targetId, {- uploader: "bot",- uploaderUserId: ctx.botUserId,- })- if (!result.ok) return result.response+ let kind: "channel" | "dm"+ let targetId: string+ if (resolved.kind === "dm") {+ const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ kind = "dm"+ targetId = resolved.dmConversationId+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ kind = "channel"+ targetId = resolved.channelId+ }- const row = await queries.communityAttachment.createPendingAttachment(db, {- uploaderId: ctx.botUserId,- kind,- targetId,- r2Key: result.r2Key,- filename: result.filename,- contentType: result.contentType,- size: result.size,- })+ const result = await handleAttachmentUpload(req, ctx.env, kind, targetId, {+ uploader: "bot",+ uploaderUserId: ctx.botUserId,+ })+ if (!result.ok) return result.response- return NextResponse.json({- id: row.id,- filename: row.filename,- contentType: result.contentType || "application/octet-stream",- size: result.size,- })+ // R2 blob is committed — remember its key so the D1-throw path can+ // compensate.+ r2KeyToCleanUp = result.r2Key++ const row = await queries.communityAttachment.createPendingAttachment(db, {+ uploaderId: ctx.botUserId,+ kind,+ targetId,+ r2Key: result.r2Key,+ filename: result.filename,+ contentType: result.contentType,+ size: result.size,+ })++ return NextResponse.json({+ id: row.id,+ filename: row.filename,+ contentType: result.contentType || "application/octet-stream",+ size: result.size,+ })+ } catch (err) {+ let r2KeyCleaned = false+ if (r2KeyToCleanUp !== null) {+ try {+ await ctx.env.COMMUNITY_MEDIA.delete(r2KeyToCleanUp)+ r2KeyCleaned = true+ } catch (cleanupErr) {+ log.error("attachment_route_r2_cleanup_failed", {+ route: "attachmentUpload",+ botUserId: ctx.botUserId,+ r2Key: r2KeyToCleanUp,+ cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ })+ }+ }+ log.error("attachment_route_failure", {+ route: "attachmentUpload",+ botUserId: ctx.botUserId,+ r2KeyCleaned,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })+ }})diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex d35e323f8..7b49aa366 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -18,10 +18,17 @@ const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockCreateChannelMember = vi.fn()const mockAddThreadParticipants = vi.fn()+const mockLogError = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {...actual,+ createLogger: () => ({+ info: vi.fn(),+ warn: vi.fn(),+ debug: vi.fn(),+ error: (...a: unknown[]) => mockLogError(...a),+ }),queries: {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),@@ -651,6 +658,76 @@ describe("createCommunityMessage — attachment reservation-first flow (agent paexpect(mockUnreserveAttachments).not.toHaveBeenCalled()})+ it("thrown reserve error + hardDelete ALSO throws → caller sees the ORIGINAL reserve error (not the rollback error)", async () => {+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })+ mockReserveAttachmentsForMessage.mockRejectedValue(new Error("d1_transient_reserve"))+ mockHardDeleteMessage.mockRejectedValue(new Error("d1_transient_rollback"))+ mockLogError.mockClear()++ await expect(+ createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1"],+ }),+ ).rejects.toThrow("d1_transient_reserve")+ // hardDelete WAS attempted; both errors are logged in one line.+ expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")+ expect(mockLogError).toHaveBeenCalledWith(+ "attachment_reserve_rollback_failed",+ expect.objectContaining({+ messageId: "msg_preminted",+ insertErr: "d1_transient_reserve",+ rollbackErr: "d1_transient_rollback",+ }),+ )+ })++ it("partial reserve + unreserve throws → hardDelete STILL fires (not skipped), caller gets 400", async () => {+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // 1 of 2+ mockUnreserveAttachments.mockRejectedValueOnce(new Error("d1_transient_unreserve"))++ const res = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1", "att_2"],+ })++ expect(res.ok).toBe(false)+ if (res.ok) return+ expect(res.status).toBe(400)+ expect(res.error).toBe("attachment not found or not attachable to this target")+ expect(mockUnreserveAttachments).toHaveBeenCalledTimes(1)+ // hardDelete must NOT be skipped just because unreserve threw first — the+ // orphan message row still needs cleanup.+ expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")+ })++ it("partial reserve + unreserve AND hardDelete both throw → caller still gets 400 envelope (no rethrow)", async () => {+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // 1 of 2+ mockUnreserveAttachments.mockRejectedValueOnce(new Error("d1_transient_unreserve"))+ mockHardDeleteMessage.mockRejectedValue(new Error("d1_transient_rollback"))++ const res = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1", "att_2"],+ })++ expect(res.ok).toBe(false)+ if (res.ok) return+ expect(res.status).toBe(400)+ expect(res.error).toBe("attachment not found or not attachable to this target")+ })+it("expectedSeq CAS-null → no reserve, no unreserve, no hardDelete, returns seq_conflict", async () => {mockCreateMessage.mockResolvedValue(null) // CAS-null (returned, not thrown)diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 6ba21a3bd..5fb4146ec 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -5,8 +5,8 @@ import {MAX_MESSAGE_CONTENT_LENGTH,MAX_ATTACHMENTS_PER_MESSAGE,WS_EVENTS,+ createLogger,} from "@alook/shared"-import { nanoid } from "nanoid"import type { MentionType } from "@alook/shared"import type { Database } from "@alook/shared"import { fanOutToChannel, fanOutToDM } from "./fanout"@@ -15,6 +15,8 @@ import { mapMessageForWs } from "./message-payload"import { mediaUrlFromKey } from "./storage"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "./audit"+const log = createLogger({ service: "community-message-handler" })+export type MessageTarget =| { kind: "channel"; channelId: string; serverId: string }| {@@ -243,7 +245,6 @@ export async function createCommunityMessage(params: {: undefinedconst baseMessageData: {- id?: string;authorId: string;content: string;channelId: string | undefined;@@ -261,19 +262,15 @@ export async function createCommunityMessage(params: {...(messageType !== undefined ? { type: messageType } : {}),}- // Agent-attachment path (plan §Send). `communityAttachment.messageId` is a- // real FK to `communityMessage.id`, so the reserve UPDATE cannot precede- // the message insert — D1 enforces FK checks eagerly and would reject a- // reserve against a not-yet-inserted pre-minted id. Insert first, then- // reserve; compensate with `hardDeleteMessage` if the reserve fails or- // partially reserves. `insertMessageRow`'s side effects (scope counter,- // `lastMessageAt`, author read-state) drift by one row on that rare- // compensating path — accepted, none of it is visible externally because- // WS fanout only runs on the success branch below.- const useAttachmentReservation =- attachmentIds !== undefined && attachmentIds.length > 0- const preMintedId = useAttachmentReservation ? nanoid() : undefined- if (preMintedId) baseMessageData.id = preMintedId+ // Insert first so `reserveAttachmentsForMessage`'s UPDATE can key off+ // `created.id` (the FK enforces the message row exists); compensate with+ // the cascading `hardDeleteMessage` on reserve failure or partial reserve.+ // See plans/attachment-pipeline-empty-body-guardrails.md Layer 5-6 for the+ // rollback contract.+ //+ // Narrow once here so downstream branches don't need `attachmentIds!`.+ const reserveIds: string[] | null =+ attachmentIds !== undefined && attachmentIds.length > 0 ? attachmentIds : null// `createMessage`'s overloads key off whether the `expectedSeq` property// is present at all, not just its runtime value — a `number | undefined`@@ -291,30 +288,59 @@ export async function createCommunityMessage(params: {return { ok: false, status: 409, error: "seq_conflict" }}- if (useAttachmentReservation) {+ if (reserveIds) {let reserved: string[]try {reserved = await queries.communityAttachment.reserveAttachmentsForMessage(db, {- ids: attachmentIds!,+ ids: reserveIds,messageId: created.id,})} catch (err) {// Reserve threw (transient D1 / constraint / etc.). The message row// exists but has zero attachments reserved to it — hard-delete it so- // the caller can retry with the same attachment ids.- await queries.communityMessage.hardDeleteMessage(db, created.id)+ // the caller can retry with the same attachment ids. If the+ // compensating hardDelete ALSO throws (same D1 outage the reserve was+ // recovering from), log both and re-throw the ORIGINAL reserve error —+ // it's the one the caller cares about; matches bots/route.ts:139's shape.+ try {+ await queries.communityMessage.hardDeleteMessage(db, created.id)+ } catch (rollbackErr) {+ log.error("attachment_reserve_rollback_failed", {+ messageId: created.id,+ insertErr: err instanceof Error ? err.message : String(err),+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }throw err}- if (reserved.length !== attachmentIds!.length) {+ if (reserved.length !== reserveIds.length) {// Partial-overlap race (S1={A,B}, S2={B,C}) or an id that no longer- // matches (uploader/kind/target/messageId-null). Unreserve whatever THIS- // caller uniquely grabbed, then hard-delete the message row so we- // don't leave an orphan with a partial attachment set.- await queries.communityAttachment.unreserveAttachments(db, {- ids: reserved,- messageId: created.id,- })- await queries.communityMessage.hardDeleteMessage(db, created.id)+ // matches (uploader/kind/target/messageId-null). Compensate:+ // unreserve whatever THIS caller uniquely grabbed AND hard-delete the+ // orphan message row. Both compensating writes are individually guarded:+ // if unreserve throws we still try the hardDelete (else we'd leave a+ // live message row alongside the stale partial-reserve); if either+ // throws we log but still return the 400 envelope — the caller-facing+ // shape doesn't depend on whether compensation succeeded.+ try {+ await queries.communityAttachment.unreserveAttachments(db, {+ ids: reserved,+ messageId: created.id,+ })+ } catch (unreserveErr) {+ log.error("attachment_partial_reserve_unreserve_failed", {+ messageId: created.id,+ unreserveErr: unreserveErr instanceof Error ? unreserveErr.message : String(unreserveErr),+ })+ }+ try {+ await queries.communityMessage.hardDeleteMessage(db, created.id)+ } catch (rollbackErr) {+ log.error("attachment_partial_reserve_rollback_failed", {+ messageId: created.id,+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }return {ok: false,status: 400,@@ -327,7 +353,7 @@ export async function createCommunityMessage(params: {// Agent path: rows were already reserved and pointed at `created.id` via// the pre-minted id, so no additional INSERT is needed here.let attachments: CreatedAttachment[] = []- if (useAttachmentReservation) {+ if (reserveIds) {const rows = await queries.communityAttachment.listByMessageIds(db, [created.id])attachments = rows.map((r) => ({id: r.id,