Skip to content

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

Go

feat(chat): support attachments & images in chat input (#2445)

Naiyuan Qing86aa5199fc80
diff --git a/e2e/chat-attachments.spec.ts b/e2e/chat-attachments.spec.ts
new file mode 100644
index 0000000000..3869f90f2c
--- /dev/null
+++ b/e2e/chat-attachments.spec.ts
@@ -0,0 +1,170 @@
+/**
+ * E2E: chat attachment upload + send back-fills the message link.
+ *
+ * Stays at the HTTP layer (auth → upload-file → send-chat-message → DB
+ * check) so the test doesn't depend on a real agent runtime being online.
+ * The UI wiring is covered by `chat-input.test.tsx` in @multica/views; this
+ * spec is the end-to-end contract proof: the backend really does persist
+ * chat_session_id at upload and back-fill chat_message_id at send.
+ */
+import "./env";
+import { test, expect } from "@playwright/test";
+import pg from "pg";
+import { createTestApi } from "./helpers";
+import type { TestApiClient } from "./fixtures";
+
+const API_BASE =
+ process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
+const DATABASE_URL =
+ process.env.DATABASE_URL ?? "postgres://multica:multica@localhost:5432/multica?sslmode=disable";
+
+interface UploadRow {
+ id: string;
+ url: string;
+ chat_session_id: string | null;
+ chat_message_id: string | null;
+}
+
+async function authedFetch(api: TestApiClient, path: string, init?: RequestInit) {
+ const token = api.getToken();
+ if (!token) throw new Error("test api client not logged in");
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${token}`,
+ ...((init?.headers as Record<string, string>) ?? {}),
+ };
+ return fetch(`${API_BASE}${path}`, { ...init, headers });
+}
+
+test.describe("Chat attachments", () => {
+ let api: TestApiClient;
+ let pgClient: pg.Client | null = null;
+ let createdSessionId: string | null = null;
+ let createdAgentId: string | null = null;
+ let createdRuntimeId: string | null = null;
+
+ test.beforeEach(async () => {
+ api = await createTestApi();
+ pgClient = new pg.Client(DATABASE_URL);
+ await pgClient.connect();
+ });
+
+ test.afterEach(async () => {
+ try {
+ if (pgClient) {
+ if (createdSessionId) {
+ await pgClient.query(`DELETE FROM chat_session WHERE id = $1`, [createdSessionId]);
+ }
+ if (createdAgentId) {
+ await pgClient.query(`DELETE FROM agent WHERE id = $1`, [createdAgentId]);
+ }
+ if (createdRuntimeId) {
+ await pgClient.query(`DELETE FROM agent_runtime WHERE id = $1`, [createdRuntimeId]);
+ }
+ }
+ } finally {
+ if (pgClient) await pgClient.end();
+ pgClient = null;
+ createdSessionId = null;
+ createdAgentId = null;
+ createdRuntimeId = null;
+ await api.cleanup();
+ }
+ });
+
+ test("upload-file binds attachment to the chat_session; send back-fills chat_message_id", async () => {
+ expect(pgClient).not.toBeNull();
+ const pgc = pgClient!;
+
+ // Resolve the workspace + caller so we can seed an agent/runtime/session
+ // directly via SQL. Going through the HTTP API would require modelling
+ // local-daemon ownership which isn't needed for this contract test.
+ const workspaces = await api.getWorkspaces();
+ const ws = workspaces[0]!;
+ api.setWorkspaceSlug(ws.slug);
+ api.setWorkspaceId(ws.id);
+
+ const userRow = await pgc.query(
+ `SELECT id FROM "user" WHERE email = $1 LIMIT 1`,
+ );
+ if (userRow.rows.length === 0) throw new Error("e2e user missing");
+ const userId = userRow.rows[0].id as string;
+
+ // Seed runtime + agent + chat_session.
+ const runtimeIns = await pgc.query(
+ `INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status,
+ device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, now())
+ RETURNING id`,
+ [ws.id, `e2e chat runtime ${Date.now()}`, "e2e_chat_runtime", "E2E chat runtime"],
+ );
+ createdRuntimeId = runtimeIns.rows[0].id as string;
+
+ const agentIns = await pgc.query(
+ `INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1, $4)
+ RETURNING id`,
+ [ws.id, `E2E Chat Agent ${Date.now()}`, createdRuntimeId, userId],
+ );
+ createdAgentId = agentIns.rows[0].id as string;
+
+ const sessionIns = await pgc.query(
+ `INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'E2E Chat Attachment Session', 'active')
+ RETURNING id`,
+ [ws.id, createdAgentId, userId],
+ );
+ createdSessionId = sessionIns.rows[0].id as string;
+
+ // 1. Upload a small PNG against the chat session.
+ const pngBytes = Buffer.from([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR
+ ]);
+ const form = new FormData();
+ form.append("file", new Blob([new Uint8Array(pngBytes)], { type: "image/png" }), "e2e.png");
+ form.append("chat_session_id", createdSessionId);
+ const uploadRes = await authedFetch(api, "/api/upload-file", {
+ method: "POST",
+ body: form,
+ headers: { "X-Workspace-Slug": ws.slug },
+ });
+ expect(uploadRes.status).toBe(200);
+ const uploaded = (await uploadRes.json()) as UploadRow;
+ expect(uploaded.chat_session_id).toBe(createdSessionId);
+ expect(uploaded.chat_message_id).toBeNull();
+ expect(uploaded.url).toBeTruthy();
+
+ // 2. Send a chat message that references the attachment.
+ const sendRes = await authedFetch(api, `/api/chat/sessions/${createdSessionId}/messages`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Workspace-Slug": ws.slug,
+ },
+ body: JSON.stringify({
+ content: `look at this ![](${uploaded.url})`,
+ attachment_ids: [uploaded.id],
+ }),
+ });
+ expect(sendRes.status).toBe(201);
+ const sendBody = (await sendRes.json()) as { message_id: string; task_id: string };
+ expect(sendBody.message_id).toBeTruthy();
+
+ // 3. DB check: the attachment row's chat_message_id matches the new message.
+ const after = await pgc.query<{ chat_message_id: string | null }>(
+ `SELECT chat_message_id::text FROM attachment WHERE id = $1`,
+ [uploaded.id],
+ );
+ expect(after.rows[0]?.chat_message_id).toBe(sendBody.message_id);
+
+ // 4. Clean up the attachment we created (chat_session cascade handles the
+ // rest in afterEach via chat_session row deletion).
+ await pgc.query(`DELETE FROM attachment WHERE id = $1`, [uploaded.id]);
+ });
+});
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 304d3df430..533661d788 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -199,4 +199,68 @@ describe("ApiClient", () => {
expect(att.download_url).toBe("");
});
});
+
+ describe("chat attachment wiring", () => {
+ it("uploadFile includes chat_session_id in the FormData body", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ id: "att-1", url: "https://cdn/x" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ const file = new File(["hi"], "hi.png", { type: "image/png" });
+ await client.uploadFile(file, { chatSessionId: "session-123" });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(url).toBe("https://api.example.test/api/upload-file");
+ expect(init?.method).toBe("POST");
+ const body = init?.body as FormData;
+ expect(body).toBeInstanceOf(FormData);
+ expect(body.get("chat_session_id")).toBe("session-123");
+ expect(body.get("issue_id")).toBeNull();
+ expect(body.get("comment_id")).toBeNull();
+ });
+
+ it("sendChatMessage serialises attachment_ids onto the JSON body when present", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "" }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.sendChatMessage("session-1", "hello", ["att-1", "att-2"]);
+
+ const [, init] = fetchMock.mock.calls[0]!;
+ expect(JSON.parse(init?.body as string)).toEqual({
+ content: "hello",
+ attachment_ids: ["att-1", "att-2"],
+ });
+ });
+
+ it("sendChatMessage omits attachment_ids when the list is empty or undefined", async () => {
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "" }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.sendChatMessage("session-1", "hello");
+ await client.sendChatMessage("session-1", "again", []);
+
+ expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({ content: "hello" });
+ expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({ content: "again" });
+ });
+ });
});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 312f4abec6..0650320ba0 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1021,11 +1021,15 @@ export class ApiClient {
}
// File Upload & Attachments
- async uploadFile(file: File, opts?: { issueId?: string; commentId?: string }): Promise<Attachment> {
+ async uploadFile(
+ file: File,
+ opts?: { issueId?: string; commentId?: string; chatSessionId?: string },
+ ): Promise<Attachment> {
const formData = new FormData();
formData.append("file", file);
if (opts?.issueId) formData.append("issue_id", opts.issueId);
if (opts?.commentId) formData.append("comment_id", opts.commentId);
+ if (opts?.chatSessionId) formData.append("chat_session_id", opts.chatSessionId);
const rid = createRequestId();
const start = Date.now();
@@ -1046,7 +1050,10 @@ export class ApiClient {
}
this.logger.info(`← ${res.status} /api/upload-file`, { rid, duration: `${Date.now() - start}ms` });
- return res.json() as Promise<Attachment>;
+ const raw = (await res.json()) as unknown;
+ return parseWithFallback(raw, AttachmentResponseSchema, EMPTY_ATTACHMENT, {
+ endpoint: "POST /api/upload-file",
+ });
}
// Chat Sessions
@@ -1074,10 +1081,18 @@ export class ApiClient {
return this.fetch(`/api/chat/sessions/${sessionId}/messages`);
}
- async sendChatMessage(sessionId: string, content: string): Promise<SendChatMessageResponse> {
+ async sendChatMessage(
+ sessionId: string,
+ content: string,
+ attachmentIds?: string[],
+ ): Promise<SendChatMessageResponse> {
+ const body: { content: string; attachment_ids?: string[] } = { content };
+ if (attachmentIds && attachmentIds.length > 0) {
+ body.attachment_ids = attachmentIds;
+ }
return this.fetch(`/api/chat/sessions/${sessionId}/messages`, {
method: "POST",
- body: JSON.stringify({ content }),
+ body: JSON.stringify(body),
});
}
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index a2047738f8..479dffbf1e 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -55,6 +55,8 @@ export const AttachmentResponseSchema = z.object({
url: z.string(),
download_url: z.string(),
filename: z.string(),
+ chat_session_id: z.string().nullable().optional(),
+ chat_message_id: z.string().nullable().optional(),
}).loose();
export const EMPTY_ATTACHMENT: Attachment = {
@@ -62,6 +64,8 @@ export const EMPTY_ATTACHMENT: Attachment = {
workspace_id: "",
issue_id: null,
comment_id: null,
+ chat_session_id: null,
+ chat_message_id: null,
uploader_type: "",
uploader_id: "",
filename: "",
diff --git a/packages/core/hooks/use-file-upload.ts b/packages/core/hooks/use-file-upload.ts
index 559d55eea6..d408c64834 100644
--- a/packages/core/hooks/use-file-upload.ts
+++ b/packages/core/hooks/use-file-upload.ts
@@ -14,6 +14,7 @@ export interface UploadResult {
export interface UploadContext {
issueId?: string;
commentId?: string;
+ chatSessionId?: string;
}
export function useFileUpload(
@@ -33,6 +34,7 @@ export function useFileUpload(
const att: Attachment = await api.uploadFile(file, {
issueId: ctx?.issueId,
commentId: ctx?.commentId,
+ chatSessionId: ctx?.chatSessionId,
});
return { id: att.id, filename: att.filename, link: att.url };
} finally {
diff --git a/packages/core/types/attachment.ts b/packages/core/types/attachment.ts
index 9908850c7b..feea5f356a 100644
--- a/packages/core/types/attachment.ts
+++ b/packages/core/types/attachment.ts
@@ -3,6 +3,8 @@ export interface Attachment {
workspace_id: string;
issue_id: string | null;
comment_id: string | null;
+ chat_session_id: string | null;
+ chat_message_id: string | null;
uploader_type: string;
uploader_id: string;
filename: string;
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index bda3530eb4..50ce7ccb57 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -28,6 +28,14 @@ export interface ChatMessage {
content: string;
task_id: string | null;
created_at: string;
+ /**
+ * Attachments linked to this message via the attachment table's
+ * chat_message_id FK. Populated by ListChatMessages. UI renders these
+ * as file/image cards inside the bubble; the markdown URL inline in
+ * `content` may have an expiring signature, while attachment metadata
+ * here is stable and the source of truth for click-time download.
+ */
+ attachments?: import("./attachment").Attachment[];
/**
* When set, this is an assistant message synthesized by the server's
* FailTask fallback (mirrors the issue path's failure system comment).
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
new file mode 100644
index 0000000000..a61e054e64
--- /dev/null
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -0,0 +1,209 @@
+import { forwardRef, useRef, useImperativeHandle } from "react";
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enChat from "../../locales/en/chat.json";
+
+const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };
+
+// Track drop-zone callbacks so the test can simulate a real drop.
+const dropHandlers = vi.hoisted(() => ({
+ onDrop: null as null | ((files: File[]) => void),
+}));
+
+vi.mock("../../editor", () => ({
+ useFileDropZone: ({ onDrop }: { onDrop: (files: File[]) => void }) => {
+ dropHandlers.onDrop = onDrop;
+ return { isDragOver: false, dropZoneProps: { "data-testid": "drop-zone" } };
+ },
+ FileDropOverlay: () => null,
+ ContentEditor: forwardRef(function MockContentEditor(
+ {
+ defaultValue,
+ onUpdate,
+ placeholder,
+ onUploadFile,
+ }: {
+ defaultValue?: string;
+ onUpdate?: (md: string) => void;
+ placeholder?: string;
+ onUploadFile?: (file: File) => Promise<{ id: string; link: string; filename: string } | null>;
+ },
+ ref: React.Ref<unknown>,
+ ) {
+ const valueRef = useRef<string>(defaultValue ?? "");
+ const uploadingRef = useRef(0);
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => valueRef.current,
+ clearContent: () => {
+ valueRef.current = "";
+ },
+ blur: () => {},
+ focus: () => {},
+ uploadFile: async (file: File) => {
+ uploadingRef.current += 1;
+ try {
+ const result = await onUploadFile?.(file);
+ if (result) {
+ valueRef.current = `${valueRef.current}![](${result.link})`.trim();
+ onUpdate?.(valueRef.current);
+ }
+ } finally {
+ uploadingRef.current = Math.max(0, uploadingRef.current - 1);
+ }
+ },
+ hasActiveUploads: () => uploadingRef.current > 0,
+ }));
+ return (
+ <textarea
+ data-testid="editor"
+ placeholder={placeholder}
+ onChange={(e) => {
+ valueRef.current = e.target.value;
+ onUpdate?.(e.target.value);
+ }}
+ />
+ );
+ }),
+}));
+
+// Mock chat store with an in-memory implementation that supports both
+// (selector) calls and getState().
+vi.mock("@multica/core/chat", () => {
+ const state = {
+ activeSessionId: null as string | null,
+ selectedAgentId: "agent-1",
+ inputDrafts: {} as Record<string, string>,
+ focusMode: false,
+ setInputDraft: vi.fn(),
+ clearInputDraft: vi.fn(),
+ };
+ return {
+ DRAFT_NEW_SESSION: "__draft_new__",
+ useChatStore: Object.assign(
+ (selector?: (s: typeof state) => unknown) =>
+ selector ? selector(state) : state,
+ { getState: () => state },
+ ),
+ };
+});
+
+import { ChatInput } from "./chat-input";
+
+function renderInput(props: Partial<React.ComponentProps<typeof ChatInput>> = {}) {
+ const onSend = props.onSend ?? vi.fn();
+ const onUploadFile =
+ props.onUploadFile ??
+ vi.fn(async (_file: File) => ({
+ id: "att-1",
+ link: "https://cdn.example/att-1.png",
+ filename: "img.png",
+ }));
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatInput onSend={onSend} onUploadFile={onUploadFile} agentName="Multica" {...props} />
+ </I18nProvider>,
+ );
+ return { onSend, onUploadFile };
+}
+
+describe("ChatInput attachment wiring", () => {
+ it("routes dropped files through the editor's upload handler", async () => {
+ const { onUploadFile } = renderInput();
+ expect(dropHandlers.onDrop).not.toBeNull();
+ const file = new File(["x"], "drop.png", { type: "image/png" });
+ dropHandlers.onDrop?.([file]);
+ // Microtask: the mock editor awaits onUploadFile before mutating its value.
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(onUploadFile).toHaveBeenCalledWith(file);
+ });
+
+ it("passes attachment_ids to onSend for uploads still referenced in the content", async () => {
+ const onSend = vi.fn();
+ const onUploadFile = vi.fn(async (_file: File) => ({
+ id: "att-42",
+ link: "https://cdn.example/att-42.png",
+ filename: "x.png",
+ }));
+ renderInput({ onSend, onUploadFile });
+
+ // Simulate the drop → editor.uploadFile → onUploadFile happy path. The
+ // mock editor appends the markdown link into its value and calls
+ // onUpdate so the input flips out of the empty state.
+ const file = new File(["x"], "drop.png", { type: "image/png" });
+ dropHandlers.onDrop?.([file]);
+
+ // Wait for the submit button to become enabled (onUpdate has fired and
+ // React has re-rendered). SubmitButton has no aria-label, so we pick
+ // the last action button on the bar (FileUploadButton, SubmitButton).
+ let sendButton: HTMLElement;
+ await waitFor(() => {
+ const buttons = screen.getAllByRole("button");
+ sendButton = buttons[buttons.length - 1]!;
+ expect(sendButton).not.toBeDisabled();
+ });
+ fireEvent.click(sendButton!);
+
+ expect(onSend).toHaveBeenCalledTimes(1);
+ const [, ids] = onSend.mock.calls[0]!;
+ expect(ids).toEqual(["att-42"]);
+ });
+
+ it("disables send while an upload is in flight, re-enables after it resolves", async () => {
+ let resolveUpload: (v: { id: string; link: string; filename: string }) => void;
+ const uploadPromise = new Promise<{ id: string; link: string; filename: string }>((res) => {
+ resolveUpload = res;
+ });
+ const onSend = vi.fn();
+ const onUploadFile = vi.fn(() => uploadPromise);
+ renderInput({ onSend, onUploadFile });
+
+ // Give the editor some text so isEmpty=false — this isolates the
+ // disabled state to the pending-upload condition (otherwise both
+ // checks would fire and the test couldn't tell them apart).
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "preview text" } });
+
+ const file = new File(["x"], "slow.png", { type: "image/png" });
+ dropHandlers.onDrop?.([file]);
+
+ // While the upload is pending the SubmitButton must be disabled.
+ // Bypassing this would send the message with the attachment id
+ // missing from the body.
+ await waitFor(() => {
+ const buttons = screen.getAllByRole("button");
+ const sendButton = buttons[buttons.length - 1]!;
+ expect(sendButton).toBeDisabled();
+ });
+
+ resolveUpload!({
+ id: "att-slow",
+ link: "https://cdn.example/att-slow.png",
+ filename: "slow.png",
+ });
+
+ let sendButton: HTMLElement;
+ await waitFor(() => {
+ const buttons = screen.getAllByRole("button");
+ sendButton = buttons[buttons.length - 1]!;
+ expect(sendButton).not.toBeDisabled();
+ });
+ fireEvent.click(sendButton!);
+ expect(onSend).toHaveBeenCalledTimes(1);
+ const [, ids] = onSend.mock.calls[0]!;
+ expect(ids).toEqual(["att-slow"]);
+ });
+
+ it("does not render the file upload button when onUploadFile is omitted", () => {
+ renderInput({ onUploadFile: undefined });
+ // FileUploadButton renders an icon button labelled by its tooltip — when
+ // upload wiring is absent the chat input falls back to "submit + extras"
+ // only. Probe by counting buttons: with no upload, only the submit
+ // button is in the action row.
+ const buttons = screen.getAllByRole("button");
+ // The agent picker / context anchor adornments may render zero buttons
+ // in this test (no leftAdornment passed). So a single button = submit.
+ expect(buttons.length).toBe(1);
+ });
+});
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index acd1889653..b6fc25c6dd 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -1,19 +1,33 @@
"use client";
import type { ReactNode } from "react";
-import { useRef, useState } from "react";
+import { useCallback, useRef, useState } from "react";
import { cn } from "@multica/ui/lib/utils";
-import { ContentEditor, type ContentEditorRef } from "../../editor";
+import {
+ ContentEditor,
+ type ContentEditorRef,
+ useFileDropZone,
+ FileDropOverlay,
+} from "../../editor";
+import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { useChatStore, DRAFT_NEW_SESSION } from "@multica/core/chat";
import { createLogger } from "@multica/core/logger";
import { enterKey, formatShortcut, modKey } from "@multica/core/platform";
+import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import { useT } from "../../i18n";
const logger = createLogger("chat.ui");
interface ChatInputProps {
- onSend: (content: string) => void;
+ onSend: (content: string, attachmentIds?: string[]) => void;
+ /** Receives a File and returns the attachment row (with id + CDN link).
+ * The wrapper owner (ChatWindow) lazy-creates a chat_session if needed
+ * and forwards `chatSessionId` to the upload — chat-input only cares
+ * about the upload result so it can map URL → id for back-fill on send.
+ * When unset, paste/drag/button still type into the editor but no upload
+ * fires (the editor's file-upload extension is a no-op without a handler). */
+ onUploadFile?: (file: File) => Promise<UploadResult | null>;
onStop?: () => void;
isRunning?: boolean;
disabled?: boolean;
@@ -34,6 +48,7 @@ interface ChatInputProps {
export function ChatInput({
onSend,
+ onUploadFile,
onStop,
isRunning,
disabled,
@@ -60,6 +75,41 @@ export function ChatInput({
const setInputDraft = useChatStore((s) => s.setInputDraft);
const clearInputDraft = useChatStore((s) => s.clearInputDraft);
const [isEmpty, setIsEmpty] = useState(!inputDraft.trim());
+ // Number of in-flight uploads. We track this explicitly (rather than
+ // peeking at the editor on every render) so the SubmitButton visibly
+ // disables the instant an upload starts and re-enables the instant it
+ // finishes. handleSend ALSO checks `hasActiveUploads()` for paths that
+ // bypass the button (Mod+Enter while paste is mid-stream, drag-drop
+ // racing the keyboard) — defense in depth.
+ const [pendingUploads, setPendingUploads] = useState(0);
+
+ // Maps "CDN URL inserted into the editor" → "attachment row id" so that
+ // on send we can ask the server to bind only the attachments still
+ // referenced in the message body. Cleared after every send. Mirrors the
+ // comment-input flow exactly.
+ const uploadMapRef = useRef<Map<string, string>>(new Map());
+
+ const handleUpload = useCallback(
+ async (file: File): Promise<UploadResult | null> => {
+ if (!onUploadFile) return null;
+ setPendingUploads((n) => n + 1);
+ try {
+ const result = await onUploadFile(file);
+ if (result) uploadMapRef.current.set(result.link, result.id);
+ return result;
+ } finally {
+ setPendingUploads((n) => Math.max(0, n - 1));
+ }
+ },
+ [onUploadFile],
+ );
+
+ // Drop zone wraps the rounded card so a drop anywhere on the input
+ // surface routes the file through the editor's upload extension (same
+ // handler as the in-editor paste path).
+ const { isDragOver, dropZoneProps } = useFileDropZone({
+ onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
+ });
const handleSend = () => {
const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();
@@ -72,12 +122,33 @@ export function ChatInput({
});
return;
}
+ // Block the send while any file is still uploading. If we let it
+ // through the attachment id is not yet in uploadMapRef (the upload
+ // resolves later) and the attachment would only end up bound to the
+ // session, not the message — the agent then can't `multica attachment
+ // download <id>` the file. The SubmitButton is also disabled in this
+ // state via `uploading`, but Mod+Enter bypasses the button so we
+ // still gate here.
+ if (editorRef.current?.hasActiveUploads()) {
+ logger.debug("input.send skipped: uploads in flight");
+ return;
+ }
+ // Only send attachment IDs for uploads still present in the content.
+ // Edits / deletions that remove the markdown URL also drop the binding.
+ const activeIds: string[] = [];
+ for (const [url, id] of uploadMapRef.current) {
+ if (content.includes(url)) activeIds.push(id);
+ }
// Capture draft key BEFORE onSend — creating a new session mutates
// activeSessionId synchronously, so reading it after onSend would point
// at the new session and leave the old draft orphaned.
const keyAtSend = draftKey;
- logger.info("input.send", { contentLength: content.length, draftKey: keyAtSend });
- onSend(content);
+ logger.info("input.send", {
+ contentLength: content.length,
+ draftKey: keyAtSend,
+ attachmentCount: activeIds.length,
+ });
+ onSend(content, activeIds.length > 0 ? activeIds : undefined);
editorRef.current?.clearContent();
// Drop focus so the caret doesn't keep blinking under the StatusPill /
// streaming reply that's about to take over the user's attention. The
@@ -88,6 +159,7 @@ export function ChatInput({
// a fair price for not stealing focus mid-action.
editorRef.current?.blur();
clearInputDraft(keyAtSend);
+ uploadMapRef.current.clear();
setIsEmpty(true);
};
@@ -99,6 +171,8 @@ export function ChatInput({
? t(($) => $.input.placeholder_named, { name: agentName })
: t(($) => $.input.placeholder_default);
+ const uploadEnabled = !!onUploadFile && !disabled && !noAgent;
+
return (
<div
className={cn(
@@ -111,6 +185,7 @@ export function ChatInput({
)}
>
<div
+ {...(uploadEnabled ? dropZoneProps : {})}
className={cn(
"relative mx-auto flex min-h-16 max-h-40 w-full max-w-4xl flex-col rounded-lg bg-card pb-9 border-1 border-border transition-colors focus-within:border-brand",
// Visual + interaction lock when there's no agent. We don't
@@ -137,6 +212,7 @@ export function ChatInput({
setInputDraft(draftKey, md);
}}
onSubmit={handleSend}
+ onUploadFile={uploadEnabled ? handleUpload : undefined}
debounceMs={100}
// Chat is short-form — the floating formatting toolbar is
// more distraction than feature here.
@@ -152,17 +228,24 @@ export function ChatInput({
{leftAdornment}
</div>
)}
- <div className="absolute bottom-1 right-1.5 flex items-center gap-2">
+ <div className="absolute bottom-1 right-1.5 flex items-center gap-1">
{rightAdornment}
+ {uploadEnabled && (
+ <FileUploadButton
+ size="sm"
+ onSelect={(file) => editorRef.current?.uploadFile(file)}
+ />
+ )}
<SubmitButton
onClick={handleSend}
- disabled={isEmpty || !!disabled || !!noAgent}
+ disabled={isEmpty || !!disabled || !!noAgent || pendingUploads > 0}
running={isRunning}
onStop={onStop}
tooltip={`${t(($) => $.input.send_tooltip)} · ${formatShortcut(modKey, enterKey)}`}
stopTooltip={t(($) => $.input.stop_tooltip)}
/>
</div>
+ {uploadEnabled && isDragOver && <FileDropOverlay />}
</div>
</div>
);
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 3769bfcb16..fcc753f326 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -31,6 +31,7 @@ import { agentListOptions, memberListOptions } from "@multica/core/workspace/que
import { canAssignAgent } from "@multica/views/issues/components";
import { api } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
+import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { ActorAvatar } from "../../common/actor-avatar";
import { OfflineBanner } from "./offline-banner";
import { NoAgentBanner } from "./no-agent-banner";
@@ -189,8 +190,62 @@ export function ChatWindow() {
// (focus mode tracks the user's page, not a per-message attachment).
const { candidate: anchorCandidate } = useRouteAnchorCandidate(wsId);
+ const { uploadWithToast } = useFileUpload(api);
+
+ // Lazy-creates a chat_session the first time the user needs an id —
+ // either to send a message or to attach an uploaded file. Pulled out of
+ // handleSend so the upload path (which fires before any text exists) can
+ // get a session_id to hang the attachment on. Returns null when no agent
+ // is available; callers must early-return in that case.
+ //
+ // Concurrent callers (e.g. user drops a file → handleUploadFile, then
+ // quickly clicks send → handleSend) would each observe activeSessionId
+ // === null and fire a separate createSession.mutateAsync, creating two
+ // sessions and orphaning the attachment on the wrong one. The in-flight
+ // promise ref dedupes those races: the first caller starts the create,
+ // every subsequent caller awaits the same promise until it settles.
+ //
+ // titleSeed is the first 50 chars of the user's message when called from
+ // send; the upload path passes "" and we leave the title empty so the
+ // session-dropdown's existing localized `window.untitled` fallback kicks
+ // in. A follow-up task may back-fill the real title from the first user
+ // message — until then this keeps the session list scannable across locales.
+ const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
+ const ensureSession = useCallback(
+ async (titleSeed: string): Promise<string | null> => {
+ if (activeSessionId) return activeSessionId;
+ if (!activeAgent) return null;
+ if (sessionPromiseRef.current) return sessionPromiseRef.current;
+
+ const promise = (async () => {
+ try {
+ const session = await createSession.mutateAsync({
+ agent_id: activeAgent.id,
+ title: titleSeed.slice(0, 50),
+ });
+ setActiveSession(session.id);
+ return session.id;
+ } finally {
+ sessionPromiseRef.current = null;
+ }
+ })();
+ sessionPromiseRef.current = promise;
+ return promise;
+ },
+ [activeSessionId, activeAgent, createSession, setActiveSession],
+ );
+
+ const handleUploadFile = useCallback(
+ async (file: File) => {
+ const sessionId = await ensureSession("");
+ if (!sessionId) return null;
+ return uploadWithToast(file, { chatSessionId: sessionId });
+ },
+ [ensureSession, uploadWithToast],
+ );
+
const handleSend = useCallback(
- async (content: string) => {
+ async (content: string, attachmentIds?: string[]) => {
if (!activeAgent) {
apiLogger.warn("sendChatMessage skipped: no active agent");
return;
@@ -201,24 +256,21 @@ export function ChatWindow() {
? `${buildAnchorMarkdown(anchorCandidate)}\n\n${content}`
: content;
- let sessionId = activeSessionId;
- const isNewSession = !sessionId;
+ const isNewSession = !activeSessionId;
apiLogger.info("sendChatMessage.start", {
- sessionId,
+ sessionId: activeSessionId,
isNewSession,
agentId: activeAgent.id,
contentLength: finalContent.length,
hasAnchor: focusOn && !!anchorCandidate,
+ attachmentCount: attachmentIds?.length ?? 0,
});
+ const sessionId = await ensureSession(finalContent);
if (!sessionId) {
- const session = await createSession.mutateAsync({
- agent_id: activeAgent.id,
- title: finalContent.slice(0, 50),
- });
- sessionId = session.id;
- setActiveSession(sessionId);
+ apiLogger.warn("sendChatMessage aborted: ensureSession returned null");
+ return;
}
// Optimistic burst — everything that gives the user "I sent a message
@@ -251,7 +303,7 @@ export function ChatWindow() {
});
apiLogger.debug("sendChatMessage.optimistic", { sessionId, optimisticId: optimistic.id });
- const result = await api.sendChatMessage(sessionId, finalContent);
+ const result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
apiLogger.info("sendChatMessage.success", {
sessionId,
messageId: result.message_id,
@@ -271,8 +323,7 @@ export function ChatWindow() {
activeSessionId,
activeAgent,
anchorCandidate,
- createSession,
- setActiveSession,
+ ensureSession,
qc,
],
);
@@ -494,6 +545,7 @@ export function ChatWindow() {
* when there's no agent (the EmptyState above carries the CTA). */}
<ChatInput
onSend={handleSend}
+ onUploadFile={handleUploadFile}
onStop={handleStop}
isRunning={!!pendingTaskId}
disabled={isSessionArchived}
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 2352555b72..a2ffebc052 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -142,6 +142,23 @@ func buildChatPrompt(task Task) string {
b.WriteString("You are running as a chat assistant for a Multica workspace.\n")
b.WriteString("A user is chatting with you directly. Respond to their message.\n\n")
fmt.Fprintf(&b, "User message:\n%s\n", task.ChatMessage)
+ // List attachments by id + filename so the agent can fetch them via
+ // the CLI. We deliberately do NOT inline the URL: chat attachments
+ // live behind a signed CDN with a short TTL, so by the time the agent
+ // has finished thinking the URL embedded in the markdown body may
+ // have expired. `multica attachment download <id>` re-signs at click
+ // time and is the only reliable path.
+ if len(task.ChatMessageAttachments) > 0 {
+ b.WriteString("\nAttachments on this message:\n")
+ for _, a := range task.ChatMessageAttachments {
+ if a.ContentType != "" {
+ fmt.Fprintf(&b, "- id=%s filename=%q content_type=%s\n", a.ID, a.Filename, a.ContentType)
+ } else {
+ fmt.Fprintf(&b, "- id=%s filename=%q\n", a.ID, a.Filename)
+ }
+ }
+ b.WriteString("Use `multica attachment download <id>` to fetch each file locally before referring to it.\n")
+ }
return b.String()
}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 12b9160e40..c8bde827e5 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -51,6 +51,7 @@ type Task struct {
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
+ ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot run_only tasks
AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this run
AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
@@ -60,6 +61,17 @@ type Task struct {
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
}
+// ChatAttachmentMeta is the structured attachment metadata the daemon
+// hands to the agent for chat tasks. We pass id + filename + content_type
+// so the chat prompt can list them explicitly and instruct the agent to
+// run `multica attachment download <id>` instead of guessing from a
+// signed CDN URL (which expires).
+type ChatAttachmentMeta struct {
+ ID string `json:"id"`
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type,omitempty"`
+}
+
// AgentData holds agent details returned by the claim endpoint.
type AgentData struct {
ID string `json:"id"`
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index da673be97c..257a94ba28 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -166,6 +166,7 @@ type AgentTaskResponse struct {
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
+ ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks
AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task
AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
@@ -176,6 +177,18 @@ type AgentTaskResponse struct {
Kind string `json:"kind"` // discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "direct" — used by the activity row to label tasks that have no linked issue
}
+// ChatAttachmentMeta is the structured attachment metadata embedded in
+// claim responses for chat tasks. The agent uses these to run
+// `multica attachment download <id>` rather than guessing from the
+// markdown URL (which is signed and 30-min expiring on private CDN).
+// The mirror struct on the daemon side lives in internal/daemon/types.go
+// and uses the same JSON field names.
+type ChatAttachmentMeta struct {
+ ID string `json:"id"`
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type,omitempty"`
+}
+
// TaskAgentData holds agent info included in claim responses so the daemon
// can set up the execution environment (branch naming, skill files, instructions).
type TaskAgentData struct {
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 8130408475..3c0be810d9 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -8,6 +8,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -305,7 +306,8 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
// ---------------------------------------------------------------------------
type SendChatMessageRequest struct {
- Content string `json:"content"`
+ Content string `json:"content"`
+ AttachmentIDs []string `json:"attachment_ids"`
}
type SendChatMessageResponse struct {
@@ -337,6 +339,14 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
return
}
+ // Pre-validate attachment ids early so invalid input returns 400 before
+ // any state mutation. The actual link runs after CreateChatMessage so we
+ // have a message_id to back-fill into the attachment rows.
+ attachmentIDs, ok := parseUUIDSliceOrBadRequest(w, req.AttachmentIDs, "attachment_ids")
+ if !ok {
+ return
+ }
+
// Load chat session and re-check the private-agent gate on every send.
// The session's creator passed the gate at create time, but their
// workspace role (or the agent's owner) may have changed since — keep
@@ -366,6 +376,22 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
return
}
+ // Back-fill chat_message_id on attachments that were uploaded against
+ // this session while the user was composing. The query only touches rows
+ // where chat_session_id matches AND chat_message_id IS NULL, so it cannot
+ // rebind an attachment that already belongs to an earlier message.
+ if len(attachmentIDs) > 0 {
+ if err := h.Queries.LinkAttachmentsToChatMessage(r.Context(), db.LinkAttachmentsToChatMessageParams{
+ ChatMessageID: msg.ID,
+ ChatSessionID: session.ID,
+ Column3: attachmentIDs,
+ }); err != nil {
+ // Don't fail the send — the message content is already saved and
+ // the attachments remain on the session (still downloadable).
+ slog.Warn("link chat attachments failed", "error", err, "message_id", uuidToString(msg.ID))
+ }
+ }
+
// Enqueue a chat task after the message exists.
task, err := h.TaskService.EnqueueChatTask(r.Context(), session)
if err != nil {
@@ -425,9 +451,15 @@ func (h *Handler) ListChatMessages(w http.ResponseWriter, r *http.Request) {
return
}
+ messageIDs := make([]pgtype.UUID, len(messages))
+ for i, m := range messages {
+ messageIDs[i] = m.ID
+ }
+ groupedAtt := h.groupChatMessageAttachments(r.Context(), workspaceID, messageIDs)
+
resp := make([]ChatMessageResponse, len(messages))
for i, m := range messages {
- resp[i] = chatMessageToResponse(m)
+ resp[i] = chatMessageToResponse(m, groupedAtt[uuidToString(m.ID)])
}
writeJSON(w, http.StatusOK, resp)
}
@@ -669,6 +701,12 @@ type ChatMessageResponse struct {
// ElapsedMs is the wall-clock duration from task creation to terminal
// state. Drives "Replied in 38s" / "Failed after 12s" captions.
ElapsedMs *int64 `json:"elapsed_ms"`
+ // Attachments linked to this message via chat_message_id. The chat
+ // bubble renders file cards from these, and the daemon claim path
+ // (daemon.go) pulls structured metadata from the same source so the
+ // agent can `multica attachment download <id>` rather than guessing
+ // from a markdown URL that may expire.
+ Attachments []AttachmentResponse `json:"attachments,omitempty"`
}
func chatSessionToResponse(s db.ChatSession) ChatSessionResponse {
@@ -684,7 +722,7 @@ func chatSessionToResponse(s db.ChatSession) ChatSessionResponse {
}
}
-func chatMessageToResponse(m db.ChatMessage) ChatMessageResponse {
+func chatMessageToResponse(m db.ChatMessage, attachments []AttachmentResponse) ChatMessageResponse {
return ChatMessageResponse{
ID: uuidToString(m.ID),
ChatSessionID: uuidToString(m.ChatSessionID),
@@ -694,5 +732,6 @@ func chatMessageToResponse(m db.ChatMessage) ChatMessageResponse {
CreatedAt: timestampToString(m.CreatedAt),
FailureReason: textToPtr(m.FailureReason),
ElapsedMs: int8ToPtr(m.ElapsedMs),
+ Attachments: attachments,
}
}
diff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.go
new file mode 100644
index 0000000000..4993829268
--- /dev/null
+++ b/server/internal/handler/chat_test.go
@@ -0,0 +1,140 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// withChatTestWorkspaceCtx injects the workspace+member context that the
+// real chi middleware chain would normally set. SendChatMessage (and most
+// other chat handlers) read workspace ID from ctxWorkspaceID; without this
+// the test harness, which calls handlers directly, gets "invalid workspace
+// id" on the parseUUIDOrBadRequest call inside SendChatMessage.
+func withChatTestWorkspaceCtx(t *testing.T, req *http.Request) *http.Request {
+ t.Helper()
+ memberRow, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: util.MustParseUUID(testUserID),
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load test member row: %v", err)
+ }
+ return req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, memberRow))
+}
+
+// TestSendChatMessage_LinksAttachments verifies that attachments uploaded
+// against a chat_session (chat_message_id NULL) are back-filled with the
+// message_id when SendChatMessage receives the matching attachment_ids.
+func TestSendChatMessage_LinksAttachments(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ defer func() { testHandler.Storage = origStorage }()
+
+ agentID := createHandlerTestAgent(t, "ChatSendAttachAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ // 1. Upload a file against the chat session.
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, _ := writer.CreateFormFile("file", "send-link.png")
+ part.Write([]byte("\x89PNG\r\n\x1a\nbytes"))
+ writer.WriteField("chat_session_id", sessionID)
+ writer.Close()
+
+ uploadReq := httptest.NewRequest("POST", "/api/upload-file", &body)
+ uploadReq.Header.Set("Content-Type", writer.FormDataContentType())
+ uploadReq.Header.Set("X-User-ID", testUserID)
+ uploadReq.Header.Set("X-Workspace-ID", testWorkspaceID)
+
+ uploadW := httptest.NewRecorder()
+ testHandler.UploadFile(uploadW, uploadReq)
+ if uploadW.Code != http.StatusOK {
+ t.Fatalf("upload precondition: %d %s", uploadW.Code, uploadW.Body.String())
+ }
+ var uploadResp AttachmentResponse
+ if err := json.Unmarshal(uploadW.Body.Bytes(), &uploadResp); err != nil {
+ t.Fatalf("decode upload: %v", err)
+ }
+ attachmentID := uploadResp.ID
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ })
+
+ // 2. Send a chat message that references the attachment.
+ sendReq := newRequest("POST", "/api/chat-sessions/"+sessionID+"/messages", map[string]any{
+ "content": "look at this ![](" + uploadResp.URL + ")",
+ "attachment_ids": []string{attachmentID},
+ })
+ sendReq = withURLParam(sendReq, "sessionId", sessionID)
+ sendReq = withChatTestWorkspaceCtx(t, sendReq)
+ sendW := httptest.NewRecorder()
+ testHandler.SendChatMessage(sendW, sendReq)
+ if sendW.Code != http.StatusCreated {
+ t.Fatalf("SendChatMessage: expected 201, got %d: %s", sendW.Code, sendW.Body.String())
+ }
+
+ var sendResp SendChatMessageResponse
+ if err := json.Unmarshal(sendW.Body.Bytes(), &sendResp); err != nil {
+ t.Fatalf("decode send: %v", err)
+ }
+ if sendResp.MessageID == "" {
+ t.Fatal("expected non-empty message_id in send response")
+ }
+
+ // 3. Verify the attachment row now points at the new message.
+ var dbMessageID *string
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT chat_message_id::text FROM attachment WHERE id = $1`,
+ attachmentID,
+ ).Scan(&dbMessageID); err != nil {
+ t.Fatalf("query attachment: %v", err)
+ }
+ if dbMessageID == nil {
+ t.Fatal("chat_message_id is still NULL after send")
+ }
+ if *dbMessageID != sendResp.MessageID {
+ t.Fatalf("chat_message_id mismatch: want %s, got %s", sendResp.MessageID, *dbMessageID)
+ }
+}
+
+// TestSendChatMessage_InvalidAttachmentIDs rejects malformed UUIDs in
+// attachment_ids with 400 before any side effects (no message row created).
+func TestSendChatMessage_InvalidAttachmentIDs(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "ChatBadAttachAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ req := newRequest("POST", "/api/chat-sessions/"+sessionID+"/messages", map[string]any{
+ "content": "hi",
+ "attachment_ids": []string{"not-a-uuid"},
+ })
+ req = withURLParam(req, "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := httptest.NewRecorder()
+ testHandler.SendChatMessage(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("SendChatMessage with bad attachment id: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Confirm no message row was created.
+ var count int
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT count(*) FROM chat_message WHERE chat_session_id = $1`,
+ sessionID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count chat_message: %v", err)
+ }
+ if count != 0 {
+ t.Fatalf("expected 0 chat_message rows after rejected send, got %d", count)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 16664d2298..6325854bc9 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1241,12 +1241,29 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.PriorWorkDir = prior.WorkDir.String
}
}
- // Load the latest user message for the chat prompt.
+ // Load the latest user message for the chat prompt, plus any
+ // attachments linked to that exact message. Without the structured
+ // attachment list the agent only sees the markdown URL in
+ // `ChatMessage` — fine for vision models inline but unusable when
+ // the agent wants to `multica attachment download <id>` (URL is
+ // signed and 30-min expiring on private CDN).
if msgs, err := h.Queries.ListChatMessages(r.Context(), cs.ID); err == nil && len(msgs) > 0 {
- // Find the last user message.
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Role == "user" {
resp.ChatMessage = msgs[i].Content
+ if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{
+ ChatMessageID: msgs[i].ID,
+ WorkspaceID: parseUUID(resp.WorkspaceID),
+ }); attErr == nil && len(atts) > 0 {
+ resp.ChatMessageAttachments = make([]ChatAttachmentMeta, len(atts))
+ for j, a := range atts {
+ resp.ChatMessageAttachments[j] = ChatAttachmentMeta{
+ ID: uuidToString(a.ID),
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ }
+ }
+ }
break
}
}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 6220b7a1f6..697415c3f7 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -34,18 +34,20 @@ const maxUploadSize = 100 << 20 // 100 MB
// ---------------------------------------------------------------------------
type AttachmentResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- IssueID *string `json:"issue_id"`
- CommentID *string `json:"comment_id"`
- UploaderType string `json:"uploader_type"`
- UploaderID string `json:"uploader_id"`
- Filename string `json:"filename"`
- URL string `json:"url"`
- DownloadURL string `json:"download_url"`
- ContentType string `json:"content_type"`
- SizeBytes int64 `json:"size_bytes"`
- CreatedAt string `json:"created_at"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ IssueID *string `json:"issue_id"`
+ CommentID *string `json:"comment_id"`
+ ChatSessionID *string `json:"chat_session_id"`
+ ChatMessageID *string `json:"chat_message_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID string `json:"uploader_id"`
+ Filename string `json:"filename"`
+ URL string `json:"url"`
+ DownloadURL string `json:"download_url"`
+ ContentType string `json:"content_type"`
+ SizeBytes int64 `json:"size_bytes"`
+ CreatedAt string `json:"created_at"`
}
func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
@@ -72,6 +74,14 @@ func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
s := uuidToString(a.CommentID)
resp.CommentID = &s
}
+ if a.ChatSessionID.Valid {
+ s := uuidToString(a.ChatSessionID)
+ resp.ChatSessionID = &s
+ }
+ if a.ChatMessageID.Valid {
+ s := uuidToString(a.ChatMessageID)
+ resp.ChatMessageID = &s
+ }
return resp
}
@@ -97,6 +107,30 @@ func (h *Handler) groupAttachments(r *http.Request, commentIDs []pgtype.UUID) ma
return grouped
}
+// groupChatMessageAttachments loads attachments for multiple chat messages
+// and groups them by chat_message_id. Mirrors groupAttachments — used so the
+// chat message list can surface attachment metadata to the UI bubble (file
+// cards, click-through download) without an N+1 query per message.
+func (h *Handler) groupChatMessageAttachments(ctx context.Context, workspaceID string, messageIDs []pgtype.UUID) map[string][]AttachmentResponse {
+ if len(messageIDs) == 0 {
+ return nil
+ }
+ attachments, err := h.Queries.ListAttachmentsByChatMessageIDs(ctx, db.ListAttachmentsByChatMessageIDsParams{
+ Column1: messageIDs,
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ slog.Error("failed to load attachments for chat messages", "error", err)
+ return nil
+ }
+ grouped := make(map[string][]AttachmentResponse, len(messageIDs))
+ for _, a := range attachments {
+ mid := uuidToString(a.ChatMessageID)
+ grouped[mid] = append(grouped[mid], h.attachmentToResponse(a))
+ }
+ return grouped
+}
+
// ---------------------------------------------------------------------------
// UploadFile — POST /api/upload-file
// ---------------------------------------------------------------------------
@@ -214,6 +248,16 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
}
params.CommentID = comment.ID
}
+ if chatSessionID := r.FormValue("chat_session_id"); chatSessionID != "" {
+ // Re-use the existing private-agent gate so the user can still
+ // reach this session — covers role downgrade and agent
+ // visibility flips. The gate writes 4xx on failure.
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, chatSessionID)
+ if !ok {
+ return
+ }
+ params.ChatSessionID = session.ID
+ }
link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)
if err != nil {
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 1304409365..841fc6a5b7 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -11,6 +11,26 @@ import (
"testing"
)
+// createHandlerTestChatSession seeds a chat_session row owned by testUserID
+// targeting the given agent and returns the session UUID. Cleanup runs after
+// the test. Used by attachment / chat tests that need an existing session.
+func createHandlerTestChatSession(t *testing.T, agentID string) string {
+ t.Helper()
+
+ var sessionID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, $4, 'active')
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, "Handler Test Chat Session").Scan(&sessionID); err != nil {
+ t.Fatalf("failed to create handler test chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, sessionID)
+ })
+ return sessionID
+}
+
type mockStorage struct{}
func (m *mockStorage) Upload(_ context.Context, key string, _ []byte, _ string, _ string) (string, error) {
@@ -160,3 +180,104 @@ func TestUploadFileResolvesWorkspaceViaIDHeaderStill(t *testing.T) {
t.Fatalf("cleanup attachment: %v", err)
}
}
+
+// TestUploadFile_AttachesToChatSession verifies that a multipart upload with
+// a chat_session_id form field creates an attachment row linked to that chat
+// session (chat_message_id remains NULL — it is back-filled on send).
+func TestUploadFile_AttachesToChatSession(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ defer func() { testHandler.Storage = origStorage }()
+
+ agentID := createHandlerTestAgent(t, "ChatUploadAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", "chat-upload.png")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Minimal PNG signature so content-type sniffs as image/png.
+ part.Write([]byte("\x89PNG\r\n\x1a\nrest-of-bytes"))
+ if err := writer.WriteField("chat_session_id", sessionID); err != nil {
+ t.Fatal(err)
+ }
+ writer.Close()
+
+ req := httptest.NewRequest("POST", "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+
+ w := httptest.NewRecorder()
+ testHandler.UploadFile(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UploadFile with chat_session_id: 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 response: %v; body: %s", err, w.Body.String())
+ }
+ if resp.ChatSessionID == nil || *resp.ChatSessionID != sessionID {
+ t.Fatalf("chat_session_id in response: want %s, got %v", sessionID, resp.ChatSessionID)
+ }
+ if resp.ChatMessageID != nil {
+ t.Fatalf("chat_message_id should be NULL before send, got %v", resp.ChatMessageID)
+ }
+ if resp.IssueID != nil || resp.CommentID != nil {
+ t.Fatalf("issue_id/comment_id should be NULL for chat-only upload: %+v", resp)
+ }
+ if resp.URL == "" {
+ t.Fatal("expected non-empty url")
+ }
+
+ // Verify the DB row directly.
+ var dbSession, dbMessage *string
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT chat_session_id::text, chat_message_id::text FROM attachment WHERE id = $1`,
+ resp.ID,
+ ).Scan(&dbSession, &dbMessage); err != nil {
+ t.Fatalf("query attachment row: %v", err)
+ }
+ if dbSession == nil || *dbSession != sessionID {
+ t.Fatalf("DB chat_session_id mismatch: want %s, got %v", sessionID, dbSession)
+ }
+ if dbMessage != nil {
+ t.Fatalf("DB chat_message_id should be NULL, got %v", dbMessage)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, resp.ID)
+ })
+}
+
+// TestUploadFile_RejectsForeignChatSession verifies a chat_session in another
+// workspace (or owned by another user) is rejected with 403/404, preventing
+// cross-tenant attachment binding.
+func TestUploadFile_RejectsForeignChatSession(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ defer func() { testHandler.Storage = origStorage }()
+
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, _ := writer.CreateFormFile("file", "evil.txt")
+ part.Write([]byte("payload"))
+ // Random non-existent UUID.
+ writer.WriteField("chat_session_id", "00000000-0000-0000-0000-0000deadbeef")
+ writer.Close()
+
+ req := httptest.NewRequest("POST", "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+
+ w := httptest.NewRecorder()
+ testHandler.UploadFile(w, req)
+ if w.Code != http.StatusNotFound && w.Code != http.StatusForbidden && w.Code != http.StatusBadRequest {
+ t.Fatalf("UploadFile with unknown chat_session_id: expected 4xx, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/migrations/083_attachment_chat_columns.down.sql b/server/migrations/083_attachment_chat_columns.down.sql
new file mode 100644
index 0000000000..5e086b4ef5
--- /dev/null
+++ b/server/migrations/083_attachment_chat_columns.down.sql
@@ -0,0 +1,5 @@
+DROP INDEX IF EXISTS idx_attachment_chat_message;
+DROP INDEX IF EXISTS idx_attachment_chat_session;
+ALTER TABLE attachment
+ DROP COLUMN chat_message_id,
+ DROP COLUMN chat_session_id;
diff --git a/server/migrations/083_attachment_chat_columns.up.sql b/server/migrations/083_attachment_chat_columns.up.sql
new file mode 100644
index 0000000000..f53b6f97e2
--- /dev/null
+++ b/server/migrations/083_attachment_chat_columns.up.sql
@@ -0,0 +1,11 @@
+ALTER TABLE attachment
+ ADD COLUMN chat_session_id UUID REFERENCES chat_session(id) ON DELETE CASCADE,
+ ADD COLUMN chat_message_id UUID REFERENCES chat_message(id) ON DELETE CASCADE;
+
+CREATE INDEX idx_attachment_chat_session
+ ON attachment(chat_session_id)
+ WHERE chat_session_id IS NOT NULL;
+
+CREATE INDEX idx_attachment_chat_message
+ ON attachment(chat_message_id)
+ WHERE chat_message_id IS NOT NULL;
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index 75b522231f..5a85fae679 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -12,22 +12,29 @@ import (
)
const createAttachment = `-- name: CreateAttachment :one
-INSERT INTO attachment (id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
-VALUES ($1, $2, $9, $10, $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
+INSERT INTO attachment (
+ id, workspace_id, issue_id, comment_id, chat_session_id,
+ uploader_type, uploader_id, filename, url, content_type, size_bytes
+)
+VALUES (
+ $1, $2, $9, $10, $11,
+ $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
`
type CreateAttachmentParams struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- UploaderType string `json:"uploader_type"`
- UploaderID pgtype.UUID `json:"uploader_id"`
- Filename string `json:"filename"`
- Url string `json:"url"`
- ContentType string `json:"content_type"`
- SizeBytes int64 `json:"size_bytes"`
- IssueID pgtype.UUID `json:"issue_id"`
- CommentID pgtype.UUID `json:"comment_id"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
+ Filename string `json:"filename"`
+ Url string `json:"url"`
+ ContentType string `json:"content_type"`
+ SizeBytes int64 `json:"size_bytes"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
@@ -42,6 +49,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
arg.SizeBytes,
arg.IssueID,
arg.CommentID,
+ arg.ChatSessionID,
)
var i Attachment
err := row.Scan(
@@ -56,6 +64,8 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
&i.ContentType,
&i.SizeBytes,
&i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
)
return i, err
}
@@ -75,7 +85,7 @@ func (q *Queries) DeleteAttachment(ctx context.Context, arg DeleteAttachmentPara
}
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 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 FROM attachment
WHERE id = $1 AND workspace_id = $2
`
@@ -99,10 +109,31 @@ func (q *Queries) GetAttachment(ctx context.Context, arg GetAttachmentParams) (A
&i.ContentType,
&i.SizeBytes,
&i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
)
return i, err
}
+const linkAttachmentsToChatMessage = `-- name: LinkAttachmentsToChatMessage :exec
+UPDATE attachment
+SET chat_message_id = $1
+WHERE chat_session_id = $2
+ AND chat_message_id IS NULL
+ AND id = ANY($3::uuid[])
+`
+
+type LinkAttachmentsToChatMessageParams struct {
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Column3 []pgtype.UUID `json:"column_3"`
+}
+
+func (q *Queries) LinkAttachmentsToChatMessage(ctx context.Context, arg LinkAttachmentsToChatMessageParams) error {
+ _, err := q.db.Exec(ctx, linkAttachmentsToChatMessage, arg.ChatMessageID, arg.ChatSessionID, arg.Column3)
+ return err
+}
+
const linkAttachmentsToComment = `-- name: LinkAttachmentsToComment :exec
UPDATE attachment
SET comment_id = $1
@@ -192,8 +223,98 @@ func (q *Queries) ListAttachmentURLsByIssueOrComments(ctx context.Context, issue
return items, nil
}
+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
+WHERE chat_message_id = $1 AND workspace_id = $2
+ORDER BY created_at ASC
+`
+
+type ListAttachmentsByChatMessageParams struct {
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListAttachmentsByChatMessage(ctx context.Context, arg ListAttachmentsByChatMessageParams) ([]Attachment, error) {
+ rows, err := q.db.Query(ctx, listAttachmentsByChatMessage, arg.ChatMessageID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Attachment{}
+ for rows.Next() {
+ var i Attachment
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.CommentID,
+ &i.UploaderType,
+ &i.UploaderID,
+ &i.Filename,
+ &i.Url,
+ &i.ContentType,
+ &i.SizeBytes,
+ &i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+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
+WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
+ORDER BY created_at ASC
+`
+
+type ListAttachmentsByChatMessageIDsParams struct {
+ Column1 []pgtype.UUID `json:"column_1"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListAttachmentsByChatMessageIDs(ctx context.Context, arg ListAttachmentsByChatMessageIDsParams) ([]Attachment, error) {
+ rows, err := q.db.Query(ctx, listAttachmentsByChatMessageIDs, arg.Column1, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Attachment{}
+ for rows.Next() {
+ var i Attachment
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.CommentID,
+ &i.UploaderType,
+ &i.UploaderID,
+ &i.Filename,
+ &i.Url,
+ &i.ContentType,
+ &i.SizeBytes,
+ &i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
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 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 FROM attachment
WHERE comment_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -224,6 +345,8 @@ func (q *Queries) ListAttachmentsByComment(ctx context.Context, arg ListAttachme
&i.ContentType,
&i.SizeBytes,
&i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
); err != nil {
return nil, err
}
@@ -236,7 +359,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 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 FROM attachment
WHERE comment_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -267,6 +390,8 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
&i.ContentType,
&i.SizeBytes,
&i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
); err != nil {
return nil, err
}
@@ -279,7 +404,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 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 FROM attachment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -310,6 +435,8 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment
&i.ContentType,
&i.SizeBytes,
&i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index ca2ecd4206..4bb1dca4e2 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -97,17 +97,19 @@ type AgentTaskQueue struct {
}
type Attachment struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- CommentID pgtype.UUID `json:"comment_id"`
- UploaderType string `json:"uploader_type"`
- UploaderID pgtype.UUID `json:"uploader_id"`
- Filename string `json:"filename"`
- Url string `json:"url"`
- ContentType string `json:"content_type"`
- SizeBytes int64 `json:"size_bytes"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
+ Filename string `json:"filename"`
+ Url string `json:"url"`
+ ContentType string `json:"content_type"`
+ SizeBytes int64 `json:"size_bytes"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
}
type Autopilot struct {
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index ac9b18eaa7..bfac7ee21d 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -1,6 +1,12 @@
-- name: CreateAttachment :one
-INSERT INTO attachment (id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
-VALUES ($1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), $3, $4, $5, $6, $7, $8)
+INSERT INTO attachment (
+ id, workspace_id, issue_id, comment_id, chat_session_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),
+ $3, $4, $5, $6, $7, $8
+)
RETURNING *;
-- name: ListAttachmentsByIssue :many
@@ -38,6 +44,23 @@ WHERE issue_id = $2
AND comment_id IS NULL
AND id = ANY($3::uuid[]);
+-- name: LinkAttachmentsToChatMessage :exec
+UPDATE attachment
+SET chat_message_id = $1
+WHERE chat_session_id = $2
+ AND chat_message_id IS NULL
+ AND id = ANY($3::uuid[]);
+
+-- name: ListAttachmentsByChatMessage :many
+SELECT * FROM attachment
+WHERE chat_message_id = $1 AND workspace_id = $2
+ORDER BY created_at ASC;
+
+-- name: ListAttachmentsByChatMessageIDs :many
+SELECT * FROM attachment
+WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
+ORDER BY created_at ASC;
+
-- name: LinkAttachmentsToIssue :exec
UPDATE attachment
SET issue_id = $1