Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(issues): build the file inventory from the issue attachment list (MUL-8830) (#10298)
Bohan Jiangd31322dd87da
diff --git a/packages/core/api/attachment-inventory.test.ts b/packages/core/api/attachment-inventory.test.tsnew file mode 100644index 0000000000..2c978bd986--- /dev/null+++ b/packages/core/api/attachment-inventory.test.ts@@ -0,0 +1,99 @@+// @vitest-environment node+import { afterEach, expect, it, vi } from "vitest";+import { ApiClient } from "./client";+import {+ collectDeliverableFiles,+ deliverableInventoryFromAttachments,+ mergeDeliverableSources,+} from "../attachments/deliverables";++afterEach(() => vi.unstubAllGlobals());++const attachment = {+ id: "attachment-1", workspace_id: "workspace-1", issue_id: "issue-1",+ comment_id: "comment-1", uploader_type: "member", uploader_id: "member-1",+ filename: "historical.png", content_type: "image/png", size_bytes: 123,+ url: "/uploads/historical.png", download_url: "/uploads/historical.png",+ markdown_url: "/api/attachments/attachment-1/download",+ created_at: "2026-11-09T00:00:00Z", comment_author_type: "agent",+ comment_author_id: "agent-1", comment_created_at: "2026-11-09T00:00:00Z",+};++async function listAttachments(body: unknown) {+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), {+ status: 200, headers: { "Content-Type": "application/json" },+ }));+ vi.stubGlobal("fetch", fetchMock);+ const result = await new ApiClient("https://api.example.test").listAttachments("issue-1");+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/issue-1/attachments");+ return result;+}++it("keeps rendering when optional comment origin metadata has the wrong JSON type", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([+ attachment,+ { ...attachment, id: "attachment-2", comment_id: "comment-2", comment_created_at: 123 },+ ]), { status: 200, headers: { "Content-Type": "application/json" } })));+ const attachments = await new ApiClient("https://api.example.test").listAttachments("issue-1");+ expect(() => mergeDeliverableSources(deliverableInventoryFromAttachments(attachments), [])).not.toThrow();+ expect(attachments).toHaveLength(2);+ expect(attachments[1]?.comment_created_at).toBeUndefined();+ expect(deliverableInventoryFromAttachments(attachments).map((entry) => entry.id)).toEqual(["comment-1"]);+});++it("preserves historical origins, same-name versions, and unknown server fields", async () => {+ const attachments = await listAttachments([+ { ...attachment, future_field: "preserved" },+ { ...attachment, id: "attachment-2", comment_id: "comment-2", comment_author_type: "future-author",+ created_at: "2026-11-10T00:00:00Z", comment_created_at: "2026-11-10T00:00:00Z" },+ ]);+ expect(attachments[0]).toMatchObject({ ...attachment, future_field: "preserved" });+ const inventory = mergeDeliverableSources(deliverableInventoryFromAttachments(attachments), []);+ expect(inventory.map((entry) => [entry.id, entry.actor_type, entry.actor_id])).toEqual([+ ["comment-1", "agent", "agent-1"],+ ["comment-2", "future-author", "agent-1"],+ ]);+ expect(collectDeliverableFiles(inventory)[0]?.versions.map((file) => file.id)).toEqual([+ "attachment-1", "attachment-2",+ ]);+});++it.each([+ ["comment_author_type", 123],+ ["comment_author_type", null],+ ["comment_author_id", { id: "agent-1" }],+ ["comment_author_id", null],+ ["comment_created_at", null],+ ["comment_created_at", "not-a-date"],+ ["comment_created_at", ""],+])("drops invalid optional %s (%j) without discarding the file or its siblings", async (field, value) => {+ const attachments = await listAttachments([+ attachment,+ { ...attachment, id: "attachment-2", comment_id: "comment-2", [field]: value },+ ]);+ expect(attachments.map((file) => file.id)).toEqual(["attachment-1", "attachment-2"]);+ expect(attachments[1]).toMatchObject({ filename: "historical.png", download_url: attachment.download_url });+ expect(attachments[1]?.[field as keyof typeof attachment]).toBeUndefined();+ expect(mergeDeliverableSources(deliverableInventoryFromAttachments(attachments), []).map((entry) => entry.id))+ .toEqual(["comment-1"]);+});++it("accepts attachments without the additive comment origin fields", async () => {+ const legacy = { ...attachment };+ Reflect.deleteProperty(legacy, "comment_author_type");+ Reflect.deleteProperty(legacy, "comment_author_id");+ Reflect.deleteProperty(legacy, "comment_created_at");+ const attachments = await listAttachments([legacy, { ...legacy, id: "description", comment_id: null }]);+ expect(attachments.map((file) => file.id)).toEqual(["attachment-1", "description"]);+ expect(deliverableInventoryFromAttachments(attachments)).toEqual([]);+});++it.each([+ null,+ { attachments: [] },+ [null],+ [{ ...attachment, filename: 123 }],+ [{ ...attachment, content_type: 123 }],+])("falls back to an empty list for an invalid response shape: %j", async (body) => {+ expect(await listAttachments(body)).toEqual([]);+});diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex d729eb3f9f..b4bce2c549 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -3473,15 +3473,6 @@ describe("ApiClient complete issue deliverables", () => {expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/issue/comments?thread=historical%2Fcomment");});- it("loads lightweight origins independently of timeline and tolerates malformed responses", async () => {- const fetchMock = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify([{ id:"old",type:"comment",actor_type:"agent",actor_id:"a",created_at:"2026-01-01T00:00:00Z",attachments:[] }]),{status:200}))- .mockResolvedValueOnce(new Response(JSON.stringify({invalid:true}),{status:200}));- vi.stubGlobal("fetch",fetchMock);- const client = new ApiClient("https://api.example.test");- expect((await client.listIssueDeliverables("issue"))[0]?.id).toBe("old");- expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/issue/deliverables");- expect(await client.listIssueDeliverables("issue")).toEqual([]);- });});describe("ApiClient issue environments", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7f6abf40dc..c829f793dd 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -287,6 +287,7 @@ import {AgentTaskListSchema,AgentTaskPageSchema,AgentActivityBucketListSchema,+ AttachmentListSchema,AttachmentResponseSchema,CancelTaskResponseSchema,ChatDraftRestoresResponseSchema,@@ -1754,13 +1755,6 @@ export class ApiClient {}// Comments- async listIssueDeliverables(issueId: string): Promise<TimelineEntry[]> {- const raw = await this.fetch<unknown>(`/api/issues/${issueId}/deliverables`);- return parseWithFallback(raw, TimelineEntriesSchema, [], {- endpoint: "GET /api/issues/:id/deliverables",- });- }-async listComments(issueId: string, options?: { thread: string }): Promise<Comment[]> {const query = options ? `?${new URLSearchParams({ thread: options.thread })}` : "";const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments${query}`);@@ -4217,7 +4211,10 @@ export class ApiClient {}async listAttachments(issueId: string): Promise<Attachment[]> {- return this.fetch(`/api/issues/${issueId}/attachments`);+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/attachments`);+ return parseWithFallback<Attachment[]>(raw, AttachmentListSchema, [], {+ endpoint: "GET /api/issues/:id/attachments",+ });}// Fetches a fresh attachment metadata record. The server re-signsdiff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex b043ea930a..701b8c6ef4 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1162,6 +1162,24 @@ export const AttachmentResponseSchema = z.object({...AttachmentImageFields,}).loose();+// The issue file inventory uses comment origins for grouping and sorting.+// Malformed optional origins must not discard otherwise usable attachments.+export const AttachmentListSchema = z.array(AttachmentResponseSchema.extend({+ workspace_id: z.string(),+ issue_id: z.string().nullable().default(null),+ comment_id: z.string().nullable().default(null),+ chat_session_id: z.string().nullable().default(null),+ chat_message_id: z.string().nullable().default(null),+ uploader_type: z.string(),+ uploader_id: z.string(),+ content_type: z.string(),+ size_bytes: z.number(),+ created_at: z.string(),+ comment_author_type: z.string().optional().catch(undefined),+ comment_author_id: z.string().optional().catch(undefined),+ comment_created_at: z.iso.datetime({ offset: true }).optional().catch(undefined),+})).default([]);+export const EMPTY_ATTACHMENT: Attachment = {id: "",workspace_id: "",diff --git a/packages/core/attachments/deliverables.test.ts b/packages/core/attachments/deliverables.test.tsindex f62584d358..8c0c95d29b 100644--- a/packages/core/attachments/deliverables.test.ts+++ b/packages/core/attachments/deliverables.test.ts@@ -6,6 +6,7 @@ import {deliverableKey,findDeliverableByName,findDeliverableVersion,+ deliverableInventoryFromAttachments,mergeDeliverableSources,} from "./deliverables";@@ -172,3 +173,20 @@ describe("findDeliverableByName", () => {expect(findDeliverableByName(files, " ")).toBeUndefined();});});++describe("deliverableInventoryFromAttachments", () => {+ it("groups comment files under their comment's origin and skips files without one", () => {+ const origin = { comment_author_type: "agent", comment_author_id: "agent-1", comment_created_at: "2026-01-01T00:00:00Z" };+ const inventory = deliverableInventoryFromAttachments([+ attachment({ id: "a", comment_id: "c1", filename: "chart.png", ...origin }),+ attachment({ id: "b", comment_id: "c1", filename: "chart.png", ...origin }),+ attachment({ id: "description", comment_id: null, filename: "spec.png" }),+ attachment({ id: "old-server", comment_id: "c2", filename: "log.txt" }),+ ]);+ expect(inventory).toEqual([expect.objectContaining({+ type: "comment", id: "c1", actor_type: "agent", actor_id: "agent-1", created_at: origin.comment_created_at,+ })]);+ expect(inventory[0]?.attachments?.map((a) => a.id)).toEqual(["a", "b"]);+ expect(collectDeliverableFiles(inventory)[0]?.versions).toHaveLength(2);+ });+});diff --git a/packages/core/attachments/deliverables.ts b/packages/core/attachments/deliverables.tsindex 7d47614b94..608a71d3c9 100644--- a/packages/core/attachments/deliverables.ts+++ b/packages/core/attachments/deliverables.ts@@ -126,6 +126,33 @@ export function findDeliverableVersion(return undefined;}+/**+ * The issue's complete file inventory as comment entries, built from the+ * issue attachment list, which carries every comment file with its comment's+ * author and time. A file without that origin (description, older server)+ * contributes nothing; the loaded timeline still supplies its own comments.+ */+export function deliverableInventoryFromAttachments(+ attachments: readonly Attachment[],+): TimelineEntry[] {+ const comments = new Map<string, { entry: TimelineEntry; files: Attachment[] }>();+ for (const attachment of attachments) {+ const { comment_id: id, comment_author_type: actorType, comment_author_id: actorId, comment_created_at: createdAt } = attachment;+ if (!id || !actorType || !actorId || !createdAt) continue;+ let comment = comments.get(id);+ if (!comment) {+ const files: Attachment[] = [];+ comment = {+ entry: { type: "comment", id, actor_type: actorType, actor_id: actorId, created_at: createdAt, attachments: files },+ files,+ };+ comments.set(id, comment);+ }+ comment.files.push(attachment);+ }+ return [...comments.values()].map(({ entry }) => entry);+}+/** Live comments override inventory metadata, including tombstones. */export function mergeDeliverableSources(inventory: readonly TimelineEntry[],diff --git a/packages/core/attachments/index.ts b/packages/core/attachments/index.tsindex 80ae55681c..c00f2e56f9 100644--- a/packages/core/attachments/index.ts+++ b/packages/core/attachments/index.ts@@ -1,5 +1,6 @@export {collectDeliverableFiles,+ deliverableInventoryFromAttachments,deliverableKey,findDeliverableVersion,type DeliverableFile,diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex cadb399688..af0e28ae7b 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -207,8 +207,6 @@ export const issueKeys = {* click time. */attachments: (issueId: string) =>[...issueKeys.attachmentsAll(), issueId] as const,- deliverables: (issueId: string) =>- [...issueKeys.attachments(issueId), "deliverables"] as const,/** Prefix for reconnects and task events without an issue scope. */tasksAll: () => ["issues", "tasks"] as const,/** Per-issue task list (issue-detail Execution log section). */@@ -742,10 +740,3 @@ export function issueAttachmentsOptions(issueId: string) {});}-/** Complete attachment inventory; independent of the bounded discussion feed. */-export function issueDeliverablesOptions(issueId: string) {- return queryOptions({- queryKey: issueKeys.deliverables(issueId),- queryFn: () => api.listIssueDeliverables(issueId),- });-}diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex c30afc990a..4a7d4ef744 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -922,12 +922,23 @@ describe("deliverable inventory freshness", () => {const qc = new QueryClient({ defaultOptions: {queries:{retry:false,staleTime:Infinity}} });const ws=createMockWs();renderHook(()=>useRealtimeSync(ws,createStores()),{wrapper:createWrapper(qc)});- qc.setQueryData(issueKeys.deliverables("affected"),[]);- qc.setQueryData(issueKeys.deliverables("unrelated"),[]);+ qc.setQueryData(issueKeys.attachments("affected"),[]);+ qc.setQueryData(issueKeys.attachments("unrelated"),[]);const listener=vi.mocked(ws.on).mock.calls.find(([name])=>name===event)?.[1];act(()=>listener?.({comment:{issue_id:"affected"},issue_id:"affected"} as never));- expect(qc.getQueryState(issueKeys.deliverables("affected"))?.isInvalidated).toBe(true);- expect(qc.getQueryState(issueKeys.deliverables("unrelated"))?.isInvalidated).toBe(false);+ expect(qc.getQueryState(issueKeys.attachments("affected"))?.isInvalidated).toBe(true);+ expect(qc.getQueryState(issueKeys.attachments("unrelated"))?.isInvalidated).toBe(false);+ qc.clear();+ });++ it.each(["activity:created", "reaction:added", "reaction:removed", "comment:resolved"])("leaves the file inventory alone on %s", (event) => {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, createStores()), { wrapper: createWrapper(qc) });+ qc.setQueryData(issueKeys.attachments("affected"), []);+ const listener = vi.mocked(ws.on).mock.calls.find(([name]) => name === event)?.[1];+ act(() => listener?.({ comment: { issue_id: "affected" }, issue_id: "affected" } as never));+ expect(qc.getQueryState(issueKeys.attachments("affected"))?.isInvalidated).toBe(false);qc.clear();});});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex da98d78719..4a1e5012dd 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1283,17 +1283,23 @@ export function useRealtimeSync(// through `refetchOnMount`. Active observers stay fresh via the// granular setQueryData handlers in `useIssueTimeline`.const invalidateTimeline = (issueId: string) => {- qc.invalidateQueries({ queryKey: issueKeys.deliverables(issueId) });qc.invalidateQueries({queryKey: issueKeys.timeline(issueId),refetchType: "none",});};+ // The issue attachment list is the complete file inventory, labelled with+ // each file's comment. Only comment writes bind, rebind or delete comment+ // files; activity, reactions and resolutions leave it as it is.+ const invalidateCommentFiles = (issueId: string) => {+ qc.invalidateQueries({ queryKey: issueKeys.attachments(issueId) });+ };const unsubCommentCreated = ws.on("comment:created", (p) => {const { comment, issue_revision: issueRevision } = p as CommentCreatedPayload;if (!comment?.issue_id) return;invalidateTimeline(comment.issue_id);+ invalidateCommentFiles(comment.issue_id);// A new comment bumps the parent issue's updated_at server-side// (MUL-5009), so any open board/list sorted by "Updated date" has// drifted. Refetch just those keys to re-sort the commented card into@@ -1318,6 +1324,7 @@ export function useRealtimeSync(const { comment, issue_revision } = p as CommentUpdatedPayload;if (!comment?.issue_id) return;invalidateTimeline(comment.issue_id);+ invalidateCommentFiles(comment.issue_id);const wsId = getCurrentWsId();if (wsId) {invalidateLastActivitySortedIssueLists(qc, wsId);@@ -1333,6 +1340,7 @@ export function useRealtimeSync(const { issue_id, issue_revision } = p as CommentDeletedPayload;if (!issue_id) return;invalidateTimeline(issue_id);+ invalidateCommentFiles(issue_id);const wsId = getCurrentWsId();if (wsId) {invalidateLastActivitySortedIssueLists(qc, wsId);diff --git a/packages/core/types/attachment.ts b/packages/core/types/attachment.tsindex f7757600da..0be4c44ac6 100644--- a/packages/core/types/attachment.ts+++ b/packages/core/types/attachment.ts@@ -3,6 +3,14 @@ export interface Attachment {workspace_id: string;issue_id: string | null;comment_id: string | null;+ /**+ * Origin of a comment file, from the issue attachment list only: the+ * comment's author and time. Absent on description files, on other+ * endpoints, and from servers older than this field.+ */+ comment_author_type?: string;+ comment_author_id?: string;+ comment_created_at?: string;chat_session_id: string | null;chat_message_id: string | null;uploader_type: string;diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex a06bf092c5..0eb808e511 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -345,7 +345,6 @@ const mockApiObj = vi.hoisted(() => ({addIssueReaction: vi.fn(),removeIssueReaction: vi.fn(),listAttachments: vi.fn().mockResolvedValue([]),- listIssueDeliverables: vi.fn().mockResolvedValue([]),addCommentReaction: vi.fn(),removeCommentReaction: vi.fn(),listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),@@ -805,7 +804,7 @@ describe("IssueDetail (shared)", () => {mockApiObj.listPins.mockResolvedValue([]);// /timeline returns the entries flat in chronological order (oldest first).mockApiObj.listTimeline.mockResolvedValue(mockTimeline);- mockApiObj.listIssueDeliverables.mockResolvedValue([]);+ mockApiObj.listAttachments.mockResolvedValue([]);mockApiObj.listComments.mockResolvedValue([]);mockApiObj.listIssueReactions.mockResolvedValue([]);mockApiObj.listIssueSubscribers.mockResolvedValue([]);@@ -889,10 +888,11 @@ describe("IssueDetail (shared)", () => {const image: Attachment = { id: "historical-chart", workspace_id: "ws-1", issue_id: "issue-1", comment_id: "older-comment",chat_session_id: null, chat_message_id: null, uploader_type: "agent", uploader_id: "agent-1",filename: "historical-chart.png", content_type: "image/png", size_bytes: 100,- url: "/chart.png", download_url: "/chart.png", markdown_url: "/chart.png", created_at: "2026-01-01T00:00:00Z" };+ url: "/chart.png", download_url: "/chart.png", markdown_url: "/chart.png", created_at: "2026-01-01T00:00:00Z",+ comment_author_type: "agent", comment_author_id: "agent-1", comment_created_at: "2026-01-01T00:00:00Z" };mockApiObj.listTimeline.mockResolvedValue([]);- mockApiObj.listIssueDeliverables.mockResolvedValue([{ id: "older-comment", type: "comment", actor_type: "agent",- actor_id: "agent-1", created_at: image.created_at, attachments: [image] }]);+ // The issue attachment list alone supplies the historical file and its origin.+ mockApiObj.listAttachments.mockResolvedValue([image]);const root = {id: "older-root", issue_id: "issue-1", author_type: "agent", author_id: "agent-1",content: "Historical image discussion", type: "comment", parent_id: null,diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 94621dee06..95954a0e42 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -132,7 +132,7 @@ import {useDeliverableDetails,type DeliverableOrigin,} from "./deliverables/deliverable-details";-import { collectDeliverableFiles, mergeDeliverableSources } from "@multica/core/attachments/deliverables";+import { collectDeliverableFiles, deliverableInventoryFromAttachments, mergeDeliverableSources } from "@multica/core/attachments/deliverables";import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";import {OpenDeliverableOnLoad,@@ -152,7 +152,7 @@ import {import { useRecentContextStore } from "@multica/core/chat";import { useRegisterCommandBarContext } from "../../search/register-context";import { useModalStore } from "@multica/core/modals";-import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions, issueDeliverablesOptions } from "@multica/core/issues/queries";+import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";import { projectDetailOptions } from "@multica/core/projects/queries";import { ProjectIcon } from "../../projects/components/project-icon";import { issueLabelsOptions } from "@multica/core/labels";@@ -2363,11 +2363,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// editor's click-time fresh-sign download: NodeViews match// `src`/`href` against this list to resolve an attachment id before// calling `/api/attachments/{id}`.+ // The same list is the issue's complete file inventory: it labels each+ // comment file with its comment, independent of the bounded timeline.const { data: issueAttachments } = useQuery(issueAttachmentsOptions(id));- const { data: deliverableInventory = EMPTY_REPLIES, error: deliverablesError } = useQuery(issueDeliverablesOptions(id));- useEffect(() => {- if (deliverablesError) toast.error(deliverablesError.message);- }, [deliverablesError]);+ const deliverableInventory = useMemo(+ () => deliverableInventoryFromAttachments(issueAttachments ?? []),+ [issueAttachments],+ );// Sub-issue queriesconst parentIssueId = issue?.parent_issue_id;diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 5f07e034ca..d1912fff2e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2173,7 +2173,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/reactions", h.AddIssueReaction)r.Delete("/reactions", h.RemoveIssueReaction)r.Get("/attachments", h.ListAttachments)- r.Get("/deliverables", h.ListIssueDeliverables)r.Get("/children", h.ListChildIssues)r.Get("/duplicates", h.ListIssueDuplicates)r.Get("/labels", h.ListLabelsForIssue)diff --git a/server/internal/handler/attachment_origin_test.go b/server/internal/handler/attachment_origin_test.gonew file mode 100644index 0000000000..c044e3447e--- /dev/null+++ b/server/internal/handler/attachment_origin_test.go@@ -0,0 +1,55 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// The issue attachment list labels each comment file with its comment's+// author and time, so the file inventory needs no second request and no+// comment bodies. Description files and files of a deleted comment carry none.+func TestListAttachmentsCarriesCommentOrigins(t *testing.T) {+ issueID := dbfx.Issue(t, "attachment origins")+ agentID := dbfx.Agent(t, "attachment origin agent", testRuntimeID)+ // Uploaded by the member, posted in the agent's comment: the label is the+ // comment's author, not the uploader.+ commentID := dbfx.Comment(t, issueID, "delivered chart", testutil.Cols{"author_type": "agent", "author_id": agentID})+ goneID := dbfx.Comment(t, issueID, "deleted", testutil.Cols{"deleted_at": testutil.Raw("now()")})+ attachment := func(name string, cols testutil.Cols) string {+ base := testutil.Cols{+ "workspace_id": testWorkspaceID, "issue_id": issueID,+ "uploader_type": "member", "uploader_id": testUserID,+ "filename": name, "url": "https://files.example.test/" + name,+ "content_type": "image/png", "size_bytes": 1,+ }+ for k, v := range cols {+ base[k] = v+ }+ return dbfx.Insert(t, "attachment", base)+ }+ inComment := attachment("chart.png", testutil.Cols{"comment_id": commentID})+ inDescription := attachment("description.png", nil)+ inDeleted := attachment("gone.png", testutil.Cols{"comment_id": goneID})++ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+issueID+"/attachments", nil), testUserID), "id", issueID)+ var got []AttachmentResponse+ testutil.Call(t, testHandler.ListAttachments, req).Want(http.StatusOK).JSON(&got)+ byID := map[string]AttachmentResponse{}+ for _, a := range got {+ byID[a.ID] = a+ }+ if len(byID) != 3 {+ t.Fatalf("attachments = %+v, want 3", got)+ }+ c := byID[inComment]+ if c.CommentAuthorType == nil || *c.CommentAuthorType != "agent" || c.CommentAuthorID == nil || *c.CommentAuthorID != agentID || c.CommentCreatedAt == nil || *c.CommentCreatedAt == "" {+ t.Fatalf("comment file origin = %+v, want agent %s", c, agentID)+ }+ for _, id := range []string{inDescription, inDeleted} {+ if a := byID[id]; a.CommentAuthorType != nil || a.CommentAuthorID != nil || a.CommentCreatedAt != nil {+ t.Fatalf("file %s must carry no comment origin: %+v", a.Filename, a)+ }+ }+}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 33c1042e54..e5eac8ccf3 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -94,9 +94,16 @@ type AttachmentResponse struct {// previous site-relative `/api/attachments/<id>/download` link only// resolved when the document origin proxied /api to the API host.MarkdownURL string `json:"markdown_url"`- ContentType string `json:"content_type"`- SizeBytes int64 `json:"size_bytes"`- CreatedAt string `json:"created_at"`+ // Comment origin, set only by the issue attachment list: who posted the+ // comment this file belongs to, and when. Absent for description files and+ // for a comment that is gone. Lets the issue's file inventory label every+ // historical file without loading the comments that carry it.+ CommentAuthorType *string `json:"comment_author_type,omitempty"`+ CommentAuthorID *string `json:"comment_author_id,omitempty"`+ CommentCreatedAt *string `json:"comment_created_at,omitempty"`+ ContentType string `json:"content_type"`+ SizeBytes int64 `json:"size_bytes"`+ CreatedAt string `json:"created_at"`// Displayed image dimensions, absent for non-images and older uploads.Width *int32 `json:"width,omitempty"`Height *int32 `json:"height,omitempty"`@@ -667,14 +674,52 @@ func (h *Handler) ListAttachments(w http.ResponseWriter, r *http.Request) {return}+ origins, err := h.attachmentCommentOrigins(r.Context(), issue, attachments)+ if err != nil {+ slog.Error("failed to load attachment comment origins", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to list attachments")+ return+ }+mode := attachmentURLModeFromRequest(r)resp := make([]AttachmentResponse, len(attachments))for i, a := range attachments {resp[i] = h.attachmentToResponse(a, mode)+ if origin, ok := origins[a.CommentID]; ok {+ authorType, authorID, createdAt := origin.AuthorType, uuidToString(origin.AuthorID), timestampToString(origin.CreatedAt)+ resp[i].CommentAuthorType, resp[i].CommentAuthorID, resp[i].CommentCreatedAt = &authorType, &authorID, &createdAt+ }}writeJSON(w, http.StatusOK, resp)}+// attachmentCommentOrigins loads, in one query, the author and time of each+// live comment the attachments belong to, scoped to the issue and workspace.+func (h *Handler) attachmentCommentOrigins(ctx context.Context, issue db.Issue, attachments []db.Attachment) (map[pgtype.UUID]db.ListCommentOriginsForIssueRow, error) {+ ids := make([]pgtype.UUID, 0)+ seen := make(map[pgtype.UUID]bool)+ for _, a := range attachments {+ if a.CommentID.Valid && !seen[a.CommentID] {+ seen[a.CommentID] = true+ ids = append(ids, a.CommentID)+ }+ }+ origins := make(map[pgtype.UUID]db.ListCommentOriginsForIssueRow, len(ids))+ if len(ids) == 0 {+ return origins, nil+ }+ rows, err := h.Queries.ListCommentOriginsForIssue(ctx, db.ListCommentOriginsForIssueParams{+ Ids: ids, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ })+ if err != nil {+ return nil, err+ }+ for _, row := range rows {+ origins[row.ID] = row+ }+ return origins, nil+}+// GetAttachmentByID — GET /api/attachments/{id}func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/handler/issue_deliverables.go b/server/internal/handler/issue_deliverables.godeleted file mode 100644index 2a00810f2c..0000000000--- a/server/internal/handler/issue_deliverables.go+++ /dev/null@@ -1,68 +0,0 @@-package handler--import (- "log/slog"- "net/http"-- "github.com/go-chi/chi/v5"- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--// ListIssueDeliverables returns every live comment's attachments independently-// of the bounded timeline, without transferring historical comment bodies.-func (h *Handler) ListIssueDeliverables(w http.ResponseWriter, r *http.Request) {- issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))- if !ok {- return- }- attachments, err := h.Queries.ListAttachmentsByIssue(r.Context(), db.ListAttachmentsByIssueParams{IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})- if err != nil {- slog.Error("failed to list deliverables", "error", err)- writeError(w, http.StatusInternalServerError, "failed to list deliverables")- return- }- ids := make([]pgtype.UUID, 0)- seen := make(map[pgtype.UUID]bool)- byComment := make(map[string][]AttachmentResponse)- mode := attachmentURLModeFromRequest(r)- for _, a := range attachments {- if !a.CommentID.Valid {- continue- }- if !seen[a.CommentID] {- ids = append(ids, a.CommentID)- seen[a.CommentID] = true- }- key := uuidToString(a.CommentID)- byComment[key] = append(byComment[key], h.attachmentToResponse(a, mode))- }- if len(ids) == 0 {- writeJSON(w, http.StatusOK, []TimelineEntry{})- return- }- comments, err := h.Queries.ListCommentsByIDsForIssue(r.Context(), db.ListCommentsByIDsForIssueParams{Ids: ids, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})- if err != nil {- slog.Error("failed to load deliverable origins", "error", err)- writeError(w, http.StatusInternalServerError, "failed to list deliverables")- return- }- writeJSON(w, http.StatusOK, issueDeliverableEntries(comments, byComment))-}--func issueDeliverableEntries(comments []db.Comment, attachments map[string][]AttachmentResponse) []TimelineEntry {- entries := make([]TimelineEntry, 0, len(comments))- for _, c := range comments {- id := uuidToString(c.ID)- if c.DeletedAt.Valid || len(attachments[id]) == 0 {- continue- }- entry := TimelineEntry{Type: "comment", ID: id, ActorType: c.AuthorType, ActorID: uuidToString(c.AuthorID), CreatedAt: c.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"), Attachments: attachments[id]}- if c.ParentID.Valid {- parent := uuidToString(c.ParentID)- entry.ParentID = &parent- }- entries = append(entries, entry)- }- return entries-}diff --git a/server/internal/handler/issue_deliverables_test.go b/server/internal/handler/issue_deliverables_test.godeleted file mode 100644index bf7a5e78b8..0000000000--- a/server/internal/handler/issue_deliverables_test.go+++ /dev/null@@ -1,29 +0,0 @@-package handler--import (- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "testing"- "time"-)--func TestIssueDeliverableEntries(t *testing.T) {- id := parseUUID("00000000-0000-0000-0000-000000000001")- gone := parseUUID("00000000-0000-0000-0000-000000000002")- parent := parseUUID("00000000-0000-0000-0000-000000000003")- comments := []db.Comment{- {ID: id, AuthorType: "agent", AuthorID: parent, ParentID: parent, Content: "large historical body", CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}},- {ID: gone, DeletedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}},- }- files := map[string][]AttachmentResponse{uuidToString(id): {{ID: "old-chart", ContentType: "image/png"}, {ID: "same-name-new-version", ContentType: "image/png"}}, uuidToString(gone): {{ID: "deleted-image"}}, "orphan": {{ID: "orphan-image"}}}- out := issueDeliverableEntries(comments, files)- if len(out) != 1 || len(out[0].Attachments) != 2 {- t.Fatalf("must retain all live uploads, omit deleted/orphan sources: %#v", out)- }- if out[0].Content != nil || out[0].ActorID != uuidToString(parent) || out[0].ParentID == nil {- t.Fatal("return lightweight origin metadata without comment bodies")- }- if len(issueDeliverableEntries(nil, files)) != 0 {- t.Fatal("an unbound attachment is not an output")- }-}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex d1142b5b11..1196a957f8 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -886,6 +886,54 @@ func (q *Queries) ListCommentAncestorPath(ctx context.Context, arg ListCommentAnreturn items, nil}+const listCommentOriginsForIssue = `-- name: ListCommentOriginsForIssue :many+SELECT id, author_type, author_id, created_at FROM comment+WHERE id = ANY($1::uuid[])+ AND issue_id = $2+ AND workspace_id = $3+ AND deleted_at IS NULL+`++type ListCommentOriginsForIssueParams struct {+ Ids []pgtype.UUID `json:"ids"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListCommentOriginsForIssueRow struct {+ ID pgtype.UUID `json:"id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++// Author and time of the live comments in @ids, without their bodies: the+// issue attachment list labels each file with the comment that delivered it.+func (q *Queries) ListCommentOriginsForIssue(ctx context.Context, arg ListCommentOriginsForIssueParams) ([]ListCommentOriginsForIssueRow, error) {+ rows, err := q.db.Query(ctx, listCommentOriginsForIssue, arg.Ids, arg.IssueID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListCommentOriginsForIssueRow{}+ for rows.Next() {+ var i ListCommentOriginsForIssueRow+ if err := rows.Scan(+ &i.ID,+ &i.AuthorType,+ &i.AuthorID,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listCommentThreadHistory = `-- name: ListCommentThreadHistory :manyWITH RECURSIVE thread_history AS (SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at, root.deleted_at, root.suppressed_agent_idsdiff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex c014e57ecf..021a78e3f5 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -40,6 +40,15 @@ WHERE id = ANY(@ids::uuid[])AND workspace_id = @workspace_idORDER BY created_at ASC, id ASC;+-- name: ListCommentOriginsForIssue :many+-- Author and time of the live comments in @ids, without their bodies: the+-- issue attachment list labels each file with the comment that delivered it.+SELECT id, author_type, author_id, created_at FROM comment+WHERE id = ANY(@ids::uuid[])+ AND issue_id = @issue_id+ AND workspace_id = @workspace_id+ AND deleted_at IS NULL;+-- name: ListChildCommentsForParents :many-- Fetch one descendant level for a bounded set of parent comments. Each parent-- maps back to its thread root in the Go breadth-first walk, avoiding one query