Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(chat): support images/files in agent chat replies (MUL-4287) (#5164)

Naiyuan Qinga19e60a9e641
diff --git a/apps/mobile/components/chat/chat-message-list.tsx b/apps/mobile/components/chat/chat-message-list.tsx
index c3dda0f344..d391f1459a 100644
--- a/apps/mobile/components/chat/chat-message-list.tsx
+++ b/apps/mobile/components/chat/chat-message-list.tsx
@@ -14,9 +14,11 @@
* v1 simplifications:
* - No "Replied in Ns" badge under assistant bubbles (elapsed_ms is
* parsed but not displayed). Easy v2 add — show below the bubble.
- * - No attachment card rendering. Attachments embedded as
- * `![](url)` / `[name](url)` in `content` flow through the existing
- * markdown renderer.
+ * - Attachments bound to a message but NOT referenced inline in `content`
+ * render as standalone cards below the bubble via `CommentAttachmentList`
+ * (same component the comment thread uses; mirrors web reusing
+ * `AttachmentList` in chat). Inline `![](url)` / `[name](url)` still flow
+ * through the markdown renderer and are de-duped out of the card list.
*
* Interaction: long-press inside a bubble fires a native iOS
* `ActionSheetIOS` (Copy / Select Text / Cancel). While the sheet is on
@@ -58,6 +60,10 @@ import { useChatSelectStore } from "@/data/chat-select-store";
import { useChatMessageLongPress } from "./message-long-press";
import { ChatEmptyState } from "./chat-empty-state";
import { ChatTimeline } from "./chat-timeline";
+// Reuse the comment thread's standalone attachment list — same design web
+// reuses in chat (AttachmentList). Renders any bound attachment not already
+// referenced inline in the message content, with same-file dedup.
+import { CommentAttachmentList } from "@/components/issue/comment-attachment-list";
import { StatusPill } from "./status-pill";
import {
Collapsible,
@@ -250,7 +256,7 @@ function MessageRow({ message }: { message: ChatMessage }) {
const body = (
<View
className={cn(
- "self-end max-w-[80%] rounded-2xl border-2 px-3.5 py-2 transition-colors",
+ "self-end max-w-[80%] gap-1.5 rounded-2xl border-2 px-3.5 py-2 transition-colors",
isSelecting
? "bg-primary/5 border-primary/30"
: longPress.isPressed
@@ -264,6 +270,10 @@ function MessageRow({ message }: { message: ChatMessage }) {
selectable={isSelecting}
compact
/>
+ <CommentAttachmentList
+ attachments={message.attachments}
+ content={message.content}
+ />
</View>
);
if (isSelecting) return body;
@@ -340,6 +350,14 @@ function AssistantRow({
selectable={isSelecting}
/>
)}
+ {/* Standalone attachment cards for anything not referenced inline. An
+ image-only reply is a real ('message') outcome with empty content, so
+ it flows through the else-branch above (renders nothing) and the cards
+ here ARE the reply. */}
+ <CommentAttachmentList
+ attachments={message.attachments}
+ content={message.content}
+ />
{message.elapsed_ms != null ? (
<ElapsedCaption
variant={isNoResponse ? "finished" : "replied"}
diff --git a/apps/mobile/components/issue/comment-attachment-list.tsx b/apps/mobile/components/issue/comment-attachment-list.tsx
index f48b4b301c..2870ca7bdd 100644
--- a/apps/mobile/components/issue/comment-attachment-list.tsx
+++ b/apps/mobile/components/issue/comment-attachment-list.tsx
@@ -25,6 +25,7 @@ import { useMemo } from "react";
import { Linking, Pressable, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import type { Attachment } from "@multica/core/types";
+import { standaloneAttachments } from "@/lib/attachment-dedup";
import { MarkdownImage } from "@/lib/markdown/markdown-image";
import { resolveAttachmentUrl } from "@/lib/attachment-url";
import { useColorScheme } from "@/lib/use-color-scheme";
@@ -45,30 +46,14 @@ export function CommentAttachmentList({ attachments, content }: Props) {
const { colorScheme } = useColorScheme();
const theme = THEME[colorScheme];
- const standalone = useMemo(() => {
- if (!attachments || attachments.length === 0) return [];
- if (!content) return attachments;
- return attachments.filter((a) => {
- // Skip attachments whose URL is already referenced inline in the
- // markdown — they'll render via MarkdownImage (images) or a markdown
- // link (files), and we'd otherwise show them twice.
- if (content.includes(a.url)) return false;
- // Dedup: if another attachment with the same file identity (name,
- // type, size) is already inline in the content, this one is a
- // duplicate upload — skip it. Mirrors web's
- // `comment-card.tsx:132-140` defense.
- const hasSiblingInContent = attachments.some(
- (other) =>
- other.id !== a.id &&
- other.filename === a.filename &&
- other.content_type === a.content_type &&
- other.size_bytes === a.size_bytes &&
- content.includes(other.url),
- );
- if (hasSiblingInContent) return false;
- return true;
- });
- }, [attachments, content]);
+ // Only render attachments not already referenced inline in the body. The
+ // dedup lives in a pure helper (lib/attachment-dedup) so it can be unit
+ // tested; it matches every real URL form the server emits (stable path /
+ // url / download_url / markdown_url), mirroring web's AttachmentList.
+ const standalone = useMemo(
+ () => standaloneAttachments(attachments, content),
+ [attachments, content],
+ );
if (standalone.length === 0) return null;
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.test.ts b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
new file mode 100644
index 0000000000..f20b1169c6
--- /dev/null
+++ b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it, vi } from "vitest";
+import { QueryClient } from "@tanstack/react-query";
+import type { ChatDonePayload, ChatMessage } from "@multica/core/types";
+
+// chat-ws-updaters imports chatKeys from data/queries/chat, which transitively
+// imports the native fetch client. Mock it so the Node test never loads RN
+// modules — chatKeys itself is a pure key factory and needs nothing from api.
+vi.mock("@/data/api", () => ({ api: {} }));
+
+import { applyChatDoneToCache } from "./chat-ws-updaters";
+import { chatKeys } from "@/data/queries/chat";
+
+const SESSION = "session-1";
+
+function donePayload(over: Partial<ChatDonePayload> = {}): ChatDonePayload {
+ return {
+ chat_session_id: SESSION,
+ task_id: "task-1",
+ message_id: "msg-1",
+ content: "here is the chart",
+ created_at: "2026-07-09T00:00:00Z",
+ elapsed_ms: 1200,
+ ...over,
+ };
+}
+
+describe("applyChatDoneToCache", () => {
+ it("patches the assistant bubble inline AND invalidates messages so bound attachments refetch", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), []);
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ applyChatDoneToCache(qc, donePayload());
+
+ // Inline patch: the bubble lands immediately (no flicker) — but without
+ // attachments, because the event payload never carries them.
+ const msgs = qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION));
+ expect(msgs).toHaveLength(1);
+ expect(msgs?.[0].id).toBe("msg-1");
+ expect(msgs?.[0].attachments).toBeUndefined();
+
+ // Refetch: the authoritative message list (with attachments) is pulled in.
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.messages(SESSION),
+ });
+ // pendingTask cleared so the status pill unmounts.
+ expect(qc.getQueryData(chatKeys.pendingTask(SESSION))).toEqual({});
+ });
+
+ it("invalidates even when the payload lacks an inline message (legacy shape)", () => {
+ const qc = new QueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ applyChatDoneToCache(
+ qc,
+ donePayload({ message_id: undefined, content: undefined, created_at: undefined }),
+ );
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.messages(SESSION),
+ });
+ });
+
+ it("does not duplicate an echoed message on reconnect", () => {
+ const qc = new QueryClient();
+ const existing: ChatMessage = {
+ id: "msg-1",
+ chat_session_id: SESSION,
+ role: "assistant",
+ content: "here is the chart",
+ task_id: "task-1",
+ created_at: "2026-07-09T00:00:00Z",
+ };
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), [existing]);
+
+ applyChatDoneToCache(qc, donePayload());
+
+ expect(qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))).toHaveLength(1);
+ });
+});
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index c4e9720746..b1a286e1db 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -100,6 +100,14 @@ export function flipSessionUnread(
* Older servers (pre-#2123 in web's commit history) sent only chat_session_id
* + task_id. Detect that and fall back to invalidate; we'll refetch the
* messages list and accept a one-frame window with no bubble.
+ *
+ * The inline patch never carries attachments: `ChatDonePayload` has no
+ * attachments field by contract, yet an assistant reply may have images/files
+ * bound to it server-side. So after the inline patch we ALWAYS invalidate the
+ * messages list to refetch the authoritative rows (which include
+ * `attachments`). Mirrors web's `use-realtime-sync.ts`, which invalidates
+ * unconditionally after its inline patch. The patch is kept purely for the
+ * instant, flicker-free bubble; the refetch is what makes attachments appear.
*/
export function applyChatDoneToCache(
qc: QueryClient,
@@ -128,11 +136,12 @@ export function applyChatDoneToCache(
return [...old, assistantMsg];
},
);
- } else {
- qc.invalidateQueries({
- queryKey: chatKeys.messages(payload.chat_session_id),
- });
}
+ // Refetch the authoritative message list so any attachments bound to the
+ // assistant reply (absent from the event payload) are pulled in.
+ qc.invalidateQueries({
+ queryKey: chatKeys.messages(payload.chat_session_id),
+ });
// Clear in-flight pointer in the same tick so StatusPill unmounts and
// the AssistantMessage owns the rendering.
qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
diff --git a/apps/mobile/lib/attachment-dedup.test.ts b/apps/mobile/lib/attachment-dedup.test.ts
new file mode 100644
index 0000000000..54eb2391a2
--- /dev/null
+++ b/apps/mobile/lib/attachment-dedup.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+import type { Attachment } from "@multica/core/types";
+import { standaloneAttachments } from "./attachment-dedup";
+
+function att(over: Partial<Attachment> = {}): Attachment {
+ return {
+ id: "att-1",
+ workspace_id: "ws-1",
+ issue_id: null,
+ comment_id: null,
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "agent",
+ uploader_id: "agent-1",
+ filename: "chart.png",
+ url: "https://cdn.example/chart.png",
+ download_url: "https://signed.example/chart.png?sig=x",
+ markdown_url: "https://public.example/api/attachments/att-1/download",
+ content_type: "image/png",
+ size_bytes: 123,
+ created_at: "2026-07-09T00:00:00Z",
+ ...over,
+ };
+}
+
+describe("standaloneAttachments", () => {
+ it("excludes an attachment referenced inline via markdown_url (the CLI snippet form)", () => {
+ const a = att();
+ const content = `see the result\n\n![chart.png](${a.markdown_url})`;
+ expect(standaloneAttachments([a], content)).toEqual([]);
+ });
+
+ it("excludes an attachment referenced inline via the stable download path", () => {
+ const a = att();
+ const content = `![chart.png](/api/attachments/${a.id}/download)`;
+ expect(standaloneAttachments([a], content)).toEqual([]);
+ });
+
+ it("excludes an attachment referenced inline via raw url", () => {
+ const a = att();
+ expect(standaloneAttachments([a], `![x](${a.url})`)).toEqual([]);
+ });
+
+ it("excludes an attachment referenced inline via signed download_url", () => {
+ const a = att();
+ expect(standaloneAttachments([a], `![x](${a.download_url})`)).toEqual([]);
+ });
+
+ it("keeps an attachment that is not referenced anywhere in the body", () => {
+ const a = att();
+ expect(standaloneAttachments([a], "just some text, no image")).toEqual([a]);
+ });
+
+ it("renders every attachment when content is undefined (no body to reference them)", () => {
+ const a = att();
+ expect(standaloneAttachments([a], undefined)).toEqual([a]);
+ });
+
+ it("drops a duplicate upload whose same-identity sibling is inline via markdown_url", () => {
+ const inline = att({ id: "att-inline" });
+ const dup = att({ id: "att-dup", url: "https://cdn.example/other.png" });
+ // Only the sibling's markdown_url appears in the body; the dup shares
+ // filename/type/size, so it must be treated as the same file and dropped.
+ const content = `![chart.png](${inline.markdown_url})`;
+ expect(standaloneAttachments([inline, dup], content)).toEqual([]);
+ });
+});
diff --git a/apps/mobile/lib/attachment-dedup.ts b/apps/mobile/lib/attachment-dedup.ts
new file mode 100644
index 0000000000..81bfa700df
--- /dev/null
+++ b/apps/mobile/lib/attachment-dedup.ts
@@ -0,0 +1,42 @@
+import type { Attachment } from "@multica/core/types";
+import { contentReferencesAttachment } from "@multica/core/types";
+
+/**
+ * The attachments to render as standalone cards below a message / comment
+ * body: the ones NOT already referenced inline in `content`, minus duplicate
+ * uploads whose same-identity sibling is already inline.
+ *
+ * "Referenced inline" is decided by the core `contentReferencesAttachment`
+ * helper, so it matches every real URL form the server emits — the stable
+ * `/api/attachments/<id>/download` path, the raw storage `url`, the signed
+ * `download_url`, and the durable `markdown_url` that agents actually paste
+ * into a reply. Checking only raw `url` (the old behaviour) missed the
+ * `markdown_url` case and rendered the same image twice.
+ *
+ * Pass `content === undefined` (not "") to render every attachment — used when
+ * the body has no markdown that could reference them.
+ *
+ * Mirrors web's `AttachmentList` filter in
+ * `packages/views/issues/components/comment-card.tsx`.
+ */
+export function standaloneAttachments(
+ attachments: Attachment[] | undefined,
+ content: string | undefined,
+): Attachment[] {
+ if (!attachments || attachments.length === 0) return [];
+ if (!content) return attachments;
+ return attachments.filter((a) => {
+ if (contentReferencesAttachment(content, a)) return false;
+ // Dedup: if another attachment with the same file identity (name, type,
+ // size) is already inline, this one is a duplicate upload — skip it.
+ const hasSiblingInContent = attachments.some(
+ (other) =>
+ other.id !== a.id &&
+ other.filename === a.filename &&
+ other.content_type === a.content_type &&
+ other.size_bytes === a.size_bytes &&
+ contentReferencesAttachment(content, other),
+ );
+ return !hasSiblingInContent;
+ });
+}
diff --git a/apps/mobile/lib/markdown/preprocess.test.ts b/apps/mobile/lib/markdown/preprocess.test.ts
new file mode 100644
index 0000000000..bed209e3a3
--- /dev/null
+++ b/apps/mobile/lib/markdown/preprocess.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import { preprocessMobileMarkdown } from "./preprocess";
+
+const UUID = "019f49e2-5b07-7970-beef-c0d537fb8c1d";
+const ABS_URL = `https://multica-app.copilothub.ai/api/attachments/${UUID}/download`;
+const REL_URL = `/api/attachments/${UUID}/download`;
+
+describe("preprocessMobileMarkdown — !file file cards", () => {
+ it("matches the CLI's escaped-bracket label and keeps it markdown-safe", () => {
+ // CLI emits `a]b.pdf` escaped as `a\]b.pdf` (cmd_attachment.go
+ // escapeMarkdownLabel). The old regex stopped at the first `]` and left the
+ // line literal; now it is captured whole and re-emitted as a tappable link
+ // whose label stays escaped so the `]` doesn't truncate the link text.
+ const out = preprocessMobileMarkdown(`!file[a\\]b.pdf](${ABS_URL})`);
+ expect(out).toBe(`[📎 a\\]b.pdf](${ABS_URL})`);
+ });
+
+ it("unescapes non-breaking metacharacters (parens) in the displayed name", () => {
+ // Parens are legal inside a markdown link label, so they are unescaped for
+ // display and not re-escaped.
+ const out = preprocessMobileMarkdown(`!file[report\\(1\\).pdf](${ABS_URL})`);
+ expect(out).toBe(`[📎 report(1).pdf](${ABS_URL})`);
+ });
+
+ it("unescapes an escaped backslash in the label", () => {
+ const out = preprocessMobileMarkdown(`!file[a\\\\b.pdf](${ABS_URL})`);
+ expect(out).toBe(`[📎 a\\\\b.pdf](${ABS_URL})`);
+ });
+
+ it("renders a plain (unescaped) label", () => {
+ const out = preprocessMobileMarkdown(`!file[notes.txt](${ABS_URL})`);
+ expect(out).toBe(`[📎 notes.txt](${ABS_URL})`);
+ });
+
+ it("accepts the site-relative /api/attachments URL form (web parity)", () => {
+ const out = preprocessMobileMarkdown(`!file[a.pdf](${REL_URL})`);
+ expect(out).toBe(`[📎 a.pdf](${REL_URL})`);
+ });
+
+ it("leaves a disallowed-scheme URL as plain text (no out-of-band navigation)", () => {
+ const line = `!file[x.pdf](javascript:alert(1))`;
+ expect(preprocessMobileMarkdown(line)).toBe(line);
+ });
+
+ it("does not touch inline images (![...] is not a file card)", () => {
+ const line = `![chart.png](${ABS_URL})`;
+ expect(preprocessMobileMarkdown(line)).toBe(line);
+ });
+
+ it("only transforms the standalone file-card line, leaving surrounding text", () => {
+ const input = `here is the file\n\n!file[a\\]b.pdf](${ABS_URL})\n\nlet me know`;
+ const output = `here is the file\n\n[📎 a\\]b.pdf](${ABS_URL})\n\nlet me know`;
+ expect(preprocessMobileMarkdown(input)).toBe(output);
+ });
+});
diff --git a/apps/mobile/lib/markdown/preprocess.ts b/apps/mobile/lib/markdown/preprocess.ts
index 6d14dad9ae..a78a0bc4bd 100644
--- a/apps/mobile/lib/markdown/preprocess.ts
+++ b/apps/mobile/lib/markdown/preprocess.ts
@@ -23,7 +23,39 @@
*/
import { preprocessMentionShortcodes } from "@multica/core/markdown";
-const FILE_LINE_RE = /^!file\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/;
+// File-card line matcher, kept in sync with web's parser in
+// `packages/ui/markdown/file-cards.ts` (NEW_FILE_CARD_RE + FILE_CARD_URL_PATTERN):
+//
+// - Label allows backslash-escaped metacharacters (`\[ \] \\ \( \)`) so a
+// filename like `a]b.pdf` — which the CLI escapes to `a\]b.pdf` in its
+// `!file[...]` output (see cmd_attachment.go escapeMarkdownLabel) — is
+// captured whole. Backslash is excluded from the negated class so
+// overlapping alternatives can't backtrack (ReDoS, web #4881).
+// - URL is restricted to the same allowlist web accepts: site-relative
+// `/uploads/...` and `/api/attachments/<UUID>/download`, plus absolute
+// `http(s)://`. Anything else (`javascript:`, `data:`, `//host`, other
+// `/api/…`) is left as plain text so a stored card can't become an
+// out-of-band navigation.
+const ATTACHMENT_UUID =
+ "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
+const FILE_CARD_URL = `/uploads/[^)]*|https?://[^)]+|/api/attachments/${ATTACHMENT_UUID}/download`;
+const FILE_LINE_RE = new RegExp(
+ `^!file\\[((?:\\\\.|[^\\]\\\\])*)\\]\\((${FILE_CARD_URL})\\)$`,
+);
+
+// Unescape the file-card label back to the real filename (mirrors web's
+// `newMatch[1].replace(/\\([[\]\\()])/g, "$1")`).
+function unescapeFileLabel(label: string): string {
+ return label.replace(/\\([[\]\\()])/g, "$1");
+}
+
+// Re-escape only the characters that would break a markdown LINK label, so the
+// emitted `[📎 name](url)` stays valid markdown. Mobile's target is a link
+// (re-parsed by marked / the enriched renderer), unlike web's HTML
+// `data-filename` attribute — so a raw `]` must not truncate the link text.
+function escapeLinkLabel(name: string): string {
+ return name.replace(/([\\[\]])/g, "\\$1");
+}
function preprocessFileCards(input: string): string {
return input
@@ -31,7 +63,8 @@ function preprocessFileCards(input: string): string {
.map((line) => {
const m = line.trim().match(FILE_LINE_RE);
if (!m) return line;
- return `[📎 ${m[1]}](${m[2]})`;
+ const label = escapeLinkLabel(unescapeFileLabel(m[1]!));
+ return `[📎 ${label}](${m[2]})`;
})
.join("\n");
}
diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.ts
index 72e19422fb..f90386b0b4 100644
--- a/apps/mobile/vitest.config.ts
+++ b/apps/mobile/vitest.config.ts
@@ -1,19 +1,28 @@
import { defineConfig } from "vitest/config";
+import path from "node:path";
// Mobile vitest is intentionally minimal — Node environment only, scoped to
-// pure-function tests in `lib/`. We don't ship jsdom or RN test renderers
-// here because the app runs on Hermes / native shims and any DOM-shaped
-// runner would be a lie. Tests that need RN component rendering would
-// need a separate jest+react-native-testing-library track; for now we
-// keep this lane for helpers and serializers only.
+// pure-function helpers in `lib/` and headless data-layer logic in `data/`
+// (query-key + cache-patch functions that take a QueryClient but touch no
+// DOM / RN native modules). We don't ship jsdom or RN test renderers here
+// because the app runs on Hermes / native shims and any DOM-shaped runner
+// would be a lie. Tests that need RN component rendering would need a
+// separate jest+react-native-testing-library track; for now we keep this
+// lane for helpers, serializers, and cache updaters only. Data-layer tests
+// must mock `@/data/api` so the native fetch chain never loads.
//
// Co-located test files (foo.ts + foo.test.ts) match how the rest of the
// monorepo organises vitest suites.
export default defineConfig({
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "."),
+ },
+ },
test: {
environment: "node",
globals: true,
- include: ["lib/**/*.test.ts"],
+ include: ["lib/**/*.test.ts", "data/**/*.test.ts"],
passWithNoTests: true,
},
});
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index d0050636de..e2f9c49d15 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -133,7 +133,9 @@ export function ChatMessageList({
scrollRef.current = node;
setScrollContainerEl(node);
}, []);
- const fadeStyle = useScrollFade(scrollRef);
+ // Soft edge fade hinting more content above/below. Kept small so it barely
+ // grazes full-bleed previews (image / HTML) at the edges.
+ const fadeStyle = useScrollFade(scrollRef, 16);
const pendingTaskId = pendingTask?.task_id ?? null;
diff --git a/server/cmd/multica/cmd_attachment.go b/server/cmd/multica/cmd_attachment.go
index 8466880af3..acbcfab1b1 100644
--- a/server/cmd/multica/cmd_attachment.go
+++ b/server/cmd/multica/cmd_attachment.go
@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "strings"
"time"
"github.com/spf13/cobra"
@@ -30,10 +31,98 @@ var attachmentDownloadCmd = &cobra.Command{
RunE: runAttachmentDownload,
}
+var attachmentUploadCmd = &cobra.Command{
+ Use: "upload <path>",
+ Short: "Upload a file to attach to your chat reply",
+ Long: `Upload a local file so it is attached to the reply of the current chat task.
+
+Intended for agents running inside a chat task: the file is tagged with the
+task and, when the task completes, the server binds it to the assistant reply
+it produces — it appears as an attachment card below your reply even if you
+paste nothing. The command also returns a markdown snippet you may paste on its
+own line to place the item: files use !file[name](url) (a card), images use
+![name](url) (inline).
+
+The task id is read from MULTICA_TASK_ID (set by the daemon inside a task);
+override it with --task when needed.`,
+ Example: ` # Attach an image to the current chat reply
+ $ multica attachment upload ./chart.png`,
+ Args: exactArgs(1),
+ RunE: runAttachmentUpload,
+}
+
func init() {
attachmentCmd.AddCommand(attachmentDownloadCmd)
+ attachmentCmd.AddCommand(attachmentUploadCmd)
attachmentDownloadCmd.Flags().StringP("output-dir", "o", ".", "Directory to save the downloaded file")
+ attachmentUploadCmd.Flags().String("task", "", "Chat task id to attach to (defaults to MULTICA_TASK_ID)")
+}
+
+func runAttachmentUpload(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ taskID, _ := cmd.Flags().GetString("task")
+ if taskID == "" {
+ taskID = client.TaskID
+ }
+ if taskID == "" {
+ return fmt.Errorf("no chat task in context: run inside a chat task (MULTICA_TASK_ID set) or pass --task <id>")
+ }
+
+ path := args[0]
+ if isHTTPURL(path) {
+ return fmt.Errorf("upload accepts a local file path, not a URL: %s", path)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return fmt.Errorf("read file %s: %w", path, err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))
+ defer cancel()
+
+ att, err := client.UploadChatAttachment(ctx, data, path, taskID)
+ if err != nil {
+ return fmt.Errorf("upload attachment: %w", err)
+ }
+
+ filename := filepath.Base(path)
+ // Escape markdown label metacharacters in the filename so a name like
+ // `report[v2].pdf` does not truncate the snippet's label. Files render as a
+ // block-level attachment card via `!file[...]( )`; images render inline via
+ // `![...]( )`.
+ label := escapeMarkdownLabel(filename)
+ markdown := fmt.Sprintf("!file[%s](%s)", label, att.MarkdownURL)
+ if strings.HasPrefix(att.ContentType, "image/") {
+ markdown = fmt.Sprintf("![%s](%s)", label, att.MarkdownURL)
+ }
+ fmt.Fprintln(os.Stderr, "Uploaded:", filename)
+
+ return cli.PrintJSON(os.Stdout, map[string]any{
+ "id": att.ID,
+ "filename": filename,
+ "markdown_url": att.MarkdownURL,
+ "markdown": markdown,
+ })
+}
+
+// escapeMarkdownLabel escapes the metacharacters a markdown link/image label
+// may not contain unescaped ([ ] ( ) and backslash), so a filename like
+// `report[v2].pdf` stays a single valid label instead of truncating the
+// snippet. Kept in sync with the renderers' unescape set
+// (packages/ui/markdown/file-cards.ts).
+func escapeMarkdownLabel(s string) string {
+ return strings.NewReplacer(
+ `\`, `\\`,
+ `[`, `\[`,
+ `]`, `\]`,
+ `(`, `\(`,
+ `)`, `\)`,
+ ).Replace(s)
}
func runAttachmentDownload(cmd *cobra.Command, args []string) error {
diff --git a/server/cmd/multica/cmd_attachment_test.go b/server/cmd/multica/cmd_attachment_test.go
index d7b5dfa8ff..7448f0f677 100644
--- a/server/cmd/multica/cmd_attachment_test.go
+++ b/server/cmd/multica/cmd_attachment_test.go
@@ -73,6 +73,181 @@ func TestRunAttachmentDownloadWritesBasenameIntoOutputDir(t *testing.T) {
}
}
+func newAttachmentUploadTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "upload"}
+ cmd.Flags().String("task", "", "")
+ return cmd
+}
+
+func TestRunAttachmentUploadSendsTaskIDAndPrintsContract(t *testing.T) {
+ const taskID = "task-abc"
+ var gotTaskID string
+ var gotFile string
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/upload-file" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
+ }
+ if err := r.ParseMultipartForm(1 << 20); err != nil {
+ t.Fatalf("parse multipart: %v", err)
+ }
+ gotTaskID = r.FormValue("task_id")
+ if f, _, err := r.FormFile("file"); err == nil {
+ _ = f.Close()
+ gotFile = "present"
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "att-999",
+ "filename": "chart.png",
+ "content_type": "image/png",
+ "url": "https://cdn.example/chart.png",
+ "download_url": "https://signed.example/chart.png?sig=x",
+ "markdown_url": "https://public.example/api/attachments/att-999/download",
+ })
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ // An agent upload always carries a task-scoped mat_ token; set one so the
+ // daemon-managed-context gate in newAPIClient admits the request.
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ dir := t.TempDir()
+ imgPath := filepath.Join(dir, "chart.png")
+ if err := os.WriteFile(imgPath, []byte("\x89PNG\r\n\x1a\nbytes"), 0o644); err != nil {
+ t.Fatalf("write temp image: %v", err)
+ }
+
+ cmd := newAttachmentUploadTestCmd()
+ _ = cmd.Flags().Set("task", taskID)
+
+ out, err := captureStdout(t, func() error { return runAttachmentUpload(cmd, []string{imgPath}) })
+ if err != nil {
+ t.Fatalf("runAttachmentUpload: %v", err)
+ }
+ if gotTaskID != taskID {
+ t.Fatalf("server task_id = %q, want %q", gotTaskID, taskID)
+ }
+ if gotFile != "present" {
+ t.Fatalf("server did not receive a file part")
+ }
+ // Output contract: id, markdown_url, and a ready-to-paste markdown snippet.
+ if !strings.Contains(out, `"id": "att-999"`) {
+ t.Fatalf("stdout missing id: %q", out)
+ }
+ if !strings.Contains(out, `"markdown_url": "https://public.example/api/attachments/att-999/download"`) {
+ t.Fatalf("stdout missing markdown_url: %q", out)
+ }
+ // Image content type → image markdown so it renders inline.
+ if !strings.Contains(out, `![chart.png](https://public.example/api/attachments/att-999/download)`) {
+ t.Fatalf("stdout missing image markdown snippet: %q", out)
+ }
+}
+
+// TestRunAttachmentUploadNonImageUsesFileCardMarkdown covers the content-type
+// branch: a non-image file emits the block-level `!file[...]( )` card snippet,
+// not image `![...]` markdown.
+func TestRunAttachmentUploadNonImageUsesFileCardMarkdown(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseMultipartForm(1 << 20); err != nil {
+ t.Fatalf("parse multipart: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "att-doc",
+ "filename": "report.pdf",
+ "content_type": "application/pdf",
+ "url": "https://cdn.example/report.pdf",
+ "markdown_url": "https://public.example/api/attachments/att-doc/download",
+ })
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ dir := t.TempDir()
+ docPath := filepath.Join(dir, "report.pdf")
+ if err := os.WriteFile(docPath, []byte("%PDF-1.4 bytes"), 0o644); err != nil {
+ t.Fatalf("write temp doc: %v", err)
+ }
+
+ cmd := newAttachmentUploadTestCmd()
+ _ = cmd.Flags().Set("task", "task-abc")
+
+ out, err := captureStdout(t, func() error { return runAttachmentUpload(cmd, []string{docPath}) })
+ if err != nil {
+ t.Fatalf("runAttachmentUpload: %v", err)
+ }
+ // Non-image uses the block-level file-card snippet, never image markdown.
+ if !strings.Contains(out, `!file[report.pdf](https://public.example/api/attachments/att-doc/download)`) {
+ t.Fatalf("stdout missing file-card markdown snippet: %q", out)
+ }
+ if strings.Contains(out, `![report.pdf]`) {
+ t.Fatalf("non-image must not use image markdown: %q", out)
+ }
+ if !strings.Contains(out, `"markdown_url": "https://public.example/api/attachments/att-doc/download"`) {
+ t.Fatalf("stdout missing markdown_url: %q", out)
+ }
+}
+
+// TestRunAttachmentUploadEscapesFilename covers filenames carrying markdown
+// label metacharacters (`[`, `]`): the snippet must escape them so the label
+// does not truncate — otherwise the card fails to render and the standalone
+// attachment is hidden by the referenced URL, showing nothing.
+func TestRunAttachmentUploadEscapesFilename(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseMultipartForm(1 << 20); err != nil {
+ t.Fatalf("parse multipart: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "att-esc",
+ "filename": "a]b.pdf",
+ "content_type": "application/pdf",
+ "markdown_url": "https://public.example/api/attachments/att-esc/download",
+ })
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ dir := t.TempDir()
+ docPath := filepath.Join(dir, "a]b.pdf")
+ if err := os.WriteFile(docPath, []byte("%PDF-1.4 bytes"), 0o644); err != nil {
+ t.Fatalf("write temp doc: %v", err)
+ }
+
+ cmd := newAttachmentUploadTestCmd()
+ _ = cmd.Flags().Set("task", "task-abc")
+
+ out, err := captureStdout(t, func() error { return runAttachmentUpload(cmd, []string{docPath}) })
+ if err != nil {
+ t.Fatalf("runAttachmentUpload: %v", err)
+ }
+ // The `]` in the filename must be escaped inside the label.
+ if !strings.Contains(out, `!file[a\\]b.pdf](https://public.example/api/attachments/att-esc/download)`) {
+ t.Fatalf("stdout missing escaped file-card snippet: %q", out)
+ }
+}
+
+func TestRunAttachmentUploadRequiresTask(t *testing.T) {
+ t.Setenv("MULTICA_TASK_ID", "")
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ dir := t.TempDir()
+ imgPath := filepath.Join(dir, "chart.png")
+ if err := os.WriteFile(imgPath, []byte("bytes"), 0o644); err != nil {
+ t.Fatalf("write temp image: %v", err)
+ }
+
+ cmd := newAttachmentUploadTestCmd() // no --task, no MULTICA_TASK_ID
+ if err := runAttachmentUpload(cmd, []string{imgPath}); err == nil || !strings.Contains(err.Error(), "no chat task in context") {
+ t.Fatalf("runAttachmentUpload error = %v, want no-chat-task error", err)
+ }
+}
+
func TestRunAttachmentDownloadRequiresDownloadURL(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/attachments/att-no-url" {
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index d73e95a037..e0f3be78ff 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -406,6 +406,9 @@ type AttachmentResponse struct {
ID string `json:"id"`
URL string `json:"url"`
DownloadURL string `json:"download_url"`
+ // MarkdownURL is the durable, persistable URL to embed in markdown bodies
+ // (chat replies, comments). Unlike DownloadURL it never carries a TTL.
+ MarkdownURL string `json:"markdown_url"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
@@ -466,6 +469,69 @@ func (c *APIClient) UploadFile(ctx context.Context, fileData []byte, filename st
return id, nil
}
+// UploadChatAttachment uploads a file via multipart form to /api/upload-file
+// tagged with a chat task (task_id). The server binds the row to the assistant
+// reply that task produces on completion. Returns the full AttachmentResponse
+// (id + markdown_url) so the agent can embed the image inline in its reply.
+func (c *APIClient) UploadChatAttachment(ctx context.Context, fileData []byte, filename, taskID string) (AttachmentResponse, error) {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+
+ part, err := writer.CreateFormFile("file", filepath.Base(filename))
+ if err != nil {
+ return AttachmentResponse{}, fmt.Errorf("create form file: %w", err)
+ }
+ if _, err := part.Write(fileData); err != nil {
+ return AttachmentResponse{}, fmt.Errorf("write file data: %w", err)
+ }
+ if taskID != "" {
+ if err := writer.WriteField("task_id", taskID); err != nil {
+ return AttachmentResponse{}, fmt.Errorf("write task_id field: %w", err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ return AttachmentResponse{}, fmt.Errorf("close multipart writer: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/api/upload-file", &body)
+ if err != nil {
+ return AttachmentResponse{}, err
+ }
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ c.setHeaders(req)
+
+ // Honor a longer context deadline for large images, same as UploadFileWithURL.
+ httpClient := c.HTTPClient
+ if deadline, ok := ctx.Deadline(); ok {
+ remaining := time.Until(deadline)
+ if remaining > httpClient.Timeout {
+ clientCopy := *httpClient
+ clientCopy.Timeout = remaining
+ httpClient = &clientCopy
+ }
+ }
+
+ resp, err := httpClient.Do(req)
+ err = wrapTransport(req, err)
+ if err != nil {
+ return AttachmentResponse{}, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ return AttachmentResponse{}, newHTTPError(http.MethodPost, "/api/upload-file", resp)
+ }
+
+ var result AttachmentResponse
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return AttachmentResponse{}, fmt.Errorf("decode upload response: %w", err)
+ }
+ if result.ID == "" {
+ return AttachmentResponse{}, fmt.Errorf("upload response missing attachment id")
+ }
+ return result, nil
+}
+
// UploadFileWithURL uploads a file via multipart form to /api/upload-file
// without associating it with an issue or comment. It decodes the full
// AttachmentResponse and returns the attachment ID and URL.
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 8b910844b2..68779fa5e3 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -382,6 +382,12 @@ func buildChatPrompt(task Task) string {
b.WriteString("Use `multica attachment download <id>` to fetch each file locally before referring to it.\n")
b.WriteString("When creating an issue that should preserve one of these attachments, pass `--attachment-id <id>` to `multica issue create` in addition to keeping the attachment markdown inline.\n")
}
+ // Outbound attachments: how the agent puts an image/file INTO its reply.
+ // Web/mobile chat only — for IM-channel chats the reply is delivered to
+ // that platform, not the Multica chat UI, so this binding does not apply.
+ if task.ChatChannelType == "" {
+ b.WriteString("\nTo include a file or image you produced in your reply, run `multica attachment upload <local-path>`. The file binds to your reply automatically and appears as an attachment card below it even if you paste nothing. The command also returns a `markdown` snippet you may paste on its own line to place the item where you want it (files render as a card, images inline).\n")
+ }
return b.String()
}
diff --git a/server/internal/handler/chat_attachment_reply_test.go b/server/internal/handler/chat_attachment_reply_test.go
new file mode 100644
index 0000000000..2e1bcd3964
--- /dev/null
+++ b/server/internal/handler/chat_attachment_reply_test.go
@@ -0,0 +1,401 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// seedRunningChatTask inserts a running chat task (chat_session_id set) for the
+// given agent and returns its id. Mirrors createHandlerTestTaskForAgentOnIssue
+// but binds a chat session instead of an issue.
+func seedRunningChatTask(t *testing.T, agentID, sessionID string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id, started_at)
+ VALUES ($1, $2, 'running', 0, $3, now())
+ RETURNING id
+ `, agentID, handlerTestRuntimeID(t), sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("seed running chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
+// seedAgentChatAttachment inserts an attachment as if the agent had uploaded it
+// during a chat task: tagged with task_id + chat_session_id, no owner message
+// yet. Returns the attachment id.
+func seedAgentChatAttachment(t *testing.T, agentID, sessionID, taskID string) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (workspace_id, task_id, chat_session_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ VALUES ($1, $2, $3, 'agent', $4, 'chart.png', 'https://cdn.example/chart.png', 'image/png', 123)
+ RETURNING id
+ `, testWorkspaceID, taskID, sessionID, agentID).Scan(&id); err != nil {
+ t.Fatalf("seed agent chat attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, id)
+ })
+ return id
+}
+
+func attachmentMessageID(t *testing.T, attachmentID string) *string {
+ t.Helper()
+ var msg *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT chat_message_id::text FROM attachment WHERE id = $1`, attachmentID).Scan(&msg); err != nil {
+ t.Fatalf("query attachment chat_message_id: %v", err)
+ }
+ return msg
+}
+
+func assistantMessageForTask(t *testing.T, taskID string) (id, content string, ok bool) {
+ t.Helper()
+ err := testPool.QueryRow(context.Background(),
+ `SELECT id::text, content FROM chat_message WHERE task_id = $1 AND role = 'assistant'`, taskID).Scan(&id, &content)
+ if err != nil {
+ return "", "", false
+ }
+ return id, content, true
+}
+
+// doUpload performs a multipart upload of a task_id form field with the given
+// request headers, and returns the recorder.
+func doUpload(t *testing.T, formTaskID string, headers map[string]string) *httptest.ResponseRecorder {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", "reply.png")
+ if err != nil {
+ t.Fatal(err)
+ }
+ part.Write([]byte("\x89PNG\r\n\x1a\nrest-of-bytes"))
+ if err := writer.WriteField("task_id", formTaskID); err != nil {
+ t.Fatal(err)
+ }
+ writer.Close()
+
+ req := httptest.NewRequest("POST", "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ w := httptest.NewRecorder()
+ testHandler.UploadFile(w, req)
+ return w
+}
+
+// uploadWithTaskID performs a multipart upload as a genuine task-token agent
+// request: it stamps the server-set X-Actor-Source=task_token + X-Task-ID pair
+// exactly as the auth middleware would for a `mat_` token (the boundary the
+// handler trusts). actorTaskID is what goes on X-Task-ID (the token's task);
+// formTaskID is the upload's task_id form field. They match in the happy path.
+// When agentID is empty the caller is a plain member (no task-token headers).
+func uploadWithTaskID(t *testing.T, agentID, actorTaskID, formTaskID string) *httptest.ResponseRecorder {
+ t.Helper()
+ headers := map[string]string{
+ "X-User-ID": testUserID,
+ "X-Workspace-ID": testWorkspaceID,
+ }
+ if agentID != "" {
+ // Mirror the middleware: a task token stamps the actor source and task.
+ headers["X-Actor-Source"] = "task_token"
+ headers["X-Agent-ID"] = agentID
+ }
+ if actorTaskID != "" {
+ headers["X-Task-ID"] = actorTaskID
+ }
+ return doUpload(t, formTaskID, headers)
+}
+
+// TestUploadFile_TaskScopedChatAttachment covers the write side: an agent
+// uploading a file for its chat reply gets a row tagged with task_id +
+// chat_session_id, and the permission/isolation gates reject the bad cases.
+func TestUploadFile_TaskScopedChatAttachment(t *testing.T) {
+ if testPool == nil {
+ t.Skip("test database not available")
+ }
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ defer func() { testHandler.Storage = origStorage }()
+
+ agentID := createHandlerTestAgent(t, "ChatReplyAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+
+ t.Run("agent uploads for own chat task", func(t *testing.T) {
+ w := uploadWithTaskID(t, agentID, taskID, taskID)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp AttachmentResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v; body: %s", err, w.Body.String())
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, resp.ID)
+ })
+ if resp.ChatSessionID == nil || *resp.ChatSessionID != sessionID {
+ t.Fatalf("chat_session_id: want %s, got %v", sessionID, resp.ChatSessionID)
+ }
+ if resp.ChatMessageID != nil {
+ t.Fatalf("chat_message_id must be NULL before completion, got %v", resp.ChatMessageID)
+ }
+ if resp.UploaderType != "agent" {
+ t.Fatalf("uploader_type: want agent, got %s", resp.UploaderType)
+ }
+ // task_id is set on the row (not exposed in the DTO — verify via DB).
+ var dbTask *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT task_id::text FROM attachment WHERE id = $1`, resp.ID).Scan(&dbTask); err != nil {
+ t.Fatalf("query task_id: %v", err)
+ }
+ if dbTask == nil || *dbTask != taskID {
+ t.Fatalf("task_id: want %s, got %v", taskID, dbTask)
+ }
+ })
+
+ t.Run("member actor rejected", func(t *testing.T) {
+ // A plain member request (no task-token headers) is rejected by the
+ // task-token boundary before any task lookup.
+ w := uploadWithTaskID(t, "", "", taskID)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("member upload: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("forged agent headers without task token rejected", func(t *testing.T) {
+ // The real forgery vector: a normal JWT / mul_ PAT request that the auth
+ // middleware did NOT stamp with X-Actor-Source=task_token, but which
+ // forges a valid X-Agent-ID + X-Task-ID pair (resolveActor's fallback
+ // would otherwise accept it). Even with the form task_id equal to the
+ // forged X-Task-ID, the missing task-token source must make it 403 —
+ // otherwise a member who learns a task ID could inject an attachment
+ // into that task's chat reply.
+ w := doUpload(t, taskID, map[string]string{
+ "X-User-ID": testUserID,
+ "X-Workspace-ID": testWorkspaceID,
+ "X-Agent-ID": agentID,
+ "X-Task-ID": taskID,
+ // deliberately NO X-Actor-Source
+ })
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("forged non-task-token upload: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("different agent's task rejected", func(t *testing.T) {
+ otherAgent := createHandlerTestAgent(t, "OtherReplyAgent", []byte("[]"))
+ otherTask := createHandlerTestTaskForAgent(t, otherAgent)
+ // Actor is agentID (valid X-Agent-ID/X-Task-ID pair), but the upload
+ // targets a task owned by a different agent.
+ w := uploadWithTaskID(t, agentID, taskID, otherTask)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("foreign task upload: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("same agent's other chat task rejected", func(t *testing.T) {
+ // X-Task-ID is this run's own task, but the form targets a DIFFERENT
+ // chat task of the SAME agent (another session, possibly another user).
+ // Without pinning the form task_id to the token's bound X-Task-ID this
+ // is a cross-session attachment-injection vector.
+ otherSession := createHandlerTestChatSession(t, agentID)
+ otherChatTask := seedRunningChatTask(t, agentID, otherSession)
+ w := uploadWithTaskID(t, agentID, taskID, otherChatTask)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("cross-task upload: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("non-chat task rejected", func(t *testing.T) {
+ issueTask := createHandlerTestTaskForAgent(t, agentID) // no chat_session_id
+ w := uploadWithTaskID(t, agentID, issueTask, issueTask)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("non-chat task upload: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("malformed task_id rejected", func(t *testing.T) {
+ w := uploadWithTaskID(t, agentID, taskID, "not-a-uuid")
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("bad task_id: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+}
+
+// TestChatAttachment_UnboundOrphanReapedOnSessionDelete locks the cleanup
+// guarantee that lets us keep task_id as a plain (FK-less) transient column: an
+// unbound task-tagged upload (task_id set, chat_message_id NULL — e.g. the turn
+// failed before binding) is reaped when its chat_session is deleted, via
+// attachment.chat_session_id's ON DELETE CASCADE. Cleanup does not depend on the
+// task relationship, so no attachment.task_id foreign key / cascade is needed.
+func TestChatAttachment_UnboundOrphanReapedOnSessionDelete(t *testing.T) {
+ if testPool == nil {
+ t.Skip("test database not available")
+ }
+ agentID := createHandlerTestAgent(t, "OrphanCleanupAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
+
+ if _, err := testPool.Exec(context.Background(),
+ `DELETE FROM chat_session WHERE id = $1`, sessionID); err != nil {
+ t.Fatalf("delete chat session: %v", err)
+ }
+
+ var exists bool
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT EXISTS(SELECT 1 FROM attachment WHERE id = $1)`, attID).Scan(&exists); err != nil {
+ t.Fatalf("check attachment: %v", err)
+ }
+ if exists {
+ t.Fatal("unbound task-tagged attachment must be reaped when its chat_session is deleted")
+ }
+}
+
+// TestCompleteTask_BindsChatAttachments covers the read/bind side: on chat task
+// completion the agent's task-scoped attachments bind to the assistant reply.
+func TestCompleteTask_BindsChatAttachments(t *testing.T) {
+ if testPool == nil {
+ t.Skip("test database not available")
+ }
+ agentID := createHandlerTestAgent(t, "BindReplyAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ t.Run("output + attachment binds to reply", func(t *testing.T) {
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
+
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":"here is the chart"}`), "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ msgID, content, ok := assistantMessageForTask(t, taskID)
+ if !ok {
+ t.Fatal("expected an assistant message to be created")
+ }
+ if content != "here is the chart" {
+ t.Fatalf("content: want %q, got %q", "here is the chart", content)
+ }
+ got := attachmentMessageID(t, attID)
+ if got == nil || *got != msgID {
+ t.Fatalf("attachment not bound: want message %s, got %v", msgID, got)
+ }
+ })
+
+ t.Run("empty output + attachment still creates message and binds", func(t *testing.T) {
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
+
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":""}`), "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ msgID, content, ok := assistantMessageForTask(t, taskID)
+ if !ok {
+ t.Fatal("image-only reply must still create an assistant message")
+ }
+ if content != "" {
+ t.Fatalf("content should be empty for image-only reply, got %q", content)
+ }
+ got := attachmentMessageID(t, attID)
+ if got == nil || *got != msgID {
+ t.Fatalf("attachment not bound: want message %s, got %v", msgID, got)
+ }
+ })
+
+ t.Run("empty output + no attachment creates no message", func(t *testing.T) {
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":""}`), "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ if _, _, ok := assistantMessageForTask(t, taskID); ok {
+ t.Fatal("no output and no attachments must not create an assistant message")
+ }
+ })
+
+ t.Run("null task_id attachment in same session is not bound", func(t *testing.T) {
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ // A loose session attachment with NO task_id (e.g. legacy row) must be
+ // left alone — binding is scoped to the producing task.
+ var looseID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (workspace_id, chat_session_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ VALUES ($1, $2, 'agent', $3, 'loose.png', 'https://cdn.example/loose.png', 'image/png', 10)
+ RETURNING id
+ `, testWorkspaceID, sessionID, agentID).Scan(&looseID); err != nil {
+ t.Fatalf("seed loose attachment: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, looseID) })
+
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ if got := attachmentMessageID(t, looseID); got != nil {
+ t.Fatalf("null-task_id attachment must not be bound, got %v", got)
+ }
+ })
+
+ t.Run("already-owned attachment is not stolen", func(t *testing.T) {
+ // The bind's WHERE guards are symmetric: comment_id IS NULL AND
+ // issue_id IS NULL AND chat_message_id IS NULL. We exercise the guard
+ // via an already-bound (chat_message_id set) row with this task's
+ // task_id — proving an attachment already claimed by another owner is
+ // never re-pointed at the new reply.
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ var claimedID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (workspace_id, task_id, chat_session_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ VALUES ($1, $2, $3, 'agent', $4, 'claimed.png', 'https://cdn.example/claimed.png', 'image/png', 10)
+ RETURNING id
+ `, testWorkspaceID, taskID, sessionID, agentID).Scan(&claimedID); err != nil {
+ t.Fatalf("seed attachment: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, claimedID) })
+ var priorMsgID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'assistant', 'prior') RETURNING id
+ `, sessionID).Scan(&priorMsgID); err != nil {
+ t.Fatalf("seed prior message: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM chat_message WHERE id = $1`, priorMsgID) })
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE attachment SET chat_message_id = $1 WHERE id = $2`, priorMsgID, claimedID); err != nil {
+ t.Fatalf("pre-bind attachment: %v", err)
+ }
+
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ got := attachmentMessageID(t, claimedID)
+ if got == nil || *got != priorMsgID {
+ t.Fatalf("already-bound attachment must keep its owner %s, got %v", priorMsgID, got)
+ }
+ })
+
+ t.Run("FailTask does not bind attachments", func(t *testing.T) {
+ taskID := seedRunningChatTask(t, agentID, sessionID)
+ attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
+ if _, err := testHandler.TaskService.FailTask(context.Background(),
+ parseUUID(taskID), "agent crashed", "", "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+ if got := attachmentMessageID(t, attID); got != nil {
+ t.Fatalf("FailTask must not bind attachments, got %v", got)
+ }
+ })
+}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index c039a317de..883af4bbf7 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -436,6 +436,62 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
}
params.ChatSessionID = session.ID
}
+ // task_id upload: an agent producing an image/file for its chat reply.
+ // The row is tagged with the producing task and its chat session so
+ // CompleteTask can bind it to the assistant message it synthesizes.
+ // Gate: the request must come from a task-scoped token, the form task_id
+ // must equal that token's task, the caller must be that task's agent,
+ // and it must be a chat task (has a chat_session_id).
+ if taskID := r.FormValue("task_id"); taskID != "" {
+ // Authoritative task-token boundary (load-bearing, mirrors
+ // chat_history.go:chatHistorySession). X-Task-ID is only trustworthy
+ // when the auth middleware set it from a task-scoped `mat_` token —
+ // that path is also the ONLY one that stamps X-Actor-Source=task_token
+ // and strips a client-forged X-Task-ID. A normal JWT / `mul_` PAT
+ // leaves X-Actor-Source empty and does NOT strip a forged X-Task-ID,
+ // and resolveActor's fallback will accept a real X-Agent-ID +
+ // X-Task-ID pair. So without this gate a member who learns a task ID
+ // could forge both headers and inject an attachment onto another chat
+ // task's assistant reply — a cross-session/privacy leak.
+ if r.Header.Get("X-Actor-Source") != "task_token" {
+ writeError(w, http.StatusForbidden, "task_id upload is only available from within an agent task")
+ return
+ }
+ taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task_id")
+ if !ok {
+ return
+ }
+ // Pin to the run's own task: the middleware-injected X-Task-ID is the
+ // single source of truth for which task this token may act on, so a
+ // run authorized for task A cannot tag an attachment onto task B —
+ // even another chat task of the same agent, whose session may belong
+ // to a different user.
+ boundTaskID := strings.TrimSpace(r.Header.Get("X-Task-ID"))
+ if boundTaskID == "" || !strings.EqualFold(boundTaskID, strings.TrimSpace(taskID)) {
+ writeError(w, http.StatusForbidden, "task_id must match the request's task token")
+ return
+ }
+ task, err := h.Queries.GetAgentTaskInWorkspace(r.Context(), db.GetAgentTaskInWorkspaceParams{
+ ID: taskUUID,
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ writeError(w, http.StatusForbidden, "invalid task_id")
+ return
+ }
+ if uploaderType != "agent" || uuidToString(task.AgentID) != uploaderID {
+ writeError(w, http.StatusForbidden, "task_id upload requires the task's own agent")
+ return
+ }
+ if !task.ChatSessionID.Valid {
+ writeError(w, http.StatusBadRequest, "task_id upload requires a chat task")
+ return
+ }
+ params.TaskID = task.ID
+ // Bind the session too so reads (groupChatMessageAttachments) and
+ // GC classify the row consistently before it gains a message id.
+ params.ChatSessionID = task.ChatSessionID
+ }
link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)
if err != nil {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 89b2d293ac..a535f94aec 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1964,6 +1964,9 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// no_response row has role='assistant' and a fresh created_at, so it counts
// as unread just like a text reply, no per-reply stamping needed.
if task.ChatSessionID.Valid {
+ // The assistant outcome row (message / no_response) and any attachment
+ // binding were written inside the completion transaction above by
+ // writeChatCompletionOutcome. Broadcast chat:done AFTER commit.
s.broadcastChatDone(ctx, task, chatAssistantMsg)
}
@@ -2009,9 +2012,29 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
body := util.UnescapeBackslashEscapes(payload.Output)
isEmpty := strings.TrimSpace(body) == ""
- // Channel/legacy empty completion: emit no assistant row, only an empty
- // chat:done for typing/lifecycle. Keeps the Slack/Lark silent-drop path.
- if isEmpty && !task.ChatInputTaskID.Valid {
+ // Attachments the agent uploaded during this task (tagged with task_id, not
+ // yet bound to any owner) are part of this reply. They make an empty-text
+ // turn a real image/file response — NOT a no_response — and need a row to
+ // hang on. Count + bind run on qtx so message creation and binding are one
+ // atomic outcome.
+ wsUUID, _ := util.ParseUUID(s.ResolveTaskWorkspaceID(ctx, task))
+ var pendingAttachments int64
+ if wsUUID.Valid {
+ n, err := qtx.CountUnboundChatAttachmentsForTask(ctx, db.CountUnboundChatAttachmentsForTaskParams{
+ WorkspaceID: wsUUID,
+ TaskID: task.ID,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("count chat attachments: %w", err)
+ }
+ pendingAttachments = n
+ }
+
+ // Channel/legacy empty completion with nothing to show: emit no assistant
+ // row, only an empty chat:done for typing/lifecycle. Keeps the Slack/Lark
+ // silent-drop path. Attachments still force a row — the agent produced a
+ // deliverable the user must see.
+ if isEmpty && pendingAttachments == 0 && !task.ChatInputTaskID.Valid {
return nil, nil
}
@@ -2021,18 +2044,43 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
TaskID: task.ID,
ElapsedMs: computeChatElapsedMs(task),
}
- if isEmpty {
- // Task-owned direct task: explicit, visible no_response outcome.
- params.Content = chatNoResponseFallback
- params.MessageKind = pgtype.Text{String: protocol.ChatMessageKindNoResponse, Valid: true}
- } else {
+ switch {
+ case !isEmpty:
params.Content = redact.Text(body)
// message_kind left NULL → COALESCE defaults to 'message'.
+ case pendingAttachments > 0:
+ // Image/file-only reply: a real 'message' outcome with empty text — the
+ // attachment cards ARE the response, so it must not read as no_response.
+ params.Content = ""
+ default:
+ // Task-owned direct task, empty output, no attachments: explicit,
+ // visible no_response outcome.
+ params.Content = chatNoResponseFallback
+ params.MessageKind = pgtype.Text{String: protocol.ChatMessageKindNoResponse, Valid: true}
}
row, err := qtx.CreateChatMessage(ctx, params)
if err != nil {
return nil, err
}
+
+ // Bind the task's still-unclaimed attachments to the reply we just wrote.
+ if pendingAttachments > 0 && wsUUID.Valid {
+ bound, err := qtx.BindChatAttachmentsToMessage(ctx, db.BindChatAttachmentsToMessageParams{
+ ChatMessageID: row.ID,
+ WorkspaceID: wsUUID,
+ TaskID: task.ID,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("bind chat attachments: %w", err)
+ }
+ if len(bound) > 0 {
+ slog.Info("bound chat attachments to assistant reply",
+ "task_id", util.UUIDToString(task.ID),
+ "message_id", util.UUIDToString(row.ID),
+ "count", len(bound),
+ )
+ }
+ }
return &row, nil
}
diff --git a/server/migrations/161_attachment_task_id.down.sql b/server/migrations/161_attachment_task_id.down.sql
new file mode 100644
index 0000000000..f014647690
--- /dev/null
+++ b/server/migrations/161_attachment_task_id.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE attachment
+ DROP COLUMN IF EXISTS task_id;
diff --git a/server/migrations/161_attachment_task_id.up.sql b/server/migrations/161_attachment_task_id.up.sql
new file mode 100644
index 0000000000..d67b73cd06
--- /dev/null
+++ b/server/migrations/161_attachment_task_id.up.sql
@@ -0,0 +1,24 @@
+-- Task-scoped attachment ownership. An agent producing an image/file for a
+-- chat reply uploads it during the run tagged with the producing task; on task
+-- completion the server binds the task's still-unclaimed rows to the assistant
+-- chat_message it synthesizes (see BindChatAttachmentsToMessage).
+--
+-- task_id is a TRANSIENT binding handle, not a durable relationship: it is
+-- written once at upload (against a task the upload handler has already
+-- validated) and read only during that task's own completion. The durable
+-- owner is chat_message_id. We deliberately add NO foreign key here:
+-- - No referential integrity is needed — the sole writer validates the task
+-- before setting the column, so a dangling/garbage value cannot get in.
+-- - No cascade cleanup is needed — orphan uploads (task_id set,
+-- chat_message_id NULL) are already reaped when their chat_session is
+-- deleted, via attachment.chat_session_id's own ON DELETE CASCADE. There is
+-- no app-layer path that hard-deletes agent_task_queue rows, so an
+-- ON DELETE action here would never fire in practice; adding an FK on the
+-- hot attachment table would only add write overhead and a cascade
+-- dependency the app does not rely on.
+ALTER TABLE attachment
+ ADD COLUMN task_id UUID;
+
+-- The task_id lookup index is built CONCURRENTLY in the next migration.
+-- CREATE INDEX CONCURRENTLY cannot share a transaction or multi-command
+-- string with the ADD COLUMN above (see 138_issue_title_trgm_index).
diff --git a/server/migrations/162_attachment_task_id_index.down.sql b/server/migrations/162_attachment_task_id_index.down.sql
new file mode 100644
index 0000000000..334b5c67d6
--- /dev/null
+++ b/server/migrations/162_attachment_task_id_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_attachment_task;
diff --git a/server/migrations/162_attachment_task_id_index.up.sql b/server/migrations/162_attachment_task_id_index.up.sql
new file mode 100644
index 0000000000..7713df4d6a
--- /dev/null
+++ b/server/migrations/162_attachment_task_id_index.up.sql
@@ -0,0 +1,8 @@
+-- Lookup index for BindChatAttachmentsToMessage (find a task's still-unbound
+-- rows on chat-task completion). Single-statement + CONCURRENTLY: CREATE INDEX
+-- CONCURRENTLY cannot run in a transaction or multi-command string (see
+-- 138_issue_title_trgm_index). Partial on task_id IS NOT NULL — only in-flight,
+-- not-yet-bound uploads qualify, so the index stays tiny.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_attachment_task
+ ON attachment(task_id)
+ WHERE task_id IS NOT NULL;
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index f5068fe177..5f86451aad 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -11,16 +11,81 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const bindChatAttachmentsToMessage = `-- name: BindChatAttachmentsToMessage :many
+UPDATE attachment
+SET chat_message_id = $1
+WHERE workspace_id = $2
+ AND task_id = $3
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_message_id IS NULL
+RETURNING id
+`
+
+type BindChatAttachmentsToMessageParams struct {
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+}
+
+// Bind a chat agent's task-scoped attachments to the assistant reply it just
+// produced. Only rows still unclaimed by any owner (issue/comment/chat_message)
+// are eligible, so an attachment already linked elsewhere is never stolen.
+// Returns the bound ids for logging.
+func (q *Queries) BindChatAttachmentsToMessage(ctx context.Context, arg BindChatAttachmentsToMessageParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, bindChatAttachmentsToMessage, arg.ChatMessageID, arg.WorkspaceID, arg.TaskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const countUnboundChatAttachmentsForTask = `-- name: CountUnboundChatAttachmentsForTask :one
+SELECT COUNT(*) FROM attachment
+WHERE workspace_id = $1
+ AND task_id = $2
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_message_id IS NULL
+`
+
+type CountUnboundChatAttachmentsForTaskParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+}
+
+// How many attachments the agent produced for this chat task that are still
+// unbound to any owner. Lets CompleteTask create an assistant message (and
+// bind them) even when the agent's text output was empty but it uploaded files.
+func (q *Queries) CountUnboundChatAttachmentsForTask(ctx context.Context, arg CountUnboundChatAttachmentsForTaskParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countUnboundChatAttachmentsForTask, arg.WorkspaceID, arg.TaskID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
const createAttachment = `-- name: CreateAttachment :one
INSERT INTO attachment (
- id, workspace_id, issue_id, comment_id, chat_session_id,
+ id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
uploader_type, uploader_id, filename, url, content_type, size_bytes
)
VALUES (
- $1, $2, $9, $10, $11,
+ $1, $2, $9, $10, $11, $12,
$3, $4, $5, $6, $7, $8
)
-RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id
+RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id
`
type CreateAttachmentParams struct {
@@ -35,6 +100,7 @@ type CreateAttachmentParams struct {
IssueID pgtype.UUID `json:"issue_id"`
CommentID pgtype.UUID `json:"comment_id"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TaskID pgtype.UUID `json:"task_id"`
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
@@ -50,6 +116,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
arg.IssueID,
arg.CommentID,
arg.ChatSessionID,
+ arg.TaskID,
)
var i Attachment
err := row.Scan(
@@ -66,6 +133,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
)
return i, err
}
@@ -88,9 +156,9 @@ const detachAttachmentsFromUserChatMessageByTask = `-- name: DetachAttachmentsFr
UPDATE attachment
SET chat_message_id = NULL
WHERE chat_message_id IN (
- SELECT id FROM chat_message WHERE task_id = $1 AND role = 'user'
+ SELECT id FROM chat_message WHERE chat_message.task_id = $1 AND role = 'user'
)
-RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id
+RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id
`
// When an empty chat task is cancelled, its user message is deleted. The
@@ -121,6 +189,7 @@ func (q *Queries) DetachAttachmentsFromUserChatMessageByTask(ctx context.Context
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
@@ -133,7 +202,7 @@ func (q *Queries) DetachAttachmentsFromUserChatMessageByTask(ctx context.Context
}
const getAttachment = `-- name: GetAttachment :one
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE id = $1 AND workspace_id = $2
`
@@ -159,12 +228,13 @@ func (q *Queries) GetAttachment(ctx context.Context, arg GetAttachmentParams) (A
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
)
return i, err
}
const getAttachmentByIDOnly = `-- name: GetAttachmentByIDOnly :one
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE id = $1
`
@@ -191,6 +261,7 @@ func (q *Queries) GetAttachmentByIDOnly(ctx context.Context, id pgtype.UUID) (At
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
)
return i, err
}
@@ -339,7 +410,7 @@ func (q *Queries) ListAttachmentURLsByIssueOrComments(ctx context.Context, issue
}
const listAttachmentsByChatMessage = `-- name: ListAttachmentsByChatMessage :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE chat_message_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -372,6 +443,7 @@ func (q *Queries) ListAttachmentsByChatMessage(ctx context.Context, arg ListAtta
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
@@ -384,7 +456,7 @@ func (q *Queries) ListAttachmentsByChatMessage(ctx context.Context, arg ListAtta
}
const listAttachmentsByChatMessageIDs = `-- name: ListAttachmentsByChatMessageIDs :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -417,6 +489,7 @@ func (q *Queries) ListAttachmentsByChatMessageIDs(ctx context.Context, arg ListA
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
@@ -429,7 +502,7 @@ func (q *Queries) ListAttachmentsByChatMessageIDs(ctx context.Context, arg ListA
}
const listAttachmentsByComment = `-- name: ListAttachmentsByComment :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE comment_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -462,6 +535,7 @@ func (q *Queries) ListAttachmentsByComment(ctx context.Context, arg ListAttachme
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
@@ -474,7 +548,7 @@ func (q *Queries) ListAttachmentsByComment(ctx context.Context, arg ListAttachme
}
const listAttachmentsByCommentIDs = `-- name: ListAttachmentsByCommentIDs :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE comment_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -507,6 +581,7 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
@@ -519,7 +594,7 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
}
const listAttachmentsByIssue = `-- name: ListAttachmentsByIssue :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -552,6 +627,7 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment
&i.CreatedAt,
&i.ChatSessionID,
&i.ChatMessageID,
+ &i.TaskID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 3d34488f5a..34d6a6d7b3 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -153,6 +153,7 @@ type Attachment struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ TaskID pgtype.UUID `json:"task_id"`
}
type Autopilot struct {
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index c50ece1731..c352404f98 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -1,10 +1,10 @@
-- name: CreateAttachment :one
INSERT INTO attachment (
- id, workspace_id, issue_id, comment_id, chat_session_id,
+ id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
uploader_type, uploader_id, filename, url, content_type, size_bytes
)
VALUES (
- $1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), sqlc.narg(chat_session_id),
+ $1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), sqlc.narg(chat_session_id), sqlc.narg(task_id),
$3, $4, $5, $6, $7, $8
)
RETURNING *;
@@ -92,10 +92,35 @@ RETURNING id;
UPDATE attachment
SET chat_message_id = NULL
WHERE chat_message_id IN (
- SELECT id FROM chat_message WHERE task_id = $1 AND role = 'user'
+ SELECT id FROM chat_message WHERE chat_message.task_id = $1 AND role = 'user'
)
RETURNING *;
+-- name: CountUnboundChatAttachmentsForTask :one
+-- How many attachments the agent produced for this chat task that are still
+-- unbound to any owner. Lets CompleteTask create an assistant message (and
+-- bind them) even when the agent's text output was empty but it uploaded files.
+SELECT COUNT(*) FROM attachment
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND task_id = sqlc.arg(task_id)
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_message_id IS NULL;
+
+-- name: BindChatAttachmentsToMessage :many
+-- Bind a chat agent's task-scoped attachments to the assistant reply it just
+-- produced. Only rows still unclaimed by any owner (issue/comment/chat_message)
+-- are eligible, so an attachment already linked elsewhere is never stolen.
+-- Returns the bound ids for logging.
+UPDATE attachment
+SET chat_message_id = sqlc.arg(chat_message_id)
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND task_id = sqlc.arg(task_id)
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_message_id IS NULL
+RETURNING id;
+
-- name: ListAttachmentsByChatMessage :many
SELECT * FROM attachment
WHERE chat_message_id = $1 AND workspace_id = $2