fix(frontend): render tool-call args only when they are strings (#8678)

* fix(frontend): render tool-call args only when they are strings

A tool schema can make description an object (rich text, for example),
and the lead agent's message group and the subtask card header passed
such args straight to JSX. React threw on the object child, and with no
error boundary the chat page became Next's error screen; a stored call
broke the thread on every reload.

Read display args through stringArg, which returns only non-empty
strings, and keep each step's fallback label.

* fix(frontend): tolerate missing task args and malformed present_files paths

The subtask collector read task fields from toolCall.args directly, so
a call with omitted or null args threw before any card rendered.
Normalize the args container first; the description keeps the localized
subtask label as its fallback.

extractPresentFilesFromMessage trusted every filepaths entry, and the
file list split each one, so a non-string entry threw and hid the valid
files on every reopen. Guard the args container and keep string paths.

Document the label fallbacks in the MCP guide and the path filtering in
the sandbox guide.

* docs(mcp): scope the tool-step label fallback to steps that read description

* fix(frontend): skip rejected present_files calls and append paths in a loop

The backend rejects a whole present_files call when a path is outside the
thread's outputs directory, but the file card and the artifact panel still
listed the call's paths. A call whose result reports an error now presents
nothing. History saved before results carried a status is matched by the
backend's legacy "Error:" prefix.

Spreading a saved list into push() can exceed the engine's argument limit and
keep the thread from opening, so paths are appended one by one.
This commit is contained in:
Hyeonsang Cho 2026-11-27 11:23:23 +09:00 committed by GitHub
parent a92a87b964
commit d3109cafe2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 476 additions and 45 deletions

View File

@ -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>" 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,

View File

@ -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

View File

@ -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.

View File

@ -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({
</ChainOfThoughtStep>
);
} 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 (
<ChainOfThoughtStep
key={id}
@ -1053,12 +1051,8 @@ function ToolCall({
</ChainOfThoughtStep>
);
} 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 (
<ChainOfThoughtStep
key={id}
@ -1073,11 +1067,7 @@ function ToolCall({
</ChainOfThoughtStep>
);
} 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 (
<ChainOfThoughtStep
@ -1101,8 +1091,7 @@ function ToolCall({
</ChainOfThoughtStep>
);
} else if (kind === "bash") {
const description: string | undefined = (args as { description: string })
?.description;
const description = stringArg(args, "description");
if (!description) {
return (
<ChainOfThoughtStep
@ -1112,7 +1101,7 @@ function ToolCall({
/>
);
}
const command: string | undefined = (args as { command: string })?.command;
const command = stringArg(args, "command");
return (
<ChainOfThoughtStep
key={id}
@ -1166,8 +1155,7 @@ function ToolCall({
</ChainOfThoughtStep>
);
} else {
const description: string | undefined = (args as { description: string })
?.description;
const description = stringArg(args, "description");
return (
<ChainOfThoughtStep
key={id}

View File

@ -1648,8 +1648,10 @@ export function MessageList({
const files = new Set<string>();
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);
}
}

View File

@ -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<typeof indexToolResults<Message>> | 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,

View File

@ -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<T = string> {
@ -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<string, unknown> | 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") {

View File

@ -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<string, unknown>;
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 } : {}),
};

View File

@ -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<string, unknown>)[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)
);
}

View File

@ -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,
}) => {

View File

@ -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();

View File

@ -859,6 +859,42 @@ describe("MessageGroup tool links", () => {
expect(html).not.toContain("<a");
});
// A tool's schema can make a display arg an object or an array (rich text,
// for example), and the call stays in the thread history, so a throw here
// would break the thread on every reload.
it.each([
["mcp_lookup", "description", "Use &quot;mcp_lookup&quot; tool"],
["ls", "description", "List folder"],
["ls", "path", "Inspect"],
["read_file", "description", "Read file"],
["read_file", "path", "Inspect"],
["write_file", "description", "Write file"],
["str_replace", "description", "Write file"],
["bash", "description", "Execute command"],
["bash", "command", "Inspect"],
])("renders a %s step whose %s arg is not a string", (name, key, label) => {
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 &quot;mcp_lookup&quot; 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([

View File

@ -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<string, unknown>) =>
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) => {

View File

@ -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<typeof collectThreadArtifactPaths>[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<typeof collectThreadArtifactPaths>[1];
expect(collectThreadArtifactPaths([], messages)).toHaveLength(200_000);
});
describe("shared artifacts in thread history", () => {
const origin = "source-thread";
const sha256 = "a".repeat(64);

View File

@ -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([