mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 02:22:44 +00:00
feat(session-ui): list Code Mode tool calls in execute rows (#55649)
This commit is contained in:
parent
8ba78414d2
commit
52c2594aae
10 changed files with 658 additions and 46 deletions
|
|
@ -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)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
>
|
||||
<Show
|
||||
when={!props.locked && (props.triggerAsLink || props.triggerHref)}
|
||||
|
|
@ -340,6 +343,7 @@ export function BasicTool(props: BasicToolProps) {
|
|||
{trigger()}
|
||||
</Collapsible.Trigger>
|
||||
</Show>
|
||||
<Show when={props.action}>{(action) => <span data-slot="basic-tool-action">{action()}</span>}</Show>
|
||||
<Show when={props.animated && hasChildren() && !props.hideDetails}>
|
||||
<div
|
||||
ref={contentRef}
|
||||
|
|
|
|||
|
|
@ -562,6 +562,206 @@
|
|||
justify-content: center;
|
||||
}
|
||||
|
||||
[data-component="execute-tool-calls"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
font-family: var(--v2-font-family-code);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
line-height: var(--line-height-base);
|
||||
letter-spacing: -0.04px;
|
||||
color: var(--v2-text-text-muted);
|
||||
|
||||
[data-slot="execute-tool-call"] {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-marker"] {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
flex-shrink: 0;
|
||||
color: var(--v2-text-text-faint);
|
||||
|
||||
/* Centre on the lowercase code text rather than its line box. */
|
||||
[data-slot="icon-svg"] {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-name"] {
|
||||
flex-shrink: 0;
|
||||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-args"] {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call"][role="button"] {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover [data-slot="execute-tool-call-name"],
|
||||
&:hover [data-slot="execute-tool-call-args"] {
|
||||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 1px solid var(--v2-text-text-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-input"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
margin: 4px 0 2px 4px;
|
||||
padding-inline-start: 13px;
|
||||
border-inline-start: 0.5px solid var(--v2-border-border-base);
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-input-entry"] {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
|
||||
dt {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
color: var(--v2-text-text-base);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-arrow"] {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
color: var(--v2-text-text-faint);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call"][aria-expanded="true"] [data-slot="execute-tool-call-arrow"] {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call"][data-status="error"] [data-slot="execute-tool-call-marker"],
|
||||
[data-slot="execute-tool-error"] {
|
||||
color: var(--v2-state-fg-danger);
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-error"] {
|
||||
margin-top: 4px;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
padding-inline-start: 20px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-marker"] [data-slot="icon-svg"] {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
[data-slot="execute-details-title"] {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
|
||||
[data-slot="execute-details-status"] {
|
||||
padding: 0 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
line-height: var(--line-height-base);
|
||||
color: var(--v2-text-text-muted);
|
||||
background: var(--v2-background-bg-layer-02);
|
||||
}
|
||||
|
||||
[data-slot="execute-details-status"][data-status="error"] {
|
||||
color: var(--v2-state-fg-danger);
|
||||
}
|
||||
|
||||
[data-slot="execute-details-meta"] {
|
||||
font-size: 12px;
|
||||
color: var(--v2-text-text-faint);
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="execute-details"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0 16px 16px;
|
||||
|
||||
[data-slot="execute-details-section"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
[data-slot="execute-details-section-header"] {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 24px;
|
||||
|
||||
> :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;
|
||||
|
|
|
|||
|
|
@ -51,20 +51,42 @@ export function shellResultFailed(metadata: Record<string, unknown>) {
|
|||
|
||||
export function executeToolFailed(metadata: Record<string, unknown>) {
|
||||
// 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<ReturnType<typeof decodeExecuteCall>>
|
||||
|
||||
// Code Mode streams the tools a script calls through metadata rather than child tool parts.
|
||||
export function executeToolCalls(metadata: Record<string, unknown>): 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) {
|
||||
|
|
|
|||
|
|
@ -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" }] },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -184,7 +184,7 @@ export const ExecuteCode = {
|
|||
render: () => (
|
||||
<CurrentSessionTimelineStory
|
||||
title="Execute code"
|
||||
description="A Code Mode execution shares the shell treatment: the code and its result split into a two-tone card."
|
||||
description="Each Code Mode execution lists the tools its script called."
|
||||
document={executeCodeDocument}
|
||||
width="786px"
|
||||
shellToolDefaultOpen
|
||||
|
|
@ -192,18 +192,29 @@ export const ExecuteCode = {
|
|||
),
|
||||
}
|
||||
|
||||
export const ExecuteGrouped = {
|
||||
render: () => (
|
||||
<CurrentSessionTimelineStory
|
||||
title="Execute grouped"
|
||||
description="Executions inside a tool group open by default to the tools their scripts called."
|
||||
document={executeCodeDocument}
|
||||
width="786px"
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const ExecuteFailed = {
|
||||
render: () => (
|
||||
<CurrentSessionTimelineStory
|
||||
title="Execute failed"
|
||||
description="Failed Code Mode executions open to show the full code and the full error message."
|
||||
description="Failed Code Mode executions mark the failed call, which expands to show its input and the full error message."
|
||||
document={storyDocument([
|
||||
storyTool(
|
||||
"tool_execute_search",
|
||||
"execute",
|
||||
"completed",
|
||||
{ code: 'const found = search({ namespace: "browser", offset: 20, limit: 30 });\nreturn found;\n' },
|
||||
{ output: "[]" },
|
||||
{ output: "[]", metadata: { toolCalls: [] } },
|
||||
),
|
||||
storyTool(
|
||||
"tool_execute_failed_url",
|
||||
|
|
@ -215,7 +226,16 @@ export const ExecuteFailed = {
|
|||
{
|
||||
output:
|
||||
"Invalid browser URL. Use an HTTP/HTTPS URL or about:blank without embedded credentials. Paths and file:// URLs are not browser URLs; use browser.preview to show a local file to the user. The connected server must be able to reach the address; localhost refers to that server.",
|
||||
metadata: { error: true },
|
||||
metadata: {
|
||||
error: true,
|
||||
toolCalls: [
|
||||
{
|
||||
tool: "browser.tabs.open",
|
||||
status: "error",
|
||||
input: { url: "file:///C:/tmp/opencode/throne-of-glass-luke.html", focus: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
{
|
||||
|
|
@ -243,7 +263,22 @@ export const ExecuteFailed = {
|
|||
{
|
||||
output:
|
||||
"[browser.operation_failed] browser.screenshot failed. Screenshot needs a visible tab. Call browser.tabs.focus and keep its desktop window visible.",
|
||||
metadata: { error: true },
|
||||
metadata: {
|
||||
error: true,
|
||||
toolCalls: [
|
||||
{
|
||||
tool: "browser.tabs.open",
|
||||
status: "completed",
|
||||
input: { url: "http://localhost:4399", focus: true },
|
||||
},
|
||||
{
|
||||
tool: "browser.wait",
|
||||
status: "completed",
|
||||
input: { tabID: "tab_4f1c", condition: "load", timeoutMs: 5000 },
|
||||
},
|
||||
{ tool: "browser.screenshot", status: "error", input: { tabID: "tab_4f1c", fullPage: true } },
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
storyTool(
|
||||
|
|
@ -251,7 +286,7 @@ export const ExecuteFailed = {
|
|||
"execute",
|
||||
"completed",
|
||||
{ code: "const list = await tools.browser.tabs.list();\nreturn list;\n" },
|
||||
{ output: "[]" },
|
||||
{ output: "[]", metadata: { toolCalls: [{ tool: "browser.tabs.list", status: "completed" }] } },
|
||||
),
|
||||
])}
|
||||
width="786px"
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ import { useMarkdown } from "../context/markdown"
|
|||
import { getDirectory, getFilename } from "@opencode/util/path"
|
||||
import { checksum } from "@opencode/util/encode"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { Dialog, DialogBody, DialogHeader, DialogTitle } from "@opencode/ui/dialog"
|
||||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
import { TextShimmer } from "@opencode/ui/text-shimmer"
|
||||
import { AnimatedNumber } from "@opencode/ui/animated-number"
|
||||
|
|
@ -55,8 +57,11 @@ import {
|
|||
currentToolInput,
|
||||
currentToolMetadata,
|
||||
currentToolOutput,
|
||||
executeToolFailed,
|
||||
executeToolCallArgs,
|
||||
executeToolCalls,
|
||||
executeToolSubtitle,
|
||||
readImagePath,
|
||||
type ExecuteToolCall,
|
||||
} from "../message/current-tool-state"
|
||||
import { AssistantReasoningContent, writeClipboard } from "../message/message-content"
|
||||
import { followShellOutput } from "./shell-output"
|
||||
|
|
@ -1125,6 +1130,7 @@ function currentContextToolTrigger(tool: SessionMessageAssistantTool, i18n: Retu
|
|||
export interface ToolProps {
|
||||
// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- see SAFETY above
|
||||
input: Record<string, unknown>
|
||||
error?: string
|
||||
// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- see SAFETY above
|
||||
metadata: Record<string, unknown>
|
||||
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(() => (
|
||||
<ExecuteDetails
|
||||
code={code()}
|
||||
output={stripAnsi(props.output ?? "").replace(/\r\n?/g, "\n").trim()}
|
||||
error={error()}
|
||||
calls={calls().length}
|
||||
status={props.status}
|
||||
/>
|
||||
))
|
||||
|
||||
return (
|
||||
<BasicTool
|
||||
{...props}
|
||||
icon="console"
|
||||
rail={false}
|
||||
hasContent
|
||||
hasContent={calls().length > 0 || !!error()}
|
||||
compact
|
||||
allowOpenWhilePending
|
||||
trigger={(open) => (
|
||||
|
|
@ -1942,22 +1974,230 @@ ToolRegistry.register({
|
|||
<span data-slot="basic-tool-tool-title">
|
||||
<TextShimmer text={i18n.t("ui.tool.execute")} active={pending()} />
|
||||
</span>
|
||||
<Show when={!open() && code()}>
|
||||
<ShellSubmessage text={code().split("\n", 1)[0]} animate={sawPending} />
|
||||
</Show>
|
||||
<Show when={!open() && subtitle()}>{(text) => <ShellSubmessage text={text()} animate={sawPending} />}</Show>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
action={
|
||||
viewable() ? (
|
||||
<Tooltip value={i18n.t("ui.tool.execute.viewCode")} placement="top">
|
||||
<IconButton
|
||||
icon={<Icon name="code-slash" size="small" />}
|
||||
size="normal"
|
||||
variant="ghost"
|
||||
aria-label={i18n.t("ui.tool.execute.viewCode")}
|
||||
aria-haspopup="dialog"
|
||||
onClick={openDetails}
|
||||
/>
|
||||
</Tooltip>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<ConsoleOutput copy={code()} variant="shell">
|
||||
<span data-slot="bash-command">{code()}</span>
|
||||
<Show when={output()}>{(value) => <span data-slot="bash-result">{value()}</span>}</Show>
|
||||
</ConsoleOutput>
|
||||
<div data-component="execute-tool-calls">
|
||||
<Index each={calls()}>
|
||||
{(call, index) => <ExecuteCallRow call={call()} error={index === owner() ? error() : undefined} />}
|
||||
</Index>
|
||||
<Show when={owner() === -1 && error()}>{(text) => <ExecuteCallRow error={text()} />}</Show>
|
||||
</div>
|
||||
</BasicTool>
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
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 (
|
||||
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),720px)] max-h-[calc(100vh_-_92px)]">
|
||||
<DialogHeader>
|
||||
<div data-slot="execute-details-title">
|
||||
<DialogTitle>{i18n.t("ui.tool.execute")}</DialogTitle>
|
||||
<span data-slot="execute-details-status" data-status={props.error ? "error" : props.status}>
|
||||
{props.error
|
||||
? i18n.t("ui.toolErrorCard.failed")
|
||||
: props.status === "running"
|
||||
? i18n.t("ui.tool.execute.running")
|
||||
: i18n.t("ui.tool.execute.completed")}
|
||||
</span>
|
||||
<span data-slot="execute-details-meta">{i18n.plural("ui.tool.execute.calls", props.calls)}</span>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<DialogBody class="min-h-0 flex-none overflow-y-auto">
|
||||
<div data-component="execute-details">
|
||||
<ExecuteDetailsSection
|
||||
label={i18n.t("ui.tool.execute.code")}
|
||||
meta={lines(props.code)}
|
||||
copy={props.code}
|
||||
copyLabel={i18n.t("ui.tool.execute.copyCode")}
|
||||
>
|
||||
<Dynamic
|
||||
component={fileComponent}
|
||||
mode="text"
|
||||
file={{ name: "execute.js", contents: props.code, cacheKey: checksum(props.code) }}
|
||||
overflow="scroll"
|
||||
/>
|
||||
</ExecuteDetailsSection>
|
||||
<Show
|
||||
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="scroll"
|
||||
/>
|
||||
</ExecuteDetailsSection>
|
||||
)}
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
{(error) => (
|
||||
<ExecuteDetailsSection
|
||||
label={i18n.t("ui.tool.execute.error")}
|
||||
copy={error()}
|
||||
copyLabel={i18n.t("ui.toolErrorCard.copyError")}
|
||||
>
|
||||
<pre data-slot="execute-details-error">{error()}</pre>
|
||||
</ExecuteDetailsSection>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</DialogBody>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<section data-slot="execute-details-section">
|
||||
<header data-slot="execute-details-section-header">
|
||||
<span data-slot="execute-details-section-label">{props.label}</span>
|
||||
<Show when={props.meta}>{(meta) => <span data-slot="execute-details-section-meta">{meta()}</span>}</Show>
|
||||
<Tooltip value={copied() ? i18n.t("ui.message.copied") : props.copyLabel} placement="top">
|
||||
<IconButton
|
||||
icon={<Icon name={copied() ? "check" : "outline-copy"} size="small" />}
|
||||
size="normal"
|
||||
variant="ghost-muted"
|
||||
aria-label={copied() ? i18n.t("ui.message.copied") : props.copyLabel}
|
||||
onClick={copy}
|
||||
/>
|
||||
</Tooltip>
|
||||
</header>
|
||||
<div data-slot="execute-details-source">{props.children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div data-slot="execute-tool-call-item">
|
||||
<div
|
||||
data-slot="execute-tool-call"
|
||||
data-status={failed() ? "error" : props.call?.status}
|
||||
data-expanded={open() ? "true" : undefined}
|
||||
dir="ltr"
|
||||
role={expandable() ? "button" : undefined}
|
||||
tabIndex={expandable() ? 0 : undefined}
|
||||
aria-expanded={expandable() ? open() : undefined}
|
||||
onClick={toggle}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return
|
||||
event.preventDefault()
|
||||
toggle()
|
||||
}}
|
||||
>
|
||||
<Show when={failed()} fallback={<span data-slot="execute-tool-call-marker">›</span>}>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<Icon name="outline-hexagonal-warning" size="small" />
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={props.call}>
|
||||
{(call) => (
|
||||
<span data-slot="execute-tool-call-name">
|
||||
<TextShimmer text={call().tool} active={call().status === "running"} />
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={!open() && summary()}>
|
||||
{(text) => (
|
||||
<span data-slot="execute-tool-call-args" title={text()}>
|
||||
{props.call ? `[${text()}]` : text()}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={props.error}>
|
||||
<span data-slot="execute-tool-call-arrow">›</span>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={open()}>
|
||||
<Show when={input().length > 0}>
|
||||
<dl data-slot="execute-tool-call-input" dir="ltr">
|
||||
<For each={input()}>
|
||||
{([key, value]) => (
|
||||
<div data-slot="execute-tool-call-input-entry">
|
||||
<dt>{key}:</dt>
|
||||
<dd>{typeof value === "string" ? value : JSON.stringify(value, null, 2)}</dd>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</dl>
|
||||
</Show>
|
||||
<Show when={props.error}>
|
||||
{(error) => (
|
||||
<div data-slot="execute-tool-error" dir="ltr">
|
||||
{error()}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
ToolRegistry.register({
|
||||
name: "shell",
|
||||
render(props) {
|
||||
|
|
|
|||
|
|
@ -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}}",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue