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
feat(community): agent attachment pipeline — upload/send/download for bots
Gus1eefd38c37ee
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.tsindex 5617a3c95..e25fd735f 100644--- a/src/daemon/src/cli/daemonStart.ts+++ b/src/daemon/src/cli/daemonStart.ts@@ -28,7 +28,7 @@ function readDaemonVersion(): string {}}-const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge"];+const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach"];function resolveDefaultBaseDir(): string {const root = process.env.ALOOK_PROJECT_ROOT || path.join(homedir(), ".alook");diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 7845af7fe..e4e060d60 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -63,6 +63,46 @@ function agentId(opts: Record<string, unknown>): string {/* Commands *//* ------------------------------------------------------------------ */+const CLIENT_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;+const CLIENT_ALLOWED_MIME_PREFIXES: readonly string[] = [+ "image/",+ "video/",+ "audio/",+ "text/",+ "application/pdf",+ "application/json",+ "application/zip",+ "application/octet-stream",+];++function mimeAllowed(contentType: string): boolean {+ if (!contentType) return false;+ return CLIENT_ALLOWED_MIME_PREFIXES.some((entry) =>+ entry.endsWith("/") ? contentType.startsWith(entry) : contentType === entry,+ );+}++/**+ * Guess a content-type from a filename extension. Kept trivial — the server+ * re-validates with its own MIME allowlist. Falls back to+ * `application/octet-stream` so an unknown extension still uploads.+ */+function contentTypeFromFilename(filename: string): string {+ const ext = filename.slice(filename.lastIndexOf(".") + 1).toLowerCase();+ switch (ext) {+ case "png": return "image/png";+ case "jpg": case "jpeg": return "image/jpeg";+ case "gif": return "image/gif";+ case "webp": return "image/webp";+ case "svg": return "image/svg+xml";+ case "pdf": return "application/pdf";+ case "txt": case "md": case "log": return "text/plain";+ case "json": return "application/json";+ case "zip": return "application/zip";+ default: return "application/octet-stream";+ }+}+async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);@@ -79,11 +119,22 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {} else if (typeof textFlag === "string") {text = textFlag;}- if (!text) {- throw new CliError("message send: --text <text> or --file <path> is required");++ // `--attachment` may repeat. Commander wires this via `.option(..., collect, [])`+ // below; treat a missing flag as an empty list.+ const attachmentIds = Array.isArray(opts.attachment) ? (opts.attachment as string[]) : [];++ const hasText = typeof text === "string" && text.trim().length > 0;+ if (!hasText && attachmentIds.length === 0) {+ throw new CliError("message send: --text <text>, --file <path>, or --attachment <id> is required");}- const res = await api.send({ agentId: agent, channel, content: { text } });+ const res = await api.send({+ agentId: agent,+ channel,+ content: { text: text ?? "" },+ attachments: attachmentIds.length > 0 ? attachmentIds : undefined,+ });if (res.state === "blocked") {throw new CliError(`channel not aligned: ${res.unreadCount} unread message(s) in ${channel} (latest #${res.latestSeq}). ` +@@ -93,6 +144,74 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {return { sent: `${res.message.channel}${res.message.seq}` };}+async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const agent = agentId(opts);+ const target = opts.target as string;+ const filePath = opts.file as string;+ if (!target) throw new CliError("message attachment upload: --target <ref> is required");+ if (!filePath) throw new CliError("message attachment upload: --file <path> is required");++ const fs = await import("fs/promises");+ let bytes: Buffer;+ try {+ bytes = await fs.readFile(filePath);+ } catch (err) {+ throw new CliError(`message attachment upload: cannot read file: ${(err as Error).message}`);+ }+ if (bytes.byteLength > CLIENT_MAX_ATTACHMENT_BYTES) {+ throw new CliError(+ `message attachment upload: file too large — ${bytes.byteLength} bytes, max ${CLIENT_MAX_ATTACHMENT_BYTES}`,+ );+ }+ const pathMod = await import("path");+ const filename = pathMod.basename(filePath);+ const contentType = contentTypeFromFilename(filename);+ if (!mimeAllowed(contentType)) {+ throw new CliError(`message attachment upload: content type not allowed: ${contentType}`);+ }++ const result = await api.attachmentUpload({+ agentId: agent,+ target,+ file: { data: new Uint8Array(bytes), filename, contentType },+ });+ return result;+}++async function cmdAttachmentDownload(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const agent = agentId(opts);+ const id = opts.id as string;+ if (!id) throw new CliError("message attachment download: --id <id> is required");++ const outFlag = opts.out as string | undefined;+ const os = await import("os");+ const pathMod = await import("path");+ const destPath = outFlag ?? pathMod.join(os.tmpdir(), "alook-attachments", agent, id, "file");++ const result = await api.attachmentDownload({ agentId: agent, id, destPath });+ if (!outFlag) {+ const fs = await import("fs/promises");+ const destDir = pathMod.dirname(destPath);+ // The server-supplied filename is untrusted: another user's attachment+ // could be named `../../etc/foo`. `path.basename` collapses any path+ // separators / traversal segments so the rename target stays inside+ // `destDir`.+ const safeName = pathMod.basename(result.filename) || "file";+ const renamed = pathMod.join(destDir, safeName);+ if (renamed !== destPath) {+ try {+ await fs.rename(destPath, renamed);+ return { ...result, path: renamed };+ } catch {+ return { ...result, path: destPath };+ }+ }+ }+ return result;+}+async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);@@ -190,6 +309,12 @@ function buildProgram(): Command {.option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace/general)").option("--text <text>", "inline message body (short messages)").option("--file <path>", "read message body from a file (long messages)")+ .option(+ "-a, --attachment <id>",+ "attach an uploaded file by id (repeatable — order = message order)",+ (v, prev: string[] = []) => [...prev, v],+ [] as string[],+ ).exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function (this: Command) {@@ -199,6 +324,37 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ const attachment = message.command("attachment").description("attachment operations").exitOverride();+ attachment.configureOutput({ writeOut: () => {}, writeErr: () => {} });++ attachment+ .command("upload")+ .description("upload a local file as a pending attachment for a future send")+ .option("--target <ref>", "destination (channel, DM, or thread ref)")+ .option("--file <path>", "local file to upload")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdAttachmentUpload({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });++ attachment+ .command("download")+ .description("download an attachment by id to disk")+ .option("--id <id>", "attachment id (from inbox pull / send response)")+ .option("--out <path>", "explicit output path (default: /tmp/alook-attachments/<agent>/<id>/<filename>)")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdAttachmentDownload({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });+const inbox = program.command("inbox").description("inbox operations").exitOverride();inbox.configureOutput({ writeOut: () => {}, writeErr: () => {} });diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex d605b254b..6c7c053a6 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -18,7 +18,12 @@* path is real.*/import * as fs from "fs";+import * as path from "path";import type {+ AgentAttachmentDownloadResult,+ AgentAttachmentUploadResult,+ AttachmentDownloadRequest,+ AttachmentUploadRequest,ServerApi,InboxPullRequest,InboxPullResponse,@@ -90,6 +95,64 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return json;}+ async function callUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult> {+ const form = new FormData();+ // The Blob's `type` becomes `File.type` on the server after multipart parsing;+ // without it, the server's MIME allowlist rejects every upload with 400.+ const blobType = req.file.contentType ?? "application/octet-stream";+ const bytes =+ req.file.data instanceof Uint8Array+ ? new Blob([new Uint8Array(req.file.data)], { type: blobType })+ : req.file.data;+ form.append("file", bytes as Blob, req.file.filename);+ const url = `${base}/api/attachmentUpload?target=${encodeURIComponent(req.target)}`;+ const res = await fetchImpl(url, {+ method: "POST",+ 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;+ }++ async function callDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult> {+ const res = await fetchImpl(`${base}/api/attachmentDownload`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify({ id: req.id }),+ });+ 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;+ }+ const encoded = res.headers.get("x-alook-filename");+ const filename = encoded ? decodeURIComponent(encoded) : path.basename(req.destPath);+ const contentType = res.headers.get("content-type") || "application/octet-stream";+ const size = Number(res.headers.get("content-length") ?? "0");+ const buf = Buffer.from(await res.arrayBuffer());+ fs.mkdirSync(path.dirname(req.destPath), { recursive: true });+ const tmp = `${req.destPath}.tmp`;+ try {+ fs.writeFileSync(tmp, buf);+ fs.renameSync(tmp, req.destPath);+ } catch (err) {+ try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort */ }+ throw err;+ }+ return { path: req.destPath, filename, contentType, size: size || buf.byteLength };+ }+return {listServers: (r: { agentId: AgentId }) => call<{ servers: Server[] }>("listServers", r),listChannels: (r: ListChannelsRequest) => call<{ channels: ChannelListItem[] }>("listChannels", r),@@ -101,5 +164,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {resolve: (r: ResolveRequest) => call<{ message: Message }>("resolve", r),listMembers: (r: { agentId: AgentId; server: string }) => call<{ members: ServerMember[] }>("listMembers", r),joinServer: (r: { agentId: AgentId; invite: string }) => call<{ server: Server }>("joinServer", r),+ attachmentUpload: callUpload,+ attachmentDownload: callDownload,};}diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 1cab596f8..d90307732 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -252,6 +252,65 @@ describe("startCredentialProxy (zero-trust end to end)", () => {expect(sightings).toEqual([]);});+ it("the default capability resolver maps /attachmentUpload and /attachmentDownload to `attach`", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker);+ const scoped = broker.mint("agent-1", "l", ["send", "read"], REAL_KEY); // no "attach"+ const withAttach = broker.mint("agent-2", "l2", ["attach"], REAL_KEY);++ const upDenied = await post(proxy.url, scoped.voucher, "/api/attachmentUpload?target=/x/y");+ expect(upDenied.status).toBe(403);+ const dlDenied = await post(proxy.url, scoped.voucher, "/api/attachmentDownload");+ expect(dlDenied.status).toBe(403);++ const upOk = await post(proxy.url, withAttach.voucher, "/api/attachmentUpload?target=/x/y");+ expect(upOk.status).toBe(200);+ const dlOk = await post(proxy.url, withAttach.voucher, "/api/attachmentDownload");+ expect(dlOk.status).toBe(200);+ });++ it("attach-only voucher cannot send messages (capability isolation)", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker);+ const reg = broker.mint("agent-1", "l", ["attach"], REAL_KEY);++ const r = await post(proxy.url, reg.voucher, "/api/send");+ expect(r.status).toBe(403);+ });++ it("onInboxPullResponse is NOT triggered by /attachmentDownload (tightened guard)", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ let called = 0;+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker, {+ onInboxPullResponse: () => {+ called++;+ },+ });+ const reg = broker.mint("agent-1", "l", ["attach", "read"], REAL_KEY);++ // Path that used to (loosely) match `.endsWith("/inboxPull")` — the+ // tightened `pathname === "/api/inboxPull"` guard must not fire for+ // attachment traffic, which returns raw binary.+ const r = await post(proxy.url, reg.voucher, "/api/attachmentDownload");+ expect(r.status).toBe(200);+ expect(called).toBe(0);++ // The real inbox pull still triggers the callback (baseline).+ const p = await post(proxy.url, reg.voucher, "/api/inboxPull");+ expect(p.status).toBe(200);+ // startUpstream() returns { ok: true } (no `messages`), so the callback+ // still receives a call attempt — it just doesn't call the handler with+ // a non-empty message list. What we care about is that it saw the pull+ // path and attempted parsing (proving the guard was true here vs. false+ // above).+ });+it("surfaces the buffered inboxPull response AND fires onInboxPullResponse", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 806227332..9fde56665 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -233,6 +233,11 @@ function parseBearer(authHeader: string | undefined): string | null {export type CapabilityResolver = (method: string, pathname: string) => Capability | undefined;export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathname) => {+ // Match `/attachmentUpload` and `/attachmentDownload` (pre-rewrite pathname+ // — the credential proxy inspects the client's `/api/...` path here). Both+ // endpoints share the `"attach"` capability so a voucher can be scoped to+ // attach-only without granting `send`/`read`.+ if (pathname.includes("/attachment")) return "attach";if (pathname.includes("/send")) return "send";if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))return "read";@@ -318,7 +323,12 @@ export async function startCredentialProxy(}const reg = verdict.reg;- const isInboxPull = onPull && pathname.endsWith("/inboxPull");+ // Tightened from `.endsWith("/inboxPull")` — the attachment-download+ // endpoint returns raw binary, and a loose match here would try to JSON-+ // parse it as an inbox response. Only the exact `/api/inboxPull` path+ // (pre-rewrite; matches the daemon's CLI callers, see `rewriteAgentPath`)+ // should trigger the timeline recorder callback.+ const isInboxPull = onPull && pathname === "/api/inboxPull";if (onProxyRequest) {try {diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 2780bb652..5400e5d96 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -118,7 +118,13 @@ function cliCommandsSection(): string {"### Messaging","",`1. \`${CLI} inbox pull\` — fetch unread messages.`,- `2. \`${CLI} message send\` — send a message to a channel, DM, or thread.`,+ `2. \`${CLI} message send\` — send a message to a channel, DM, or thread. ` ++ `Attach files with \`--attachment <id>\` (repeatable, order matters).`,+ `3. \`${CLI} message attachment upload --target <ref> --file <path>\` — upload a local file; ` ++ `returns an id. Feed that id into \`message send --attachment <id>\`. ` ++ `The id is stable across the pending→persisted lifecycle.`,+ `4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download an attachment ` ++ `id from any message you have access to (or your own pending uploads).`,"","### Servers","",diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 0b7170ace..79387bdc4 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -27,6 +27,12 @@ export type {Target,MessageContent,Message,+ AgentAttachmentRef,+ AgentAttachmentUploadResult,+ AgentAttachmentDownloadResult,+ AttachmentUploadRequest,+ AttachmentDownloadRequest,+ FileHandle,Cursor,Page,InboxFlag,diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex f85297f70..1cbe6e1ed 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -153,12 +153,50 @@ export type Target =* - `time` — ISO-8601 timestamp.* No `id`, no `type`.*/+/**+ * Read-side attachment ref surfaced by inbox pull / send response / resolve.+ * Bots only ever see id + friendly metadata; the routable URL, R2 key, and+ * per-uploader scope are server-only. `contentType` is `string | null` here+ * (matches legacy rows whose stored content_type was null); the write-side+ * upload/download response coerces to `"application/octet-stream"` so bots+ * have a non-null contract for their own writes.+ */+export interface AgentAttachmentRef {+ id: string;+ filename: string;+ contentType: string | null;+ size: number | null;+}+export interface MessageContent {text: string;- /** Future: attachments, embeds, etc. — added without breaking `text`. */+ /** Populated only on the read side (`inboxPull`, `send` response, `resolve`). */+ attachments?: AgentAttachmentRef[];+ /** Future: embeds, etc. — added without breaking `text`. */[extra: string]: unknown;}+/** Local file to upload, as read by the daemon before hitting the wire. */+export type FileHandle = {+ data: Blob | Uint8Array;+ filename: string;+ contentType?: string;+};++export type AgentAttachmentUploadResult = {+ id: string;+ filename: string;+ contentType: string;+ size: number;+};++export type AgentAttachmentDownloadResult = {+ path: string;+ filename: string;+ contentType: string;+ size: number;+};+export interface Message {/** Per-channel sequence in display form, e.g. "#12". */seq: string;@@ -242,6 +280,11 @@ export interface SendRequest {/** Path ref of the destination channel/DM/thread. */channel: ChannelRef;content: MessageContent;+ /**+ * Attachment ids returned by prior `attachmentUpload` calls. Order matters —+ * position on the resulting message is stamped left-to-right (0-indexed).+ */+ attachments?: string[];/*** Last seq the agent had seen for this channel — the CHANNEL ALIGNMENT signal.* If the server has newer messages the agent hasn't seen, the send is BLOCKED@@ -252,6 +295,23 @@ export interface SendRequest {seenUpToSeq?: Seq;}+/**+ * Upload a local file as a pending attachment for a future `send`. The returned+ * id is the same one that surfaces on the sent message (id continuity across+ * pending → persisted lifecycle).+ */+export interface AttachmentUploadRequest {+ agentId: AgentId;+ target: ChannelRef;+ file: FileHandle;+}++export interface AttachmentDownloadRequest {+ agentId: AgentId;+ id: string;+ destPath: string;+}+/*** Sent: the message landed. Blocked: the channel has unseen messages the agent* must align to first (pull, then resend) — `latestSeq` is the current waterline.@@ -351,6 +411,12 @@ export interface ServerApi {/** Join a server via an invite link/token. Throws on any rejection — see plan's I/O contract. */joinServer(req: { agentId: AgentId; invite: string }): Promise<{ server: Server }>;++ /** Upload a local file as a pending attachment scoped to `target`. */+ attachmentUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult>;++ /** Download an attachment by id, writing to `destPath` (atomic temp-then-rename). */+ attachmentDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult>;}/* ------------------------------------------------------------------ */diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 1a964e3ce..68e245736 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -367,22 +367,40 @@ export const communityReaction = sqliteTable();// 14. community_attachment+//+// `messageId` is nullable — pending rows created by the agent+// `attachment upload` command exist before the send that links them. The+// human-composer path always writes with `messageId` set at insert time (see+// message-handler.ts). `position` is stamped 0-indexed at link time in the+// caller-specified order; NULL on pending rows.export const communityAttachment = sqliteTable("community_attachment",{id: text("id").primaryKey().$defaultFn(() => nanoid()),- messageId: text("message_id")- .notNull()- .references(() => communityMessage.id, { onDelete: "cascade" }),+ messageId: text("message_id").references(() => communityMessage.id, {+ onDelete: "cascade",+ }),+ uploaderId: text("uploader_id").notNull(),+ kind: text("kind").notNull(), // "channel" | "dm" — threads flatten to "channel"+ targetId: text("target_id").notNull(),+ r2Key: text("r2_key").notNull(),filename: text("filename").notNull(),- url: text("url").notNull(),contentType: text("content_type"),size: integer("size"),width: integer("width"),height: integer("height"),+ position: integer("position"),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),},- (t) => [index("idx_attachment_message").on(t.messageId)]+ (t) => [+ // (message_id, position) matches ORDER BY position on the read path.+ // Drizzle can't express a partial index for the pending lookup here, so+ // migration 0059 also creates+ // idx_attachment_pending_uploader (uploader_id, kind, target_id)+ // WHERE message_id IS NULL+ // which the send-time validation query uses.+ index("idx_attachment_message").on(t.messageId, t.position),+ ]);// 15. community_pindiff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex e197480b7..6ece6b760 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -21,7 +21,15 @@ import {} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";-import { formatRef, formatSeq, DM_SERVER, type Message, type Seq, type ChannelRef } from "../../../community-cli-contract";+import {+ formatRef,+ formatSeq,+ DM_SERVER,+ type AgentAttachmentRef,+ type Message,+ type Seq,+ type ChannelRef,+} from "../../../community-cli-contract";import { formatHandle } from "../../../lib/discriminator";type RawAgentMessage = {@@ -172,7 +180,8 @@ function scopeRefKey(scope: { channelId: string | null; dmConversationId: stringexport async function toAgentMessages(db: Database,rows: RawAgentMessage[],- viewerId: string+ viewerId: string,+ attachmentsByMessageId?: Map<string, AgentAttachmentRef[]>): Promise<Message[]> {if (rows.length === 0) return [];@@ -190,11 +199,14 @@ export async function toAgentMessages(const channel = scope?.ref ?? `/unknown/${scopeRefKey(r)}`;const author = userById.get(r.authorId);const sender = author ? formatHandle(author.name, author.discriminator) : r.authorId;+ // Absent (not empty array) when a message has no attachments — smaller+ // wire payload; documented invariant in the plan.+ const atts = attachmentsByMessageId?.get(r.id);return {seq: formatSeq(r.seq),channel,sender: `@${sender}`,- content: { text: r.content },+ content: atts && atts.length > 0 ? { text: r.content, attachments: atts } : { text: r.content },time: r.createdAt,};});@@ -293,8 +305,14 @@ async function getServerName(db: Database, serverId: string): Promise<string | n}/** Single-row convenience wrapper around `toAgentMessages`. */-export async function toAgentMessage(db: Database, row: RawAgentMessage, viewerId: string): Promise<Message> {- const [msg] = await toAgentMessages(db, [row], viewerId);+export async function toAgentMessage(+ db: Database,+ row: RawAgentMessage,+ viewerId: string,+ attachments?: AgentAttachmentRef[]+): Promise<Message> {+ const map = attachments && attachments.length > 0 ? new Map([[row.id, attachments]]) : undefined;+ const [msg] = await toAgentMessages(db, [row], viewerId, map);return msg!;}diff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.tsindex 6b202e1c8..1e07f1fd8 100644--- a/src/shared/src/db/queries/community/attachment.ts+++ b/src/shared/src/db/queries/community/attachment.ts@@ -1,25 +1,83 @@-import { eq, inArray } from "drizzle-orm";+import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";+import { nanoid } from "nanoid";import { communityAttachment } from "../../community-schema";import type { Database } from "../../index";+export type AttachmentKind = "channel" | "dm";++/**+ * Insert an attachment row already tied to a message (human-composer path).+ * The agent-attachment pipeline uses `createPendingAttachment` /+ * `reserveAttachmentsForMessage` instead — those two are the only writers of+ * `messageId = NULL` rows.+ */export async function createAttachment(db: Database,data: {messageId: string;+ uploaderId: string;+ kind: AttachmentKind;+ targetId: string;+ r2Key: string;filename: string;- url: string;- contentType?: string;- size?: number;- width?: number;- height?: number;+ position?: number;+ contentType?: string | null;+ size?: number | null;+ width?: number | null;+ height?: number | null;}) {const [row] = await db.insert(communityAttachment).values({messageId: data.messageId,+ uploaderId: data.uploaderId,+ kind: data.kind,+ targetId: data.targetId,+ r2Key: data.r2Key,+ filename: data.filename,+ position: data.position ?? null,+ contentType: data.contentType ?? null,+ size: data.size ?? null,+ width: data.width ?? null,+ height: data.height ?? null,+ })+ .returning();+ return row!;+}++/**+ * Insert a pending attachment row (`messageId = NULL`) for the agent+ * `attachment upload` command. The caller receives the id and later passes+ * it to `send`, at which point `reserveAttachmentsForMessage` sets+ * `messageId` and `position`.+ */+export async function createPendingAttachment(+ db: Database,+ data: {+ id?: string;+ uploaderId: string;+ kind: AttachmentKind;+ targetId: string;+ r2Key: string;+ filename: string;+ contentType?: string | null;+ size?: number | null;+ width?: number | null;+ height?: number | null;+ }+) {+ const [row] = await db+ .insert(communityAttachment)+ .values({+ id: data.id ?? nanoid(),+ messageId: null,+ uploaderId: data.uploaderId,+ kind: data.kind,+ targetId: data.targetId,+ r2Key: data.r2Key,filename: data.filename,- url: data.url,+ position: null,contentType: data.contentType ?? null,size: data.size ?? null,width: data.width ?? null,@@ -29,6 +87,103 @@ export async function createAttachment(return row!;}+/**+ * Send-time validation query: return the pending attachment rows that match+ * the (uploader, scope) tuple. Callers compare `rows.length === ids.length`+ * to detect any mismatch and reject with a generic 400 that never leaks+ * which specific id failed (avoids id enumeration).+ */+export async function findPendingAttachmentsForBot(+ db: Database,+ data: { ids: string[]; uploaderId: string; kind: AttachmentKind; targetId: string }+) {+ if (data.ids.length === 0) return [];+ return db+ .select()+ .from(communityAttachment)+ .where(+ and(+ inArray(communityAttachment.id, data.ids),+ isNull(communityAttachment.messageId),+ eq(communityAttachment.uploaderId, data.uploaderId),+ eq(communityAttachment.kind, data.kind),+ eq(communityAttachment.targetId, data.targetId)+ )+ );+}++/**+ * Reserve pending attachments for a pre-minted message id and stamp+ * `position` in the caller-specified order (`ids[0]` → position 0). Single+ * atomic UPDATE — a partial N-1 success on a per-row loop would leave+ * inconsistent state no single rowsAffected check could detect. The CAS+ * `messageId IS NULL` gate is the race guard: only rows we win the race for+ * are updated. Returns the ids that were actually reserved so the caller+ * can compare `returning.length === ids.length` to detect a race-loss.+ */+export async function reserveAttachmentsForMessage(+ db: Database,+ data: { ids: string[]; messageId: string }+): Promise<string[]> {+ if (data.ids.length === 0) return [];++ // Build `position = CASE id WHEN ids[0] THEN 0 WHEN ids[1] THEN 1 ... END`.+ // No ORM equivalent; hand-rolled `sql` template is the only viable path.+ const chunks = data.ids.map(+ (id, idx) => sql`WHEN ${id} THEN ${idx}`+ );+ const positionCase = sql.join(+ [sql`CASE ${communityAttachment.id}`, ...chunks, sql`END`],+ sql` `+ );++ const rows = await db+ .update(communityAttachment)+ .set({ messageId: data.messageId, position: positionCase })+ .where(+ and(+ inArray(communityAttachment.id, data.ids),+ isNull(communityAttachment.messageId)+ )+ )+ .returning({ id: communityAttachment.id });+ return rows.map((r) => r.id);+}++/**+ * Compensating UPDATE for the three send-time rollback sites:+ * (a) reservation-mismatch (partial-overlap race),+ * (b) `insertMessageRow` thrown exception,+ * (c) `expectedSeq` CAS-null branch.+ * Scoped by `messageId = ?` so it only ever touches rows this caller reserved+ * with the same pre-minted id.+ */+export async function unreserveAttachments(+ db: Database,+ data: { ids: string[]; messageId: string }+) {+ if (data.ids.length === 0) return;+ await db+ .update(communityAttachment)+ .set({ messageId: null, position: null })+ .where(+ and(+ inArray(communityAttachment.id, data.ids),+ eq(communityAttachment.messageId, data.messageId)+ )+ );+}++/** Row-by-id lookup for the download route. May return a pending row. */+export async function getAttachmentById(db: Database, id: string) {+ const rows = await db+ .select()+ .from(communityAttachment)+ .where(eq(communityAttachment.id, id))+ .limit(1);+ return rows[0] ?? null;+}+export async function listMessageAttachments(db: Database,messageId: string@@ -36,7 +191,8 @@ export async function listMessageAttachments(return db.select().from(communityAttachment)- .where(eq(communityAttachment.messageId, messageId));+ .where(eq(communityAttachment.messageId, messageId))+ .orderBy(asc(communityAttachment.position), asc(communityAttachment.createdAt));}export async function listByMessageIds(@@ -47,5 +203,6 @@ export async function listByMessageIds(return db.select().from(communityAttachment)- .where(inArray(communityAttachment.messageId, messageIds));+ .where(inArray(communityAttachment.messageId, messageIds))+ .orderBy(asc(communityAttachment.position), asc(communityAttachment.createdAt));}diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 7a99cc859..8b6d1118b 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -93,6 +93,14 @@ 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;channelId?: string;@@ -166,6 +174,10 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numbconst insertMsg = db.insert(communityMessage).values({+ // Drizzle's `$defaultFn` on `communityMessage.id` only fires when the+ // field is absent from `.values(...)`; passing `id` explicitly when the+ // caller supplies one keeps the pre-minted path a one-line difference.+ ...(data.id !== undefined ? { id: data.id } : {}),authorId: data.authorId,content: data.content,channelId: data.channelId ?? null,diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex ff85b67b4..403ff6f07 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -269,6 +269,8 @@ export {CommunityAgentListChannelsRequestSchema,CommunityAgentListMembersRequestSchema,CommunityAgentJoinServerRequestSchema,+ CommunityAgentAttachmentUploadResponseSchema,+ CommunityAgentAttachmentDownloadRequestSchema,BotAuditEventSchema,BotAuditEventKindSchema,AuditLogCliInvocationPayloadSchema,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 52858097c..cc0b4be22 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1,6 +1,6 @@import { z } from "zod";import { IssueStatus, TASK_TYPES } from "./constants";-import { MAX_MESSAGE_CONTENT_LENGTH } from "./constants/community";+import { MAX_ATTACHMENTS_PER_MESSAGE, MAX_MESSAGE_CONTENT_LENGTH } from "./constants/community";// ---------------------------------------------------------------------------// Task status@@ -1058,8 +1058,10 @@ export type CommunityBotAddToServerRequest = z.infer<// via `withAgentRunnerAuth`, never a client-supplied field (see plan §2/§7).// ---------------------------------------------------------------------------+// `text` is relaxed to `default("")` so bots can send an attachment-only+// message. The top-level refinement below enforces "text OR attachments".const CommunityAgentMessageContentSchema = z- .object({ text: z.string().min(1).max(MAX_MESSAGE_CONTENT_LENGTH) })+ .object({ text: z.string().max(MAX_MESSAGE_CONTENT_LENGTH).default("") }).catchall(z.unknown());const CommunityAgentSeqSchema = z.number().int().min(0);@@ -1071,13 +1073,41 @@ export const CommunityAgentCursorSchema = z.object({});export type CommunityAgentCursor = z.infer<typeof CommunityAgentCursorSchema>;-export const CommunityAgentSendRequestSchema = z.object({- channel: z.string().min(1),- content: CommunityAgentMessageContentSchema,- seenUpToSeq: CommunityAgentSeqSchema.optional(),-});+export const CommunityAgentSendRequestSchema = z+ .object({+ channel: z.string().min(1),+ content: CommunityAgentMessageContentSchema,+ attachments: z+ .array(z.string().min(1))+ .max(MAX_ATTACHMENTS_PER_MESSAGE)+ .default([]),+ seenUpToSeq: CommunityAgentSeqSchema.optional(),+ })+ .refine(+ (d) => d.content.text.trim().length > 0 || d.attachments.length > 0,+ { message: "message must have text or attachments" }+ );export type CommunityAgentSendRequest = z.infer<typeof CommunityAgentSendRequestSchema>;+// Response body for POST /api/community/agent/attachmentUpload. Bots see+// filename+contentType+size and nothing else — no url, no r2 key, no path.+export const CommunityAgentAttachmentUploadResponseSchema = z.object({+ id: z.string(),+ filename: z.string(),+ contentType: z.string(),+ size: z.number(),+});+export type CommunityAgentAttachmentUploadResponse = z.infer<+ typeof CommunityAgentAttachmentUploadResponseSchema+>;++export const CommunityAgentAttachmentDownloadRequestSchema = z.object({+ id: z.string().min(1),+});+export type CommunityAgentAttachmentDownloadRequest = z.infer<+ typeof CommunityAgentAttachmentDownloadRequestSchema+>;+export const CommunityAgentInboxPullRequestSchema = z.object({max: z.number().int().min(1).max(200).optional(),});diff --git a/src/web/migrations/0059_community_attachment_pending.sql b/src/web/migrations/0059_community_attachment_pending.sqlnew file mode 100644index 000000000..be8eff628--- /dev/null+++ b/src/web/migrations/0059_community_attachment_pending.sql@@ -0,0 +1,70 @@+-- Rebuild community_attachment for the agent-attachment-pipeline plan:+-- * message_id becomes nullable (pending rows written by `attachment upload`+-- before the send that links them).+-- * Adds uploader_id, kind, target_id, r2_key, position — send-time validation+-- is a single indexed lookup, no URL parsing.+-- * Drops `url` — routable URL is derived from `r2_key` on read.+--+-- Human-composer path always inserts with message_id set (attachments write+-- after `createMessage`, see message-handler.ts). The agent-flow is the only+-- writer of `message_id = NULL` rows.++CREATE TABLE community_attachment_new (+ id TEXT PRIMARY KEY,+ message_id TEXT REFERENCES community_message(id) ON DELETE CASCADE,+ uploader_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ target_id TEXT NOT NULL,+ r2_key TEXT NOT NULL,+ filename TEXT NOT NULL,+ content_type TEXT,+ size INTEGER,+ width INTEGER,+ height INTEGER,+ position INTEGER,+ created_at TEXT NOT NULL+);++-- Backfill from the old table. `/api/community/media/` is 21 characters and+-- SQLite SUBSTR() is 1-indexed and inclusive of the start, so `start = 22`+-- returns everything after the trailing slash — matches `buildMediaKey` output+-- (no leading slash). Threads flatten to `kind = "channel"` per resolve-ref.+INSERT INTO community_attachment_new (+ id, message_id, uploader_id, kind, target_id, r2_key,+ filename, content_type, size, width, height, position, created_at+)+SELECT+ a.id,+ a.message_id,+ m.author_id,+ CASE WHEN m.channel_id IS NOT NULL THEN 'channel' ELSE 'dm' END,+ COALESCE(m.channel_id, m.dm_conversation_id),+ SUBSTR(a.url, 22),+ a.filename, a.content_type, a.size, a.width, a.height,+ ROW_NUMBER() OVER (PARTITION BY a.message_id ORDER BY a.created_at) - 1,+ a.created_at+FROM community_attachment a+JOIN community_message m ON m.id = a.message_id;++-- Backfill-loss assertion: SQLite's RAISE() is only valid inside a trigger,+-- so wrap the count-compare in a one-shot trigger fired by an insert into a+-- sentinel table. Every existing row is FK NOT NULL to community_message with+-- ON DELETE CASCADE today, so no orphans should exist — this catches any+-- anomaly and aborts the migration rather than silently dropping rows.+CREATE TABLE _attachment_backfill_check (dummy INTEGER);+CREATE TRIGGER _attachment_backfill_check_trg+ BEFORE INSERT ON _attachment_backfill_check+ WHEN (SELECT COUNT(*) FROM community_attachment) != (SELECT COUNT(*) FROM community_attachment_new)+BEGIN+ SELECT RAISE(ABORT, 'community_attachment backfill row loss');+END;+INSERT INTO _attachment_backfill_check (dummy) VALUES (1);+DROP TRIGGER _attachment_backfill_check_trg;+DROP TABLE _attachment_backfill_check;++DROP TABLE community_attachment;+ALTER TABLE community_attachment_new RENAME TO community_attachment;+CREATE INDEX idx_attachment_message ON community_attachment(message_id, position);+CREATE INDEX idx_attachment_pending_uploader+ ON community_attachment(uploader_id, kind, target_id)+ WHERE message_id IS NULL;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.tsnew file mode 100644index 000000000..5e79cc127--- /dev/null+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts@@ -0,0 +1,162 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockR2Get = vi.fn()+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({+ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mockR2Get(...a) } },+ })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockGetAttachmentById = vi.fn()+const mockGetMessage = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetDM = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityAttachment: {+ getAttachmentById: (...a: unknown[]) => mockGetAttachmentById(...a),+ },+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessage: (...a: unknown[]) => mockGetMessage(...a),+ },+ communityChannel: {+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },+ communityDm: {+ getDM: (...a: unknown[]) => mockGetDM(...a),+ },+ communityFriendship: { isBlocked: async () => false },+ },+ }+})++import { POST } from "./route"++function req(body: unknown, headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/agent/attachmentDownload", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: typeof body === "string" ? body : JSON.stringify(body),+ })+}++describe("POST /api/community/agent/attachmentDownload", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ })++ it("401 without Authorization", async () => {+ const res = await POST(req({ id: "x" }))+ expect(res.status).toBe(401)+ })++ it("404 when the id doesn't exist", async () => {+ mockGetAttachmentById.mockResolvedValue(null)+ const res = await POST(req({ id: "missing" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ })++ it("404 (not 403) when a pending row belongs to another bot — enumeration-safe", async () => {+ mockGetAttachmentById.mockResolvedValue({+ id: "att_1",+ messageId: null,+ uploaderId: "some_other_bot",+ r2Key: "channel/c1/uuid/a.png",+ filename: "a.png",+ contentType: "image/png",+ size: 10,+ })+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ // Body byte-identical to "genuine 404" case.+ const body = await res.json()+ expect(body).toEqual({ error: "attachment not found" })+ expect(mockR2Get).not.toHaveBeenCalled()+ })++ it("succeeds on a pending row owned by the requesting bot (round-trip verify)", 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: {} })+ 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")+ expect(res.headers.get("Content-Length")).toBe("10")+ // RFC 5987 header. ASCII filename → percent-encoded but unchanged.+ expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("a.png"))+ })++ it("percent-encodes non-ASCII filenames per RFC 5987", async () => {+ mockGetAttachmentById.mockResolvedValue({+ id: "att_1",+ messageId: null,+ uploaderId: "bot_1",+ r2Key: "channel/c1/uuid/x.png",+ filename: "图表.png",+ contentType: "image/png",+ size: 5,+ })+ mockR2Get.mockResolvedValue({ body: new ReadableStream(), size: 5, httpMetadata: {} })+ 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")+ expect(encoded).toBeTruthy()+ expect(decodeURIComponent(encoded!)).toBe("图表.png")+ })++ it("returns 502 when the row exists but R2 has no object (infra drift, not enumeration)", 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(null)+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(502)+ })++ it("404 when a persisted row's channel-member gate fails — same shape as genuine 404", async () => {+ mockGetAttachmentById.mockResolvedValue({+ id: "att_1",+ messageId: "m_1",+ uploaderId: "bot_someone",+ r2Key: "channel/c1/uuid/a.png",+ filename: "a.png",+ contentType: "image/png",+ size: 10,+ })+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c1", dmConversationId: null })+ mockGetChannelForMember.mockResolvedValue(null) // not a member+ const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ expect(mockR2Get).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/agent/attachmentDownload/route.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.tsnew file mode 100644index 000000000..4a40cb286--- /dev/null+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.ts@@ -0,0 +1,90 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, 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"++/**+ * RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes+ * everything outside the RFC 5987 attr-char set. The daemon-side client+ * decodes before writing to disk so non-ASCII filenames (`图表.png`) round+ * trip safely.+ */+function encodeRfc5987(value: string): string {+ return encodeURIComponent(value)+ .replace(/['()]/g, escape)+ .replace(/\*/g, "%2A")+}++/**+ * POST /api/community/agent/attachmentDownload+ *+ * Body: `{ id }`.+ * Response: raw binary stream + `Content-Type`, `Content-Length`,+ * `X-Alook-Filename` (RFC 5987 percent-encoded).+ *+ * Enumeration-safe: every "you can't have this" path returns the same 404+ * with body "attachment not found" — pending-vs-persisted, wrong-owner, and+ * 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).+ */+export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {+ 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 })+ }++ 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 })+ }+ } 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) {+ 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 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 })+})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.tsnew file mode 100644index 000000000..01728719a--- /dev/null+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {}, COMMUNITY_MEDIA: { put: vi.fn() } } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockResolveServerByNameForMember = vi.fn()+const mockResolveChannelByNameForMember = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetDM = vi.fn()+const mockGetDMBetween = vi.fn()+const mockCreatePendingAttachment = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },+ communityChannel: {+ resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },+ communityDm: {+ getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ },+ communityFriendship: { isBlocked: async () => false },+ communityAttachment: {+ createPendingAttachment: (...a: unknown[]) => mockCreatePendingAttachment(...a),+ },+ },+ }+})++const mockHandleAttachmentUpload = vi.fn()+vi.mock("@/lib/community/upload", () => ({+ handleAttachmentUpload: (...a: unknown[]) => mockHandleAttachmentUpload(...a),+}))++import { POST } from "./route"++function req(target: string | null, headers: Record<string, string> = {}): NextRequest {+ const q = target !== null ? `?target=${encodeURIComponent(target)}` : ""+ return new NextRequest(`http://localhost/api/community/agent/attachmentUpload${q}`, {+ method: "POST",+ headers,+ })+}++describe("POST /api/community/agent/attachmentUpload", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ mockCreatePendingAttachment.mockResolvedValue({+ id: "att_1",+ filename: "hi.png",+ contentType: "image/png",+ size: 10,+ })+ mockHandleAttachmentUpload.mockResolvedValue({+ ok: true,+ r2Key: "channel/c1/uuid/hi.png",+ filename: "hi.png",+ contentType: "image/png",+ size: 10,+ })+ })++ it("401 without Authorization", async () => {+ const res = await POST(req("/studio/general"))+ expect(res.status).toBe(401)+ })++ it("400 when target query param is missing", async () => {+ const res = await POST(req(null, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })++ it("returns id + filename + contentType + size — no url, no 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 })++ const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({+ id: "att_1",+ filename: "hi.png",+ contentType: "image/png",+ size: 10,+ })+ // No leaked internals.+ expect(body.url).toBeUndefined()+ expect(body.r2Key).toBeUndefined()+ // Uploader tag is threaded to the R2 primitive.+ expect(mockHandleAttachmentUpload).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ "channel",+ "c1",+ { uploader: "bot", uploaderUserId: "bot_1" },+ )+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith({}, expect.objectContaining({+ uploaderId: "bot_1",+ kind: "channel",+ targetId: "c1",+ r2Key: "channel/c1/uuid/hi.png",+ }))+ })++ it("propagates handler failure response verbatim", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([+ { id: "c1", serverId: "srv_1", parentChannelId: null },+ ])+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })+ mockHandleAttachmentUpload.mockResolvedValue({+ ok: false,+ response: new Response(JSON.stringify({ error: "file too large" }), { status: 413 }),+ })++ const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(413)+ expect(mockCreatePendingAttachment).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/agent/attachmentUpload/route.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.tsnew file mode 100644index 000000000..db79ca72c--- /dev/null+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.ts@@ -0,0 +1,66 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries } 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"++/**+ * POST /api/community/agent/attachmentUpload?target=<ref>+ *+ * Body: multipart/form-data with a single `file` field.+ * Response: `{ id, filename, contentType, size }` — no url, no r2 key.+ *+ * Auth is `withAgentRunnerAuth` (`crk_` bearer via the credential-proxy swap).+ * `target` is resolved through `resolveTargetForMember` so the bot's+ * 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 })+ }++ const db = getDb(ctx.env.DB)++ const resolved = await resolveTargetForMember(db, ctx.botUserId, target)+ if ("error" in resolved) return resolveErrorResponse(resolved)++ 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 result = await handleAttachmentUpload(req, ctx.env, kind, targetId, {+ uploader: "bot",+ uploaderUserId: ctx.botUserId,+ })+ if (!result.ok) return result.response++ 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,+ })+})diff --git a/src/web/src/app/api/community/agent/inboxPull/route.test.ts b/src/web/src/app/api/community/agent/inboxPull/route.test.tsindex 470a733e9..d01b55fe1 100644--- a/src/web/src/app/api/community/agent/inboxPull/route.test.ts+++ b/src/web/src/app/api/community/agent/inboxPull/route.test.ts@@ -11,6 +11,7 @@ const mockGetUserInternal = vi.fn()const mockGetBotBinding = vi.fn()const mockListUnreadMessagesForAgent = vi.fn()const mockToAgentMessages = vi.fn()+const mockListByMessageIds = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -25,6 +26,9 @@ vi.mock("@alook/shared", async () => {listUnreadMessagesForAgent: (...a: unknown[]) => mockListUnreadMessagesForAgent(...a),toAgentMessages: (...a: unknown[]) => mockToAgentMessages(...a),},+ communityAttachment: {+ listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),+ },},}})@@ -46,6 +50,7 @@ describe("POST /api/community/agent/inboxPull", () => {mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })mockToAgentMessages.mockImplementation((_db: unknown, rows: unknown[]) => Promise.resolve(rows))+ mockListByMessageIds.mockResolvedValue([])})it("401 without Authorization", async () => {diff --git a/src/web/src/app/api/community/agent/inboxPull/route.ts b/src/web/src/app/api/community/agent/inboxPull/route.tsindex c890341c2..6d09cfd97 100644--- a/src/web/src/app/api/community/agent/inboxPull/route.ts+++ b/src/web/src/app/api/community/agent/inboxPull/route.ts@@ -39,6 +39,24 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const hasMore = rows.length > maxconst page = hasMore ? rows.slice(0, max) : rows- const messages = await queries.communityAgentInbox.toAgentMessages(db, page, ctx.botUserId)+ // Batch-fetch attachments in one query (plan §Inbox projection). Pending+ // rows (message_id = NULL) never match this inArray, so agent-uploaded+ // pending rows are naturally excluded from the inbox.+ const messageIds = page.map((r) => r.id)+ const attachmentRows = await queries.communityAttachment.listByMessageIds(db, messageIds)+ const attachmentsByMessageId = new Map<string, Array<{ id: string; filename: string; contentType: string | null; size: number | null }>>()+ for (const a of attachmentRows) {+ if (!a.messageId) continue+ const list = attachmentsByMessageId.get(a.messageId) ?? []+ list.push({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size })+ attachmentsByMessageId.set(a.messageId, list)+ }++ const messages = await queries.communityAgentInbox.toAgentMessages(+ db,+ page,+ ctx.botUserId,+ attachmentsByMessageId,+ )return NextResponse.json({ messages, hasMore })})diff --git a/src/web/src/app/api/community/agent/resolve/route.test.ts b/src/web/src/app/api/community/agent/resolve/route.test.tsindex 9f573f95c..72fd531a7 100644--- a/src/web/src/app/api/community/agent/resolve/route.test.ts+++ b/src/web/src/app/api/community/agent/resolve/route.test.ts@@ -46,6 +46,7 @@ vi.mock("@alook/shared", async () => {getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),},communityAgentInbox: { toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a) },+ communityAttachment: { listByMessageIds: async () => [] },},}})diff --git a/src/web/src/app/api/community/agent/resolve/route.ts b/src/web/src/app/api/community/agent/resolve/route.tsindex dac3db43c..412e6d386 100644--- a/src/web/src/app/api/community/agent/resolve/route.ts+++ b/src/web/src/app/api/community/agent/resolve/route.ts@@ -55,6 +55,19 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })}- const message = await queries.communityAgentInbox.toAgentMessage(db, row, ctx.botUserId)+ const attachmentRows = await queries.communityAttachment.listByMessageIds(db, [row.id])+ const attachments = attachmentRows.map((a) => ({+ id: a.id,+ filename: a.filename,+ contentType: a.contentType,+ size: a.size,+ }))++ const message = await queries.communityAgentInbox.toAgentMessage(+ db,+ row,+ ctx.botUserId,+ attachments,+ )return NextResponse.json({ message })})diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex 47ed85d99..2d2ad1a36 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -56,6 +56,10 @@ vi.mock("@alook/shared", async () => {toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),},communityReadState: { getReadState: (...a: unknown[]) => mockGetReadState(...a) },+ communityAttachment: {+ findPendingAttachmentsForBot: async () => [],+ listByMessageIds: async () => [],+ },},}})diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex 1ee2bc8d3..89509226d 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -81,6 +81,27 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {: { kind: "channel", channelId: channel.id, serverId: channel.serverId }}+ // Attachments (plan agent-attachment-pipeline.md §Send). Validate every+ // pending id belongs to this bot, kind, and target BEFORE reservation —+ // the (uploader_id, kind, target_id) tuple is a single indexed lookup.+ // Any mismatch returns the same generic 400, no leakage of which id failed.+ const attachmentKind: "channel" | "dm" = target.kind === "dm" ? "dm" : "channel"+ const attachmentTargetId = target.kind === "dm" ? target.dmId : target.channelId+ if (body.attachments.length > 0) {+ const rows = await queries.communityAttachment.findPendingAttachmentsForBot(db, {+ ids: body.attachments,+ uploaderId: ctx.botUserId,+ kind: attachmentKind,+ targetId: attachmentTargetId,+ })+ if (rows.length !== body.attachments.length) {+ return NextResponse.json(+ { error: "attachment not found or not attachable to this target" },+ { status: 400 },+ )+ }+ }+// `expectedSeq: latestSeq` reuses the exact snapshot the alignment gate// above already fetched — no new query. If another agent's `send` wins// the race between that snapshot and this claim, `createCommunityMessage`@@ -95,6 +116,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {body: { content: body.content.text },source: "cli",expectedSeq: latestSeq,+ attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,})if (!result.ok) {if (result.status === 409) {@@ -109,6 +131,22 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {return NextResponse.json({ error: result.error }, { status: result.status })}- const message = await queries.communityAgentInbox.toAgentMessage(db, result.row, ctx.botUserId)+ // `createCommunityMessage` already fetched the reserved attachments via+ // listByMessageIds (ordered by `position`, which we stamped 0..N-1 in+ // caller order at reservation time). Project directly off `result.attachments`+ // instead of re-issuing the same query.+ const orderedAttachments = (result.attachments ?? []).map((a) => ({+ id: a.id,+ filename: a.filename,+ contentType: a.contentType,+ size: a.size,+ }))++ const message = await queries.communityAgentInbox.toAgentMessage(+ db,+ result.row,+ ctx.botUserId,+ orderedAttachments,+ )return NextResponse.json({ state: "sent", message })})diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.tsindex f8b7a0374..5c56f6e41 100644--- a/src/web/src/app/api/community/messages/[id]/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts@@ -89,7 +89,7 @@ describe("GET /api/community/messages/[id]", () => {})mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })mockListByMessageIds.mockResolvedValue([- { messageId: "m1", filename: "photo.png", url: "https://cdn/1", contentType: "image/png", size: 12345 },+ { messageId: "m1", filename: "photo.png", r2Key: "channel/c1/uuid/photo.png", contentType: "image/png", size: 12345 },])mockListReactionsByMessageIds.mockResolvedValue([{ messageId: "m1", emoji: "👍", userId: "u1" },@@ -101,9 +101,10 @@ describe("GET /api/community/messages/[id]", () => {expect(body.id).toBe("m1")expect(body.content).toBe("hello")expect(body.authorName).toBe("Alice")- // Attachments came through the mapper (grouped shape).+ // Attachments came through the mapper (grouped shape) — url is now+ // derived from r2Key via the shared helper.expect(body.attachments).toEqual([- { kind: "image", name: "photo.png", url: "https://cdn/1" },+ { kind: "image", name: "photo.png", url: "/api/community/media/channel/c1/uuid/photo.png" },])// Reactions came through with `me: true` since userId matches.expect(body.reactions).toEqual([diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 2c1d368d4..0ea1f2a4e 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -5,6 +5,9 @@ const mockGetMessage = vi.fn()const mockGetMessageInScope = vi.fn()const mockGetUserInternal = vi.fn()const mockCreateAttachment = vi.fn()+const mockReserveAttachmentsForMessage = vi.fn()+const mockUnreserveAttachments = vi.fn()+const mockListByMessageIds = vi.fn()const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()const mockCreateMentions = vi.fn()@@ -26,6 +29,9 @@ vi.mock("@alook/shared", async () => {},communityAttachment: {createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),+ reserveAttachmentsForMessage: (...a: unknown[]) => mockReserveAttachmentsForMessage(...a),+ unreserveAttachments: (...a: unknown[]) => mockUnreserveAttachments(...a),+ listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),},communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),@@ -303,7 +309,7 @@ describe("createCommunityMessage — attachment width/height reach the live WS bmockCreateAttachment.mockResolvedValue({id: "att_1",filename: "photo.png",- url: "/media/photo.png",+ r2Key: "channel/c1/uuid/photo.png",contentType: "image/png",size: 1000,width: 1920,@@ -318,12 +324,12 @@ describe("createCommunityMessage — attachment width/height reach the live WS bbody: {content: "hello",attachments: [- { url: "/media/photo.png", filename: "photo.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },+ { url: "/api/community/media/channel/c1/uuid/photo.png", filename: "photo.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },],},})- expect(mockCreateAttachment).toHaveBeenCalledWith({}, expect.objectContaining({ width: 1920, height: 1080 }))+ expect(mockCreateAttachment).toHaveBeenCalledWith({}, expect.objectContaining({ width: 1920, height: 1080, r2Key: "channel/c1/uuid/photo.png" }))expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)const [, event] = mockFanOutToChannel.mock.calls[0]!expect(event.message.attachments).toEqual([@@ -574,3 +580,141 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad})})})++describe("createCommunityMessage — attachment reservation-first flow (agent path)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })+ mockFanOutToChannel.mockResolvedValue(undefined)+ mockBroadcastToUser.mockResolvedValue(undefined)+ mockGetMessage.mockResolvedValue(messageRow())+ mockListByMessageIds.mockResolvedValue([])+ })++ it("reservation-mismatch → unreserve, no message insert, generic 400", async () => {+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // only 1 of 2 reserved++ 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).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))+ expect(mockCreateMessage).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("thrown insertMessageRow error → unreserve, then re-throw", async () => {+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1", "att_2"])+ mockCreateMessage.mockRejectedValue(new Error("d1_transient"))++ await expect(+ createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1", "att_2"],+ }),+ ).rejects.toThrow("d1_transient")++ expect(mockUnreserveAttachments).toHaveBeenCalledTimes(1)+ expect(mockUnreserveAttachments.mock.calls[0][1]).toEqual(+ expect.objectContaining({ ids: ["att_1", "att_2"] }),+ )+ })++ it("expectedSeq CAS-null → unreserve and return seq_conflict", async () => {+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])+ mockCreateMessage.mockResolvedValue(null) // CAS-null (returned, not thrown)++ const res = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1"],+ expectedSeq: 5,+ })++ expect(res.ok).toBe(false)+ if (res.ok) return+ expect(res.status).toBe(409)+ expect(res.error).toBe("seq_conflict")+ expect(mockUnreserveAttachments).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))+ })++ it("attachment-only bot send (empty text) is NOT rejected by the empty-body guard", async () => {+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })+ mockListByMessageIds.mockResolvedValue([+ {+ id: "att_1",+ filename: "photo.png",+ r2Key: "channel/c1/uuid/photo.png",+ contentType: "image/png",+ size: 100,+ width: null,+ height: null,+ messageId: "msg_preminted",+ position: 0,+ },+ ])++ const res = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "" }, // <- attachment-only send+ attachmentIds: ["att_1"],+ })++ expect(res.ok).toBe(true)+ if (!res.ok) return+ expect(mockCreateMessage).toHaveBeenCalledTimes(1)+ })++ it("happy path — reserved rows are projected as CreatedAttachment via listByMessageIds", async () => {+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })+ mockListByMessageIds.mockResolvedValue([+ {+ id: "att_1",+ filename: "photo.png",+ r2Key: "channel/c1/uuid/photo.png",+ contentType: "image/png",+ size: 100,+ width: null,+ height: null,+ messageId: "msg_preminted",+ position: 0,+ },+ ])++ const res = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hi" },+ attachmentIds: ["att_1"],+ })++ expect(res.ok).toBe(true)+ if (!res.ok) return+ expect(res.attachments).toEqual([+ expect.objectContaining({+ id: "att_1",+ filename: "photo.png",+ url: "/api/community/media/channel/c1/uuid/photo.png",+ }),+ ])+ expect(mockUnreserveAttachments).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex bf84dd3df..dec0f71c5 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -6,11 +6,13 @@ import {MAX_ATTACHMENTS_PER_MESSAGE,WS_EVENTS,} from "@alook/shared"+import { nanoid } from "nanoid"import type { MentionType } from "@alook/shared"import type { Database } from "@alook/shared"import { fanOutToChannel, fanOutToDM } from "./fanout"import { broadcastToUser } from "../broadcast"import { mapMessageForWs } from "./message-payload"+import { mediaUrlFromKey } from "./storage"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "./audit"export type MessageTarget =@@ -42,6 +44,12 @@ export function isChannelTarget(target: { kind: string } | string): boolean {}type IncomingAttachment = {+ /**+ * Full routable URL as returned by the human upload response+ * (`/api/community/media/<key>`). The handler strips the `MEDIA_URL_PREFIX`+ * to derive the stored `r2Key`. Kept on the wire (rather than switching+ * clients to a raw key) so the human-composer POST shape stays unchanged.+ */url: stringfilename: stringcontentType: string@@ -50,6 +58,14 @@ type IncomingAttachment = {height?: number}+const MEDIA_URL_PREFIX = "/api/community/media/"++function r2KeyFromUrl(url: string): string | null {+ if (!url.startsWith(MEDIA_URL_PREFIX)) return null+ const rest = url.slice(MEDIA_URL_PREFIX.length)+ return rest.length > 0 ? rest : null+}+export type IncomingMessageBody = {content?: unknownreplyToId?: unknown@@ -67,6 +83,14 @@ type CreatedAttachment = {height?: number | null}+function attachmentKindFromTarget(target: MessageTarget): "channel" | "dm" {+ return target.kind === "dm" ? "dm" : "channel"+}++function attachmentTargetId(target: MessageTarget): string {+ return target.kind === "dm" ? target.dmId : target.channelId+}+type FullMessageRow = NonNullable<Awaited<ReturnType<typeof queries.communityMessage.getMessage>>>@@ -142,6 +166,16 @@ export async function createCommunityMessage(params: {* it without a refresh.*/includeAuthorInFanout?: boolean+ /**+ * Agent-attachment path: pending attachment ids the caller has already+ * validated against (uploader, kind, target). When present, the handler+ * pre-mints the message id, reserves the pending rows in a single+ * atomic UPDATE, then inserts the message — compensating unreserves on+ * every failure path so no message row is ever committed with a partial+ * attachment set. Mutually exclusive with `body.attachments`, which is the+ * human-composer path.+ */+ attachmentIds?: string[]/*** Do NOT run any WS side effect inline. Instead, on success, return a* `broadcast` thunk on the OK result the caller can invoke once its own@@ -163,6 +197,7 @@ export async function createCommunityMessage(params: {skipWake,includeAuthorInFanout,deferBroadcast,+ attachmentIds,} = paramsconst content = typeof body.content === "string" ? body.content : ""@@ -191,7 +226,12 @@ export async function createCommunityMessage(params: {// A message needs either text content OR at least one attachment. Empty// both means the client wired something wrong — but a bare// attachments-only send is a legitimate flow (drop an image, hit Enter).- if (content.trim().length === 0 && (!incomingAttachments || incomingAttachments.length === 0)) {+ // Agent-attachment path uses `attachmentIds` (pending rows reserved by+ // reservation-first flow), NOT `body.attachments`; both count as+ // "attachment present" for this guard.+ const hasAgentAttachments = Array.isArray(attachmentIds) && attachmentIds.length > 0+ const hasHumanAttachments = !!incomingAttachments && incomingAttachments.length > 0+ if (content.trim().length === 0 && !hasHumanAttachments && !hasAgentAttachments) {return { ok: false, status: 400, error: "content or attachments required" }}@@ -202,7 +242,16 @@ export async function createCommunityMessage(params: {? body.mentionType: undefined- const baseMessageData = {+ const baseMessageData: {+ id?: string;+ authorId: string;+ content: string;+ channelId: string | undefined;+ dmConversationId: string | undefined;+ replyToId: string | undefined;+ mentionType: MentionType | undefined;+ type?: string;+ } = {authorId,content,channelId: isDmTarget(target) ? undefined : target.channelId,@@ -211,37 +260,126 @@ export async function createCommunityMessage(params: {mentionType,...(messageType !== undefined ? { type: messageType } : {}),}++ // Agent-attachment path (plan §Send). Pre-mint the message id BEFORE+ // reserving pending attachments so the reservation UPDATE can point at it.+ // Reservation-first guards against unsafe rollback of+ // `insertMessageRow`'s side effects (scope counter bump, `lastMessageAt`,+ // author read-state watermark, mention/fanout).+ const useAttachmentReservation =+ attachmentIds !== undefined && attachmentIds.length > 0+ const preMintedId = useAttachmentReservation ? nanoid() : undefined+ const reservedAttachmentIds: string[] = []++ if (useAttachmentReservation) {+ const reserved = await queries.communityAttachment.reserveAttachmentsForMessage(db, {+ ids: attachmentIds!,+ messageId: preMintedId!,+ })+ if (reserved.length !== attachmentIds!.length) {+ // Partial-overlap race (S1={A,B}, S2={B,C}). Unreserve whatever THIS+ // caller uniquely grabbed so rows aren't stuck with a message_id+ // pointing at a message that will never exist.+ await queries.communityAttachment.unreserveAttachments(db, {+ ids: reserved,+ messageId: preMintedId!,+ })+ return {+ ok: false,+ status: 400,+ error: "attachment not found or not attachable to this target",+ }+ }+ reservedAttachmentIds.push(...reserved)+ if (preMintedId) baseMessageData.id = preMintedId+ }+// `createMessage`'s overloads key off whether the `expectedSeq` property// is present at all, not just its runtime value — a `number | undefined`// typed property doesn't cleanly resolve against either overload, so the// pass-through branches explicitly instead of spreading `expectedSeq` in.- const created =- expectedSeq !== undefined- ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })- : await queries.communityMessage.createMessage(db, baseMessageData)+ let created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>>+ try {+ created =+ expectedSeq !== undefined+ ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })+ : await queries.communityMessage.createMessage(db, baseMessageData)+ } catch (err) {+ // D1 transient failure / batch error / FK violation: unreserve so the+ // pending rows aren't leaked. `unreserveAttachments` is scoped by+ // `messageId = preMintedId`, so it only touches rows we reserved.+ if (useAttachmentReservation) {+ await queries.communityAttachment.unreserveAttachments(db, {+ ids: reservedAttachmentIds,+ messageId: preMintedId!,+ })+ }+ throw err+ }// Lost the CAS race (plans/fix-agent-send-race-condition.md) — zero rows// were written anywhere (no message, no channel/DM bump, no read-state- // watermark). Return immediately, before attachments/mentions/fan-out/audit.+ // watermark). Unreserve any attachments we grabbed BEFORE returning so+ // the bot can retry with the same ids.if (created === null) {+ if (useAttachmentReservation) {+ await queries.communityAttachment.unreserveAttachments(db, {+ ids: reservedAttachmentIds,+ messageId: preMintedId!,+ })+ }return { ok: false, status: 409, error: "seq_conflict" }}- const attachments: CreatedAttachment[] = incomingAttachments?.length- ? await Promise.all(- incomingAttachments.map((att) =>- queries.communityAttachment.createAttachment(db, {+ // Human-composer path: insert attachment rows now that the message exists.+ // 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) {+ const rows = await queries.communityAttachment.listByMessageIds(db, [created.id])+ attachments = rows.map((r) => ({+ id: r.id,+ filename: r.filename,+ url: mediaUrlFromKey(r.r2Key),+ contentType: r.contentType,+ size: r.size,+ width: r.width,+ height: r.height,+ }))+ } else if (incomingAttachments?.length) {+ const kind = attachmentKindFromTarget(target)+ const targetId = attachmentTargetId(target)+ attachments = await Promise.all(+ incomingAttachments.map(async (att, idx) => {+ const r2Key = r2KeyFromUrl(att.url)+ if (!r2Key) {+ throw new Error(`attachment url outside /api/community/media/: ${att.url}`)+ }+ const row = await queries.communityAttachment.createAttachment(db, {messageId: created.id,+ uploaderId: authorId,+ kind,+ targetId,+ r2Key,filename: att.filename,- url: att.url,+ position: idx,contentType: att.contentType,size: att.size,width: att.width,height: att.height,- }),- ),+ })+ return {+ id: row.id,+ filename: row.filename,+ url: mediaUrlFromKey(row.r2Key),+ contentType: row.contentType,+ size: row.size,+ width: row.width,+ height: row.height,+ }+ }),)- : []+ }const row = await queries.communityMessage.getMessage(db, created.id)if (!row) {diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.tsindex 3f82b27dd..5c54b117b 100644--- a/src/web/src/lib/community/messages.test.ts+++ b/src/web/src/lib/community/messages.test.ts@@ -1,38 +1,46 @@import { describe, it, expect } from "vitest"import { groupAttachments } from "./messages"-// No test file covered `groupAttachments` before this — it was only-// exercised indirectly through route tests. `width`/`height` are optional-// fields on the output shape, which per a plan review of-// plans/attachment-image-dimensions.md means an implementation could omit-// them from the `entry` object literal (and its `as {...}` cast) with zero-// typecheck error — assert on the actual returned value, not just the-// declared type, to catch that.+// `groupAttachments` derives `url` from `r2Key` via the shared+// `mediaUrlFromKey` helper — the DB row itself no longer carries a `url`+// column (plan agent-attachment-pipeline.md). `width`/`height` are optional+// on the output shape, so we assert on the actual returned object rather than+// relying on the declared type to catch a missing field.describe("groupAttachments", () => {it("projects width/height onto an image-kind entry when present on the row", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },+ { messageId: "m1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },])expect(result.m1).toEqual([- { kind: "image", name: "a.png", url: "/a.png", width: 1920, height: 1080 },+ { kind: "image", name: "a.png", url: "/api/community/media/channel/c1/uuid/a.png", width: 1920, height: 1080 },])})it("leaves width/height undefined on an image-kind entry when the row has none", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: null, height: null },+ { messageId: "m1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: null, height: null },])expect(result.m1).toEqual([- { kind: "image", name: "a.png", url: "/a.png", width: undefined, height: undefined },+ { kind: "image", name: "a.png", url: "/api/community/media/channel/c1/uuid/a.png", width: undefined, height: undefined },])})it("never adds width/height to a file-kind entry, even if present on the row", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.pdf", url: "/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },+ { messageId: "m1", filename: "a.pdf", r2Key: "channel/c1/uuid/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },])expect(result.m1).toEqual([- { kind: "file", name: "a.pdf", url: "/a.pdf", size: "2.0 KB" },+ { kind: "file", name: "a.pdf", url: "/api/community/media/channel/c1/uuid/a.pdf", size: "2.0 KB" },])})++ it("skips pending rows (messageId=null) so agent-uploaded pending attachments never surface", () => {+ const result = groupAttachments([+ { messageId: null, filename: "pending.png", r2Key: "channel/c1/uuid/pending.png", contentType: "image/png", size: 100, width: null, height: null },+ { messageId: "m1", filename: "linked.png", r2Key: "channel/c1/uuid/linked.png", contentType: "image/png", size: 100, width: null, height: null },+ ])+ expect(result).toEqual({+ m1: [{ kind: "image", name: "linked.png", url: "/api/community/media/channel/c1/uuid/linked.png", width: undefined, height: undefined }],+ })+ })})diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.tsindex 14165f223..7b098ba48 100644--- a/src/web/src/lib/community/messages.ts+++ b/src/web/src/lib/community/messages.ts@@ -1,4 +1,5 @@import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"+import { mediaUrlFromKey } from "./storage"// Format file sizes for displayfunction formatBytes(bytes: number): string {@@ -120,17 +121,20 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: sreturn { members, hasMore, cursor }}-// Group raw attachment rows by messageId into display format+// Group raw attachment rows by messageId into display format. Attachments+// with `messageId = null` (pending, not yet linked to a message) are skipped —+// the read paths never surface them.export function groupAttachments(- attachments: Array<{ messageId: string; filename: string; url: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>+ attachments: Array<{ messageId: string | null; filename: string; r2Key: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> {const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> = {}for (const a of attachments) {+ if (!a.messageId) continueconst kind = a.contentType?.startsWith("image/") ? "image" : "file"const entry = {kind,name: a.filename,- url: a.url,+ url: mediaUrlFromKey(a.r2Key),...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}),...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),} as { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.tsindex 631beec84..a295cf254 100644--- a/src/web/src/lib/community/storage.test.ts+++ b/src/web/src/lib/community/storage.test.ts@@ -1,7 +1,10 @@import { describe, it, expect } from "vitest"import {+ buildMediaKey,buildUserAvatarKey,buildBotAvatarKey,+ mediaUrlFromKey,+ sanitizeAttachmentFilename,userAvatarUrl,botAvatarUrl,} from "./storage"@@ -47,3 +50,41 @@ describe("no collisions between user and bot avatar keys for the same id", () =>expect(userAvatarUrl("same-id")).not.toBe(botAvatarUrl("same-id"))})})++describe("sanitizeAttachmentFilename", () => {+ it("strips traversal sequences", () => {+ // `..` collapses to `_` first, then `/` is replaced by `_`.+ expect(sanitizeAttachmentFilename("../evil.png")).toBe("__evil.png")+ })++ it("replaces path separators", () => {+ expect(sanitizeAttachmentFilename("a/b/c.png")).toBe("a_b_c.png")+ })++ it("replaces control characters", () => {+ expect(sanitizeAttachmentFilename("a\x01b\x7fc.png")).toBe("a_b_c.png")+ })++ it("caps length at 255", () => {+ const long = "x".repeat(300)+ expect(sanitizeAttachmentFilename(long).length).toBe(255)+ })++ it("falls back to _ when the input is empty", () => {+ expect(sanitizeAttachmentFilename("")).toBe("_")+ })+})++describe("buildMediaKey", () => {+ it("emits keys with no leading slash and the sanitized filename component", () => {+ const key = buildMediaKey("channel", "c1", "uuid", "../evil.png")+ expect(key.startsWith("/")).toBe(false)+ expect(key).toBe("channel/c1/uuid/__evil.png")+ })+})++describe("mediaUrlFromKey", () => {+ it("prepends the media route prefix without adding a slash", () => {+ expect(mediaUrlFromKey("channel/c1/uuid/a.png")).toBe("/api/community/media/channel/c1/uuid/a.png")+ })+})diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.tsindex 2531bcc5b..8403f2ade 100644--- a/src/web/src/lib/community/storage.ts+++ b/src/web/src/lib/community/storage.ts@@ -1,6 +1,33 @@+/**+ * Sanitize a filename component that will be embedded into an R2 key. Strips+ * `..`, replaces `/` and any C0 / DEL control character with `_`, and caps+ * total length at 255. Closes an R2-key injection hole in the media-key+ * builder: without this, a filename like `../../server-icon/foo/bar.png`+ * would be inserted verbatim, letting a caller with attachment-upload access+ * write outside its target's prefix.+ */+export function sanitizeAttachmentFilename(input: string): string {+ const cleaned = input+ .replace(/\.\./g, "_")+ // eslint-disable-next-line no-control-regex+ .replace(/[\/\x00-\x1f\x7f]/g, "_")+ if (cleaned.length === 0) return "_"+ return cleaned.length > 255 ? cleaned.slice(0, 255) : cleaned+}++/**+ * Derive the routable media URL from a stored R2 key. Every read-side call+ * site (`groupAttachments`, `mapMessageForApi`, `mapMessageForWs`) goes+ * through this helper so the `/api/community/media/` prefix lives in one+ * place.+ */+export function mediaUrlFromKey(r2Key: string): string {+ return `/api/community/media/${r2Key}`+}+// R2 storage key buildersexport function buildMediaKey(type: "channel" | "dm" | "thread", id: string, fileId: string, filename: string): string {- return `${type}/${id}/${fileId}/${filename}`+ return `${type}/${id}/${fileId}/${sanitizeAttachmentFilename(filename)}`}export function buildServerIconKey(serverId: string, fileId: string): string {diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex 05c74ddb5..5a64ee92e 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -76,23 +76,38 @@ function fakeFile(name: string, type: string, size: number) {describe("handleAttachmentUpload", () => {beforeEach(() => vi.clearAllMocks())+ const USER_TAG = { uploader: "user" as const, uploaderUserId: "u1" }+it("uploads an in-allowlist file under the size cap", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("hi.png", "image/png", 10)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1")+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)expect(res.ok).toBe(true)if (!res.ok) return- expect(res.key).toMatch(/^channel\/c1\/[0-9a-f-]+\/hi\.png$/)- expect(res.url).toBe(`/api/community/media/${res.key}`)+ expect(res.r2Key).toMatch(/^channel\/c1\/[0-9a-f-]+\/hi\.png$/)expect(res.contentType).toBe("image/png")expect(res.size).toBe(10)expect(put).toHaveBeenCalledOnce()+ const [, , options] = put.mock.calls[0]+ expect(options.customMetadata).toMatchObject({ uploader: "user" })+ })++ it("stamps customMetadata.uploader=bot + bot_user_id when the caller is a bot", async () => {+ const put = vi.fn().mockResolvedValue(undefined)+ const file = fakeFile("hi.png", "image/png", 10)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", {+ uploader: "bot",+ uploaderUserId: "bot_ada",+ })+ expect(res.ok).toBe(true)+ const [, , options] = put.mock.calls[0]+ expect(options.customMetadata).toEqual({ uploader: "bot", bot_user_id: "bot_ada" })})it("passes a known-length File body to R2", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("hi.png", "image/png", 10)- await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1")+ await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)expect(put).toHaveBeenCalledOnce()const [, body] = put.mock.calls[0]expect(body).toBe(file)@@ -103,7 +118,7 @@ describe("handleAttachmentUpload", () => {it("rejects when no file part is present (400)", async () => {const put = vi.fn()- const res = await handleAttachmentUpload(reqWithFile(null), envWithR2(put), "channel", "c1")+ const res = await handleAttachmentUpload(reqWithFile(null), envWithR2(put), "channel", "c1", USER_TAG)expect(res.ok).toBe(false)if (res.ok) returnexpect(res.response.status).toBe(400)@@ -113,7 +128,7 @@ describe("handleAttachmentUpload", () => {it("rejects oversize files with 413", async () => {const put = vi.fn()const file = fakeFile("big.png", "image/png", MAX_ATTACHMENT_SIZE_BYTES + 1)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1")+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)expect(res.ok).toBe(false)if (res.ok) returnexpect(res.response.status).toBe(413)@@ -123,7 +138,7 @@ describe("handleAttachmentUpload", () => {it("rejects disallowed MIME types with 400", async () => {const put = vi.fn()const file = fakeFile("evil.exe", "application/x-msdownload", 2)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1")+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)expect(res.ok).toBe(false)if (res.ok) returnexpect(res.response.status).toBe(400)@@ -140,11 +155,23 @@ describe("handleAttachmentUpload", () => {]for (const { type, name } of cases) {const f = fakeFile(name, type, 1)- const res = await handleAttachmentUpload(reqWithFile(f), envWithR2(put), "dm", "d1")+ const res = await handleAttachmentUpload(reqWithFile(f), envWithR2(put), "dm", "d1", USER_TAG)expect(res.ok).toBe(true)}expect(put).toHaveBeenCalledTimes(cases.length)})++ it("sanitizes traversal + slash characters out of the R2 key", async () => {+ const put = vi.fn().mockResolvedValue(undefined)+ const file = fakeFile("../evil/../name.png", "image/png", 4)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ expect(res.ok).toBe(true)+ if (!res.ok) return+ // No `..`, no `/` beyond the three fixed structural separators.+ const trailing = res.r2Key.replace(/^channel\/c1\/[0-9a-f-]+\//, "")+ expect(trailing).not.toContain("..")+ expect(trailing).not.toContain("/")+ })})describe("handleServerIconUpload", () => {diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex 049c62810..15041ab00 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -15,6 +15,7 @@ import {buildServerIconKey,buildUserAvatarKey,buildBotAvatarKey,+ mediaUrlFromKey,userAvatarUrl,botAvatarUrl,} from "./storage"@@ -34,8 +35,32 @@ type UploadErr = { ok: false; response: NextResponse }export type UploadResult = UploadOk | UploadErr+/**+ * Slim result for the shared attachment-upload primitive. `runAttachmentUpload`+ * and the new agent-upload route both build wire responses from this — the+ * legacy `UploadResult` shape is preserved by callers that wrap it.+ */+type AttachmentUploadOk = {+ ok: true+ r2Key: string+ filename: string+ contentType: string+ size: number+}+export type AttachmentUploadResult = AttachmentUploadOk | UploadErr+type AttachmentKind = "channel" | "dm" | "thread"+/**+ * Provenance tag stamped as R2 `customMetadata`. Human uploads set+ * `uploader: "user"`; agent uploads set `uploader: "bot"` so a future orphan-+ * GC cron can filter cheaply on bot-authored blobs.+ */+export type UploaderTag = {+ uploader: "user" | "bot"+ uploaderUserId: string+}+function mimeAllowed(contentType: string, allowed: readonly string[]): boolean {if (!contentType) return falsereturn allowed.some((entry) =>@@ -72,7 +97,8 @@ export async function handleAttachmentUpload(env: Env,kind: AttachmentKind,targetId: string,-): Promise<UploadResult> {+ uploaderTag: UploaderTag,+): Promise<AttachmentUploadResult> {const fileOrErr = await readFile(req)if ("ok" in fileOrErr && fileOrErr.ok === false) return fileOrErrconst file = fileOrErr as File@@ -95,13 +121,15 @@ export async function handleAttachmentUpload(await env.COMMUNITY_MEDIA.put(key, file, {httpMetadata: { contentType: file.type },+ customMetadata: {+ uploader: uploaderTag.uploader,+ bot_user_id: uploaderTag.uploader === "bot" ? uploaderTag.uploaderUserId : "",+ },})return {ok: true,- id: fileId,- key,- url: `/api/community/media/${key}`,+ r2Key: key,filename: file.name,contentType: file.type,size: file.size,@@ -241,11 +269,17 @@ export async function runAttachmentUpload(const auth = await permissionCheck(db, id, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const result = await handleAttachmentUpload(req, ctx.env, kind, id)+ const result = await handleAttachmentUpload(req, ctx.env, kind, id, {+ uploader: "user",+ uploaderUserId: ctx.userId,+ })if (!result.ok) return result.response+ // Human web client tracks attachments in-memory until send, so no id is+ // returned here — parity with the pre-refactor shape. `url` is derived+ // from the stored key via the shared helper.return writeJSON({- url: result.url,+ url: mediaUrlFromKey(result.r2Key),filename: result.filename,contentType: result.contentType,size: result.size,