mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
fix(codemode): return compact JSON results (#63258)
This commit is contained in:
committed by
GitHub
Unverified
parent
1002a979f9
commit
1af61ee45c
@@ -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<Content>): Array<typeof ExecuteFile.Type> {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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"') })
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),720px)] max-h-[calc(100vh_-_92px)]">
|
||||
@@ -2052,26 +2054,23 @@ function ExecuteDetails(props: { code: string; output: string; error?: string; c
|
||||
when={props.error}
|
||||
fallback={
|
||||
<Show when={props.output}>
|
||||
{(output) => (
|
||||
<ExecuteDetailsSection
|
||||
label={i18n.t("ui.tool.execute.output")}
|
||||
meta={lines(output())}
|
||||
copy={output()}
|
||||
copyLabel={i18n.t("ui.tool.execute.copyOutput")}
|
||||
>
|
||||
<Dynamic
|
||||
component={fileComponent}
|
||||
mode="text"
|
||||
file={{
|
||||
// Code Mode returns structured results as JSON; highlight those, leave anything else plain.
|
||||
name: Option.isSome(decodeJson(output())) ? "output.json" : "output.txt",
|
||||
contents: output(),
|
||||
cacheKey: checksum(output()),
|
||||
}}
|
||||
overflow="wrap"
|
||||
/>
|
||||
</ExecuteDetailsSection>
|
||||
)}
|
||||
<ExecuteDetailsSection
|
||||
label={i18n.t("ui.tool.execute.output")}
|
||||
meta={lines(output().text)}
|
||||
copy={output().text}
|
||||
copyLabel={i18n.t("ui.tool.execute.copyOutput")}
|
||||
>
|
||||
<Dynamic
|
||||
component={fileComponent}
|
||||
mode="text"
|
||||
file={{
|
||||
name: output().json !== undefined && output().rest === undefined ? "output.json" : "output.txt",
|
||||
contents: output().text,
|
||||
cacheKey: checksum(output().text),
|
||||
}}
|
||||
overflow="wrap"
|
||||
/>
|
||||
</ExecuteDetailsSection>
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
@@ -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 }) {
|
||||
</span>
|
||||
<span data-slot="execute-tool-call-name">{i18n.t("ui.tool.execute.output")}</span>
|
||||
<span data-slot="execute-tool-call-args">
|
||||
{i18n.plural("ui.tool.execute.lines", props.output.split("\n").length)}
|
||||
{i18n.plural("ui.tool.execute.lines", text().split("\n").length)}
|
||||
</span>
|
||||
</div>
|
||||
<Show when={open()}>
|
||||
<div data-slot="execute-tool-output">
|
||||
<ConsoleOutput output={props.output} />
|
||||
<ConsoleOutput output={text()} />
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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" })
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user