diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index caf985af046..d6227079960 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -437,9 +437,10 @@ function formatResult(result: CodeMode.Result) { return [output, warnings, logs].filter((part) => part !== undefined && part !== "").join("\n\n") } +// Compact JSON: indentation adds tokens on every later step without helping the model. Clients pretty-print it. function formatValue(value: CodeMode.DataValue) { if (typeof value === "string") return value - return JSON.stringify(value, null, 2) ?? String(value) + return JSON.stringify(value) ?? String(value) } function outputFiles(content: ReadonlyArray): Array { diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index cb26ce32e3a..4f64f9c32d1 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -330,7 +330,7 @@ describe.each([ { tool: "slack.admin.create", status: "completed" }, ], }) - expect(result.content).toEqual([{ type: "text", text: '[\n "admin",\n "created"\n]' }]) + expect(result.content).toEqual([{ type: "text", text: '["admin","created"]' }]) }) test("executions share the prepared runtime of an inventory while keeping per-call state", async () => { diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index b07765cb56a..2a62821caa4 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -520,7 +520,7 @@ describe("Tool", () => { }, }) expect(callable.output).toMatchObject({ - output: expect.stringContaining('"text": "sales"'), + output: expect.stringContaining('"text":"sales"'), toolCalls: [ { tool: "registry.search", status: "completed" }, { tool: "registry.search.sales", status: "completed" }, @@ -589,7 +589,7 @@ describe("Tool", () => { }, }, }) - expect(result.output).toMatchObject({ output: expect.stringContaining('"text": "sales"') }) + expect(result.output).toMatchObject({ output: expect.stringContaining('"text":"sales"') }) }), ) diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index a7b01dec043..271925ebd13 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -38,6 +38,7 @@ import { createImagePreview } from "../components/image-preview" import { useMarkdown } from "../context/markdown" import { getDirectory, getFilename } from "@opencode/util/path" import { checksum } from "@opencode/util/encode" +import { formatExecuteOutput } from "@opencode/util/execute-output" import { Tooltip } from "@opencode/ui/tooltip" import { useDialog } from "@opencode/ui/context/dialog" import { Dialog, DialogBody, DialogHeader, DialogTitle } from "@opencode/ui/dialog" @@ -2006,17 +2007,18 @@ ToolRegistry.register({ }, }) -const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) - function ExecuteDetails(props: { code: string; output: string; error?: string; calls: number; status?: string }) { const i18n = useI18n() const fileComponent = useFileComponent() const lineCount = (text: string) => text.split("\n").length const lines = (text: string) => i18n.plural("ui.tool.execute.lines", lineCount(text)) + // Code Mode returns structured results as compact JSON; show those indented, and highlight a bare JSON result. + const output = createMemo(() => formatExecuteOutput(props.output)) + // Code and output share one number gutter, sized to the longer block, so their content starts on the same column. const numberDigits = () => - String(Math.max(lineCount(props.code), props.output && !props.error ? lineCount(props.output) : 0)).length + String(Math.max(lineCount(props.code), props.output && !props.error ? lineCount(output().text) : 0)).length return ( @@ -2052,26 +2054,23 @@ function ExecuteDetails(props: { code: string; output: string; error?: string; c when={props.error} fallback={ - {(output) => ( - - - - )} + + + } > @@ -2124,6 +2123,7 @@ function ExecuteDetailsSection(props: { function ExecuteOutputRow(props: { output: string }) { const i18n = useI18n() const [open, setOpen] = createSignal(false) + const text = createMemo(() => formatExecuteOutput(props.output).text) const toggle = () => { if (window.getSelection()?.toString()) return @@ -2150,12 +2150,12 @@ function ExecuteOutputRow(props: { output: string }) { {i18n.t("ui.tool.execute.output")} - {i18n.plural("ui.tool.execute.lines", props.output.split("\n").length)} + {i18n.plural("ui.tool.execute.lines", text().split("\n").length)}
- +
diff --git a/packages/tui/src/routes/session/dialog-execute.tsx b/packages/tui/src/routes/session/dialog-execute.tsx index 8062a47f9e8..6f5fef2c26d 100644 --- a/packages/tui/src/routes/session/dialog-execute.tsx +++ b/packages/tui/src/routes/session/dialog-execute.tsx @@ -1,7 +1,6 @@ import { TextAttributes, type CodeRenderable, type LineInfo, type ScrollBoxRenderable } from "@opentui/core" import { useTerminalDimensions } from "@opentui/solid" import type { SessionMessageAssistantTool } from "@opencode/client/promise" -import { Option, Schema } from "effect" import { createMemo, createSignal, onCleanup, Show } from "solid-js" import stripAnsi from "strip-ansi" import { useConfig } from "../../config" @@ -20,8 +19,7 @@ import { import { useToast } from "../../ui/toast" import { Locale } from "../../util/locale" import { getScrollAcceleration } from "../../util/scroll" - -const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) +import { formatExecuteOutput } from "@opencode/util/execute-output" // The part is the live store object, so the dialog follows the tool while child // calls stream and the output arrives. @@ -219,13 +217,11 @@ function outputText(state: SessionMessageAssistantTool["state"]) { return text || undefined } -// The tool prints a JSON result, optionally followed by "\n\nWarnings:" and "\n\nLogs:". +// A JSON result shows indented and highlighted, with any "Warnings:" and "Logs:" sections below it. function highlightedOutput(text: string) { - if (!text.startsWith("{") && !text.startsWith("[")) return - const end = text.search(/\n\n(Warnings|Logs):\n/) - const json = end === -1 ? text : text.slice(0, end) - if (Option.isNone(decodeJson(json))) return - return { json, rest: text.slice(json.length).trim() || undefined } + const formatted = formatExecuteOutput(text) + if (formatted.json === undefined) return + return { json: formatted.json, rest: formatted.rest } } function lineCount(text: string | undefined) { diff --git a/packages/util/src/execute-output.test.ts b/packages/util/src/execute-output.test.ts new file mode 100644 index 00000000000..e9843e6235e --- /dev/null +++ b/packages/util/src/execute-output.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test" +import { formatExecuteOutput } from "./execute-output.js" + +describe("execute output", () => { + test("indents a JSON result", () => { + expect(formatExecuteOutput('{"a":1,"b":[2]}')).toEqual({ + json: '{\n "a": 1,\n "b": [\n 2\n ]\n}', + rest: undefined, + text: '{\n "a": 1,\n "b": [\n 2\n ]\n}', + }) + }) + + test("indents a JSON result followed by warnings and logs", () => { + expect(formatExecuteOutput('["x"]\n\nWarnings:\n- [unhandled] boom\n\nLogs:\nhi')).toEqual({ + json: '[\n "x"\n]', + rest: "Warnings:\n- [unhandled] boom\n\nLogs:\nhi", + text: '[\n "x"\n]\n\nWarnings:\n- [unhandled] boom\n\nLogs:\nhi', + }) + }) + + test("leaves other results as they are", () => { + expect(formatExecuteOutput("exit 0\nok\n\nLogs:\nhi")).toEqual({ + json: undefined, + rest: "Logs:\nhi", + text: "exit 0\nok\n\nLogs:\nhi", + }) + expect(formatExecuteOutput("{not json")).toEqual({ json: undefined, rest: undefined, text: "{not json" }) + }) +}) diff --git a/packages/util/src/execute-output.ts b/packages/util/src/execute-output.ts new file mode 100644 index 00000000000..5794b2b0bc7 --- /dev/null +++ b/packages/util/src/execute-output.ts @@ -0,0 +1,23 @@ +import { Option, Schema } from "effect" + +const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) + +/** + * Code Mode's `execute` output for display. The tool returns its result (compact JSON for structured values) followed + * by optional "Warnings:" and "Logs:" sections. A JSON result comes back indented as `json`, the sections as `rest`, + * and `text` joins them. + */ +export function formatExecuteOutput(output: string) { + const end = output.search(/\n\n(Warnings|Logs):\n/) + const result = end === -1 ? output : output.slice(0, end) + const rest = end === -1 ? undefined : output.slice(end).trim() + const json = indentedJson(result) + return { json, rest, text: rest === undefined ? (json ?? result) : `${json ?? result}\n\n${rest}` } +} + +function indentedJson(text: string) { + if (!text.startsWith("{") && !text.startsWith("[")) return + const decoded = decodeJson(text) + if (Option.isNone(decoded)) return + return JSON.stringify(decoded.value, null, 2) +}