From a3d5923aca2b5e693817a5e8d118de7cf5217cd1 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 8 Sep 2026 19:12:15 +1000 Subject: [PATCH] fix(session-ui): stop refetching missing shell output (#47926) --- .../session-ui/src/tools/shell-output.test.ts | 128 ++++++++++++++++++ packages/session-ui/src/tools/shell-output.ts | 74 ++++++++++ .../session-ui/src/tools/tool-renderer.tsx | 31 +---- 3 files changed, 206 insertions(+), 27 deletions(-) create mode 100644 packages/session-ui/src/tools/shell-output.test.ts create mode 100644 packages/session-ui/src/tools/shell-output.ts diff --git a/packages/session-ui/src/tools/shell-output.test.ts b/packages/session-ui/src/tools/shell-output.test.ts new file mode 100644 index 00000000000..ba78ef41c9d --- /dev/null +++ b/packages/session-ui/src/tools/shell-output.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, test, vi } from "bun:test" +import type { ShellOutputInput, ShellOutputOutput } from "@opencode/client/promise" +import { followShellOutput, SHELL_OUTPUT_TAIL_BYTES } from "./shell-output" + +const location = { directory: "/repo", project: { id: "project", directory: "/repo", canonical: "/repo" } } + +// Serves the current text from the requested cursor, at most one page per request. +function server(text: () => string, page = Infinity) { + const cursors: number[] = [] + return { + cursors, + load: (input: ShellOutputInput): Promise => { + const cursor = input.cursor ?? 0 + cursors.push(cursor) + const full = text() + const output = full.slice(cursor, cursor + page) + return Promise.resolve({ + location, + data: { output, cursor: cursor + output.length, size: full.length, truncated: false }, + }) + }, + } +} + +// Reads settle within a few microtasks; timers are faked so this never waits on the clock. +async function flush() { + for (let i = 0; i < 20; i++) await Promise.resolve() +} + +describe("followShellOutput", () => { + test("stops polling a missing shell and never requests it again", async () => { + vi.useFakeTimers() + try { + const cursors: number[] = [] + const load = (input: ShellOutputInput): Promise => { + cursors.push(input.cursor ?? 0) + return Promise.reject({ _tag: "ShellNotFoundError", id: input.id, message: "Shell command not found" }) + } + const follow = () => + followShellOutput({ id: "shell_missing", directory: "/repo", running: true, load, onOutput() {} }) + + const stop = follow() + await flush() + expect(cursors).toEqual([0]) + + vi.advanceTimersByTime(10_000) + await flush() + expect(cursors).toEqual([0]) + + stop() + const remounted = follow() + await flush() + vi.advanceTimersByTime(10_000) + remounted() + expect(cursors).toEqual([0]) + } finally { + vi.useRealTimers() + } + }) + + test("polls a running shell once per second and resumes from the cached cursor after a remount", async () => { + vi.useFakeTimers() + try { + let text = "hello\n" + const shell = server(() => text) + const outputs: string[] = [] + const follow = (running: boolean) => + followShellOutput({ + id: "shell_live", + directory: "/repo", + running, + load: shell.load, + onOutput: (output) => outputs.push(output), + }) + + const first = follow(true) + await flush() + expect(outputs.at(-1)).toBe("hello\n") + + text += "world\n" + vi.advanceTimersByTime(1_000) + await flush() + expect(shell.cursors).toEqual([0, 6]) + expect(outputs.at(-1)).toBe("hello\nworld\n") + + first() + text += "done\n" + const second = follow(true) + await flush() + expect(shell.cursors).toEqual([0, 6, 12]) + expect(outputs.at(-1)).toBe("hello\nworld\ndone\n") + + second() + const exited = follow(false) + await flush() + exited() + expect(shell.cursors).toEqual([0, 6, 12, 17]) + + outputs.length = 0 + follow(false)() + await flush() + expect(shell.cursors).toEqual([0, 6, 12, 17]) + expect(outputs).toEqual(["hello\nworld\ndone\n"]) + + // The running-shell inventory can arrive late; a complete shell believed to be live is re-read from its cursor. + follow(true)() + expect(shell.cursors).toEqual([0, 6, 12, 17, 17]) + } finally { + vi.useRealTimers() + } + }) + + test("keeps only the most recent tail of a large output", async () => { + const shell = server(() => "a".repeat(SHELL_OUTPUT_TAIL_BYTES) + "tail", SHELL_OUTPUT_TAIL_BYTES) + const outputs: string[] = [] + followShellOutput({ + id: "shell_large", + directory: "/repo", + running: false, + load: shell.load, + onOutput: (output) => outputs.push(output), + }) + await flush() + expect(shell.cursors).toEqual([0, SHELL_OUTPUT_TAIL_BYTES]) + expect(outputs.at(-1)?.length).toBe(SHELL_OUTPUT_TAIL_BYTES) + expect(outputs.at(-1)?.endsWith("a".repeat(8) + "tail")).toBe(true) + }) +}) diff --git a/packages/session-ui/src/tools/shell-output.ts b/packages/session-ui/src/tools/shell-output.ts new file mode 100644 index 00000000000..6cb3dbff9e6 --- /dev/null +++ b/packages/session-ui/src/tools/shell-output.ts @@ -0,0 +1,74 @@ +import { isShellNotFoundError, type ShellOutputInput, type ShellOutputOutput } from "@opencode/client/promise" + +// Same page size as the TUI shell output viewer; only this much recent output is retained and rendered. +export const SHELL_OUTPUT_TAIL_BYTES = 64 * 1024 +const PROGRESS_LIMIT = 32 + +type Progress = { cursor: number; output: string; state: "partial" | "complete" | "missing" } + +// Virtualized timelines remount shell tools frequently. Progress is remembered per shell so a +// remount resumes from its cursor instead of re-reading from zero, and so a shell the server no +// longer knows is never requested again. +const progress = new Map() + +function remember(id: string, entry: Progress) { + progress.delete(id) + progress.set(id, entry) + if (progress.size <= PROGRESS_LIMIT) return + const oldest = progress.keys().next().value + if (oldest !== undefined) progress.delete(oldest) +} + +export function followShellOutput(input: { + id: string + directory: string + running: boolean + load: (input: ShellOutputInput) => Promise + onOutput: (output: string) => void +}) { + const cached = progress.get(input.id) + if (cached) { + remember(input.id, cached) + input.onOutput(cached.output) + } + // A missing shell never comes back. A complete one is only re-read while the shell is believed to be + // running, because the running-shell inventory can arrive after history has already rendered. + if (cached?.state === "missing" || (cached?.state === "complete" && !input.running)) return () => {} + let cursor = cached?.cursor ?? 0 + let text = cached?.output ?? "" + let loading = false + let disposed = false + const read = async () => { + if (loading) return + loading = true + while (true) { + const page = await input.load({ id: input.id, location: { directory: input.directory }, cursor }).then( + (response) => response.data, + (cause: unknown) => (isShellNotFoundError(cause) ? "missing" : undefined), + ) + if (disposed) break + if (page === "missing") { + // The server drops exited shells past its retention limit; stop asking for this one. + remember(input.id, { cursor, output: text, state: "missing" }) + clearInterval(interval) + break + } + if (!page) break + const advanced = page.cursor > cursor + cursor = Math.max(cursor, page.cursor) + text = (text + page.output).slice(-SHELL_OUTPUT_TAIL_BYTES) + const complete = !input.running && cursor >= page.size + remember(input.id, { cursor, output: text, state: complete ? "complete" : "partial" }) + input.onOutput(text) + if (input.running || complete || !advanced) break + } + loading = false + } + void read() + // Refresh the final snapshot on exit, but poll only while the shell is live. + const interval = input.running ? setInterval(() => void read(), 1_000) : undefined + return () => { + disposed = true + clearInterval(interval) + } +} diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 0f0d2b7e050..eb583cad2e9 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -51,6 +51,7 @@ import { executeToolFailed, } from "../message/current-tool-state" import { AssistantReasoningContent, writeClipboard } from "../message/message-content" +import { followShellOutput } from "./shell-output" function ShellSubmessage(props: { text: string; animate?: boolean }) { let widthRef: HTMLSpanElement | undefined @@ -1629,33 +1630,9 @@ ToolRegistry.register({ createEffect(() => { if (saved() !== undefined) return const id = props.metadata.shellID - const shellOutput = data.shellOutput - if (typeof id !== "string" || !shellOutput) return - const directory = data.directory - const running = pending() - let cursor = 0 - let loading = false - let disposed = false - const load = async () => { - if (loading) return - loading = true - do { - const response = await shellOutput({ id, location: { directory }, cursor }).catch(() => undefined) - if (disposed || !response) break - setStreamed((output) => (cursor === 0 ? response.data.output : output + response.data.output)) - if (response.data.cursor <= cursor) break - cursor = response.data.cursor - if (running || cursor >= response.data.size) break - } while (!disposed) - loading = false - } - void load() - // Refresh the final snapshot on exit, but poll only while the shell is live. - const interval = running ? setInterval(() => void load(), 1_000) : undefined - onCleanup(() => { - disposed = true - clearInterval(interval) - }) + const load = data.shellOutput + if (typeof id !== "string" || !load) return + onCleanup(followShellOutput({ id, directory: data.directory, running: pending(), load, onOutput: setStreamed })) }) const command = () => { if (typeof props.input.command === "string") return props.input.command