diff --git a/packages/session-ui/component-tests/session-tool-projection.spec.ts b/packages/session-ui/component-tests/session-tool-projection.spec.ts index f1eb2a6b0b94..72a94ade7b73 100644 --- a/packages/session-ui/component-tests/session-tool-projection.spec.ts +++ b/packages/session-ui/component-tests/session-tool-projection.spec.ts @@ -47,15 +47,25 @@ story("renders every tool error outcome without leaking hidden tools", async ({ for (const name of names) await expect(timeline.locator(`[data-timeline-part-id="tool_error_${name}"]`)).toBeVisible() }) -story("expands a failed execute to its full code and error", async ({ mount }) => { +story("lists a failed execute's calls and keeps its error under the failed call", async ({ mount }) => { const timeline = await mount("current-session-terminal-work--execute-failed") await timeline.getByRole("button", { name: /^Used 5 / }).click() const failed = timeline.locator('[data-timeline-part-id="tool_execute_failed_url"]') - await failed.getByRole("button", { name: /Invalid browser URL/ }).click() - await expect(failed.locator('[data-slot="tool-error-card-subtitle"]')).toContainText( - "const shot = await tools.browser.screenshot({ tabID: tab.id, fullPage: true });", + const call = failed.locator('[data-slot="execute-tool-call"]') + // Executions open by default, so the calls show without expanding the row. + await expect(call).toHaveText([/browser\.tabs\.open/]) + await expect(call).toHaveAttribute("data-status", "error") + await expect(timeline.locator('[data-kind="tool-error-card"]')).toHaveCount(0) + + // The runtime error stays collapsed under the failed call until it is expanded. + const error = failed.locator('[data-slot="execute-tool-error"]') + await expect(error).toHaveCount(0) + await call.click() + await expect(call).toHaveAttribute("aria-expanded", "true") + await expect(failed.locator('[data-slot="execute-tool-call-input"]')).toContainText( + "url:file:///C:/tmp/opencode/throne-of-glass-luke.html", ) - await expect(failed.locator('[data-slot="card-description"]')).toContainText( + await expect(error).toContainText( "The connected server must be able to reach the address; localhost refers to that server.", ) }) @@ -155,3 +165,30 @@ story("combines adjacent edit calls and repeated files into one group", async ({ await expect(group.locator('[data-scope="apply-patch"] button')).toContainText("+2") await expect(group.locator('[data-scope="apply-patch"] button')).toHaveAttribute("aria-expanded", "true") }) + +story("opens an execution's code and output from its View code action", async ({ mount }) => { + const timeline = await mount("current-session-terminal-work--execute-code") + await timeline.getByRole("button", { name: "View code" }).first().click() + const dialog = timeline.page().getByRole("dialog") + await expect(dialog.getByRole("heading", { name: "Execute" })).toBeVisible() + await expect(dialog).toContainText("Completed") + await expect(dialog).toContainText("2 calls") + await expect(dialog).toContainText('const tab = await tools.browser.tabs.open({ url: "http://localhost:4399" })') + await expect(dialog).toContainText('"tab": "tab_4f1c"') + await expect(dialog.getByRole("button", { name: "Copy code" })).toBeVisible() + await expect(dialog.getByRole("button", { name: "Copy output" })).toBeVisible() +}) + +story("shows a failed execution's error in place of its output", async ({ mount }) => { + const timeline = await mount("current-session-terminal-work--execute-failed") + await timeline.getByRole("button", { name: /^Used 5 / }).click() + await timeline + .locator('[data-timeline-part-id="tool_execute_failed_url"]') + .getByRole("button", { name: "View code" }) + .click() + const dialog = timeline.page().getByRole("dialog") + await expect(dialog).toContainText("Failed") + await expect(dialog).toContainText("Invalid browser URL.") + await expect(dialog.getByRole("button", { name: "Copy error" })).toBeVisible() + await expect(dialog.getByRole("button", { name: "Copy output" })).toHaveCount(0) +}) diff --git a/packages/session-ui/src/components/basic-tool.css b/packages/session-ui/src/components/basic-tool.css index 1346efdb6521..7a8d746f41af 100644 --- a/packages/session-ui/src/components/basic-tool.css +++ b/packages/session-ui/src/components/basic-tool.css @@ -170,6 +170,52 @@ } } +/* The action sits on the trigger's line as a sibling, since buttons cannot nest inside the trigger button. */ +[data-component="collapsible"].tool-collapsible[data-has-action="true"] { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + column-gap: 2px; + + > [data-slot="collapsible-trigger"] { + flex: 0 1 auto; + width: auto; + min-width: 0; + /* Leave room for the action so a long collapsed subtitle truncates instead of wrapping it. */ + max-width: calc(100% - 26px); + + /* The trigger now sizes to its content, so the content's room for the arrow would clip the title. */ + [data-slot="basic-tool-tool-trigger-content"] { + max-width: none; + } + } + + > [data-slot="collapsible-content"] { + flex-basis: 100%; + } +} + +[data-slot="basic-tool-action"] { + display: inline-flex; + align-items: center; + flex-shrink: 0; + opacity: 0; + transition: opacity 0.15s ease; +} + +[data-slot="collapsible-trigger"]:hover + [data-slot="basic-tool-action"], +[data-slot="collapsible-trigger"]:focus-visible + [data-slot="basic-tool-action"], +[data-slot="basic-tool-action"]:hover, +[data-slot="basic-tool-action"]:focus-within { + opacity: 1; +} + +@media (hover: none) { + [data-slot="basic-tool-action"] { + opacity: 1; + } +} + [data-component="collapsible"].tool-collapsible[data-compact="true"] > [data-slot="collapsible-trigger"] { height: 28px; diff --git a/packages/session-ui/src/components/basic-tool.tsx b/packages/session-ui/src/components/basic-tool.tsx index fc294109ccc9..18c0488edfd1 100644 --- a/packages/session-ui/src/components/basic-tool.tsx +++ b/packages/session-ui/src/components/basic-tool.tsx @@ -60,6 +60,8 @@ export interface BasicToolProps { triggerAsLink?: boolean clickable?: boolean compact?: boolean + /** Rendered beside the trigger rather than inside it, so it can be its own button. Shown on hover or focus. */ + action?: JSX.Element } const SPRING = { type: "spring" as const, visualDuration: 0.35, bounce: 0 } @@ -303,6 +305,7 @@ export function BasicTool(props: BasicToolProps) { class="tool-collapsible" data-compact={props.compact ? "true" : undefined} data-rail={props.rail === false ? "false" : undefined} + data-has-action={props.action ? "true" : undefined} > + {(action) => {action()}}
:last-child { + margin-inline-start: auto; + } + } + + [data-slot="execute-details-section-label"] { + font-size: 13px; + font-weight: 530; + color: var(--v2-text-text-muted); + } + + [data-slot="execute-details-section-meta"] { + font-size: 12px; + color: var(--v2-text-text-faint); + } + + [data-slot="execute-details-source"] { + max-height: 360px; + overflow: auto; + border-radius: 8px; + box-shadow: 0 0 0 0.5px var(--v2-border-border-base); + } + + [data-slot="execute-details-error"] { + margin: 0; + padding: 12px 14px; + font-family: var(--v2-font-family-code); + font-size: 13px; + line-height: var(--line-height-base); + white-space: pre-wrap; + overflow-wrap: anywhere; + color: var(--v2-state-fg-danger); + background: var(--v2-background-bg-layer-01); + } +} + [data-component="exa-tool-output"] { display: flex; flex-direction: column; diff --git a/packages/session-ui/src/message/current-tool-state.ts b/packages/session-ui/src/message/current-tool-state.ts index a987149ae62a..bef408a57fb5 100644 --- a/packages/session-ui/src/message/current-tool-state.ts +++ b/packages/session-ui/src/message/current-tool-state.ts @@ -51,20 +51,42 @@ export function shellResultFailed(metadata: Record) { export function executeToolFailed(metadata: Record) { // Code Mode can report failed nested calls in a completed tool result. + return metadata.error === true || executeToolCalls(metadata).some((call) => call.status === "error") +} + +const decodeExecuteCall = Schema.decodeUnknownOption( + Schema.Struct({ + tool: Schema.String, + status: Schema.Literals(["running", "completed", "error"]), + input: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)), + }), +) + +export type ExecuteToolCall = Option.Option.Value> + +// Code Mode streams the tools a script calls through metadata rather than child tool parts. +export function executeToolCalls(metadata: Record): ExecuteToolCall[] { const calls = metadata.toolCalls - return ( - metadata.error === true || - (Array.isArray(calls) && - calls.some( - (call) => - call !== null && - typeof call === "object" && - !Array.isArray(call) && - "status" in call && - call.status === "error", - )) - ) + if (!Array.isArray(calls)) return [] + + return calls.flatMap((call) => Option.toArray(decodeExecuteCall(call))) +} + +export function executeToolCallArgs(call: ExecuteToolCall) { + return Object.entries(call.input ?? {}) + .filter(([, value]) => typeof value === "string" || typeof value === "number" || typeof value === "boolean") + .map(([key, value]) => `${key}=${String(value).replace(/\s+/g, " ")}`) +} + +// Collapsed rows name the failed call, or else the latest one. +export function executeToolSubtitle(calls: readonly ExecuteToolCall[]) { + const call = calls.find((item) => item.status === "error") ?? calls.at(-1) + + if (!call) return undefined + const args = executeToolCallArgs(call) + + return args.length ? `${call.tool} [${args.join(", ")}]` : call.tool } export function currentToolHasLoadedFiles(tool: SessionMessageAssistantTool) { diff --git a/packages/session-ui/src/storybook/current-session-fixtures.ts b/packages/session-ui/src/storybook/current-session-fixtures.ts index 469cd38c36d3..db602161a69b 100644 --- a/packages/session-ui/src/storybook/current-session-fixtures.ts +++ b/packages/session-ui/src/storybook/current-session-fixtures.ts @@ -544,9 +544,23 @@ export const executeCodeDocument = document([ name: "execute", offset: 52_300, args: { - code: 'const greeting = "Code Mode execute completed"\nreturn { greeting, timestamp: new Date().toISOString() }', + code: 'const tab = await tools.browser.tabs.open({ url: "http://localhost:4399" })\nconst usage = await tools.opencode_console.get_usage({ range: "24h" })\nreturn { tab: tab.id, cost: usage.cost_usd }', }, - output: '{\n "greeting": "Code Mode execute completed",\n "timestamp": "2026-08-17T09:01:43.590Z"\n}', + output: '{\n "tab": "tab_4f1c",\n "cost": 0.42\n}', + metadata: { + toolCalls: [ + { tool: "browser.tabs.open", status: "completed", input: { url: "http://localhost:4399" } }, + { tool: "opencode_console.get_usage", status: "completed", input: { range: "24h" } }, + ], + }, + }), + completedTool({ + id: "tool_execute_followup", + name: "execute", + offset: 52_600, + args: { code: "return await tools.browser.tabs.list()" }, + output: "[]", + metadata: { toolCalls: [{ tool: "browser.tabs.list", status: "completed" }] }, }), ], }), diff --git a/packages/session-ui/src/timeline/session-timeline-row.tsx b/packages/session-ui/src/timeline/session-timeline-row.tsx index 8dd9c0a87187..901c6bd22be4 100644 --- a/packages/session-ui/src/timeline/session-timeline-row.tsx +++ b/packages/session-ui/src/timeline/session-timeline-row.tsx @@ -252,7 +252,7 @@ export function createSessionTimelineRowRenderer(input: { } reasoningOpen={(id) => input.disclosure.value(id)} onReasoningOpenChange={(id, open) => input.disclosure.set(id, open)} - toolDefaultOpen={(tool) => (input.timelineDetail ? contentDefaultOpen(tool) : false)} + toolDefaultOpen={(tool) => (input.timelineDetail || tool.name === "execute" ? contentDefaultOpen(tool) : false)} toolOpen={(id) => input.disclosure.value(`${row().group.key}:tool:${id}`)} onToolOpenChange={(id, open) => input.disclosure.set(`${row().group.key}:tool:${id}`, open)} fileOpen={(path) => @@ -391,6 +391,8 @@ export function createSessionTimelineRowRenderer(input: { } function contentDefaultOpen(item: SessionMessageAssistant["content"][number]) { + if (item.type === "tool" && item.name === "execute") return true + if (input.timelineDetail) { const category = timelineCategory(item) diff --git a/packages/session-ui/src/timeline/terminal-work.stories.tsx b/packages/session-ui/src/timeline/terminal-work.stories.tsx index 3eb2223ca25c..a67fdeb4dcd7 100644 --- a/packages/session-ui/src/timeline/terminal-work.stories.tsx +++ b/packages/session-ui/src/timeline/terminal-work.stories.tsx @@ -184,7 +184,7 @@ export const ExecuteCode = { render: () => ( ( + + ), +} + export const ExecuteFailed = { render: () => ( + error?: string // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- see SAFETY above metadata: Record tool: string @@ -1370,7 +1376,7 @@ export function ToolDisplay( }) const errorSubtitle = createMemo(() => toolErrorSubtitle(props, i18n)) - const error = createMemo(() => toolDisplayError(props, i18n.t("ui.toolErrorCard.failed"))) + const error = createMemo(() => toolDisplayError(props)) const render = createMemo(() => ToolRegistry.render(props.tool) ?? GenericTool) return ( @@ -1436,8 +1442,6 @@ function toolErrorSubtitle(props: ToolProps, i18n: UiI18n) { if (props.tool === "shell") return input.command || metadata.command || undefined - if (props.tool === "execute") return input.code || undefined - if (props.tool === "read" || props.tool === "edit" || props.tool === "write") return getFilename(input.path ?? "") if (props.tool === "list" || props.tool === "glob" || props.tool === "grep") @@ -1468,14 +1472,13 @@ function toolErrorSubtitle(props: ToolProps, i18n: UiI18n) { return undefined } -function toolDisplayError(props: ToolProps & { error?: string }, fallback: string) { +function toolDisplayError(props: ToolProps & { error?: string }) { + // Code Mode failures render inline in the execution's call list. + if (props.tool === "execute") return undefined + if (props.status === "error") return props.error - if (props.tool !== "execute") return undefined - - if (!executeToolFailed(props.metadata)) return undefined - - return props.output || fallback + return undefined } ToolRegistry.register({ @@ -1923,17 +1926,46 @@ ToolRegistry.register({ name: "execute", render(props) { const i18n = useI18n() + const dialog = useDialog() const pending = () => props.status === "streaming" || props.status === "running" - const code = createMemo(() => toolInput(props.input).code ?? "") - const output = () => stripAnsi(props.output ?? "").replace(/\r\n?/g, "\n") + const calls = createMemo(() => executeToolCalls(props.metadata)) + const subtitle = createMemo(() => executeToolSubtitle(calls())) + const code = createMemo(() => (toolInput(props.input).code ?? "").trimEnd()) + + // Like the TUI, only a runtime failure shows its output; a failed nested call is marked on its row. + const error = createMemo(() => { + if (props.status !== "error" && props.metadata.error !== true) return undefined + const fallback = i18n.t("ui.toolErrorCard.failed") + const text = stripAnsi((props.status === "error" ? props.error : undefined) || props.output || fallback) + + return text.replace(/^Error:\s*/, "").trim() || fallback + }) + + // A runtime failure belongs to the call that raised it; scripts can also fail outside any call. + const owner = createMemo(() => calls().findLastIndex((call) => call.status === "error")) + const sawPending = pending() + // The script is complete once the call leaves streaming, so the dialog can show it while it runs. + const viewable = () => props.status !== "streaming" && !!code() + + const openDetails = () => + dialog.show(() => ( + + )) + return ( 0 || !!error()} compact allowOpenWhilePending trigger={(open) => ( @@ -1942,22 +1974,230 @@ ToolRegistry.register({ - - - + {(text) => }
)} + action={ + viewable() ? ( + + } + size="normal" + variant="ghost" + aria-label={i18n.t("ui.tool.execute.viewCode")} + aria-haspopup="dialog" + onClick={openDetails} + /> + + ) : undefined + } > - - {code()} - {(value) => {value()}} - +
+ + {(call, index) => } + + {(text) => } +
) }, }) +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 lines = (text: string) => i18n.plural("ui.tool.execute.lines", text.split("\n").length) + + return ( + + +
+ {i18n.t("ui.tool.execute")} + + {props.error + ? i18n.t("ui.toolErrorCard.failed") + : props.status === "running" + ? i18n.t("ui.tool.execute.running") + : i18n.t("ui.tool.execute.completed")} + + {i18n.plural("ui.tool.execute.calls", props.calls)} +
+
+ +
+ + + + + {(output) => ( + + + + )} + + } + > + {(error) => ( + +
{error()}
+
+ )} + +
+
+
+ ) +} + +function ExecuteDetailsSection(props: { + label: string + meta?: string + copy: string + copyLabel: string + children: JSX.Element +}) { + const i18n = useI18n() + const [copied, setCopied] = createSignal(false) + + const copy = async () => { + if (!(await writeClipboard(props.copy))) return + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } + + return ( +
+
+ {props.label} + {(meta) => {meta()}} + + } + size="normal" + variant="ghost-muted" + aria-label={copied() ? i18n.t("ui.message.copied") : props.copyLabel} + onClick={copy} + /> + +
+
{props.children}
+
+ ) +} + +function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) { + const [open, setOpen] = createSignal(false) + const args = createMemo(() => (props.call ? executeToolCallArgs(props.call) : [])) + const input = createMemo(() => Object.entries(props.call?.input ?? {})) + const failed = () => !props.call || props.call.status === "error" + const expandable = () => input().length > 0 || !!props.error + const summary = () => (props.call ? args().join(", ") : props.error?.split("\n", 1)[0]) + + const toggle = () => { + if (!expandable() || window.getSelection()?.toString()) return + setOpen((value) => !value) + } + + return ( +
+
{ + if (event.key !== "Enter" && event.key !== " ") return + event.preventDefault() + toggle() + }} + > + ›}> + + + + + + {(call) => ( + + + + )} + + + {(text) => ( + + {props.call ? `[${text()}]` : text()} + + )} + + + › + +
+ + 0}> +
+ + {([key, value]) => ( +
+
{key}:
+
{typeof value === "string" ? value : JSON.stringify(value, null, 2)}
+
+ )} +
+
+
+ + {(error) => ( +
+ {error()} +
+ )} +
+
+
+ ) +} + ToolRegistry.register({ name: "shell", render(props) { diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index 8264c01c778d..ef90500ee82d 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -209,6 +209,18 @@ const source = { "ui.tool.shell.timeout": "Command timed out", "ui.tool.shell.cancelled": "Command cancelled", "ui.tool.execute": "Execute", + "ui.tool.execute.viewCode": "View code", + "ui.tool.execute.code": "Code", + "ui.tool.execute.output": "Output", + "ui.tool.execute.error": "Error", + "ui.tool.execute.copyCode": "Copy code", + "ui.tool.execute.copyOutput": "Copy output", + "ui.tool.execute.running": "Running", + "ui.tool.execute.completed": "Completed", + "ui.tool.execute.calls.one": "{{count}} call", + "ui.tool.execute.calls.other": "{{count}} calls", + "ui.tool.execute.lines.one": "{{count}} line", + "ui.tool.execute.lines.other": "{{count}} lines", "ui.tool.patch": "Patch", "ui.tool.questions": "Questions", "ui.tool.questions.numbered": "Questions {{number}}",