diff --git a/.github/workflows/desktop-smoke.yml b/.github/workflows/desktop-smoke.yml index 6e0911907..b082fb2f2 100644 --- a/.github/workflows/desktop-smoke.yml +++ b/.github/workflows/desktop-smoke.yml @@ -129,7 +129,7 @@ jobs: run: bun install --frozen-lockfile - name: Repair Electron install - run: node node_modules/electron/install.js + run: node ./scripts/repair-electron-install.mjs working-directory: packages/desktop-electron - name: Prepare OfficeCLI @@ -144,7 +144,7 @@ jobs: PAWWORK_FEEDBACK_FORM_URL: https://example.com/pawwork-feedback - name: Repair Electron install after build - run: node node_modules/electron/install.js + run: node ./scripts/repair-electron-install.mjs working-directory: packages/desktop-electron - name: Check desktop runtime imports diff --git a/packages/desktop-electron/scripts/repair-electron-install.mjs b/packages/desktop-electron/scripts/repair-electron-install.mjs new file mode 100644 index 000000000..a783238dd --- /dev/null +++ b/packages/desktop-electron/scripts/repair-electron-install.mjs @@ -0,0 +1,72 @@ +import { execFileSync } from "node:child_process" +import { existsSync, rmSync, writeFileSync } from "node:fs" +import { createRequire } from "node:module" +import { join } from "node:path" +import process from "node:process" + +const require = createRequire(import.meta.url) + +export function platformPathForElectron(platform = process.platform) { + switch (platform) { + case "darwin": + case "mas": + return "Electron.app/Contents/MacOS/Electron" + case "freebsd": + case "openbsd": + case "linux": + return "electron" + case "win32": + return "electron.exe" + default: + throw new Error(`Electron builds are not available on platform: ${platform}`) + } +} + +export function isElectronInstallComplete(electronDir, platform = process.platform) { + const platformPath = platformPathForElectron(platform) + const binaryPath = join(electronDir, "dist", platformPath) + if (!existsSync(binaryPath)) return false + + if (platform === "darwin" || platform === "mas") { + return existsSync( + join( + electronDir, + "dist", + "Electron.app", + "Contents", + "Frameworks", + "Electron Framework.framework", + "Electron Framework", + ), + ) + } + + return true +} + +export function writeElectronPathFileIfInstallComplete(electronDir, platform = process.platform) { + if (!isElectronInstallComplete(electronDir, platform)) return false + + writeFileSync(join(electronDir, "path.txt"), platformPathForElectron(platform)) + return true +} + +export function repairElectronInstall() { + const electronDir = join(require.resolve("electron/package.json"), "..") + const installScript = join(electronDir, "install.js") + + if (!writeElectronPathFileIfInstallComplete(electronDir)) { + rmSync(join(electronDir, "path.txt"), { force: true }) + execFileSync(process.execPath, [installScript], { stdio: "inherit" }) + } + + if (!writeElectronPathFileIfInstallComplete(electronDir)) { + throw new Error(`Electron install is still incomplete after repair: ${electronDir}`) + } + + console.log(`Electron install ready: ${join(electronDir, "dist", platformPathForElectron())}`) +} + +if (import.meta.url === `file://${process.argv[1]}`) { + repairElectronInstall() +} diff --git a/packages/desktop-electron/scripts/repair-electron-install.test.ts b/packages/desktop-electron/scripts/repair-electron-install.test.ts new file mode 100644 index 000000000..984c21e54 --- /dev/null +++ b/packages/desktop-electron/scripts/repair-electron-install.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { + isElectronInstallComplete, + platformPathForElectron, + writeElectronPathFileIfInstallComplete, +} from "./repair-electron-install.mjs" + +describe("repair Electron install", () => { + test("uses the macOS Electron executable path", () => { + expect(platformPathForElectron("darwin")).toBe("Electron.app/Contents/MacOS/Electron") + }) + + test("does not treat a macOS install as complete when the framework is missing", () => { + const electronDir = mkdtempSync(join(tmpdir(), "pawwork-electron-install-")) + const platformPath = platformPathForElectron("darwin") + mkdirSync(join(electronDir, "dist", "Electron.app", "Contents", "MacOS"), { recursive: true }) + writeFileSync(join(electronDir, "dist", platformPath), "") + + expect(isElectronInstallComplete(electronDir, "darwin")).toBe(false) + expect(writeElectronPathFileIfInstallComplete(electronDir, "darwin")).toBe(false) + }) + + test("writes path.txt when the Electron install is complete", () => { + const electronDir = mkdtempSync(join(tmpdir(), "pawwork-electron-install-")) + const platformPath = platformPathForElectron("darwin") + mkdirSync(join(electronDir, "dist", "Electron.app", "Contents", "MacOS"), { recursive: true }) + mkdirSync(join(electronDir, "dist", "Electron.app", "Contents", "Frameworks", "Electron Framework.framework"), { + recursive: true, + }) + writeFileSync(join(electronDir, "dist", platformPath), "") + writeFileSync( + join(electronDir, "dist", "Electron.app", "Contents", "Frameworks", "Electron Framework.framework", "Electron Framework"), + "", + ) + + expect(isElectronInstallComplete(electronDir, "darwin")).toBe(true) + expect(writeElectronPathFileIfInstallComplete(electronDir, "darwin")).toBe(true) + expect(readFileSync(join(electronDir, "path.txt"), "utf8")).toBe(platformPath) + }) +}) diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index dd9a062f3..f5259bb87 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -32,6 +32,7 @@ export const Event = { export const PRUNE_MINIMUM = 20_000 export const PRUNE_PROTECT = 40_000 const TOOL_OUTPUT_MAX_CHARS = 2_000 +const TOOL_INPUT_MAX_CHARS = 2_000 const PRUNE_PROTECTED_TOOLS = ["skill"] const DEFAULT_TAIL_TURNS = 2 const MIN_PRESERVE_RECENT_TOKENS = 2_000 @@ -252,6 +253,7 @@ export const layer: Layer.Layer< const msgs = yield* MessageV2.toModelMessagesEffect(input.messages, input.model, { stripMedia: true, toolOutputMaxChars: TOOL_OUTPUT_MAX_CHARS, + toolInputMaxChars: TOOL_INPUT_MAX_CHARS, }) return Token.estimate(JSON.stringify(msgs)) }) @@ -497,6 +499,7 @@ export const layer: Layer.Layer< const modelMessages = yield* MessageV2.toModelMessagesEffect(msgs, model, { stripMedia: true, toolOutputMaxChars: TOOL_OUTPUT_MAX_CHARS, + toolInputMaxChars: TOOL_INPUT_MAX_CHARS, }) const processor = yield* processors.create({ assistantMessage: msg, diff --git a/packages/opencode/src/session/message-v2.ts b/packages/opencode/src/session/message-v2.ts index 0ea7837be..9f2e31e16 100644 --- a/packages/opencode/src/session/message-v2.ts +++ b/packages/opencode/src/session/message-v2.ts @@ -45,6 +45,85 @@ function truncateToolOutput(text: string, maxChars?: number) { return `${text.slice(0, sliceLen)}${suffixTemplate(omitted)}` } +function truncateToolInputString(text: string, maxChars?: number) { + if (maxChars == null || text.length <= maxChars) return text + if (maxChars <= 0) return "" + const suffixTemplate = (n: number) => `\n[Tool input truncated for compaction: omitted ${n} chars]` + const reserve = suffixTemplate(text.length).length + if (reserve >= maxChars) return text.slice(0, maxChars) + const sliceLen = Math.max(0, maxChars - reserve) + const omitted = text.length - sliceLen + return `${text.slice(0, sliceLen)}${suffixTemplate(omitted)}` +} + +function serializedToolInputLength(input: unknown) { + try { + return JSON.stringify(input).length + } catch { + return String(input).length + } +} + +function toolInputTruncatedMarker(maxChars: number): unknown { + const marker = { _truncated: "Tool input truncated for compaction" } + return serializedToolInputLength(marker) <= maxChars ? marker : {} +} + +function appendToolInputMarkerToArray(items: unknown[], maxChars: number): unknown[] { + const marker = toolInputTruncatedMarker(maxChars) + const output = [...items] + while (output.length > 0 && serializedToolInputLength([...output, marker]) > maxChars) { + output.pop() + } + const withMarker = [...output, marker] + return serializedToolInputLength(withMarker) <= maxChars ? withMarker : output +} + +function appendToolInputMarkerToObject(input: Record, maxChars: number): Record { + const marker = toolInputTruncatedMarker(maxChars) as Record + const output = { ...input } + const keys = Object.keys(output) + while (keys.length > 0 && serializedToolInputLength({ ...output, ...marker }) > maxChars) { + const key = keys.pop() + if (key) delete output[key] + } + const withMarker = { ...output, ...marker } + return serializedToolInputLength(withMarker) <= maxChars ? withMarker : output +} + +function truncateToolInput(input: unknown, maxChars?: number): unknown { + if (maxChars == null) return input + if (maxChars <= 0) return "" + if (typeof input === "string") { + const truncated = truncateToolInputString(input, maxChars) + return serializedToolInputLength(truncated) <= maxChars ? truncated : toolInputTruncatedMarker(maxChars) + } + if (!input || typeof input !== "object") { + return serializedToolInputLength(input) <= maxChars ? input : toolInputTruncatedMarker(maxChars) + } + if (Array.isArray(input)) { + const output: unknown[] = [] + for (const item of input) { + const projected = truncateToolInput(item, maxChars) + const next = [...output, projected] + if (serializedToolInputLength(next) > maxChars) return appendToolInputMarkerToArray(output, maxChars) + output.push(projected) + } + return output + } + + const output: Record = {} + const record = input as Record + for (const key in record) { + if (!Object.prototype.propertyIsEnumerable.call(record, key)) continue + const projected = truncateToolInput(record[key], maxChars) + const next = { ...output, [key]: projected } + if (serializedToolInputLength(next) > maxChars) return appendToolInputMarkerToObject(output, maxChars) + output[key] = projected + } + return output +} + /** Error shape thrown by Bun's fetch() when gzip/br decompression fails mid-stream */ interface FetchDecompressionError extends Error { code: "ZlibError" @@ -695,7 +774,7 @@ function providerMeta(metadata: Record | undefined) { export const toModelMessagesEffect = Effect.fnUntraced(function* ( input: WithParts[], model: Provider.Model, - options?: { stripMedia?: boolean; toolOutputMaxChars?: number }, + options?: { stripMedia?: boolean; toolOutputMaxChars?: number; toolInputMaxChars?: number }, ) { const result: UIMessage[] = [] const toolNames = new Set() @@ -866,7 +945,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* ( type: ("tool-" + part.tool) as `tool-${string}`, state: "output-available", toolCallId: part.callID, - input: part.state.input, + input: truncateToolInput(part.state.input, options?.toolInputMaxChars), output, ...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}), ...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }), @@ -887,7 +966,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* ( type: ("tool-" + part.tool) as `tool-${string}`, state: "output-available", toolCallId: part.callID, - input: part.state.input, + input: truncateToolInput(part.state.input, options?.toolInputMaxChars), output, ...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}), ...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }), @@ -897,7 +976,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* ( type: ("tool-" + part.tool) as `tool-${string}`, state: "output-error", toolCallId: part.callID, - input: part.state.input, + input: truncateToolInput(part.state.input, options?.toolInputMaxChars), errorText: formatToolFailureForModel(part.state.error, part.state.metadata?.diagnostics?.failure), ...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}), ...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }), @@ -911,7 +990,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* ( type: ("tool-" + part.tool) as `tool-${string}`, state: "output-error", toolCallId: part.callID, - input: part.state.input, + input: truncateToolInput(part.state.input, options?.toolInputMaxChars), errorText: "[Tool execution was interrupted]", ...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}), ...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }), @@ -976,7 +1055,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* ( export function toModelMessages( input: WithParts[], model: Provider.Model, - options?: { stripMedia?: boolean; toolOutputMaxChars?: number }, + options?: { stripMedia?: boolean; toolOutputMaxChars?: number; toolInputMaxChars?: number }, ): Promise { return Effect.runPromise(toModelMessagesEffect(input, model, options).pipe(Effect.provide(EffectLogger.layer))) } diff --git a/packages/opencode/test/github/desktop-smoke-workflow.test.ts b/packages/opencode/test/github/desktop-smoke-workflow.test.ts index a449e97ef..84fd56e5c 100644 --- a/packages/opencode/test/github/desktop-smoke-workflow.test.ts +++ b/packages/opencode/test/github/desktop-smoke-workflow.test.ts @@ -62,10 +62,10 @@ describe("desktop smoke workflow", () => { expect(smokeCheckoutStep?.with).toEqual({ "persist-credentials": false }) expect(smokeBunStep?.uses).toBe("oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6") expect(installStep?.run).toBe("bun install --frozen-lockfile") - expect(repairElectronStep?.run).toBe("node node_modules/electron/install.js") + expect(repairElectronStep?.run).toBe("node ./scripts/repair-electron-install.mjs") expect(repairElectronStep?.["working-directory"]).toBe("packages/desktop-electron") expect(repairElectronAfterBuildStep).toBeDefined() - expect(repairElectronAfterBuildStep?.run).toBe("node node_modules/electron/install.js") + expect(repairElectronAfterBuildStep?.run).toBe("node ./scripts/repair-electron-install.mjs") expect(repairElectronAfterBuildStep?.["working-directory"]).toBe("packages/desktop-electron") expect(prepareOfficeCliStep).toBeDefined() expect(prepareOfficeCliStep?.run).toBe("bun ./scripts/prepare-officecli.ts --platform darwin --arch arm64") diff --git a/packages/opencode/test/session/compaction.test.ts b/packages/opencode/test/session/compaction.test.ts index 01d9a3c95..6f4393018 100644 --- a/packages/opencode/test/session/compaction.test.ts +++ b/packages/opencode/test/session/compaction.test.ts @@ -901,7 +901,34 @@ describe("session.compaction.process", () => { fn: async () => { const session = await svc.create() const first = await user(session.id, "first request") - await assistant(session.id, first.id, tmp.path) + const firstAssistant = await assistant(session.id, first.id, tmp.path) + const longQuestion = `${"Tauri backend Rust, OpenCode server TypeScript. ".repeat(200)}UNIQUE_COMPACTION_INPUT_TAIL` + await svc.updatePart({ + id: PartID.ascending(), + messageID: firstAssistant.id, + sessionID: session.id, + type: "tool", + callID: "call-question", + tool: "question", + state: { + status: "error", + input: { + questions: [ + { + question: longQuestion, + header: "Runtime", + options: [ + { label: "External", description: "Run Node separately" }, + { label: "Rust", description: "Rewrite backend" }, + ], + }, + ], + }, + error: "invalid question", + time: { start: 0, end: 1 }, + metadata: {}, + }, + }) const second = await user(session.id, "second request") await assistant(session.id, second.id, tmp.path) const compact = await user(session.id, "compact now") @@ -948,6 +975,9 @@ describe("session.compaction.process", () => { expect(compactPart?.tail_start_id).toBe(second.id) expect(inputText(captured?.messages)).toContain("first request") expect(inputText(captured?.messages)).not.toContain("second request") + const capturedPayload = JSON.stringify(captured?.messages) + expect(capturedPayload).toContain("Tool input truncated") + expect(capturedPayload).not.toContain("UNIQUE_COMPACTION_INPUT_TAIL") }, }) }) diff --git a/packages/opencode/test/session/message-v2.test.ts b/packages/opencode/test/session/message-v2.test.ts index de3d02cfd..1bf6e4409 100644 --- a/packages/opencode/test/session/message-v2.test.ts +++ b/packages/opencode/test/session/message-v2.test.ts @@ -882,6 +882,266 @@ describe("session.message-v2.toModelMessage", () => { ]) }) + test("bounds long tool inputs separately from tool output for compaction replay", async () => { + const userID = "m-user" + const assistantID = "m-assistant" + const longQuestion = `${"Tauri backend Rust, OpenCode server TypeScript. ".repeat(200)}UNIQUE_LONG_QUESTION_TAIL` + const error = + 'The question tool was called with invalid arguments: SchemaError(Missing key at ["questions"][0]["options"][3]["description"]).\nPlease rewrite the input so it satisfies the expected schema.' + const input: MessageV2.WithParts[] = [ + { + info: userInfo(userID), + parts: [ + { + ...basePart(userID, "u1"), + type: "text", + text: "ask a question", + }, + ] as MessageV2.Part[], + }, + { + info: assistantInfo(assistantID, userID), + parts: [ + { + ...basePart(assistantID, "a1"), + type: "tool", + callID: "call-question", + tool: "question", + state: { + status: "error", + input: { + questions: [ + { + question: longQuestion, + header: "Runtime", + options: [ + { label: "External", description: "Run Node separately" }, + { label: "Rust", description: "Rewrite backend" }, + { label: "Shell", description: "Spawn child process" }, + { label: "Unsure" }, + ], + }, + ], + }, + error, + time: { start: 0, end: 1 }, + metadata: {}, + }, + }, + ] as MessageV2.Part[], + }, + ] + + const [, assistant, tool] = await MessageV2.toModelMessages(input, model, { + toolInputMaxChars: 200, + toolOutputMaxChars: 32, + }) + const toolCall = assistant?.content[0] as any + const toolResult = tool?.content[0] as any + + const serializedInput = JSON.stringify(toolCall.input) + expect(serializedInput.length).toBeLessThanOrEqual(200) + expect(serializedInput).not.toContain("UNIQUE_LONG_QUESTION_TAIL") + expect(serializedInput).toContain("Tool input truncated") + expect(toolResult.output.value).toContain("SchemaError") + }) + + test("bounds the entire serialized tool input for compaction replay", async () => { + const userID = "m-user" + const assistantID = "m-assistant" + const input: MessageV2.WithParts[] = [ + { + info: userInfo(userID), + parts: [ + { + ...basePart(userID, "u1"), + type: "text", + text: "write many todos", + }, + ] as MessageV2.Part[], + }, + { + info: assistantInfo(assistantID, userID), + parts: [ + { + ...basePart(assistantID, "a1"), + type: "tool", + callID: "call-todos", + tool: "todowrite", + state: { + status: "completed", + input: { + todos: Array.from({ length: 100 }, (_, index) => ({ + content: `short todo item ${index}`, + status: index % 2 === 0 ? "completed" : "pending", + })), + }, + output: "ok", + title: "", + metadata: {}, + time: { start: 0, end: 1 }, + }, + }, + ] as MessageV2.Part[], + }, + ] + + const [, assistant] = await MessageV2.toModelMessages(input, model, { + toolInputMaxChars: 600, + }) + const toolCall = assistant?.content[0] as any + const serializedInput = JSON.stringify(toolCall.input) + + expect(serializedInput.length).toBeLessThanOrEqual(600) + expect(serializedInput).toContain("Tool input truncated") + expect(serializedInput).not.toContain("short todo item 99") + }) + + test("uses a flat truncation marker for object tool input projections", async () => { + const userID = "m-user" + const assistantID = "m-assistant" + const input: MessageV2.WithParts[] = [ + { + info: userInfo(userID), + parts: [ + { + ...basePart(userID, "u1"), + type: "text", + text: "run a tool", + }, + ] as MessageV2.Part[], + }, + { + info: assistantInfo(assistantID, userID), + parts: [ + { + ...basePart(assistantID, "a1"), + type: "tool", + callID: "call-object", + tool: "example", + state: { + status: "completed", + input: { + first: "a".repeat(30), + second: "b".repeat(30), + third: "c".repeat(30), + }, + output: "ok", + title: "", + metadata: {}, + time: { start: 0, end: 1 }, + }, + }, + ] as MessageV2.Part[], + }, + ] + + const [, assistant] = await MessageV2.toModelMessages(input, model, { + toolInputMaxChars: 90, + }) + const toolCall = assistant?.content[0] as any + + expect(typeof toolCall.input._truncated).toBe("string") + expect(toolCall.input._truncated).toContain("Tool input truncated") + }) + + test("uses empty tool input for non-positive projection budgets", async () => { + const userID = "m-user" + const assistantID = "m-assistant" + const input: MessageV2.WithParts[] = [ + { + info: userInfo(userID), + parts: [ + { + ...basePart(userID, "u1"), + type: "text", + text: "run a tool", + }, + ] as MessageV2.Part[], + }, + { + info: assistantInfo(assistantID, userID), + parts: [ + { + ...basePart(assistantID, "a1"), + type: "tool", + callID: "call-zero", + tool: "example", + state: { + status: "completed", + input: { value: "kept out" }, + output: "ok", + title: "", + metadata: {}, + time: { start: 0, end: 1 }, + }, + }, + ] as MessageV2.Part[], + }, + ] + + const [, assistant] = await MessageV2.toModelMessages(input, model, { + toolInputMaxChars: 0, + }) + const toolCall = assistant?.content[0] as any + + expect(toolCall.input).toBe("") + }) + + test("stops traversing oversized tool input after the projection budget is exhausted", async () => { + const userID = "m-user" + const assistantID = "m-assistant" + let contentAccesses = 0 + const todos = Array.from({ length: 5_000 }, (_, index) => ({ + get content() { + contentAccesses++ + return `small todo item ${index}` + }, + status: "pending", + })) + const input: MessageV2.WithParts[] = [ + { + info: userInfo(userID), + parts: [ + { + ...basePart(userID, "u1"), + type: "text", + text: "write many todos", + }, + ] as MessageV2.Part[], + }, + { + info: assistantInfo(assistantID, userID), + parts: [ + { + ...basePart(assistantID, "a1"), + type: "tool", + callID: "call-todos", + tool: "todowrite", + state: { + status: "completed", + input: { todos }, + output: "ok", + title: "", + metadata: {}, + time: { start: 0, end: 1 }, + }, + }, + ] as MessageV2.Part[], + }, + ] + + const [, assistant] = await MessageV2.toModelMessages(input, model, { + toolInputMaxChars: 600, + }) + const toolCall = assistant?.content[0] as any + const serializedInput = JSON.stringify(toolCall.input) + + expect(serializedInput.length).toBeLessThanOrEqual(600) + expect(serializedInput).toContain("Tool input truncated") + expect(contentAccesses).toBeLessThan(500) + }) + test("converts permission denial diagnostic into model-facing error text", async () => { const userID = "m-user" const assistantID = "m-assistant" diff --git a/packages/ui/src/components/message-part/context-tool-helpers.test.ts b/packages/ui/src/components/message-part/context-tool-helpers.test.ts index 4aa82b08b..8309678ab 100644 --- a/packages/ui/src/components/message-part/context-tool-helpers.test.ts +++ b/packages/ui/src/components/message-part/context-tool-helpers.test.ts @@ -30,10 +30,11 @@ function tool( metadata: Record = {}, input: Record = {}, title = "", + error = "boom", ): ToolPart { const state: ToolState = status === "error" - ? { status, input, error: "boom", time: { start: 0, end: 1 } } + ? { status, input, error, time: { start: 0, end: 1 } } : { status, input, output: "", title, metadata, time: { start: 0, end: 1 } } return { @@ -134,4 +135,83 @@ describe("contextTrowSummaryText", () => { expect(contextToolSummaryText(part, i18n("en"))).toBe("Edit files 1 file") }) + + test("keeps failed question summaries bounded instead of exposing raw schema errors", () => { + const schemaError = + 'The question tool was called with invalid arguments: SchemaError(Missing key at ["questions"][0]["options"][3]["description"]).\nPlease rewrite the input so it satisfies the expected schema.' + const part = tool( + "question", + "question", + "error", + {}, + { + questions: [ + { + question: "Tauri backend Rust, OpenCode server TypeScript. ".repeat(20), + options: [ + { label: "External", description: "Run Node separately" }, + { label: "Rust", description: "Rewrite backend" }, + { label: "Shell", description: "Spawn child process" }, + { label: "Unsure" }, + ], + }, + ], + }, + "", + schemaError, + ) + + const summary = contextToolSummaryText(part, i18n("en")) + + expect(summary).toBe("Questions 1 question") + expect(summary).not.toContain("SchemaError") + expect(summary).not.toContain("\n") + expect(summary.length).toBeLessThanOrEqual(80) + }) + + test("keeps short generic tool errors in compact summaries", () => { + const part = tool("issue", "linear_create_issue", "error", {}, {}, "", "Rate limit exceeded") + + expect(contextToolSummaryText(part, i18n("en"))).toBe("linear_create_issue Rate limit exceeded") + }) + + test("bounds long generic tool errors in compact summaries", () => { + const part = tool( + "issue", + "linear_create_issue", + "error", + {}, + {}, + "", + `Request failed with details ${"sensitive payload ".repeat(20)}UNIQUE_ERROR_TAIL`, + ) + + const summary = contextToolSummaryText(part, i18n("en")) + + expect(summary).toContain("Request failed with details") + expect(summary).not.toContain("UNIQUE_ERROR_TAIL") + expect(summary).not.toContain("\n") + expect(summary.length).toBeLessThanOrEqual(150) + }) + + test("summarizes todowrite input by localized item count instead of raw content", () => { + const part = tool( + "todos", + "todowrite", + "completed", + {}, + { + todos: [ + { content: "Investigate tool input projection boundaries", status: "completed" }, + { content: "Add regression tests for compaction replay", status: "pending" }, + ], + }, + ) + + const summary = contextToolSummaryText(part, i18n("zh")) + + expect(summary).toBe("待办 2 个待办") + expect(summary).not.toContain("Investigate tool input projection boundaries") + expect(summary.length).toBeLessThanOrEqual(80) + }) }) diff --git a/packages/ui/src/components/message-part/context-tool-helpers.ts b/packages/ui/src/components/message-part/context-tool-helpers.ts index a76b6a72f..d2a69bb5f 100644 --- a/packages/ui/src/components/message-part/context-tool-helpers.ts +++ b/packages/ui/src/components/message-part/context-tool-helpers.ts @@ -4,10 +4,12 @@ import type { UiI18n, UiI18nKey } from "../../context/i18n" import { getDirectory } from "./markdown-render" import { toolInfoForInput } from "../tool-info" +const TOOL_ERROR_DETAIL_MAX = 120 + export function contextToolDetail(part: ToolPart, i18n: UiI18n): string | undefined { const info = toolInfoForInput(part.tool, part.state.input ?? {}, toolStateMetadata(part.state), i18n) if (info.subtitle) return info.subtitle - if (part.state.status === "error") return toolStateError(part.state) + if (part.state.status === "error") return boundedToolStateError(part.state) if ((part.state.status === "running" || part.state.status === "completed") && part.state.title) return part.state.title const description = part.state.input?.description @@ -91,6 +93,13 @@ export function toolStateError(state: ToolPart["state"] | undefined): string | u } } +function boundedToolStateError(state: ToolPart["state"] | undefined): string | undefined { + const error = toolStateError(state)?.replace(/\s+/g, " ").trim() + if (!error) return undefined + if (error.length <= TOOL_ERROR_DETAIL_MAX) return error + return `${error.slice(0, TOOL_ERROR_DETAIL_MAX - 3)}...` +} + export function contextToolSummary(parts: ToolPart[]) { const read = parts.filter((part) => part.tool === "read").length const search = parts.filter((part) => part.tool === "glob" || part.tool === "grep").length diff --git a/packages/ui/src/components/tool-info.ts b/packages/ui/src/components/tool-info.ts index 183a6ad1f..3ec9af98d 100644 --- a/packages/ui/src/components/tool-info.ts +++ b/packages/ui/src/components/tool-info.ts @@ -219,16 +219,26 @@ export function toolInfoForInput( : undefined, } } - case TOOL_TODOWRITE: + case TOOL_TODOWRITE: { + const todoCount = Array.isArray(input.todos) ? input.todos.length : 0 return { icon, title: i18n.t("ui.tool.todos"), + subtitle: todoCount + ? `${todoCount} ${i18n.t(todoCount > 1 ? "ui.common.todo.other" : "ui.common.todo.one")}` + : undefined, } - case TOOL_QUESTION: + } + case TOOL_QUESTION: { + const count = Array.isArray(input.questions) ? input.questions.length : 0 return { icon, title: i18n.t("ui.tool.questions"), + subtitle: count + ? `${count} ${i18n.t(count > 1 ? "ui.common.question.other" : "ui.common.question.one")}` + : undefined, } + } case "skill": return { icon, diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index b3f2ab91b..218039117 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -204,6 +204,8 @@ export const dict: Record = { "ui.common.file.one": "file", "ui.common.file.other": "files", + "ui.common.todo.one": "todo", + "ui.common.todo.other": "todos", "ui.common.question.one": "question", "ui.common.question.other": "questions", diff --git a/packages/ui/src/i18n/zh.ts b/packages/ui/src/i18n/zh.ts index b13ebf94b..dd92ac41d 100644 --- a/packages/ui/src/i18n/zh.ts +++ b/packages/ui/src/i18n/zh.ts @@ -190,6 +190,8 @@ export const dict = { "ui.common.file.one": "个文件", "ui.common.file.other": "个文件", + "ui.common.todo.one": "个待办", + "ui.common.todo.other": "个待办", "ui.common.question.one": "个问题", "ui.common.question.other": "个问题",