⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: give internal agents and MCP the full set of document tools (#813)
Crofffdd9b696ea8a
diff --git a/apps/api/src/mcp/__tests__/integration/attachments.test.ts b/apps/api/src/mcp/__tests__/integration/attachments.test.tsindex 5a47942e..132e93c5 100644--- a/apps/api/src/mcp/__tests__/integration/attachments.test.ts+++ b/apps/api/src/mcp/__tests__/integration/attachments.test.ts@@ -100,6 +100,67 @@ describe('MCP attachments', () => {expect(stored.data!.description).toBe(`Before\n\n`);});+ it('adds a file to a document and opens it as an image', async () => {+ const { asOwner, client } = await setup();+ const documentId = (+ await asOwner.projects({ projectKey: 'MKT' }).documents.post({ title: 'Spec' })+ ).data!.id;++ const added = await callTool(client, {+ name: 'add_document_asset',+ arguments: {+ projectKey: 'MKT',+ documentId,+ filename: 'shot.png',+ contentBase64: IMAGE_BLOCK.data,+ contentType: 'image/png',+ },+ });+ expect(added.isError).toBe(false);+ const asset = added.structuredContent?.data as { id: string; url: string; embedUrl: string };+ // A document asset needs a session, so its url stays a path and is not made public.+ expect(asset.url).toStartWith('/projects/');+ expect(asset.embedUrl).toBe(`/protected-media${asset.url}`);++ const viewed = await callTool(client, {+ name: 'view_document_asset',+ arguments: { projectKey: 'MKT', documentId, publicId: asset.id },+ });+ expect(viewed.content[1]).toEqual(IMAGE_BLOCK);+ expect(named(viewed).images).toEqual([+ { id: asset.id, filename: 'shot.png', contentType: 'image/png' },+ ]);+ });++ it('copies a chat file into a document', async () => {+ const { asOwner, client } = await setup();+ const documentId = (+ await asOwner.projects({ projectKey: 'MKT' }).documents.post({ title: 'Spec' })+ ).data!.id;+ const chatFile = await callTool(client, {+ name: 'upload_chat_attachment',+ arguments: {+ projectKey: 'MKT',+ filename: 'note.txt',+ contentBase64: Buffer.from('hello').toString('base64'),+ },+ });++ const copied = await callTool(client, {+ name: 'add_document_asset_from_chat',+ arguments: {+ projectKey: 'MKT',+ documentId,+ chatAttachmentId: (chatFile.structuredContent?.data as { id: string }).id,+ },+ });+ expect(copied.structuredContent).toMatchObject({+ ok: true,+ status: 201,+ data: { filename: 'note.txt', sizeBytes: 5 },+ });+ });+it('shows the images of an issue and lists the other files with their urls', async () => {const { client, issueId, imageId, noteId } = await setup();const listed = await client.listTools();diff --git a/apps/api/src/mcp/__tests__/integration/structured-results.test.ts b/apps/api/src/mcp/__tests__/integration/structured-results.test.tsindex 0e585807..67085bb3 100644--- a/apps/api/src/mcp/__tests__/integration/structured-results.test.ts+++ b/apps/api/src/mcp/__tests__/integration/structured-results.test.ts@@ -41,6 +41,7 @@ describe('MCP structured results through the SDK client', () => {const withoutSchema = listed.tools.filter((tool) => tool.outputSchema === undefined);expect(withoutSchema.map((tool) => tool.name).sort()).toEqual(['view_attachment',+ 'view_document_asset','view_initiative_images','view_issue_images',]);diff --git a/apps/api/src/mcp/generate.ts b/apps/api/src/mcp/generate.tsindex f4723d24..2d682390 100644--- a/apps/api/src/mcp/generate.ts+++ b/apps/api/src/mcp/generate.ts@@ -70,7 +70,7 @@ export function mcpTool(return { 'x-mcp': { tool, annotations } };}-// Marks a route answering with ViewAttachmentsResponse as an MCP tool whose images+// Marks a route answering in the shape of ViewAttachmentsResponse as an MCP tool whose images// reach the model as image content, not as base64 text.export function mcpImageTool(tool: string): { 'x-mcp': { tool: string; images: true } } {return { 'x-mcp': { tool, images: true } };diff --git a/apps/api/src/mcp/instructions.ts b/apps/api/src/mcp/instructions.tsindex 5137a687..190cb9b1 100644--- a/apps/api/src/mcp/instructions.ts+++ b/apps/api/src/mcp/instructions.ts@@ -94,6 +94,9 @@ attachment, call view_attachment with its url: it shows an image and returns theof a PDF or a text file and the rows of a spreadsheet. A file can be replaced behindthe same url, so view it again rather than reusing what you saw earlier.+A file of a document is different: its url needs a session. Open it with+view_document_asset.+## MentionsA comment, an issue description, a document or a comment on a document tags someonediff --git a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.tsindex 03edadc3..04c965da 100644--- a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts@@ -325,6 +325,145 @@ describe('internal agent route tools', () => {]);});+ it('links a document to an issue and an initiative, and reads each link from both sides', async () => {+ const { asOwner } = await setup();+ const project = asOwner.projects({ projectKey: 'MKT' });+ const view = await project.get();+ const issueId = (+ await project.issues.post({ columnId: view.data!.columns[0]!.id, title: 'Task' })+ ).data!.id;+ const initiativeId = (await project.initiatives.post({ title: 'Launch' })).data!.id;+ const documentId = (await project.documents.post({ title: 'Spec' })).data!.id;+ const tools = await toolsFor(asOwner, [+ 'link_document_issue',+ 'unlink_document_issue',+ 'list_document_issues',+ 'list_issue_documents',+ 'link_document_initiative',+ 'unlink_document_initiative',+ 'list_initiative_documents',+ 'list_document_initiatives',+ ]);++ expect(await run(tools, 'link_document_issue', { documentId, issueId })).toMatchObject({+ issueId,+ });+ expect(await run(tools, 'list_document_issues', { documentId })).toMatchObject([{ issueId }]);+ expect(await run(tools, 'list_issue_documents', { issueId })).toMatchObject([{ documentId }]);+ await run(tools, 'unlink_document_issue', { documentId, issueId });+ expect(await run(tools, 'list_issue_documents', { issueId })).toEqual([]);++ await run(tools, 'link_document_initiative', { documentId, initiativeId });+ expect(await run(tools, 'list_initiative_documents', { initiativeId })).toMatchObject([+ { documentId },+ ]);+ expect(await run(tools, 'list_document_initiatives', { documentId })).toMatchObject([+ { initiativeId },+ ]);+ await run(tools, 'unlink_document_initiative', { documentId, initiativeId });+ expect(await run(tools, 'list_document_initiatives', { documentId })).toEqual([]);+ });++ it('reads a comment thread of a document, replies in it and resolves it', async () => {+ const { asOwner } = await setup();+ const documents = asOwner.projects({ projectKey: 'MKT' }).documents;+ const page = (+ await documents.post({+ title: 'Plan',+ content: 'Hello world',+ contentJson: {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello world' }] }],+ },+ })+ ).data!;+ const documentId = page.id;+ const root = await documents({ documentId }).comments.post({+ body: 'Is this right?',+ quote: 'Hello',+ from: 1,+ to: 6,+ version: page.version,+ });+ const commentId = root.data!.id;+ const tools = await toolsFor(asOwner, [+ 'list_document_comments',+ 'add_document_comment',+ 'update_document_comment',+ ]);++ expect(await run(tools, 'list_document_comments', { documentId })).toMatchObject([+ { id: commentId, parentId: null, quote: 'Hello', body: 'Is this right?' },+ ]);+ await run(tools, 'add_document_comment', { documentId, parentId: commentId, body: 'Yes' });+ await run(tools, 'update_document_comment', { documentId, commentId, resolved: true });++ const thread = (await run(tools, 'list_document_comments', { documentId })) as {+ parentId: string | null;+ body: string;+ resolvedAt: string | null;+ }[];+ expect(thread.map((comment) => comment.body)).toEqual(['Is this right?', 'Yes']);+ expect(thread[1]!.parentId).toBe(commentId);+ expect(thread[0]!.resolvedAt).not.toBeNull();+ });++ it('adds a file to a document, opens it and deletes it', async () => {+ const { asOwner } = await setup();+ const tools = await toolsFor(asOwner, [+ 'create_document',+ 'add_document_asset',+ 'list_document_assets',+ 'view_document_asset',+ 'delete_document_asset',+ ]);+ // Deleting a file takes owning its page, so the agent makes the page.+ const { id: documentId } = (await run(tools, 'create_document', { title: 'Spec' })) as {+ id: number;+ };++ const added = (await run(tools, 'add_document_asset', {+ documentId,+ filename: 'note.txt',+ contentBase64: Buffer.from('hello').toString('base64'),+ contentType: 'text/plain',+ })) as { id: string; embedUrl: string };+ expect(added.embedUrl).toStartWith('/protected-media/projects/');+ expect(await run(tools, 'list_document_assets', { documentId })).toMatchObject([+ { id: added.id },+ ]);+ expect(+ await run(tools, 'view_document_asset', { documentId, publicId: added.id }),+ ).toMatchObject({ images: [], others: [{ id: added.id, text: 'hello' }] });++ await run(tools, 'delete_document_asset', { documentId, publicId: added.id });+ expect(await run(tools, 'list_document_assets', { documentId })).toEqual([]);+ });++ it('copies a file attached in the chat into a document', async () => {+ const { asOwner } = await setup();+ const tools = await toolsFor(asOwner, [+ 'create_document',+ 'add_document_asset_from_chat',+ 'view_document_asset',+ ]);+ const { id: documentId } = (await run(tools, 'create_document', { title: 'Spec' })) as {+ id: number;+ };+ const { id: chatAttachmentId } = (await run(tools, 'upload_chat_attachment', {+ filename: 'note.txt',+ contentBase64: Buffer.from('hello').toString('base64'),+ })) as { id: string };++ const copied = (await run(tools, 'add_document_asset_from_chat', {+ documentId,+ chatAttachmentId,+ })) as { id: string };+ expect(+ await run(tools, 'view_document_asset', { documentId, publicId: copied.id }),+ ).toMatchObject({ images: [], others: [{ filename: 'note.txt', text: 'hello' }] });+ });+it("provisions a legacy agent's key once, even when two runs start together", async () => {const { asOwner, teamId } = await setup();const created = await createAgent(asOwner, 'MKT', {diff --git a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.tsindex 87fc667d..9b8ea93b 100644--- a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts@@ -85,6 +85,32 @@ describe('normalizeToolKeys', () => {'update_document','delete_document','add_document_comment',+ 'list_document_comments',+ 'update_document_comment',+ 'list_document_issues',+ 'list_issue_documents',+ 'link_document_issue',+ 'unlink_document_issue',+ 'list_initiative_documents',+ 'list_document_initiatives',+ 'link_document_initiative',+ 'unlink_document_initiative',+ 'list_document_assets',+ 'view_document_asset',+ 'add_document_asset',+ 'add_document_asset_from_chat',+ 'delete_document_asset',+ 'list_document_revisions',+ 'get_document_revision',+ 'restore_document_revision',+ 'archive_document',+ 'restore_document',+ 'duplicate_document',+ 'lock_document',+ 'unlock_document',+ 'export_document',+ 'set_document_access',+ 'transfer_document_ownership',];expect(normalizeToolKeys(keys)).toEqual(keys);});diff --git a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.tsindex 35084b4f..25081ad2 100644--- a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts+++ b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts@@ -240,7 +240,7 @@ export const AGENT_ACTIONS: ToolMeta[] = [key: 'delete_document',group: 'documents',label: 'Delete documents',- description: 'Permanently delete shared project documents.',+ description: 'Permanently delete documents this agent owns.',always: false,},// A new thread is anchored to text the agent cannot select, so its copy only replies.@@ -256,6 +256,188 @@ export const AGENT_ACTIONS: ToolMeta[] = ['Reply in a comment thread of a document. `parentId` is the id of the first comment of the thread.',},},+ {+ key: 'list_document_comments',+ group: 'documents',+ label: 'Read document comments',+ description: 'Read the comment threads of documents.',+ always: false,+ },+ {+ key: 'update_document_comment',+ group: 'documents',+ label: 'Edit document comments',+ description: "Edit this agent's own comments, and resolve or reopen threads.",+ always: false,+ },+ {+ key: 'list_document_issues',+ group: 'documents',+ label: "List a document's issues",+ description: 'See which issues are linked to a document.',+ always: false,+ },+ {+ key: 'list_issue_documents',+ group: 'documents',+ label: "List an issue's documents",+ description: 'See which documents are linked to an issue.',+ always: false,+ },+ {+ key: 'link_document_issue',+ group: 'documents',+ label: 'Link documents to issues',+ description: 'Link a document to an issue in the project.',+ always: false,+ },+ {+ key: 'unlink_document_issue',+ group: 'documents',+ label: 'Unlink documents from issues',+ description: 'Remove the link between a document and an issue.',+ always: false,+ },+ {+ key: 'list_initiative_documents',+ group: 'documents',+ label: "List an initiative's documents",+ description: 'See which documents are linked to an initiative.',+ always: false,+ },+ {+ key: 'list_document_initiatives',+ group: 'documents',+ label: "List a document's initiatives",+ description: 'See which initiatives are linked to a document.',+ always: false,+ },+ {+ key: 'link_document_initiative',+ group: 'documents',+ label: 'Link documents to initiatives',+ description: 'Link a document to an initiative in the project.',+ always: false,+ },+ {+ key: 'unlink_document_initiative',+ group: 'documents',+ label: 'Unlink documents from initiatives',+ description: 'Remove the link between a document and an initiative.',+ always: false,+ },+ {+ key: 'list_document_assets',+ group: 'documents',+ label: 'List document files',+ description: 'See the images and files of a document.',+ always: false,+ },+ {+ key: 'view_document_asset',+ group: 'documents',+ label: 'Open document files',+ description: 'Open an image or file of a document.',+ always: false,+ },+ {+ key: 'add_document_asset',+ group: 'documents',+ label: 'Add document files',+ description: 'Add an image or file to a document from a URL or inline content.',+ always: false,+ },+ {+ key: 'add_document_asset_from_chat',+ group: 'documents',+ label: 'Add chat files to documents',+ description: 'Copy a file attached in the chat into a document.',+ always: false,+ },+ {+ key: 'delete_document_asset',+ group: 'documents',+ label: 'Delete document files',+ description: 'Permanently delete images and files from documents this agent owns.',+ always: false,+ },+ {+ key: 'list_document_revisions',+ group: 'documents',+ label: 'List document versions',+ description: 'See the saved versions of a document.',+ always: false,+ },+ {+ key: 'get_document_revision',+ group: 'documents',+ label: 'Read document versions',+ description: 'Read the content of a saved version.',+ always: false,+ },+ {+ key: 'restore_document_revision',+ group: 'documents',+ label: 'Restore document versions',+ description: 'Bring back a saved version as the current one.',+ always: false,+ },+ {+ key: 'archive_document',+ group: 'documents',+ label: 'Archive documents',+ description: 'Archive a document this agent owns, with its nested pages.',+ always: false,+ },+ {+ key: 'restore_document',+ group: 'documents',+ label: 'Restore documents',+ description: 'Bring back an archived document this agent owns, with its nested pages.',+ always: false,+ },+ {+ key: 'duplicate_document',+ group: 'documents',+ label: 'Duplicate documents',+ description: 'Copy a document into a new one owned by this agent.',+ always: false,+ },+ {+ key: 'lock_document',+ group: 'documents',+ label: 'Lock documents',+ description: 'Lock a document this agent owns against changes.',+ always: false,+ },+ {+ key: 'unlock_document',+ group: 'documents',+ label: 'Unlock documents',+ description: 'Unlock a document this agent owns so it can be changed again.',+ always: false,+ },+ {+ key: 'export_document',+ group: 'documents',+ label: 'Export documents',+ description: 'Get a document as a Markdown file.',+ always: false,+ },+ {+ key: 'set_document_access',+ group: 'documents',+ label: 'Change document access',+ description: 'Make a document this agent owns private, or share it with the project.',+ always: false,+ },+ {+ key: 'transfer_document_ownership',+ group: 'documents',+ label: 'Transfer document ownership',+ description: 'Hand a document this agent owns over to another project member.',+ always: false,+ },{key: 'list_note_boards',group: 'notes',diff --git a/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.tsindex a63eb5cc..0229452a 100644--- a/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts+++ b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, afterEach, beforeEach } from 'bun:test';+import { getStorageSettings } from '@repo/db';import { api, authedApi, createProject } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';@@ -380,6 +381,41 @@ describe('attachments', () => {expect(res.status).toBe(400);});+ it('stops reading a url at the size limit, whatever the server declares', async () => {+ const { asOwner, issueId } = await setupIssue();+ const { maxAttachmentMb } = await getStorageSettings();+ const chunk = new Uint8Array(1024 * 1024);+ let chunksLeft = maxAttachmentMb * 4;+ const { promise: cancelled, resolve: onCancel } = Promise.withResolvers<void>();+ const server = Bun.serve({+ hostname: '127.0.0.1',+ port: 0,+ fetch: () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ if (chunksLeft-- > 0) controller.enqueue(chunk);+ else controller.close();+ },+ cancel: onCancel,+ }),+ ),+ });+ // Outside production and test, the SSRF guard lets a local http url through.+ const nodeEnv = process.env.NODE_ENV;+ process.env.NODE_ENV = 'development';+ try {+ const res = await asOwner+ .issues({ issueId })+ .attachments.import.post({ filename: 'big.bin', url: server.url.href });+ expect(res.status).toBe(413);+ await cancelled;+ } finally {+ process.env.NODE_ENV = nodeEnv;+ await server.stop(true);+ }+ });+it('rejects a url that points at a private address (SSRF)', async () => {const { asOwner, issueId } = await setupIssue();const res = await asOwnerdiff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.tsindex 17066e71..c3d63024 100644--- a/apps/api/src/modules/attachments/index.ts+++ b/apps/api/src/modules/attachments/index.ts@@ -4,16 +4,14 @@ import { authContext } from '#shared/auth-context';import { assertMcpAllowed, assertProjectReachable, entityGuard } from '#shared/guards';import { assertPermission } from '#shared/access';import { HttpError } from '#shared/lib';-import { pinnedFetch } from '#shared/net';import { mcpImageTool, mcpTool } from '#mcp/generate';import { accessErrors, commonErrors, errors } from '#shared/responses';import { getIssueProjectId } from '#modules/issues/service';-import { readAttachmentContent } from '#modules/chat-attachments/service';+import { viewFile } from '#modules/chat-attachments/service';import {getInitiativeAttachment,getInitiativeAttachmentProjectId,} from '#modules/initiatives/attachments';-import { getStorageSettings, MB } from '@repo/db';import {AttachmentResponse,AttachmentListResponse,@@ -39,6 +37,7 @@ import {attachmentObjectKey,attachmentObjectResponse,deleteAttachmentObject,+ readImportedFile,safeAttachmentFilename,storeAttachmentObject,viewAttachments,@@ -163,52 +162,12 @@ export const attachmentRoutes = new Elysia({},)- // Adds an attachment from a URL or inline base64, for callers that cannot send a- // multipart file (internal agents). Exactly one of url / contentBase64 is given.- // A URL is fetched server-side, so it is SSRF-guarded (https only in prod, no- // private/local hosts, no redirects) and size-capped like a direct upload..post('/issues/:issueId/attachments/import',async ({ params, body, set, projectId }) => {const issueId = params.issueId;const filename = safeAttachmentFilename(body.filename);- const { url, contentBase64 } = body;- if ((url == null) === (contentBase64 == null)) {- throw new HttpError(400, 'Provide exactly one of url or contentBase64');- }- const limits = await getStorageSettings();-- let bytes: Buffer;- let contentType: string;- if (url != null) {- let res: Response;- try {- res = await pinnedFetch(url, { timeoutMs: 15000 });- } catch (err) {- if (err instanceof HttpError) throw err;- throw new HttpError(400, 'Could not fetch the url');- }- if (res.status >= 300 && res.status < 400) {- throw new HttpError(400, 'The url redirects; provide the final url');- }- if (!res.ok) throw new HttpError(400, `Could not fetch the url (status ${res.status})`);- const declared = Number(res.headers.get('content-length') ?? '');- if (declared && declared > limits.maxAttachmentMb * MB) {- throw new HttpError(413, `File exceeds the ${limits.maxAttachmentMb} MB limit`);- }- bytes = Buffer.from(await res.arrayBuffer());- contentType =- body.contentType ||- res.headers.get('content-type')?.split(';')[0]?.trim() ||- 'application/octet-stream';- } else {- bytes = Buffer.from(contentBase64 as string, 'base64');- if (bytes.length === 0)- throw new HttpError(400, 'contentBase64 is empty or not valid base64');- contentType = body.contentType || 'application/octet-stream';- }-- if (bytes.length === 0) throw new HttpError(400, 'The file is empty');+ const { bytes, contentType } = await readImportedFile(body);await assertAttachmentUploadAllowed(projectId, bytes.length, contentType);const key = attachmentObjectKey(projectId, 'attachments', issueId, filename);@@ -316,32 +275,21 @@ export const attachmentRoutes = new Elysia({},)- .get(- '/attachments/view',- async ({ viewed }) => {- const asImage = await viewAttachments([viewed.row], () => viewed.dto);- if (asImage.images.length > 0) return asImage;- return {- images: [],- others: [{ ...viewed.dto, ...(await readAttachmentContent(viewed.row)) }],- };+ .get('/attachments/view', ({ viewed }) => viewFile(viewed.row, viewed.dto), {+ query: viewAttachmentQuery,+ viewableAttachment: true,+ response: { 200: ViewAttachmentsResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'View an attachment',+ description:+ 'Open one attachment of an issue or an initiative, given the url a result carries ' ++ `for it or its id. An image comes back as the image itself (${VIEWABLE_IMAGES}). ` ++ 'Any other file comes back in `others` with its url and, for a PDF or a text file, ' ++ 'its full text; for a spreadsheet or document (.xlsx, .csv, .docx), its column ' ++ 'headers and first rows. A scanned PDF has no text to read.',+ ...mcpImageTool('view_attachment'),},- {- query: viewAttachmentQuery,- viewableAttachment: true,- response: { 200: ViewAttachmentsResponse, ...commonErrors },- detail: {- summary: 'View an attachment',- description:- 'Open one attachment of an issue or an initiative, given the url a result carries ' +- `for it or its id. An image comes back as the image itself (${VIEWABLE_IMAGES}). ` +- 'Any other file comes back in `others` with its url and, for a PDF or a text file, ' +- 'its full text; for a spreadsheet or document (.xlsx, .csv, .docx), its column ' +- 'headers and first rows. A scanned PDF has no text to read.',- ...mcpImageTool('view_attachment'),- },- },- )+ }).get('/issues/:issueId/images',diff --git a/apps/api/src/modules/attachments/storage.ts b/apps/api/src/modules/attachments/storage.tsindex 5c111d00..f8539edf 100644--- a/apps/api/src/modules/attachments/storage.ts+++ b/apps/api/src/modules/attachments/storage.ts@@ -13,6 +13,7 @@ import {import { putObject, getObject, deleteObject } from '@repo/storage';import { HttpError } from '#shared/lib';import { getLimits } from '#shared/limits';+import { pinnedFetch, ResponseTooLargeError } from '#shared/net';// Re-exported so this stays the one place every attachment-owning module (issue,// chat, document, initiative) imports the key/filename helpers from — the@@ -81,6 +82,52 @@ export async function assertAttachmentFileAllowed(}}+// The file of a caller that cannot send a multipart upload. A URL is fetched server-side,+// so it is SSRF-guarded (https only in prod, no private/local hosts, no redirects) and+// size-capped like a direct upload.+export async function readImportedFile(input: {+ url?: string;+ contentBase64?: string;+ contentType?: string;+}): Promise<{ bytes: Buffer; contentType: string }> {+ const { url, contentBase64 } = input;+ if ((url == null) === (contentBase64 == null)) {+ throw new HttpError(400, 'Provide exactly one of url or contentBase64');+ }++ let bytes: Buffer;+ let contentType: string;+ if (url != null) {+ const { maxAttachmentMb } = await getStorageSettings();+ let res: Response;+ try {+ res = await pinnedFetch(url, { timeoutMs: 15000, maxBytes: maxAttachmentMb * MB });+ } catch (err) {+ if (err instanceof HttpError) throw err;+ if (err instanceof ResponseTooLargeError) {+ throw new HttpError(413, `File exceeds the ${maxAttachmentMb} MB limit`);+ }+ throw new HttpError(400, 'Could not fetch the url');+ }+ if (res.status >= 300 && res.status < 400) {+ throw new HttpError(400, 'The url redirects; provide the final url');+ }+ if (!res.ok) throw new HttpError(400, `Could not fetch the url (status ${res.status})`);+ bytes = Buffer.from(await res.arrayBuffer());+ contentType =+ input.contentType ||+ res.headers.get('content-type')?.split(';')[0]?.trim() ||+ 'application/octet-stream';+ } else {+ bytes = Buffer.from(contentBase64 as string, 'base64');+ if (bytes.length === 0) throw new HttpError(400, 'contentBase64 is empty or not valid base64');+ contentType = input.contentType || 'application/octet-stream';+ }++ if (bytes.length === 0) throw new HttpError(400, 'The file is empty');+ return { bytes, contentType };+}+export async function storeAttachmentObject(key: string,bytes: Buffer,diff --git a/apps/api/src/modules/chat-attachments/service.ts b/apps/api/src/modules/chat-attachments/service.tsindex 0c0773e5..050f4f20 100644--- a/apps/api/src/modules/chat-attachments/service.ts+++ b/apps/api/src/modules/chat-attachments/service.ts@@ -7,6 +7,7 @@ import { pdfToMarkdown } from './pdf';import {assertAttachmentStorageCapacity,lockAttachmentStorage,+ viewAttachments,} from '#modules/attachments/storage';// Data access for chat attachments. File bytes live in the S3-compatible object@@ -107,7 +108,7 @@ function isReadableFile(row: StoredFile): boolean {return isTableFilename(row.filename) || isTextLike(row) || isPdf(row);}-// The content of a stored file, chat or issue attachment alike: a table for a+// The content of a stored file, whichever feature owns it: a table for a// spreadsheet or document, the full text for a text file or a PDF, nothing for any// other file (its download url is in the metadata either way). A text is returned// whole: what it costs in context is the user's call, and the chat shows the@@ -128,3 +129,14 @@ export async function readAttachmentContent(row: StoredFile): Promise<Attachmentif (isPdf(row)) return { text: await pdfToMarkdown(bytes) };return { text: bytes.toString('utf8') };}++// One stored file opened for an assistant: an image as the image itself, any other file+// as its DTO plus what readAttachmentContent finds in it.+export async function viewFile<Dto extends object>(+ row: StoredFile & { publicId: string; sizeBytes: number },+ dto: Dto,+) {+ const asImage = await viewAttachments([row], () => dto);+ if (asImage.images.length > 0) return asImage;+ return { images: [], others: [{ ...dto, ...(await readAttachmentContent(row)) }] };+}diff --git a/apps/api/src/modules/documents/__tests__/integration/assets.test.ts b/apps/api/src/modules/documents/__tests__/integration/assets.test.tsindex 7766e564..2b14ae24 100644--- a/apps/api/src/modules/documents/__tests__/integration/assets.test.ts+++ b/apps/api/src/modules/documents/__tests__/integration/assets.test.ts@@ -1,7 +1,8 @@-import { beforeEach, describe, expect, it } from 'bun:test';+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';import { api, authedApi, createProject } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';+import { clearLimits, setLimits } from '#tests/helpers/limits';import { createRole } from '#tests/helpers/roles';type Client = ReturnType<typeof authedApi>;@@ -39,8 +40,28 @@ function upload(client: Client, documentId: number, filename = 'diagram.png', ty});}+function addFromContent(client: Client, documentId: number) {+ return documents(client)({ documentId }).assets.import.post({+ filename: 'note.txt',+ contentBase64: Buffer.from('hello').toString('base64'),+ contentType: 'text/plain',+ });+}++function uploadToChat(client: Client, projectKey = 'MKT') {+ return client.projects({ projectKey })['chat-attachments'].post({+ filename: 'note.txt',+ contentBase64: Buffer.from('hello').toString('base64'),+ });+}++function copyFromChat(client: Client, documentId: number, chatAttachmentId: string) {+ return documents(client)({ documentId }).assets['from-chat'].post({ chatAttachmentId });+}+describe('document assets', () => {beforeEach(resetDb);+ afterEach(clearLimits);it('uploads, lists, securely downloads, and deletes an asset', async () => {const { asOwner, project } = await setupProject();@@ -189,6 +210,196 @@ describe('document assets', () => {expect((await upload(asOwner, page.id)).status).toBe(409);});+ it('adds an asset from inline content, with the address a page shows it by', async () => {+ const { asOwner, project } = await setupProject();+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ const added = await addFromContent(asOwner, page.id);+ expect(added.status).toBe(201);+ const url = `/projects/${project.teamId}.MKT/documents/${page.id}/assets/${added.data!.id}/raw`;+ expect(added.data).toMatchObject({+ filename: 'note.txt',+ contentType: 'text/plain',+ sizeBytes: 5,+ url,+ embedUrl: `/protected-media${url}`,+ });++ const list = await documents(asOwner)({ documentId: page.id }).assets.get();+ expect(list.data!.map((asset) => asset.id)).toEqual([added.data!.id]);++ const embedded = await documents(asOwner)({ documentId: page.id }).patch({+ version: page.version,+ contentJson: {+ type: 'doc',+ content: [{ type: 'image', attrs: { src: added.data!.embedUrl } }],+ },+ });+ expect(embedded.status).toBe(200);+ });++ it('refuses an import without exactly one source, or from a private address', async () => {+ const { asOwner } = await setupProject();+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ const { assets } = documents(asOwner)({ documentId: page.id });++ expect((await assets.import.post({ filename: 'x.txt' })).status).toBe(400);+ expect(+ (+ await assets.import.post({+ filename: 'x.txt',+ url: 'https://example.com/x.txt',+ contentBase64: 'aGk=',+ })+ ).status,+ ).toBe(400);+ expect((await assets.import.post({ filename: 'x.txt', contentBase64: '' })).status).toBe(400);+ expect(+ (await assets.import.post({ filename: 'x.txt', url: 'https://127.0.0.1/x.txt' })).status,+ ).toBe(400);+ expect((await assets.get()).data).toEqual([]);+ });++ it('applies the rules of an upload to an import', async () => {+ const { asOwner } = await setupProject();+ const secret = (await documents(asOwner).post({ title: 'Secret', isPrivate: true })).data!;+ const page = (await documents(asOwner).post({ title: 'Public' })).data!;+ const readerRole = await createRole(asOwner, 'MKT', {+ name: 'Reader',+ permissions: { documents: { read: true } },+ });+ const reader = await addMember(asOwner, readerRole.data!.id);+ const member = await addMember(asOwner);++ expect((await addFromContent(reader.client, page.id)).status).toBe(403);+ expect((await addFromContent(member.client, secret.id)).status).toBe(404);++ await documents(asOwner)({ documentId: page.id }).lock.post({ version: page.version });+ expect((await addFromContent(asOwner, page.id)).status).toBe(409);+ });++ it('refuses an import past the storage limit', async () => {+ const { asOwner } = await setupProject();+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ setLimits({ maxStorageBytes: 1 });++ expect((await addFromContent(asOwner, page.id)).status).toBe(413);+ expect((await documents(asOwner)({ documentId: page.id }).assets.get()).data).toEqual([]);+ });++ it('copies a chat file into a page and leaves it in the chat', async () => {+ const { asOwner } = await setupProject();+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ const chatFile = (await uploadToChat(asOwner)).data!;++ const copied = await copyFromChat(asOwner, page.id, chatFile.id);+ expect(copied.status).toBe(201);+ expect(copied.data).toMatchObject({+ filename: 'note.txt',+ contentType: 'text/plain',+ sizeBytes: 5,+ });+ expect(copied.data!.id).not.toBe(chatFile.id);++ const viewed = await documents(asOwner)({ documentId: page.id })+ .assets({ publicId: copied.data!.id })+ .view.get();+ expect(viewed.data).toMatchObject({ others: [{ text: 'hello' }] });+ expect((await asOwner['chat-attachments']({ publicId: chatFile.id }).get()).status).toBe(200);+ });++ it('refuses a chat file the caller may not copy, or a page it may not change', async () => {+ const { asOwner } = await setupProject();+ await createProject(asOwner, { key: 'OPS', name: 'Operations' });+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ const secret = (await documents(asOwner).post({ title: 'Secret', isPrivate: true })).data!;+ const chatFile = (await uploadToChat(asOwner)).data!;+ const otherProjectFile = (await uploadToChat(asOwner, 'OPS')).data!;++ expect((await copyFromChat(asOwner, page.id, otherProjectFile.id)).status).toBe(404);+ expect((await copyFromChat(asOwner, page.id, crypto.randomUUID())).status).toBe(404);++ const docsOnly = await createRole(asOwner, 'MKT', {+ name: 'Docs editor',+ permissions: { documents: { read: true, edit: true } },+ });+ const editor = await addMember(asOwner, docsOnly.data!.id);+ expect((await copyFromChat(editor.client, page.id, chatFile.id)).status).toBe(403);++ const member = await addMember(asOwner);+ expect((await copyFromChat(member.client, secret.id, chatFile.id)).status).toBe(404);++ await documents(asOwner)({ documentId: page.id }).lock.post({ version: page.version });+ expect((await copyFromChat(asOwner, page.id, chatFile.id)).status).toBe(409);+ expect((await documents(asOwner)({ documentId: page.id }).assets.get()).data).toEqual([]);+ });++ it('opens an image as the image, and a text file with its text', async () => {+ const { asOwner } = await setupProject();+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;+ const assets = documents(asOwner)({ documentId: page.id }).assets;+ const image = (await upload(asOwner, page.id)).data!;+ const note = (await addFromContent(asOwner, page.id)).data!;++ const viewedImage = await assets({ publicId: image.id }).view.get();+ expect(viewedImage.data).toEqual({+ images: [+ {+ id: image.id,+ filename: 'diagram.png',+ contentType: 'image/png',+ data: Buffer.from('asset bytes').toString('base64'),+ },+ ],+ others: [],+ });++ const viewedNote = await assets({ publicId: note.id }).view.get();+ expect(viewedNote.data).toMatchObject({+ images: [],+ others: [+ {+ id: note.id,+ filename: 'note.txt',+ url: note.url,+ embedUrl: note.embedUrl,+ text: 'hello',+ },+ ],+ });+ });++ it('opens an asset only for those who can read its page', async () => {+ const { asOwner } = await setupProject();+ const secret = (await documents(asOwner).post({ title: 'Secret', isPrivate: true })).data!;+ const other = (await documents(asOwner).post({ title: 'Other' })).data!;+ const asset = (await upload(asOwner, secret.id)).data!;+ const member = await addMember(asOwner);+ const noDocs = await createRole(asOwner, 'MKT', {+ name: 'No docs',+ permissions: { work_items: { read: true } },+ });+ const outsider = await addMember(asOwner, noDocs.data!.id);++ expect(+ (+ await documents(outsider.client)({ documentId: other.id })+ .assets({ publicId: asset.id })+ .view.get()+ ).status,+ ).toBe(403);+ expect(+ (+ await documents(member.client)({ documentId: secret.id })+ .assets({ publicId: asset.id })+ .view.get()+ ).status,+ ).toBe(404);+ expect(+ (await documents(asOwner)({ documentId: other.id }).assets({ publicId: asset.id }).view.get())+ .status,+ ).toBe(404);+ });+it('rejects empty uploads and cross-document asset ids', async () => {const { asOwner } = await setupProject();const first = (await documents(asOwner).post({ title: 'First' })).data!;diff --git a/apps/api/src/modules/documents/__tests__/integration/documents.test.ts b/apps/api/src/modules/documents/__tests__/integration/documents.test.tsindex 8a0d1508..025d932a 100644--- a/apps/api/src/modules/documents/__tests__/integration/documents.test.ts+++ b/apps/api/src/modules/documents/__tests__/integration/documents.test.ts@@ -435,6 +435,74 @@ describe('documents', () => {);});+ it('closes the routes of Docs while the section is off', async () => {+ const owner = await setupOwnerProject();+ const project = owner.api.projects({ projectKey: 'MKT' });+ const view = await project.get();+ const issueId = (+ await project.issues.post({ columnId: view.data!.columns[0]!.id, title: 'Task' })+ ).data!.id;+ const initiativeId = (await project.initiatives.post({ title: 'Launch' })).data!.id;+ const page = (await documents(owner.api).post({ title: 'Guide' })).data!;+ const doc = documents(owner.api)({ documentId: page.id });++ await project.settings.patch({ features: { documents: false } });+ const statuses = [+ (await documents(owner.api).get()).status,+ (await documents(owner.api).post({ title: 'New' })).status,+ (await doc.get()).status,+ (await doc.comments.get()).status,+ (await doc.assets.get()).status,+ (await doc.assets.import.post({ filename: 'x.txt', contentBase64: 'aGk=' })).status,+ (await doc.issues.get()).status,+ (await doc.initiatives.get()).status,+ (await doc.initiatives.post({ initiativeId })).status,+ (await documents(owner.api)['for-issue']({ issueId }).get()).status,+ (await documents(owner.api)['for-initiative']({ initiativeId }).get()).status,+ ];+ expect(statuses).toEqual(statuses.map(() => 403));++ await project.settings.patch({ features: { documents: true } });+ expect((await doc.get()).status).toBe(200);+ });++ it('lists the initiatives of a page for whoever reads both', async () => {+ const owner = await setupOwnerProject();+ const strategy = (+ await owner.api.projects({ projectKey: 'MKT' }).initiatives.post({ title: 'Q3 Launch' })+ ).data!;+ const page = (await documents(owner.api).post({ title: 'Release guide' })).data!;+ const secret = (await documents(owner.api).post({ title: 'Notes', isPrivate: true })).data!;+ await documents(owner.api)({ documentId: page.id }).initiatives.post({+ initiativeId: strategy.id,+ });++ const list = await documents(owner.api)({ documentId: page.id }).initiatives.get();+ expect(list.status).toBe(200);+ expect(list.data).toMatchObject([{ initiativeId: strategy.id, title: 'Q3 Launch' }]);++ const readerRole = await createRole(owner.api, 'MKT', {+ name: 'Reader',+ permissions: { documents: { read: true }, initiatives: { read: true } },+ });+ const reader = await addMember(owner.api, readerRole.data!.id);+ expect((await documents(reader.api)({ documentId: page.id }).initiatives.get()).status).toBe(+ 200,+ );+ expect((await documents(reader.api)({ documentId: secret.id }).initiatives.get()).status).toBe(+ 404,+ );++ const docsRole = await createRole(owner.api, 'MKT', {+ name: 'Docs only',+ permissions: { documents: { read: true } },+ });+ const docsOnly = await addMember(owner.api, docsRole.data!.id);+ expect((await documents(docsOnly.api)({ documentId: page.id }).initiatives.get()).status).toBe(+ 403,+ );+ });+it('links visible Docs and initiatives, and hides a private page from a reader', async () => {const owner = await setupOwnerProject();const strategy = (diff --git a/apps/api/src/modules/documents/collaboration-routes.ts b/apps/api/src/modules/documents/collaboration-routes.tsindex 5b61ffe7..f193cbc1 100644--- a/apps/api/src/modules/documents/collaboration-routes.ts+++ b/apps/api/src/modules/documents/collaboration-routes.ts@@ -32,6 +32,7 @@ export const documentCollaborationRoutes = new Elysia({openDocumentSession(project.id, params.documentId, requireUser(user).id, body),{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: collaborationOpenBody,response: { 200: collaborationSessionResponse, ...commonErrors, ...errors(409) },@@ -50,6 +51,7 @@ export const documentCollaborationRoutes = new Elysia({),{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,query: collaborationQuery,response: { 200: collaborationStepsResponse, ...commonErrors, ...errors(409) },@@ -62,6 +64,7 @@ export const documentCollaborationRoutes = new Elysia({saveDocumentSteps(project.id, params.documentId, requireUser(user).id, body),{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: collaborationSaveBody,response: { 200: t.Nullable(DocumentResponse), ...commonErrors, ...errors(409) },@@ -74,9 +77,15 @@ export const documentCollaborationRoutes = new Elysia({listDocumentComments(project.id, params.documentId, requireUser(user).id),{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: t.Array(documentCommentResponse), ...commonErrors },- detail: { summary: 'Read document comment threads' },+ detail: {+ summary: 'Read document comment threads',+ description:+ "List a document's comments, oldest first. A reply has the id of the first comment of its thread in `parentId`. `quote` is the text a thread is about, and `resolvedAt` is set on a resolved thread.",+ ...mcpTool('list_document_comments'),+ },},).post(@@ -87,6 +96,7 @@ export const documentCollaborationRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: documentCommentBody,response: { 201: t.Object({ id: t.String() }), ...commonErrors, ...errors(409) },@@ -110,9 +120,15 @@ export const documentCollaborationRoutes = new Elysia({),{permission: ['documents', 'edit'],+ feature: 'documents',params: documentCommentParams,body: documentCommentUpdateBody,response: { 200: t.Object({ ok: t.Boolean() }), ...commonErrors },- detail: { summary: 'Edit a document comment or resolve a thread' },+ detail: {+ summary: 'Edit a document comment or resolve a thread',+ description:+ 'Change the `body` of your own comment, or set `resolved` on the first comment of a thread to resolve or reopen the thread.',+ ...mcpTool('update_document_comment'),+ },},);diff --git a/apps/api/src/modules/documents/index.ts b/apps/api/src/modules/documents/index.tsindex a9df955a..5e20a587 100644--- a/apps/api/src/modules/documents/index.ts+++ b/apps/api/src/modules/documents/index.ts@@ -5,20 +5,25 @@ import { assertPermission, getProjectAccess, requireUser } from '#shared/access'import { guards } from '#shared/guards';import { noContent } from '#shared/http';import { HttpError } from '#shared/lib';-import { mcpTool } from '#mcp/generate';+import { mcpImageTool, mcpTool } from '#mcp/generate';import { commonErrors, errors } from '#shared/responses';-import { rawAttachmentQuery } from '#modules/attachments/model';+import { importAttachmentBody, rawAttachmentQuery } from '#modules/attachments/model';import {- assertAttachmentUploadAllowed,- attachmentObjectKey,attachmentObjectResponse,deleteAttachmentObject,+ readImportedFile,safeAttachmentFilename,- storeAttachmentObject,+ VIEWABLE_IMAGES,} from '#modules/attachments/storage';+import {+ getChatAttachmentByPublicId,+ readAttachmentBytes,+ viewFile,+} from '#modules/chat-attachments/service';import {createDocumentBody,deleteDocumentQuery,+ documentAssetFromChatBody,documentAssetParams,documentAccessBody,documentOwnershipBody,@@ -28,6 +33,7 @@ import {DocumentAssetListResponse,DocumentAssetResponse,DocumentPreferenceResponse,+ DocumentInitiativeLinkListResponse,DocumentIssueLinkListResponse,DocumentIssueLinkResponse,IssueDocumentLinkListResponse,@@ -48,12 +54,12 @@ import {updateDocumentBody,updateDocumentPreferenceBody,uploadDocumentAssetBody,+ ViewDocumentAssetResponse,} from './model';import {archiveDocument,assertDocumentAssetUploadTarget,createDocument,- createDocumentAsset,deleteDocument,deleteDocumentAsset,duplicateDocument,@@ -69,6 +75,7 @@ import {setDocumentAccess,setDocumentLocked,setDocumentPreference,+ storeDocumentAsset,transferDocumentOwnership,updateDocument,type DocumentAssetRow,@@ -77,6 +84,7 @@ import {import {addDocumentInitiativeLink,addDocumentIssueLink,+ listDocumentInitiativeLinks,listDocumentIssueLinks,listInitiativeDocumentLinks,listIssueDocumentLinks,@@ -89,6 +97,7 @@ function documentAssetDto(documentId: number,asset: DocumentAssetRow,) {+ const url = documentAssetPath(project, documentId, asset.publicId);return {id: asset.publicId,filename: asset.filename,@@ -96,10 +105,16 @@ function documentAssetDto(sizeBytes: asset.sizeBytes,uploadedByUserId: asset.uploadedByUserId,createdAt: asset.createdAt,- url: documentAssetPath(project, documentId, asset.publicId),+ url,+ // The web serves a page's files through its own route.+ embedUrl: `/protected-media${url}`,};}+const OWNER_ONLY = 'Only the page owner can do this, or a project owner on a public page.';+const EMBED_HINT =+ 'It does not appear in the page by itself: add `embedUrl` from the result to the page text, as  for an image or [name](embedUrl) for a file.';+async function isProjectOwner(projectId: number, userId: string): Promise<boolean> {return (await getProjectAccess(projectId, userId))?.role === 'owner';}@@ -120,6 +135,7 @@ export const documentRoutes = new Elysia({}),{permission: ['documents', 'read'],+ feature: 'documents',query: listDocumentsQuery,response: { 200: DocumentSummaryListResponse, ...commonErrors },detail: {@@ -139,6 +155,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: DocumentResponse, ...commonErrors },detail: {@@ -164,6 +181,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: DocumentIssueLinkListResponse, ...commonErrors },detail: {@@ -190,6 +208,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: linkDocumentIssueBody,response: { 201: DocumentIssueLinkResponse, ...commonErrors, ...errors(409) },@@ -217,6 +236,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentIssueParams,response: { 204: t.Void(), ...commonErrors },detail: {@@ -237,6 +257,7 @@ export const documentRoutes = new Elysia({},{permission: ['work_items', 'read'],+ feature: 'documents',params: issueDocumentsParams,response: { 200: IssueDocumentLinkListResponse, ...commonErrors },detail: {@@ -257,7 +278,7 @@ export const documentRoutes = new Elysia({},{permission: ['initiatives', 'read'],- feature: 'initiatives',+ feature: ['initiatives', 'documents'],params: initiativeDocumentsParams,response: { 200: IssueDocumentLinkListResponse, ...commonErrors },detail: {@@ -267,6 +288,27 @@ export const documentRoutes = new Elysia({},},)+ .get(+ '/projects/:projectKey/documents/:documentId/initiatives',+ async ({ project, params, user }) => {+ const current = requireUser(user);+ await assertPermission(project.id, current, 'initiatives', 'read');+ const links = await listDocumentInitiativeLinks(project.id, params.documentId, current.id);+ if (!links) throw new HttpError(404, 'Document not found');+ return links;+ },+ {+ permission: ['documents', 'read'],+ feature: ['initiatives', 'documents'],+ params: documentParams,+ response: { 200: DocumentInitiativeLinkListResponse, ...commonErrors },+ detail: {+ summary: 'List initiatives linked to a document',+ description: 'Return initiatives explicitly linked to one visible Docs page.',+ ...mcpTool('list_document_initiatives'),+ },+ },+ ).post('/projects/:projectKey/documents/:documentId/initiatives',async ({ project, params, body, user, set }) => {@@ -283,7 +325,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],- feature: 'initiatives',+ feature: ['initiatives', 'documents'],params: documentParams,body: linkDocumentInitiativeBody,response: { 201: IssueDocumentLinkResponse, ...commonErrors, ...errors(409) },@@ -311,7 +353,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],- feature: 'initiatives',+ feature: ['initiatives', 'documents'],params: documentInitiativeParams,response: { 204: t.Void(), ...commonErrors },detail: {@@ -330,11 +372,13 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: DocumentAssetListResponse, ...commonErrors },detail: {summary: 'List document assets',- description: 'List files embedded in a visible Docs page.',+ description:+ 'List the files of a visible Docs page. Open one with view_document_asset: `url` needs a session.',...mcpTool('list_document_assets'),},},@@ -348,32 +392,20 @@ export const documentRoutes = new Elysia({}const file = body.file;if (!(file instanceof File) || file.size === 0) throw new HttpError(400, 'File is empty');- const filename = safeAttachmentFilename(file.name);- const contentType = file.type || 'application/octet-stream';- await assertAttachmentUploadAllowed(project.id, file.size, contentType);- const key = attachmentObjectKey(project.id, 'documents', params.documentId, filename);- const bytes = Buffer.from(await file.arrayBuffer());- await storeAttachmentObject(key, bytes, contentType);- try {- const asset = await createDocumentAsset({- projectId: project.id,- documentId: params.documentId,- userId,- s3Key: key,- filename,- contentType,- sizeBytes: bytes.length,- });- if (!asset) throw new HttpError(404, 'Document not found');- set.status = 201;- return documentAssetDto(project, params.documentId, asset);- } catch (error) {- await deleteAttachmentObject(key);- throw error;- }+ const asset = await storeDocumentAsset({+ projectId: project.id,+ documentId: params.documentId,+ userId,+ filename: safeAttachmentFilename(file.name),+ contentType: file.type || 'application/octet-stream',+ bytes: Buffer.from(await file.arrayBuffer()),+ });+ set.status = 201;+ return documentAssetDto(project, params.documentId, asset);},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: uploadDocumentAssetBody,response: { 201: DocumentAssetResponse, ...commonErrors, ...errors(409, 413, 502) },@@ -384,6 +416,99 @@ export const documentRoutes = new Elysia({},},)+ .post(+ '/projects/:projectKey/documents/:documentId/assets/import',+ async ({ project, params, user, body, set }) => {+ const userId = requireUser(user).id;+ if (!(await assertDocumentAssetUploadTarget(project.id, params.documentId, userId))) {+ throw new HttpError(404, 'Document not found');+ }+ const { bytes, contentType } = await readImportedFile(body);+ const asset = await storeDocumentAsset({+ projectId: project.id,+ documentId: params.documentId,+ userId,+ filename: safeAttachmentFilename(body.filename),+ contentType,+ bytes,+ });+ set.status = 201;+ return documentAssetDto(project, params.documentId, asset);+ },+ {+ permission: ['documents', 'edit'],+ feature: 'documents',+ params: documentParams,+ body: importAttachmentBody,+ response: { 201: DocumentAssetResponse, ...commonErrors, ...errors(409, 413, 502) },+ detail: {+ summary: 'Add a document asset from a URL or base64',+ description: `Store a file for an active, unlocked Docs page, from \`url\` or \`contentBase64\`. ${EMBED_HINT}`,+ ...mcpTool('add_document_asset'),+ },+ },+ )+ .post(+ '/projects/:projectKey/documents/:documentId/assets/from-chat',+ async ({ project, params, user, body, set }) => {+ const current = requireUser(user);+ await assertPermission(project.id, current, 'ai_agents', 'read');+ if (!(await assertDocumentAssetUploadTarget(project.id, params.documentId, current.id))) {+ throw new HttpError(404, 'Document not found');+ }+ const source = await getChatAttachmentByPublicId(body.chatAttachmentId);+ if (source?.projectId !== project.id) throw new HttpError(404, 'Attachment not found');+ const asset = await storeDocumentAsset({+ projectId: project.id,+ documentId: params.documentId,+ userId: current.id,+ filename: source.filename,+ contentType: source.contentType,+ bytes: await readAttachmentBytes(source.s3Key),+ });+ set.status = 201;+ return documentAssetDto(project, params.documentId, asset);+ },+ {+ permission: ['documents', 'edit'],+ feature: 'documents',+ params: documentParams,+ body: documentAssetFromChatBody,+ response: { 201: DocumentAssetResponse, ...commonErrors, ...errors(409, 413, 502) },+ detail: {+ summary: 'Copy a chat attachment into a document',+ description: `Copy a file attached in the chat of this project into an active, unlocked Docs page. The id is in the [file: "name" (attachment id: …)] marker, and the chat keeps its file. ${EMBED_HINT}`,+ ...mcpTool('add_document_asset_from_chat'),+ },+ },+ )+ .get(+ '/projects/:projectKey/documents/:documentId/assets/:publicId/view',+ async ({ project, params, user }) => {+ const asset = await getDocumentAsset(+ project.id,+ params.documentId,+ params.publicId,+ requireUser(user).id,+ );+ if (!asset) throw new HttpError(404, 'Asset not found');+ return viewFile(asset, documentAssetDto(project, params.documentId, asset));+ },+ {+ permission: ['documents', 'read'],+ feature: 'documents',+ params: documentAssetParams,+ response: { 200: ViewDocumentAssetResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'View a document asset',+ description:+ `Open one file of a Docs page. An image comes back as the image itself (${VIEWABLE_IMAGES}). ` ++ 'Any other file comes back in `others` and, for a PDF or a text file, carries its full ' ++ 'text; for a spreadsheet or document (.xlsx, .csv, .docx), its column headers and first rows.',+ ...mcpImageTool('view_document_asset'),+ },+ },+ ).get('/projects/:projectKey/documents/:documentId/assets/:publicId/raw',async ({ project, params, query, request, user }) => {@@ -404,6 +529,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentAssetParams,query: rawAttachmentQuery,response: { ...commonErrors },@@ -430,11 +556,13 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'delete'],+ feature: 'documents',params: documentAssetParams,response: { 204: t.Void(), ...commonErrors, ...errors(409) },detail: {summary: 'Delete a document asset',- description: 'Delete one asset from an active, unlocked Docs page.',+ description: `Delete one asset from an active, unlocked Docs page. Irreversible. The page text keeps its reference, so remove that with update_document. ${OWNER_ONLY}`,+ ...mcpTool('delete_document_asset'),},},)@@ -447,6 +575,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: DocumentExportResponse, ...commonErrors },detail: {@@ -469,6 +598,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,response: { 200: DocumentRevisionListResponse, ...commonErrors },detail: {@@ -492,6 +622,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentRevisionParams,response: { 200: DocumentRevisionResponse, ...commonErrors },detail: {@@ -520,6 +651,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'create'],+ feature: 'documents',body: createDocumentBody,response: { 201: DocumentResponse, ...commonErrors },detail: {@@ -544,6 +676,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: updateDocumentBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },@@ -571,6 +704,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: documentAccessBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },@@ -599,6 +733,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: documentOwnershipBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },@@ -627,10 +762,15 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: documentVersionBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },- detail: { summary: 'Lock a document', ...mcpTool('lock_document') },+ detail: {+ summary: 'Lock a document',+ description: `Lock a page against changes. ${OWNER_ONLY}`,+ ...mcpTool('lock_document'),+ },},).post(@@ -650,10 +790,15 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentParams,body: documentVersionBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },- detail: { summary: 'Unlock a document', ...mcpTool('unlock_document') },+ detail: {+ summary: 'Unlock a document',+ description: `Unlock a page so it can be changed again. ${OWNER_ONLY}`,+ ...mcpTool('unlock_document'),+ },},).post(@@ -672,13 +817,13 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'delete'],+ feature: 'documents',params: documentParams,body: documentVersionBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Archive a document tree',- description:- 'Archive a page and all descendants without deleting their content or history.',+ description: `Archive a page and all descendants without deleting their content or history. ${OWNER_ONLY}`,...mcpTool('archive_document'),},},@@ -699,13 +844,13 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'delete'],+ feature: 'documents',params: documentParams,body: documentVersionBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },detail: {summary: 'Restore a document tree',- description:- 'Restore an archived page and its descendants. It returns to the root if its parent remains archived.',+ description: `Restore an archived page and its descendants. It returns to the root if its parent remains archived. ${OWNER_ONLY}`,...mcpTool('restore_document'),},},@@ -727,6 +872,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'create'],+ feature: 'documents',params: documentParams,body: duplicateDocumentBody,response: { 201: DocumentResponse, ...commonErrors, ...errors(409, 413, 502) },@@ -752,6 +898,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'read'],+ feature: 'documents',params: documentParams,body: updateDocumentPreferenceBody,response: { 200: DocumentPreferenceResponse, ...commonErrors },@@ -777,6 +924,7 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'edit'],+ feature: 'documents',params: documentRevisionParams,body: documentVersionBody,response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },@@ -807,13 +955,13 @@ export const documentRoutes = new Elysia({},{permission: ['documents', 'delete'],+ feature: 'documents',params: documentParams,query: deleteDocumentQuery,response: { 204: t.Void(), ...commonErrors, ...errors(409) },detail: {summary: 'Delete a document',- description:- 'Permanently delete an archived document and its history. Its child pages move to the project root.',+ description: `Permanently delete an archived document and its history. Its child pages move to the project root. ${OWNER_ONLY}`,...mcpTool('delete_document'),},},diff --git a/apps/api/src/modules/documents/links.ts b/apps/api/src/modules/documents/links.tsindex 3c1cdb48..36190e5f 100644--- a/apps/api/src/modules/documents/links.ts+++ b/apps/api/src/modules/documents/links.ts@@ -18,6 +18,12 @@ export interface DocumentIssueLinkRow {createdAt: string;}+export interface DocumentInitiativeLinkRow {+ initiativeId: number;+ title: string;+ createdAt: string;+}+// The same shape serves both owners: a Docs page linked to an issue and one// linked to an initiative are rendered by the same list.export interface IssueDocumentLinkRow {@@ -215,6 +221,30 @@ export async function removeDocumentIssueLink(input: {});}+export async function listDocumentInitiativeLinks(+ projectId: number,+ documentId: number,+ userId: string,+): Promise<DocumentInitiativeLinkRow[] | null> {+ if (!(await visibleDocument(projectId, documentId, userId))) return null;+ const rows = await db+ .select({+ initiativeId: initiative.id,+ title: initiative.title,+ createdAt: projectDocumentInitiative.createdAt,+ })+ .from(projectDocumentInitiative)+ .innerJoin(initiative, eq(initiative.id, projectDocumentInitiative.initiativeId))+ .where(+ and(+ eq(projectDocumentInitiative.documentId, documentId),+ eq(initiative.projectId, projectId),+ ),+ )+ .orderBy(asc(initiative.title), asc(initiative.id));+ return rows.map((row) => ({ ...row, createdAt: row.createdAt.toISOString() }));+}+export async function listInitiativeDocumentLinks(projectId: number,initiativeId: number,diff --git a/apps/api/src/modules/documents/model.ts b/apps/api/src/modules/documents/model.tsindex 959be0b9..e0c53aac 100644--- a/apps/api/src/modules/documents/model.ts+++ b/apps/api/src/modules/documents/model.ts@@ -1,4 +1,5 @@import { t } from 'elysia';+import { AttachmentContent, ViewAttachmentsResponse } from '#modules/attachments/model';export const documentParams = t.Object({projectKey: t.String(),@@ -14,7 +15,10 @@ export const documentRevisionParams = t.Object({export const documentAssetParams = t.Object({projectKey: t.String(),documentId: t.Numeric(),- publicId: t.String({ format: 'uuid' }),+ publicId: t.String({+ format: 'uuid',+ description: "The asset's id, from list_document_assets or from its url in the page text.",+ }),});const DocumentSummaryResponse = t.Object({@@ -159,6 +163,14 @@ export const IssueDocumentLinkResponse = t.Object({export const IssueDocumentLinkListResponse = t.Array(IssueDocumentLinkResponse);+export const DocumentInitiativeLinkListResponse = t.Array(+ t.Object({+ initiativeId: t.Number(),+ title: t.String(),+ createdAt: t.String(),+ }),+);+const DocumentRevisionSummaryResponse = t.Object({id: t.Number(),documentId: t.Number(),@@ -196,6 +208,13 @@ export const DocumentExportResponse = t.Object({export const uploadDocumentAssetBody = t.Object({ file: t.File() });+export const documentAssetFromChatBody = t.Object({+ chatAttachmentId: t.String({+ format: 'uuid',+ description: 'The attachment id of the file in the chat.',+ }),+});+export const DocumentAssetResponse = t.Object({id: t.String({ format: 'uuid' }),filename: t.String(),@@ -204,10 +223,16 @@ export const DocumentAssetResponse = t.Object({uploadedByUserId: t.Nullable(t.String()),createdAt: t.String(),url: t.String(),+ embedUrl: t.String({ description: 'The address to use in the page text to show this file.' }),});export const DocumentAssetListResponse = t.Array(DocumentAssetResponse);+export const ViewDocumentAssetResponse = t.Object({+ images: ViewAttachmentsResponse.properties.images,+ others: t.Array(t.Composite([DocumentAssetResponse, AttachmentContent])),+});+export const deleteDocumentQuery = t.Object({version: t.Integer({ minimum: 1 }),});diff --git a/apps/api/src/modules/documents/service.ts b/apps/api/src/modules/documents/service.tsindex da692966..968052d7 100644--- a/apps/api/src/modules/documents/service.ts+++ b/apps/api/src/modules/documents/service.ts@@ -28,10 +28,12 @@ import { documentMentionHandles, fanOutTextMentions } from './mentions';import {assertAttachmentStorageCapacity,assertAttachmentFileAllowed,+ assertAttachmentUploadAllowed,attachmentObjectKey,cloneAttachmentObject,deleteAttachmentObject,lockAttachmentStorage,+ storeAttachmentObject,} from '#modules/attachments/storage';type Executor = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];@@ -340,7 +342,37 @@ export async function assertDocumentAssetUploadTarget(return true;}-export async function createDocumentAsset(input: {+export async function storeDocumentAsset(input: {+ projectId: number;+ documentId: number;+ userId: string;+ filename: string;+ contentType: string;+ bytes: Buffer;+}): Promise<DocumentAssetRow> {+ const { projectId, documentId, userId, filename, contentType, bytes } = input;+ await assertAttachmentUploadAllowed(projectId, bytes.length, contentType);+ const key = attachmentObjectKey(projectId, 'documents', documentId, filename);+ await storeAttachmentObject(key, bytes, contentType);+ try {+ const asset = await createDocumentAsset({+ projectId,+ documentId,+ userId,+ s3Key: key,+ filename,+ contentType,+ sizeBytes: bytes.length,+ });+ if (!asset) throw new HttpError(404, 'Document not found');+ return asset;+ } catch (error) {+ await deleteAttachmentObject(key);+ throw error;+ }+}++async function createDocumentAsset(input: {projectId: number;documentId: number;userId: string;diff --git a/apps/api/src/modules/mentions/index.ts b/apps/api/src/modules/mentions/index.tsindex c273577c..4f393414 100644--- a/apps/api/src/modules/mentions/index.ts+++ b/apps/api/src/modules/mentions/index.ts@@ -40,6 +40,7 @@ export const mentionRoutes = new Elysia({ name: 'mentions', detail: { tags: ['Me}),{permission: ['documents', 'read'],+ feature: 'documents',params: documentMentionParams,query: mentionCandidatesQuery,response: { 200: t.Array(MentionCandidateResponse), ...commonErrors },diff --git a/apps/api/src/shared/guards.ts b/apps/api/src/shared/guards.tsindex 077c848b..216c966f 100644--- a/apps/api/src/shared/guards.ts+++ b/apps/api/src/shared/guards.ts@@ -182,19 +182,19 @@ export const guards = new Elysia({ name: 'guards' }).use(authContext).macro({};},- // The optional section a route belongs to, set beside the permission the route+ // The optional section or sections a route belongs to, set beside the permission the route// asserts. A section its project has turned off closes its routes, so what the// settings page hides cannot be reached through the API either. It reads the project// the route's guard resolved when that guard is set before it in the route options;// otherwise it resolves the project through the membership check itself, so it// belongs on a route that already requires membership.- feature(name: ProjectFeature) {+ feature(name: ProjectFeature | ProjectFeature[]) {return {async resolve(ctx) {const project =(ctx as { project?: ProjectRow }).project ??(await requireProjectAccess((ctx.params as ProjectKeyParams).projectKey, ctx.user));- assertFeatureEnabled(project, name);+ for (const feature of [name].flat()) assertFeatureEnabled(project, feature);},};},diff --git a/apps/api/src/shared/net.ts b/apps/api/src/shared/net.tsindex beac44f7..60793f12 100644--- a/apps/api/src/shared/net.ts+++ b/apps/api/src/shared/net.ts@@ -6,6 +6,8 @@ import {} from '@repo/net';import { HttpError } from './lib';+export { ResponseTooLargeError } from '@repo/net';+function as400<T>(run: () => Promise<T>): Promise<T> {return run().catch((err: unknown) => {if (err instanceof UrlNotAllowedError) throw new HttpError(400, err.message);diff --git a/apps/web/src/features/initiatives/components/detail/InitiativeOverview.tsx b/apps/web/src/features/initiatives/components/detail/InitiativeOverview.tsxindex 9c3017c8..cb80ff72 100644--- a/apps/web/src/features/initiatives/components/detail/InitiativeOverview.tsx+++ b/apps/web/src/features/initiatives/components/detail/InitiativeOverview.tsx@@ -1,6 +1,7 @@'use client';import { useTranslations } from 'next-intl';+import { useProjectFeatures } from '@/hooks/useProjectFeatures';import type { Initiative } from '@/lib/api/endpoints/initiatives';import MarkdownEditor from '@/components/common/editor/MarkdownEditor';import InitiativeAttachments from './InitiativeAttachments';@@ -17,6 +18,7 @@ export default function InitiativeOverview({projectKey: string;}) {const t = useTranslations('initiatives');+ const features = useProjectFeatures();const hasDescription = initiative.description.trim().length > 0;return (@@ -39,7 +41,9 @@ export default function InitiativeOverview({)}</div><aside className="flex flex-col gap-6 @4xl:ms-auto @4xl:w-88 @4xl:shrink-0">- <InitiativeDocuments projectKey={projectKey} initiativeId={initiative.id} />+ {features.documents && (+ <InitiativeDocuments projectKey={projectKey} initiativeId={initiative.id} />+ )}<InitiativeAttachments initiativeId={initiative.id} /></aside></div>diff --git a/docs/dev/access-model.md b/docs/dev/access-model.mdindex 5bf07451..2101832f 100644--- a/docs/dev/access-model.md+++ b/docs/dev/access-model.md@@ -57,7 +57,7 @@ or on the request body is checked in the handler or the service.- `teamRunsProject: true`: an owner or manager of its team.- `memberAdmin`, `memberSelfOrAdmin`: see [Member lists](#member-lists).- `feature: "<section>"` goes beside them and closes the route while the project has that- section off.+ section off. A route that belongs to two sections takes both in an array.- **Team routes:** `teamMember`, `teamManager`, `teamOwner` and `teamPermission` inject`membership`.- **Workspace routes:** `workspaceManager`, `workspaceOwner` and `workspaceScim` inject `standing`.diff --git a/docs/mcp-results.md b/docs/mcp-results.mdindex b9354316..da5ef361 100644--- a/docs/mcp-results.md+++ b/docs/mcp-results.md@@ -28,19 +28,20 @@ is never stored. The arguments of a call get the web path back, so a descriptionassistant writes keeps `/media/...`. A string argument that is only a url is passed as itis. Document assets need a session and keep their paths.-`view_attachment` (one attachment, by its url or id), `view_issue_images` and-`view_initiative_images` return images as `image` content blocks: PNG, JPEG, GIF and-WebP, up to 5 MB each, 8 images and 10 MB per call. A text block comes first and names-the images in order, `{ images: [{ id, filename, contentType }], others: [...] }`, where-`others` holds every attachment left out, with its url. When `view_attachment` opens a file-that is not returned as an image, its entry in `others` also carries the content: `text`-for a PDF or a text file, `table` for a spreadsheet or document. An internal agent gets-`view_attachment` too, with the images as image parts of the tool result-(`toModelOutput` in `runtime/tools/route-tools.ts`). These three tools advertise no-`outputSchema` and a successful call has no `structuredContent`: Claude Code gives the-model `structuredContent` in place of the text block when it is present, which loses the-names and the urls of the attachments left out, and earlier versions dropped the images as-well. A failed call has the error envelope below.+`view_attachment` (one attachment, by its url or id), `view_document_asset` (one file of+a document, by its id), `view_issue_images` and `view_initiative_images` return images as+`image` content blocks: PNG, JPEG, GIF and WebP, up to 5 MB each, 8 images and 10 MB per+call. A text block comes first and names the images in order,+`{ images: [{ id, filename, contentType }], others: [...] }`, where `others` holds every+attachment left out, with its url. When `view_attachment` or `view_document_asset` opens a+file that is not returned as an image, its entry in `others` also carries the content:+`text` for a PDF or a text file, `table` for a spreadsheet or document. An internal agent+gets `view_attachment` and, when granted, `view_document_asset`, with the images as image+parts of the tool result (`toModelOutput` in `runtime/tools/route-tools.ts`). These four+tools advertise no `outputSchema` and a successful call has no `structuredContent`: Claude+Code gives the model `structuredContent` in place of the text block when it is present,+which loses the names and the urls of the attachments left out, and earlier versions dropped+the images as well. A failed call has the error envelope below.A successful call returns: