From d84e1d7bb3711ffdd54494950c4af644155cb542 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:44:34 -0600 Subject: [PATCH] fix(session-ui): open a group of long Code Mode scripts without freezing the timeline (#65696) --- packages/app/perf/README.md | 2 +- packages/app/perf/fixtures/scripts.ts | 37 ++++++++++++ packages/app/perf/fixtures/timeline.ts | 6 +- packages/app/perf/timeline.bench.ts | 47 +++++++++++++-- .../session-tool-projection.spec.ts | 17 ++++++ .../session-ui/src/components/markdown.css | 9 ++- .../src/components/message-part.css | 20 +++++++ .../src/message/current-tool-state.ts | 38 +++++++++--- .../src/storybook/current-session-fixtures.ts | 28 +++++++++ .../src/timeline/terminal-work.stories.tsx | 13 ++++ .../session-ui/src/tools/tool-renderer.tsx | 59 +++++++++++++++---- packages/ui/src/components/collapsible.tsx | 21 +++++-- 12 files changed, 264 insertions(+), 33 deletions(-) create mode 100644 packages/app/perf/fixtures/scripts.ts diff --git a/packages/app/perf/README.md b/packages/app/perf/README.md index 7e5b5232cd9..1ec2bbf6db2 100644 --- a/packages/app/perf/README.md +++ b/packages/app/perf/README.md @@ -7,7 +7,7 @@ build on the e2e mock server, so they need no backend. | File | Cases | Workload | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. | +| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · open a group of scripts · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. | | `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · with Find open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. | | `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. | | `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home, scroll) | The stress fixture, paginated, from a fresh document every run. | diff --git a/packages/app/perf/fixtures/scripts.ts b/packages/app/perf/fixtures/scripts.ts new file mode 100644 index 00000000000..8cd9921c1e2 --- /dev/null +++ b/packages/app/perf/fixtures/scripts.ts @@ -0,0 +1,37 @@ +import type { SessionMessageAssistant } from "@opencode/client/promise" + +// How many calls each of 46 Code Mode scripts made in one turn of a real audit session: most made a few, six walked a +// source tree file by file. 19,039 calls in all. +const calls = [ + 1, 3, 6965, 1, 1, 2, 1, 1, 3, 1, 1592, 4, 1, 377, 2, 1893, 2, 7, 2, 1, 1, 3, 3906, 3, 2004, 2, 1, 8, 1, 0, 2, 1, 1, 1, + 1, 2, 1, 4, 2, 86, 2, 1, 3, 2138, 3, 2, +] + +/** The turn's scripts, completed, each listing the files it read through `Bun.file`. */ +export function scriptTools(): SessionMessageAssistant["content"] { + return calls.map((count, script) => ({ + type: "tool", + id: `prt_script_${String(script).padStart(2, "0")}`, + name: "execute", + time: { + created: 1700000001000 + script * 1_000, + ran: 1700000001000 + script * 1_000, + completed: 1700000001500 + script * 1_000, + }, + state: { + status: "completed", + input: { code: `const files = await Array.fromAsync(new Bun.Glob("**/*.ts").scan(root))\nreturn files.length` }, + content: [{ type: "text", text: `${count} files` }], + metadata: { + toolCalls: Array.from({ length: count }, (_, call) => ({ + tool: "Bun", + status: "completed", + input: { + method: "file", + path: `C:/OpenCode/TimelineStateRegression/packages/app/src/module-${script}-${call}.ts`, + }, + })), + }, + }, + })) +} diff --git a/packages/app/perf/fixtures/timeline.ts b/packages/app/perf/fixtures/timeline.ts index 55f4aa8802b..d89362f28fb 100644 --- a/packages/app/perf/fixtures/timeline.ts +++ b/packages/app/perf/fixtures/timeline.ts @@ -72,6 +72,8 @@ type TimelineOptions = { vcsDiff?: unknown[] /** Edits listed one per file and collapsed, each file opening on its own (by default they start open). */ collapsedEdits?: boolean + /** The app's default timeline detail (Compact), which folds a turn's calls into one group. */ + compact?: boolean /** The last assistant turn's tool parts, in place of its one small edit. */ tools?: SessionMessageAssistant["content"] /** Events arrive from a real SSE endpoint (`source`); otherwise the mock's own stream stays idle. */ @@ -140,7 +142,9 @@ export async function mockTimelineSession(page: Page, options: TimelineOptions) showReasoningSummaries: true, timelineDetail: options.collapsedEdits ? { ...timelinePresets[2].value, edit: { placement: "separate", details: "collapsed" } } - : undefined, + : options.compact + ? timelinePresets[2].value + : undefined, }) return { path: `/server/${base64Encode(options.server)}/session/${sessionID}`, source } diff --git a/packages/app/perf/timeline.bench.ts b/packages/app/perf/timeline.bench.ts index ee71ef6ca2f..fff32f5e632 100644 --- a/packages/app/perf/timeline.bench.ts +++ b/packages/app/perf/timeline.bench.ts @@ -1,9 +1,11 @@ // One long session (120 turns of markdown, code fences, tool calls and diffs) at normal speed. import { bench, web } from "@hona/strobe" +import { Match } from "effect" import { editTools, reviewDiffs } from "./fixtures/diffs" import { dragDivider, measureDivider, type Divider } from "./fixtures/drag" import { cached } from "./fixtures/mock" import { openReview } from "./fixtures/review" +import { scriptTools } from "./fixtures/scripts" import { composer, mockTimelineSession, oldestPrompt, timeline } from "./fixtures/timeline" const find = '[data-component="timeline-search-bar"] input' @@ -17,6 +19,14 @@ const diff = '[data-component="apply-patch-file-diff"] diffs-container >>> [data const drag = "drag the review's edge" +const scripts = "open a group of scripts" + +// The turn's one group of scripts, and the calls its scripts list once open. +const group = + '[data-component="collapsed-tool-group"] > [data-component="collapsible"] > [data-slot="collapsible-trigger"]' + +const groupList = '[data-component="collapsed-tool-group"] [data-component="execute-tool-calls"]' + // The divider between the session and the side panel, read once the review is open. The session panel keeps at least // 400px, the side panel 320px and the 8px gap. const handle = '[data-slot="session-chat-panel"] > div > [data-component="resize-handle"]' @@ -24,9 +34,16 @@ const handle = '[data-slot="session-chat-panel"] > div > [data-component="resize let divider: Divider | undefined export default bench({ - // The session a case's launch loads: the edits alone, the history beside the review, or the history. Cases with the - // same one share a launch. - setupKey: (ctx) => (ctx.case === "expand an edit" ? "edits" : ctx.case === drag ? "review" : "history"), + // The session a case's launch loads: the edits alone, the scripts alone, the history beside the review, or the history. + // Cases with the same one share a launch. + setupKey: (ctx) => + ctx.case === "expand an edit" + ? "edits" + : ctx.case === scripts + ? "scripts" + : ctx.case === drag + ? "review" + : "history", targets: { web: web({ @@ -36,9 +53,14 @@ export default bench({ mockTimelineSession(cached(ctx), { server: new URL(ctx.url).origin, // The edits alone, so the case measures the diff, not the history around it. - historyTurns: ctx.setupKey === "edits" ? 0 : 120, + historyTurns: ctx.setupKey === "edits" || ctx.setupKey === "scripts" ? 0 : 120, collapsedEdits: ctx.setupKey === "edits", - tools: ctx.setupKey === "edits" ? await editTools() : undefined, + compact: ctx.setupKey === "scripts", + tools: await Match.value(ctx.setupKey).pipe( + Match.when("edits", () => editTools()), + Match.when("scripts", async () => scriptTools()), + Match.orElse(async () => undefined), + ), vcsDiff: ctx.setupKey === "review" ? reviewDiffs() : undefined, }), url: ({ prepared }) => prepared.path, @@ -116,6 +138,21 @@ export default bench({ }, }, + // 46 Code Mode scripts of one turn folded into one group, six of which read a source tree file by file: 19,039 calls + // in all. Opening the group opens each script, as the default timeline detail does. + [scripts]: { + primary: "main.work", + metrics: ["interaction.p50", "run.duration", "main.style", "main.layout", "main.script"], + async run({ page }) { + await page.click(group, { until: groupList }) + await page.idle() + }, + async reset({ page }) { + await page.click(group) + await page.idle() + }, + }, + // The divider beside the review (72 changed files) held for five seconds and dragged as a hand does, a pointer // move every display frame: a slow stretch toward the session, jiggles, a fast throw toward the review and a slow // pull back (fixtures/drag.ts). The timeline narrows and widens on every frame, so the rows in view rewrap; each 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 c097c086795..297453a837e 100644 --- a/packages/session-ui/component-tests/session-tool-projection.spec.ts +++ b/packages/session-ui/component-tests/session-tool-projection.spec.ts @@ -252,6 +252,23 @@ story("keeps long execute calls inside the tool and shows the script output", as expect(overflow).toBeLessThanOrEqual(0) }) +story("lists a long script's latest calls and reveals earlier ones on request", async ({ mount }) => { + const timeline = await mount("current-session-terminal-work--execute-many-calls") + const tool = timeline.locator('[data-timeline-part-id="tool_execute_many_calls"]') + const rows = tool.locator('[data-slot="execute-tool-call"]:not([data-kind="output"])') + await expect(rows).toHaveCount(10) + await expect(rows.first()).toContainText("module-65.ts") + + await tool.getByRole("button", { name: "+65 more" }).click() + await expect(rows).toHaveCount(60) + + // The last reveal removes the button, so focus moves on to the first call instead of the page. + await tool.getByRole("button", { name: "+15 more" }).press("Enter") + await expect(rows).toHaveCount(75) + await expect(rows.first()).toContainText("module-0.ts") + await expect(rows.first()).toBeFocused() +}) + story("opens execute rows while a text field elsewhere keeps its selection", async ({ mount }) => { const timeline = await mount("current-session-terminal-work--execute-code") const rows = timeline.locator('[data-timeline-part-id="tool_execute_long_call"] [data-slot="execute-tool-call"]') diff --git a/packages/session-ui/src/components/markdown.css b/packages/session-ui/src/components/markdown.css index a0c4c209f74..45637ba9b1b 100644 --- a/packages/session-ui/src/components/markdown.css +++ b/packages/session-ui/src/components/markdown.css @@ -389,8 +389,13 @@ --markdown-code-background: var(--color-background-stronger); } - /* A completed block's highlighter paints its own background inline, which the shell colours don't override. */ - [data-component="markdown-code"][data-code-kind="shell"]:has(> pre:not([style*="background"])) { + /* A completed block's highlighter paints its own background inline, which the shell colours don't override. Matched + from the toolbar after the code rather than with :has(): a style attribute in a :has() argument makes Chromium + recheck every :has() above each element whose inline style changes, and the session timeline sets its rows' + positions inline, so each change restyled the whole timeline. */ + [data-component="markdown-code"][data-code-kind="shell"] + > pre:not([style*="background"]) + ~ [data-slot="markdown-code-toolbar"] { --markdown-code-background: var(--markdown-shell-code-background); } diff --git a/packages/session-ui/src/components/message-part.css b/packages/session-ui/src/components/message-part.css index bd9caa28184..4fcad244fe1 100644 --- a/packages/session-ui/src/components/message-part.css +++ b/packages/session-ui/src/components/message-part.css @@ -1066,6 +1066,26 @@ } } + /* Lines up with the calls' names, past their markers. */ + [data-slot="execute-tool-call-more"] { + all: unset; + width: fit-content; + margin-inline-start: 20px; + cursor: pointer; + color: var(--v2-text-text-faint); + user-select: none; + + &:hover { + color: var(--v2-text-text-base); + } + + &:focus-visible { + outline: 2px solid var(--v2-border-border-focus); + outline-offset: 2px; + border-radius: 4px; + } + } + [data-slot="execute-tool-call-input"] { 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 4322bedd657..af5015f5484 100644 --- a/packages/session-ui/src/message/current-tool-state.ts +++ b/packages/session-ui/src/message/current-tool-state.ts @@ -51,7 +51,7 @@ export function shellResultFailed(metadata: Schema.JsonObject) { } function executeToolFailed(metadata: Schema.JsonObject) { - return metadata.error === true || executeToolCalls(metadata).some((call) => call.status === "error") + return metadata.error === true || executeToolErrorIndex(metadata) >= 0 } const decodeExecuteCall = Schema.decodeUnknownOption( @@ -64,15 +64,35 @@ const decodeExecuteCall = Schema.decodeUnknownOption( 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: ToolProps["metadata"]): ExecuteToolCall[] { +// Code Mode streams the tools a script calls through metadata rather than child tool parts. A script can make thousands +// of calls, so readers count and search them as they are and decode only the calls they show. +function executeToolCallList(metadata: ToolProps["metadata"]): readonly unknown[] { const calls = metadata.toolCalls - if (!Array.isArray(calls)) return [] - - return calls.flatMap((call) => Option.toArray(decodeExecuteCall(call))) + return Array.isArray(calls) ? calls : [] } +export function executeToolCallCount(metadata: ToolProps["metadata"]) { + return executeToolCallList(metadata).length +} + +/** The position of the last call that failed, or -1. */ +export function executeToolErrorIndex(metadata: ToolProps["metadata"]) { + return executeToolCallList(metadata).findLastIndex(callFailed) +} + +/** The calls from `start` on, each with its position among all of them. */ +export function executeToolCalls(metadata: ToolProps["metadata"], start = 0) { + return executeToolCallList(metadata) + .slice(start) + .flatMap((call, offset) => + Option.toArray(decodeExecuteCall(call)).map((value) => ({ index: start + offset, call: value })), + ) +} + +// Matches only calls the rows can decode, so a failure is never counted on a call that shows nowhere. +const callFailed = Schema.is(Schema.Struct({ tool: Schema.String, status: Schema.Literal("error") })) + const isCallArg = Schema.is(Schema.Union([Schema.String, Schema.Number, Schema.Boolean])) export function executeToolCallArgs(call: ExecuteToolCall) { @@ -82,8 +102,10 @@ export function executeToolCallArgs(call: ExecuteToolCall) { } // 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) +export function executeToolSubtitle(metadata: ToolProps["metadata"]) { + const calls = executeToolCallList(metadata) + const failed = calls.findIndex(callFailed) + const call = Option.getOrUndefined(decodeExecuteCall(calls[failed >= 0 ? failed : calls.length - 1])) if (!call) return undefined const args = executeToolCallArgs(call) diff --git a/packages/session-ui/src/storybook/current-session-fixtures.ts b/packages/session-ui/src/storybook/current-session-fixtures.ts index 176e2ae2540..7f11ac9a184 100644 --- a/packages/session-ui/src/storybook/current-session-fixtures.ts +++ b/packages/session-ui/src/storybook/current-session-fixtures.ts @@ -589,6 +589,34 @@ export const executeCodeDocument = document([ }), ] satisfies SessionMessageInfo[]) +// A script that read a source tree file by file: its rows start at the latest calls. +export const executeManyCallsDocument = document([ + user("msg_user_execute_many", "Find every state machine in the app.", 52_100), + assistant({ + id: "msg_assistant_execute_many", + offset: 52_200, + completed: 52_900, + content: [ + completedTool({ + id: "tool_execute_many_calls", + name: "execute", + offset: 52_300, + args: { + code: 'const files = await Array.fromAsync(new Bun.Glob("src/**/*.ts").scan())\nreturn files.filter((file) => Bun.file(file).name?.endsWith("machine.ts")).length', + }, + output: "48", + metadata: { + toolCalls: Array.from({ length: 75 }, (_, index) => ({ + tool: "Bun", + status: "completed", + input: { method: "file", path: `src/session/module-${index}.ts` }, + })), + }, + }), + ], + }), +] satisfies SessionMessageInfo[]) + const executeWorktreeNames = [ "child-permission-sync", "frontmatter-flow-repair", diff --git a/packages/session-ui/src/timeline/terminal-work.stories.tsx b/packages/session-ui/src/timeline/terminal-work.stories.tsx index efd441b4783..60c20ec09ae 100644 --- a/packages/session-ui/src/timeline/terminal-work.stories.tsx +++ b/packages/session-ui/src/timeline/terminal-work.stories.tsx @@ -9,6 +9,7 @@ import { STORY_TIME, executeCodeDocument, executeLongDetailsDocument, + executeManyCallsDocument, expandedShellDocument, recoveryDocument, standaloneShellCompletedDocument, @@ -193,6 +194,18 @@ export const ExecuteCode = { ), } +export const ExecuteManyCalls = { + render: () => ( + + ), +} + export const ExecuteLongDetails = { render: () => ( props.status === "streaming" || props.status === "running" - const calls = createMemo(() => executeToolCalls(props.metadata)) - const subtitle = createMemo(() => executeToolSubtitle(calls())) + const count = createMemo(() => executeToolCallCount(props.metadata)) + const subtitle = createMemo(() => executeToolSubtitle(props.metadata)) const code = createMemo(() => (toolInput(props.input).code ?? "").trimEnd()) // A runtime failure shows its output on the failing row; a successful script shows its result below the calls. @@ -2122,16 +2123,32 @@ ToolRegistry.register({ ) // 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 owner = createMemo(() => executeToolErrorIndex(props.metadata)) + + // A script can make thousands of calls, and a row costs as much to style as a line of a diff, so the list shows the + // latest and reveals earlier ones on request. + const [shown, setShown] = createSignal(executeCallsShown) + const hidden = createMemo(() => Math.max(0, count() - shown())) + const visible = createMemo(() => executeToolCalls(props.metadata, hidden())) + + const reveal = (event: { currentTarget: HTMLElement }) => { + const list = event.currentTarget.parentElement + setShown((count) => count + executeCallsRevealed) + + // The button leaves with the last hidden call, so focus moves on to the first call rather than the page. + if (hidden() === 0) list?.querySelector('[data-slot="execute-tool-call"][tabindex]')?.focus() + } const sawPending = pending() + // A shimmer is six elements; a group opens dozens of finished scripts, so only one that ran while shown gets it. + const shimmered = createMemo((was: boolean) => was || pending(), false) // 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 ( @@ -2139,14 +2156,16 @@ ToolRegistry.register({ {...props} icon="terminal" rail={false} - hasContent={calls().length > 0 || !!error() || !!output()} + hasContent={count() > 0 || !!error() || !!output()} compact allowOpenWhilePending trigger={(open) => (
- + + + {(text) => } @@ -2170,10 +2189,18 @@ ToolRegistry.register({ } >
- - {(call, index) => } + + {(count) => ( + + )} + + + {(item) => } - {(text) => } + {/* A failure with no call, or one that belongs to a call still hidden above, shows on its own. */} + {(text) => } {(value) => }
@@ -2181,6 +2208,10 @@ ToolRegistry.register({ }, }) +const executeCallsShown = 10 + +const executeCallsRevealed = 50 + function ExecuteDetails(props: { code: string; output: string; error?: string; calls: number; status?: string }) { const i18n = useI18n() const fileComponent = useFileComponent() @@ -2358,6 +2389,8 @@ function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) { 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]) + // Only a call that ran while shown gets a shimmer, kept so it fades out when the call finishes. + const shimmered = createMemo((was: boolean) => was || props.call?.status === "running", false) const toggle = (event: { currentTarget: HTMLElement }) => { if (!expandable() || selectsRowText(event.currentTarget)) return @@ -2389,7 +2422,9 @@ function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) { {(call) => ( - + + + )} diff --git a/packages/ui/src/components/collapsible.tsx b/packages/ui/src/components/collapsible.tsx index 6eb8f838a0b..650158e03ba 100644 --- a/packages/ui/src/components/collapsible.tsx +++ b/packages/ui/src/components/collapsible.tsx @@ -1,5 +1,5 @@ -import { Collapsible as Kobalte, CollapsibleRootProps } from "@kobalte/core/collapsible" -import { ComponentProps, ParentProps, splitProps } from "solid-js" +import { Collapsible as Kobalte, CollapsibleRootProps, useCollapsibleContext } from "@kobalte/core/collapsible" +import { ComponentProps, createEffect, onCleanup, ParentProps, Show, splitProps } from "solid-js" import { Icon } from "@opencode/ui/icon" export interface CollapsibleProps extends ParentProps { @@ -28,8 +28,21 @@ function CollapsibleTrigger(props: ComponentProps) { return } -function CollapsibleContent(props: ComponentProps) { - return +// Kobalte's content reads its own animation and size each time it opens or closes so a CSS animation can play, which +// forces a style and layout pass per collapsible: a group of tool calls opening forced one for each tool in it. No +// collapsible here animates its content, so it mounts and unmounts with the open state. +function CollapsibleContent(props: ComponentProps<"div">) { + const context = useCollapsibleContext() + const [local, others] = splitProps(props, ["id"]) + const id = () => local.id ?? context.generateId("content") + + createEffect(() => onCleanup(context.registerContentId(id()))) + + return ( + +
+ + ) } function CollapsibleArrow(props?: ComponentProps<"div">) {