diff --git a/docs/guide/mcp.md b/docs/guide/mcp.md index 8813aa3f6c..eacc80b5e3 100644 --- a/docs/guide/mcp.md +++ b/docs/guide/mcp.md @@ -2,6 +2,14 @@ Tool steps mark explicit execution failures. Scheduled-task steps show completed operations only after a valid response, rather than when the request is issued. +MCP and other unrecognized tool steps, and the `ls`, `read_file`, `write_file`, +`str_replace` and `bash` steps, take their label from the call's `description` +argument when it is a non-empty string. When it is missing, empty or another +type, such as an object, the step shows its default label; for an MCP tool that +is `Use "" tool`. Search, web fetch and the other built-in steps keep +their own labels. A running subagent's card header shows a search call's +`query`, and without a string `query` it shows the description or the tool +name. In the chat UI, enable **Token Usage → Debug** to inspect generic/MCP tool calls. Each **Tool details** panel starts collapsed and shows the tool name, call ID, diff --git a/docs/guide/sandbox.md b/docs/guide/sandbox.md index a2a1c45e6f..2e96914115 100644 --- a/docs/guide/sandbox.md +++ b/docs/guide/sandbox.md @@ -473,7 +473,7 @@ This remains a best-effort scan, not an atomic filesystem snapshot. When you reopen the destination conversation, the Artifacts sidebar restores files from confirmed handoffs. -Files presented through `present_files` remain part of the thread's artifact state, and the Web UI restores the artifact panel and selected document after a page refresh. Long artifact lists scroll within the panel on desktop and in the mobile drawer, keeping every file reachable. When a completed response successfully presents between 2 and 50 files, its final file card also offers one ZIP download. Archive membership comes from the terminal delivery receipt rather than browser-supplied paths, and the ZIP contains the current file versions, which may have changed since the response. The currently selected formal artifact is refreshed once when the run finishes so edits become visible without a manual reload. Existing UTF-8 text artifacts under `/mnt/user-data/outputs` can also be edited and explicitly saved from the panel on Unix and Windows while the thread is idle; saves use content revisions to prevent overwriting agent changes. A delayed background read cannot replace a successfully saved revision in the editor; cancelled preview and full-file reads also abort their HTTP requests. Source previews also recognize extensionless `Dockerfile` and `Makefile` artifacts by their file names. Unknown file types, including names such as `constructor` and `__proto__`, retain the download fallback. +Files presented through `present_files` remain part of the thread's artifact state, and the Web UI restores the artifact panel and selected document after a page refresh. The file card lists only the string paths in the call's `filepaths`, so a malformed entry does not hide the valid files. When the backend rejects a call, for example because a path is outside `/mnt/user-data/outputs`, neither the file card nor the artifact panel lists its paths. Long artifact lists scroll within the panel on desktop and in the mobile drawer, keeping every file reachable. When a completed response successfully presents between 2 and 50 files, its final file card also offers one ZIP download. Archive membership comes from the terminal delivery receipt rather than browser-supplied paths, and the ZIP contains the current file versions, which may have changed since the response. The currently selected formal artifact is refreshed once when the run finishes so edits become visible without a manual reload. Existing UTF-8 text artifacts under `/mnt/user-data/outputs` can also be edited and explicitly saved from the panel on Unix and Windows while the thread is idle; saves use content revisions to prevent overwriting agent changes. A delayed background read cannot replace a successfully saved revision in the editor; cancelled preview and full-file reads also abort their HTTP requests. Source previews also recognize extensionless `Dockerfile` and `Makefile` artifacts by their file names. Unknown file types, including names such as `constructor` and `__proto__`, retain the download fallback. Unsaved artifact edits survive switching chats, workspace pages, or visiting the home page and returning in the same browser tab. Drafts stay in memory for the diff --git a/frontend/src/AGENTS.md b/frontend/src/AGENTS.md index 5d68d08fd0..20f8b5d001 100644 --- a/frontend/src/AGENTS.md +++ b/frontend/src/AGENTS.md @@ -52,6 +52,10 @@ pnpm test:e2e # Playwright, for anything that depends on a re anchor in `core/messages` and render it once. - **Tool failures come from structured status.** Use `core/messages/tool-error.ts`. Classifying result text marks normal output as an error. +- **Tool-call args are model output.** A tool schema can make `description` an + object, and a malformed call can carry anything. Read display text with + `stringArg` from `core/tools/utils.ts`, because an object rendered as a React + child throws and no error boundary keeps it from replacing the page. - **Exports read every persisted page.** The loaded window and the compacted checkpoint both omit messages. diff --git a/frontend/src/components/workspace/messages/message-group.tsx b/frontend/src/components/workspace/messages/message-group.tsx index bb24f92edc..743dfb37dc 100644 --- a/frontend/src/components/workspace/messages/message-group.tsx +++ b/frontend/src/components/workspace/messages/message-group.tsx @@ -46,6 +46,7 @@ import { extractTextFromMessage, } from "@/core/messages/utils"; import type { ArtifactEntry } from "@/core/threads/types"; +import { stringArg } from "@/core/tools/utils"; import { extractTitleFromMarkdown } from "@/core/utils/markdown"; import { env } from "@/env"; import { cn } from "@/lib/utils"; @@ -1033,12 +1034,9 @@ function ToolCall({ ); } else if (kind === "ls") { - let description: string | undefined = (args as { description: string }) - ?.description; - if (!description) { - description = t.toolCalls.listFolder; - } - const path: string | undefined = (args as { path: string })?.path; + const description = + stringArg(args, "description") ?? t.toolCalls.listFolder; + const path = stringArg(args, "path"); return ( ); } else if (kind === "read_file") { - let description: string | undefined = (args as { description: string }) - ?.description; - if (!description) { - description = t.toolCalls.readFile; - } - const { path } = args as { path: string; content: string }; + const description = stringArg(args, "description") ?? t.toolCalls.readFile; + const path = stringArg(args, "path"); return ( ); } else if (kind === "write_file" || kind === "str_replace") { - let description: string | undefined = (args as { description: string }) - ?.description; - if (!description) { - description = t.toolCalls.writeFile; - } + const description = stringArg(args, "description") ?? t.toolCalls.writeFile; return ( ); } else if (kind === "bash") { - const description: string | undefined = (args as { description: string }) - ?.description; + const description = stringArg(args, "description"); if (!description) { return ( ); } - const command: string | undefined = (args as { command: string })?.command; + const command = stringArg(args, "command"); return ( ); } else { - const description: string | undefined = (args as { description: string }) - ?.description; + const description = stringArg(args, "description"); return ( (); for (const message of group.messages) { if (hasPresentFiles(message)) { - const presentFiles = - extractPresentFilesFromMessage(message); + const presentFiles = extractPresentFilesFromMessage( + message, + group.messages, + ); for (const file of presentFiles) files.add(file); } } diff --git a/frontend/src/core/artifacts/utils.ts b/frontend/src/core/artifacts/utils.ts index 97fef75486..d8cfdb6b4f 100644 --- a/frontend/src/core/artifacts/utils.ts +++ b/frontend/src/core/artifacts/utils.ts @@ -2,7 +2,10 @@ import type { AIMessage, Message, ToolMessage } from "@langchain/langgraph-sdk"; import { getBackendBaseURL } from "../config"; import { indexToolResults } from "../messages/tool-result"; -import { extractPresentFilesFromMessage } from "../messages/utils"; +import { + extractPresentFilesFromMessage, + hasPresentFiles, +} from "../messages/utils"; import { isStaticWebsiteOnly } from "../static-mode"; import type { AgentThreadState } from "../threads"; @@ -189,25 +192,29 @@ function extractSharedArtifactPaths( /** * Recovers artifact paths from history when the Gateway omits `artifacts`. - * `present_files` contributes its paths directly. A shared artifact also needs - * a confirmed handoff receipt. Returns `stateArtifacts` itself if neither - * tool contributes paths. + * `present_files` contributes the paths of each call the backend did not + * reject. A shared artifact also needs a confirmed handoff receipt. Returns + * `stateArtifacts` itself if neither tool contributes paths. */ export function collectThreadArtifactPaths( stateArtifacts: readonly string[], messages: readonly Message[], ): readonly string[] { let toolResults: ReturnType> | undefined; + const resultsAt = (index: number) => + (toolResults ??= indexToolResults(messages)).get(index); const presented = messages .flatMap((message, index) => { - const paths = extractPresentFilesFromMessage(message); + const paths = hasPresentFiles(message) + ? extractPresentFilesFromMessage(message, resultsAt(index) ?? []) + : []; if ( message.type !== "ai" || !message.tool_calls?.some((call) => call.name === SHARED_ARTIFACT_TOOL) ) { return paths; } - const results = (toolResults ??= indexToolResults(messages)).get(index); + const results = resultsAt(index); if (!results) return paths; return [ ...paths, diff --git a/frontend/src/core/messages/utils.ts b/frontend/src/core/messages/utils.ts index 182991517b..9139900fd5 100644 --- a/frontend/src/core/messages/utils.ts +++ b/frontend/src/core/messages/utils.ts @@ -13,6 +13,7 @@ import { } from "@/core/streamdown/fences"; import { modelControlDisplayText } from "./model-control"; +import { isErrorToolMessage } from "./tool-error"; import { indexToolResults } from "./tool-result"; interface GenericMessageGroup { @@ -1089,22 +1090,66 @@ export function isClarificationToolMessage(message: Message) { return message.type === "tool" && message.name === "ask_clarification"; } -export function extractPresentFilesFromMessage(message: Message) { +/** + * The files an assistant message presents through `present_files`. + * + * `results` are the tool results that message owns, such as its group's + * messages or `indexToolResults(messages).get(index)`. The backend rejects the + * whole call when any path is outside the thread's outputs directory, so a call + * with an error result presents nothing. A call without a result yet, while + * the run streams, keeps its paths. + */ +export function extractPresentFilesFromMessage( + message: Message, + results: readonly Message[], +) { if (message.type !== "ai" || !hasPresentFiles(message)) { return []; } const files: string[] = []; for (const toolCall of message.tool_calls ?? []) { if ( - toolCall.name === "present_files" && - Array.isArray(toolCall.args.filepaths) + toolCall.name !== "present_files" || + isRejectedToolCall(toolCall.id, results) ) { - files.push(...(toolCall.args.filepaths as string[])); + continue; + } + // The args are the model's output, and the file list splits each path, + // so keep only string entries; one bad entry must not hide the others. + const filepaths = (toolCall.args as Record | null) + ?.filepaths; + if (!Array.isArray(filepaths)) { + continue; + } + // Append one by one: spreading a saved list of any length into `push` + // can exceed the engine's argument limit and fail the whole thread. + for (const filepath of filepaths) { + if (typeof filepath === "string") { + files.push(filepath); + } } } return files; } +function isRejectedToolCall( + toolCallId: string | undefined, + results: readonly Message[], +) { + if (!toolCallId) { + return false; + } + return results.some( + (result) => + result.type === "tool" && + result.tool_call_id === toolCallId && + // History saved before results carried a status marks the error only + // by this prefix, which is also the backend's legacy error rule. + (isErrorToolMessage(result) || + extractTextFromMessage(result).startsWith("Error:")), + ); +} + export function hasSubagent(message: AIMessage) { for (const toolCall of message.tool_calls ?? []) { if (toolCall.name === "task") { diff --git a/frontend/src/core/tasks/subtask-render.ts b/frontend/src/core/tasks/subtask-render.ts index 19f53b5357..7a74fb1f7d 100644 --- a/frontend/src/core/tasks/subtask-render.ts +++ b/frontend/src/core/tasks/subtask-render.ts @@ -99,15 +99,17 @@ export function collectRenderedSubtasks( group.messages, groupIsLoading, ); + // Persisted or mid-stream calls can arrive without an args object. + const args = (toolCall.args ?? {}) as Record; const task: Subtask = { id: toolCall.id, - subagent_type: toolCall.args.subagent_type, + subagent_type: args.subagent_type as string, description: resolveSubtaskDescription( - toolCall.args.description, - toolCall.args.prompt, + args.description, + args.prompt, subtaskLabel, ), - prompt: toolCall.args.prompt, + prompt: args.prompt as string, status, ...(status === "failed" ? { error: failedLabel } : {}), }; diff --git a/frontend/src/core/tools/utils.ts b/frontend/src/core/tools/utils.ts index 10f8c6ffa8..9876a027ab 100644 --- a/frontend/src/core/tools/utils.ts +++ b/frontend/src/core/tools/utils.ts @@ -4,6 +4,24 @@ import type { AIMessage } from "@langchain/langgraph-sdk"; import type { Translations } from "../i18n"; import { hasToolCalls } from "../messages/utils"; +/** + * Read a tool-call argument for display: the value when it is a non-empty + * string, otherwise `undefined`, so callers can fall back with `??`. + * + * Tool-call args are the model's output, not validated input: a tool's schema + * can make `description` an object or an array, and a malformed or + * mid-stream call can carry anything. React throws on an object child, and + * the chat has no error boundary around tool steps, so one such value would + * take down the whole page. + */ +export function stringArg(args: unknown, key: string): string | undefined { + if (typeof args !== "object" || args === null) { + return undefined; + } + const value = (args as Record)[key]; + return typeof value === "string" && value ? value : undefined; +} + export function explainLastToolCall(message: AIMessage, t: Translations) { if (hasToolCalls(message)) { const lastToolCall = message.tool_calls![message.tool_calls!.length - 1]!; @@ -13,17 +31,21 @@ export function explainLastToolCall(message: AIMessage, t: Translations) { } export function explainToolCall(toolCall: ToolCall, t: Translations) { - if (toolCall.name === "web_search" || toolCall.name === "image_search") { - return t.toolCalls.searchFor(toolCall.args.query); + const query = stringArg(toolCall.args, "query"); + if ( + (toolCall.name === "web_search" || toolCall.name === "image_search") && + query + ) { + return t.toolCalls.searchFor(query); } else if (toolCall.name === "web_fetch") { return t.toolCalls.viewWebPage; } else if (toolCall.name === "present_files") { return t.toolCalls.presentFiles; } else if (toolCall.name === "write_todos") { return t.toolCalls.writeTodos; - } else if (toolCall.args.description) { - return toolCall.args.description; - } else { - return t.toolCalls.useTool(toolCall.name); } + return ( + stringArg(toolCall.args, "description") ?? + t.toolCalls.useTool(toolCall.name) + ); } diff --git a/frontend/tests/e2e/artifact-preview.spec.ts b/frontend/tests/e2e/artifact-preview.spec.ts index 9bc7bf443f..db17e602b2 100644 --- a/frontend/tests/e2e/artifact-preview.spec.ts +++ b/frontend/tests/e2e/artifact-preview.spec.ts @@ -19,6 +19,7 @@ const PRESENTED_THREAD_ID = "00000000-0000-0000-0000-000000003123"; const PERSISTED_PANEL_THREAD_ID = "00000000-0000-0000-0000-000000003125"; const PDF_THREAD_ID = "00000000-0000-0000-0000-000000003124"; const LARGE_JSON_THREAD_ID = "00000000-0000-0000-0000-000000003126"; +const REJECTED_PRESENT_THREAD_ID = "00000000-0000-0000-0000-000000003127"; function writeFileMessages({ path = ARTIFACT_PATH, @@ -734,6 +735,85 @@ test.describe("Artifact preview stability", () => { ).toBeVisible(); }); + test("offers no file the backend rejected in the card or the panel", async ({ + page, + }) => { + // The backend rejects a present_files call whose path is outside the + // outputs directory, and the agent then presents the file it wrote. + const [human, presented] = presentFilesMessages(); + mockLangGraphAPI(page, { + threads: [ + { + thread_id: REJECTED_PRESENT_THREAD_ID, + title: "Rejected present_files call", + messages: [ + human, + { + type: "ai", + id: "msg-ai-present-rejected", + content: "", + tool_calls: [ + { + id: "present-file-rejected", + name: "present_files", + args: { filepaths: ["/mnt/user-data/uploads/secret.md"] }, + }, + ], + }, + { + type: "tool", + id: "msg-tool-present-rejected", + name: "present_files", + tool_call_id: "present-file-rejected", + content: + "Error: Only files in /mnt/user-data/outputs can be presented: /mnt/user-data/uploads/secret.md", + additional_kwargs: { deerflow_tool_meta: { status: "error" } }, + }, + presented, + { + type: "tool", + id: "msg-tool-present-file", + name: "present_files", + tool_call_id: "present-file-artifact", + content: "Successfully presented files", + }, + ], + artifacts: [], + }, + ], + }); + await page.route( + `**/api/threads/${REJECTED_PRESENT_THREAD_ID}/artifacts/mnt/user-data/outputs/presented-report.md`, + (route) => + route.fulfill({ + status: 200, + contentType: "text/markdown", + body: "# Presented Report\n\nGenerated content", + }), + ); + + await page.goto(`/workspace/chats/${REJECTED_PRESENT_THREAD_ID}`); + + const presentedCard = page.getByRole("button", { + name: /presented-report\.md/, + }); + await expect(presentedCard.first()).toBeVisible({ timeout: 15_000 }); + await expect(page.getByRole("button", { name: /secret\.md/ })).toHaveCount( + 0, + ); + + await page.getByText("presented-report.md").first().click(); + const artifactsPanel = page.locator("#artifacts"); + await expect(artifactsPanel.getByText("Presented Report")).toBeVisible(); + await artifactsPanel.getByRole("combobox").click(); + await expect( + page.getByRole("option", { name: "presented-report.md" }), + ).toBeVisible(); + await expect(page.getByRole("option", { name: /secret\.md/ })).toHaveCount( + 0, + ); + }); + test("renders a PDF in an unsandboxed iframe so Chromium's viewer can display it (urlOfArtifact path)", async ({ page, }) => { diff --git a/frontend/tests/unit/components/workspace/artifacts/artifact-file-list.dom.test.tsx b/frontend/tests/unit/components/workspace/artifacts/artifact-file-list.dom.test.tsx index f084915d70..d1411c8ba6 100644 --- a/frontend/tests/unit/components/workspace/artifacts/artifact-file-list.dom.test.tsx +++ b/frontend/tests/unit/components/workspace/artifacts/artifact-file-list.dom.test.tsx @@ -1,3 +1,4 @@ +import type { Message } from "@langchain/langgraph-sdk"; import { afterEach, describe, expect, it, rs } from "@rstest/core"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { @@ -50,6 +51,7 @@ import { ArtifactFileList } from "@/components/workspace/artifacts/artifact-file import { ArtifactRequestError } from "@/core/artifacts/api"; import { I18nContext } from "@/core/i18n/context"; import { enUS } from "@/core/i18n/locales/en-US"; +import { extractPresentFilesFromMessage } from "@/core/messages/utils"; const files = [ "/mnt/user-data/outputs/report.md", @@ -88,6 +90,83 @@ afterEach(() => { rs.restoreAllMocks(); }); +// `present_files` args are the model's output, and the same extraction runs +// when a thread is reopened, so one bad entry must not hide the valid files. +it("renders the valid presented files next to malformed entries", () => { + const presented = [ + { + type: "ai", + content: "", + tool_calls: [ + { + id: "present-1", + name: "present_files", + args: { + filepaths: [{ path: "/mnt/user-data/outputs/bad.md" }, files[0], 7], + }, + }, + { id: "present-2", name: "present_files", args: null }, + ], + }, + ] as unknown as Message[]; + + renderList({ + files: presented.flatMap((message) => + extractPresentFilesFromMessage(message, presented), + ), + }); + + expect( + screen.getByRole("button", { name: "report.md Markdown" }), + ).toBeTruthy(); + expect(screen.queryByRole("button", { name: /bad\.md/ })).toBeNull(); +}); + +// The backend rejects the whole call when a path is outside the outputs +// directory, and the card must not offer files it never presented. +it("omits the files of a present_files call the backend rejected", () => { + const group = [ + { + type: "ai", + content: "", + tool_calls: [ + { + id: "present-rejected", + name: "present_files", + args: { + filepaths: [files[1], "/mnt/user-data/uploads/secret.md"], + }, + }, + { + id: "present-accepted", + name: "present_files", + args: { filepaths: [files[0]] }, + }, + ], + }, + { + type: "tool", + tool_call_id: "present-rejected", + content: + "Error: Only files in /mnt/user-data/outputs can be presented: /mnt/user-data/uploads/secret.md", + additional_kwargs: { deerflow_tool_meta: { status: "error" } }, + }, + { + type: "tool", + tool_call_id: "present-accepted", + content: "Successfully presented files", + }, + ] as unknown as Message[]; + + renderList({ files: extractPresentFilesFromMessage(group[0]!, group) }); + + expect( + screen.getByRole("button", { name: "report.md Markdown" }), + ).toBeTruthy(); + expect(screen.queryByRole("button", { name: /data\.csv/ })).toBeNull(); + expect(screen.queryByRole("button", { name: /secret\.md/ })).toBeNull(); +}); + describe("ArtifactFileList archive download", () => { it("keeps preview and download actions separate", () => { renderList(); diff --git a/frontend/tests/unit/components/workspace/messages/message-group.test.ts b/frontend/tests/unit/components/workspace/messages/message-group.test.ts index 618d4a10e9..ce033cca66 100644 --- a/frontend/tests/unit/components/workspace/messages/message-group.test.ts +++ b/frontend/tests/unit/components/workspace/messages/message-group.test.ts @@ -859,6 +859,42 @@ describe("MessageGroup tool links", () => { expect(html).not.toContain(" { + for (const value of [ + { text: "Roadmap" }, + [{ type: "text", text: { content: "Roadmap" } }], + ]) { + const html = renderToolCall(name, { + description: "Inspect", + path: "/mnt/user-data/workspace", + command: "ls", + [key]: value, + }); + + expect(html).toContain(label); + expect(html).not.toContain("Roadmap"); + } + }); + + it("labels a generic step with an empty description by its tool name", () => { + const html = renderToolCall("mcp_lookup", { description: "" }); + + expect(html).toContain("Use "mcp_lookup" tool"); + }); + // Persisted or mid-stream tool calls can arrive without an args object; // every specialized branch reads args, so none may throw on its absence. it.each([ diff --git a/frontend/tests/unit/components/workspace/messages/subtask-card.dom.test.tsx b/frontend/tests/unit/components/workspace/messages/subtask-card.dom.test.tsx index 87b2c3230f..7a66631f01 100644 --- a/frontend/tests/unit/components/workspace/messages/subtask-card.dom.test.tsx +++ b/frontend/tests/unit/components/workspace/messages/subtask-card.dom.test.tsx @@ -128,6 +128,44 @@ function setup(history = false) { } describe("SubtaskCard message synchronization", () => { + // The collapsed header explains the subagent's latest tool call from the + // live `task_running` message. Its args are the subagent model's output, so + // a non-string description must fall back instead of reaching JSX. + it("explains the running tool call only from string args", () => { + const view = setup(); + const running = (name: string, args: Record) => + act(() => { + view.publish({ + id: "task-1", + status: "in_progress", + latestMessage: { + type: "ai", + id: `child-${name}-${JSON.stringify(args)}`, + content: "", + tool_calls: [{ id: "call-1", name, args }], + }, + }); + }); + + for (const description of [ + { text: "Roadmap" }, + [{ type: "text", text: { content: "Roadmap" } }], + 42, + ]) { + running("notion_create_database", { description }); + expect( + screen.getByText('Use "notion_create_database" tool'), + ).toBeTruthy(); + expect(screen.queryByText(/Roadmap|42/)).toBeNull(); + } + + running("web_search", { query: { text: "Roadmap" } }); + expect(screen.getByText('Use "web_search" tool')).toBeTruthy(); + + running("notion_create_database", { description: "Create the roadmap" }); + expect(screen.getByText("Create the roadmap")).toBeTruthy(); + }); + it.each([false, true])( "renders forwarded evidence on completion/replay (replay=%s)", async (replay) => { diff --git a/frontend/tests/unit/core/artifacts/utils.test.ts b/frontend/tests/unit/core/artifacts/utils.test.ts index 9285083d28..4d0c7f5b27 100644 --- a/frontend/tests/unit/core/artifacts/utils.test.ts +++ b/frontend/tests/unit/core/artifacts/utils.test.ts @@ -453,6 +453,97 @@ describe("artifact URL helpers", () => { expect(collectThreadArtifactPaths(state, [messages[0]!])).toBe(state); }); + // The backend rejects the whole call when a path is outside the outputs + // directory. A result reports the failure by its status, which these cases + // check apart from the text; history saved before results carried a status + // marks it only by the "Error:" prefix. + test.each([ + [ + "an error status", + { + content: "present_files was not run", + additional_kwargs: { deerflow_tool_meta: { status: "error" } }, + }, + ], + [ + "a ToolMessage error status", + { content: "present_files was not run", status: "error" }, + ], + [ + "only the error prefix", + { + content: + "Error: Only files in /mnt/user-data/outputs can be presented: /mnt/user-data/uploads/secret.md", + }, + ], + ])( + "collectThreadArtifactPaths skips a present_files call rejected with %s", + async (_label, result) => { + const { collectThreadArtifactPaths } = await loadFreshArtifactUtils(); + const messages = [ + { type: "human", id: "h", content: "go" }, + { + type: "ai", + id: "a1", + content: "", + tool_calls: [ + { + id: "p1", + name: "present_files", + args: { + filepaths: [ + "/mnt/user-data/outputs/a.md", + "/mnt/user-data/uploads/secret.md", + ], + }, + }, + { + id: "p2", + name: "present_files", + args: { filepaths: ["/mnt/user-data/outputs/b.md"] }, + }, + ], + }, + { + type: "tool", + id: "t1", + tool_call_id: "p1", + ...result, + }, + { + type: "tool", + id: "t2", + tool_call_id: "p2", + content: "Successfully presented files", + }, + ] as Parameters[1]; + + expect(collectThreadArtifactPaths([], messages)).toEqual([ + "/mnt/user-data/outputs/b.md", + ]); + }, + ); + + // Spreading a list this long into one call exceeds the engine's argument + // limit, which would keep the thread from opening. + test("collectThreadArtifactPaths keeps a saved present_files list of any length", async () => { + const { collectThreadArtifactPaths } = await loadFreshArtifactUtils(); + const filepaths = Array.from( + { length: 200_000 }, + (_, index) => `/mnt/user-data/outputs/${index}.md`, + ); + const messages = [ + { + type: "ai", + id: "a1", + content: "", + tool_calls: [{ id: "p1", name: "present_files", args: { filepaths } }], + }, + ] as Parameters[1]; + + expect(collectThreadArtifactPaths([], messages)).toHaveLength(200_000); + }); + describe("shared artifacts in thread history", () => { const origin = "source-thread"; const sha256 = "a".repeat(64); diff --git a/frontend/tests/unit/core/tasks/subtask-render.test.ts b/frontend/tests/unit/core/tasks/subtask-render.test.ts index b4d9577fcb..a2f93e2a02 100644 --- a/frontend/tests/unit/core/tasks/subtask-render.test.ts +++ b/frontend/tests/unit/core/tasks/subtask-render.test.ts @@ -109,6 +109,35 @@ describe("collectRenderedSubtasks", () => { expect(rendered.updates).toHaveLength(1); }); + // Persisted or mid-stream task calls can arrive without an args object. + it.each([undefined, null])( + "renders a task call whose args are %s with the subtask label", + (args) => { + const groups = [ + subagentGroup([ + { + type: "ai", + tool_calls: [{ id: "task-1", name: "task", args }], + content: "", + } as unknown as Message, + ]), + ]; + + const rendered = collectRenderedSubtasks( + groups, + () => true, + "Subtask failed", + "Subtask", + ); + + expect(rendered.tasks.get("task-1")).toMatchObject({ + id: "task-1", + status: "in_progress", + description: "Subtask", + }); + }, + ); + it("marks a task as failed once its turn ended without a tool result", () => { const groups = [ subagentGroup([