Compare commits

...
27 changed files with 1004 additions and 132 deletions
+11 -53
View File
@@ -433,7 +433,6 @@ export interface ParserState {
type ReasoningSummaryStatus = "active" | "can-conclude" | "concluded"
interface ReasoningStreamItem {
readonly open: boolean
readonly encryptedContent: string | null | undefined
// Keyed by the wire protocol's numeric `summary_index`. JS object keys coerce to
// strings, but typing the map as `Record<number, ...>` documents intent
@@ -950,7 +949,7 @@ export const normalize = (state: ParserState, input: Event): NormalizedEvent =>
const startReasoningSummaryPart = (state: ParserState, itemID: string, index: number): StepResult => {
const item = state.reasoningItems[itemID]
if (!item?.open || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
if (!item || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
const events: LLMEvent[] = []
const lifecycle = Object.entries(item.summaryParts)
@@ -990,7 +989,7 @@ const startReasoningSummaryPart = (state: ParserState, itemID: string, index: nu
export const onReasoningDelta = (state: ParserState, event: Event, itemID: string): StepResult => {
const item = state.reasoningItems[itemID]
if (!event.delta || !item?.open) return [state, NO_EVENTS]
if (!event.delta || !item) return [state, NO_EVENTS]
const index = event.summary_index ?? 0
if (item.summaryParts[index] === "concluded") return [state, NO_EVENTS]
const [started, emitted] = startReasoningSummaryPart(state, itemID, index)
@@ -1015,7 +1014,7 @@ export const onReasoningDelta = (state: ParserState, event: Event, itemID: strin
// as a single delta unless that summary index already streamed one.
export const onReasoningDone = (state: ParserState, event: Event, itemID: string): StepResult => {
const item = state.reasoningItems[itemID]
if (!item?.open || typeof event.text !== "string") return [state, NO_EVENTS]
if (!item || typeof event.text !== "string") return [state, NO_EVENTS]
const index = event.summary_index ?? 0
if (item.deltaIndexes.has(index)) return [state, NO_EVENTS]
return onReasoningDelta(state, { ...event, delta: event.text }, itemID)
@@ -1074,7 +1073,6 @@ const onOutputItemAdded = (state: ParserState, event: NormalizedEvent): StepResu
reasoningItems: {
...state.reasoningItems,
[item.id]: {
open: true,
encryptedContent: item.encrypted_content,
summaryParts: { 0: "active" },
deltaIndexes: new Set(),
@@ -1112,7 +1110,7 @@ const onReasoningSummaryPartAdded = (state: ParserState, event: Event): StepResu
const onReasoningSummaryPartDone = (state: ParserState, event: Event): StepResult => {
if (event.item_id === undefined || event.summary_index === undefined) return [state, NO_EVENTS]
const item = state.reasoningItems[event.item_id]
if (!item?.open) return [state, NO_EVENTS]
if (!item) return [state, NO_EVENTS]
if (item.summaryParts[event.summary_index] !== "active") return [state, NO_EVENTS]
return [
{
@@ -1247,7 +1245,6 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
}
if (item.type === "reasoning") {
if (state.reasoningItems[item.id]?.open === false) return [state, NO_EVENTS] satisfies StepResult
const metadata = reasoningMetadata(state, item)
const summaryParts: ReadonlyArray<unknown> = Array.isArray(item.summary) ? item.summary : []
const summary: Array<string | undefined> = []
@@ -1274,53 +1271,14 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
const finalText = fragments.length === 1 ? itemText : summary[Number(index)]
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, `${item.id}:${index}`, metadata, finalText || undefined)
}
return [
{
...state,
lifecycle,
reasoningItems: {
...state.reasoningItems,
[item.id]: {
...reasoningItem,
open: false,
encryptedContent: item.encrypted_content ?? reasoningItem.encryptedContent,
},
},
},
events,
] satisfies StepResult
const reasoningItems = { ...state.reasoningItems }
delete reasoningItems[item.id]
return [{ ...state, lifecycle, reasoningItems }, events] satisfies StepResult
}
if (!state.lifecycle.reasoning.has(item.id)) {
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
events.push(LLMEvent.reasoningStart({ id: item.id, providerMetadata: metadata }))
events.push(
LLMEvent.reasoningEnd({
id: item.id,
providerMetadata: metadata,
text: itemText,
}),
)
return [
{
...state,
lifecycle,
reasoningItems: {
...state.reasoningItems,
[item.id]: {
open: false,
encryptedContent: item.encrypted_content,
summaryParts: { 0: "concluded" },
deltaIndexes: new Set(),
},
},
},
events,
] satisfies StepResult
}
return [
{ ...state, lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, item.id, metadata) },
events,
] satisfies StepResult
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
events.push(LLMEvent.reasoningStart({ id: item.id, providerMetadata: metadata }))
events.push(LLMEvent.reasoningEnd({ id: item.id, providerMetadata: metadata, text: itemText }))
return [{ ...state, lifecycle }, events] satisfies StepResult
}
return [state, NO_EVENTS] satisfies StepResult
@@ -71,7 +71,7 @@ function expectLifecycle(events: ReadonlyArray<LLMEvent>, completed: boolean) {
}
describe("Open Responses basic-item lifecycles", () => {
it.effect("closes implicit summary boundaries and ignores late events for completed reasoning", () =>
it.effect("closes implicit summary boundaries", () =>
Effect.gen(function* () {
const item = { type: "reasoning", id: "rs_1", encrypted_content: "encrypted-state" }
const events = yield* collect(
@@ -90,12 +90,6 @@ describe("Open Responses basic-item lifecycles", () => {
delta: "Third",
},
{ type: "response.output_item.done", item },
{ type: "response.output_item.done", item },
{ type: "response.output_item.added", item },
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 3 },
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 3, delta: "late" },
{ type: "response.reasoning_summary_text.done", item_id: "rs_1", summary_index: 2, text: "late final" },
{ type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 3 },
completed,
)
@@ -129,7 +123,7 @@ describe("Open Responses basic-item lifecycles", () => {
}),
)
it.effect("preserves done-only reasoning text and encryption without replaying late events", () =>
it.effect("preserves done-only reasoning text and encryption", () =>
Effect.gen(function* () {
const item = {
type: "reasoning",
@@ -139,11 +133,6 @@ describe("Open Responses basic-item lifecycles", () => {
}
const events = yield* collect(
{ type: "response.output_item.done", item },
{ type: "response.output_item.done", item },
{ type: "response.output_item.added", item },
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", delta: "late" },
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
{ type: "response.reasoning_summary_text.done", item_id: "rs_1", summary_index: 1, text: "late final" },
completed,
// Route termination must also prevent events after response completion.
{ type: "response.output_item.added", item: { type: "reasoning", id: "rs_after" } },
@@ -2861,7 +2861,6 @@ describe("OpenAI Responses route", () => {
{ type: "response.output_item.added", item: { type: "reasoning", id: "rs_1" } },
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: "Think" },
{ type: "response.output_item.done", item: { type: "reasoning", id: "rs_1" } },
{ type: "response.output_item.done", item: { type: "reasoning", id: "rs_1" } },
{
type: "response.output_item.added",
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "" },
@@ -0,0 +1,18 @@
import { expect, story } from "../../storybook/playwright/story"
for (const theme of ["light", "dark"]) {
story(`keeps the Open in border visible without hovering (${theme})`, async ({ mount, page }, testInfo) => {
const component = await mount("ui-split-button--open-in", { globals: { theme } })
const control = component.locator('[data-component="split-button-v2"]')
await page.mouse.move(0, 0)
await expect(control).toBeVisible()
await expect(control).not.toHaveCSS("box-shadow", "none")
const border = await control.evaluate((element) => getComputedStyle(element).boxShadow)
await component.getByRole("button", { name: "Open options" }).hover()
await expect(control).toHaveCSS("box-shadow", border)
await page.mouse.move(0, 0)
await expect(control).toHaveCSS("box-shadow", border)
await control.screenshot({ path: testInfo.outputPath(`open-in-${theme}.png`) })
})
}
@@ -0,0 +1,189 @@
import { base64Encode } from "@opencode-ai/util/encode"
import { expect, test, type Locator } from "@playwright/test"
import { mockOpenCodeServer } from "../utils/mock-server"
import { expectSessionTitle } from "../utils/waits"
const directory = "C:/OpenCode/ReviewTogglePosition"
const sessionID = "ses_review_toggle_position"
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
test.beforeEach(async ({ page }) => {
await mockOpenCodeServer(page, {
directory,
project: {
id: "proj_review_toggle_position",
worktree: directory,
vcs: "git",
name: "review-toggle-position",
time: { created: 1700000000000, updated: 1700000000000 },
sandboxes: [],
},
provider: { all: [], connected: [], default: {} },
sessions: [
{
id: sessionID,
slug: "review-toggle-position",
projectID: "proj_review_toggle_position",
directory,
title: "Review toggle position",
version: "dev",
time: { created: 1700000000000, updated: 1700000000000 },
},
],
pageMessages: () => ({ items: [] }),
})
})
for (const width of [1000, 1440]) {
for (const direction of ["ltr", "rtl"] as const) {
test(`keeps the review toggle at the outer header edge (${width}px, ${direction})`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 })
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
await expectSessionTitle(page, "Review toggle position")
await page.locator("html").evaluate((element, dir) => element.setAttribute("dir", dir), direction)
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
const header = page.locator("[data-session-title]")
const panel = page.locator("#review-panel")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
const closed = await toggle.boundingBox()
if (!closed) throw new Error("Review toggle bounds are unavailable")
const headerBox = await header.boundingBox()
if (!headerBox) throw new Error("Session header bounds are unavailable")
expect(closed.y).toBeGreaterThanOrEqual(headerBox.y)
expect(closed.y + closed.height).toBeLessThanOrEqual(headerBox.y + headerBox.height)
await toggle.click()
await expect(toggle).toHaveAttribute("aria-expanded", "true")
await expect(panel).toHaveAttribute("aria-hidden", "false")
await expect(toggle).toHaveCount(1)
await expect.poll(() => toggle.boundingBox()).toEqual(closed)
await expect
.poll(async () => {
const box = await panel.boundingBox()
if (!box) return false
return (
closed.x >= box.x &&
closed.x + closed.width <= box.x + box.width &&
closed.y >= box.y &&
closed.y + closed.height <= box.y + 52
)
})
.toBe(true)
await expect
.poll(async () => {
const box = await panel.locator('[data-slot="session-side-panel-actions"]').boundingBox()
return box ? box.y + box.height / 2 : undefined
})
.toBe(closed.y + closed.height / 2)
await toggle.press("Enter")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await expect(toggle).toBeFocused()
await expect(toggle).toHaveCount(1)
await expect.poll(() => toggle.boundingBox()).toEqual(closed)
})
test(`keeps terminal controls clear of the review toggle (${width}px, ${direction})`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 })
const ptys: { id: string; title: string }[] = []
const removed: string[] = []
await page.route("**/api/pty**", async (route) => {
const path = new URL(route.request().url()).pathname
const location = { directory, project: { id: "proj_review_toggle_position", directory } }
if (route.request().method() === "DELETE") {
removed.push(path.split("/").at(-1)!)
return route.fulfill({ status: 204 })
}
if (path.endsWith("/connect-token")) {
return route.fulfill({ json: { location, data: { ticket: "e2e-ticket", expires_in: 60 } } })
}
if (path === "/api/pty" && route.request().method() === "POST") {
const pty = { id: `pty_review_${ptys.length + 1}`, title: `Terminal ${ptys.length + 1}` }
ptys.push(pty)
return route.fulfill({ json: { location, data: pty } })
}
return route.fulfill({ json: { location, data: ptys.find((pty) => path.endsWith(pty.id)) ?? ptys } })
})
await page.routeWebSocket(/\/api\/pty\/pty_review_\d+\/connect/, () => undefined)
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
await expectSessionTitle(page, "Review toggle position")
await page.locator("html").evaluate((element, dir) => element.setAttribute("dir", dir), direction)
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await page.keyboard.press("Control+Backquote")
const terminal = page.getByRole("region", { name: "Terminal", exact: true })
await expect(terminal.getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute(
"aria-selected",
"true",
)
for (const number of [2, 3, 4]) {
await terminal.getByRole("button", { name: "New terminal", exact: true }).click()
await expect(terminal.getByRole("tab", { name: `Terminal ${number}`, exact: true })).toHaveAttribute(
"aria-selected",
"true",
)
}
await expect
.poll(async () => {
const tabs = await terminal.getByRole("tablist").boundingBox()
const button = await toggle.boundingBox()
if (!tabs || !button) return false
return direction === "rtl" ? tabs.x >= button.x + button.width : tabs.x + tabs.width <= button.x
})
.toBe(true)
await expectTerminalControlsAligned(terminal, toggle)
const fourth = terminal.locator('[data-slot="tabs-trigger-wrapper"][data-value="pty_review_4"]')
await fourth.getByRole("button", { name: "Close terminal", exact: true }).click()
await expect(terminal.getByRole("tab")).toHaveText(["Terminal 1", "Terminal 2", "Terminal 3"])
expect(removed).toEqual(["pty_review_4"])
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await terminal.getByRole("button", { name: "New terminal", exact: true }).click()
await expect(terminal.getByRole("tab", { name: "Terminal 5", exact: true })).toHaveAttribute(
"aria-selected",
"true",
)
await expect(toggle).toHaveAttribute("aria-expanded", "false")
const position = await toggle.boundingBox()
await toggle.click()
await expect(toggle).toHaveAttribute("aria-expanded", "true")
await expect(page.locator("#review-panel")).toHaveAttribute("aria-hidden", "false")
await expect.poll(() => toggle.boundingBox()).toEqual(position)
await expect
.poll(async () => {
const actions = await page.locator('[data-slot="session-side-panel-actions"]').boundingBox()
const button = await toggle.boundingBox()
if (!actions || !button) return undefined
return actions.y + actions.height / 2 - (button.y + button.height / 2)
})
.toBe(0)
await toggle.press("Enter")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await expect(toggle).toBeFocused()
await expect.poll(() => toggle.boundingBox()).toEqual(position)
await expectTerminalControlsAligned(terminal, toggle)
})
}
}
async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator) {
await expect
.poll(async () => {
const centers = await Promise.all(
[terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) =>
button.locator("svg").evaluate((element) => {
const svg = element as SVGSVGElement
const path = svg.getBBox()
return new DOMPoint(path.x + path.width / 2, path.y + path.height / 2).matrixTransform(svg.getScreenCTM()!)
.y
}),
),
)
return centers[0]! - centers[1]!
})
.toBeCloseTo(0, 1)
}
@@ -24,7 +24,7 @@ for (const direction of ["ltr", "rtl"] as const) {
const header = page.locator("[data-session-title]")
const more = header.getByRole("button", { name: "More options", exact: true })
const project = header.getByRole("button", { name: fixture.project.name, exact: true })
const review = header.getByRole("button", { name: "Toggle review", exact: true })
const review = page.getByRole("button", { name: "Toggle review", exact: true })
const details = header.getByRole("button", { name: "Session details", exact: true })
await expect(header.getByRole("heading")).toHaveText(fixture.expected.targetTitle)
await page.evaluate((direction) => document.documentElement.setAttribute("dir", direction), direction)
@@ -427,11 +427,16 @@ export function SessionSidePanel(props: {
</div>
</Tabs.List>
<div
class="session-review-v2-open-in-app-slot shrink-0 flex items-center pr-3"
data-slot="session-side-panel-actions"
class="session-review-v2-open-in-app-slot self-start shrink-0 flex items-center gap-2 pe-3"
classList={{ "h-[51px]": props.stacked, "h-12": !props.stacked }}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
>
<OpenInAppButton directory={projectDirectory} />
<Show when={reviewOpen()}>
<div class="size-7 shrink-0" aria-hidden />
</Show>
</div>
</div>
@@ -3,6 +3,28 @@ import { Icon } from "@opencode-ai/ui/icon"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { Keybind } from "@opencode-ai/ui/keybind"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { useCommand } from "@/shell/commands/command"
import { reviewTooltipKeybind } from "@/shell/commands/tooltip-keybind"
import { useLanguage } from "@/runtime/i18n/language"
import { useSessionLayout } from "@/session/session-layout"
export function SessionReviewToggle() {
const command = useCommand()
const language = useLanguage()
const { view } = useSessionLayout()
return (
<SessionHeaderActions
state={{
reviewLabel: language.t("command.review.toggle"),
reviewKeybind: reviewTooltipKeybind(command),
reviewVisible: true,
reviewOpened: view().reviewPanel.opened(),
onReviewToggle: () => view().reviewPanel.toggle(),
}}
/>
)
}
export type SessionHeaderActionsState = {
reviewLabel: string
@@ -1,31 +1,19 @@
import { createMemo, Show } from "solid-js"
import { Show } from "solid-js"
import { createMediaQuery } from "@solid-primitives/media"
import { useCommand } from "@/shell/commands/command"
import { useLanguage } from "@/runtime/i18n/language"
import { useSettings } from "@/settings/model"
import { useSessionLayout } from "@/session/session-layout"
import { reviewTooltipKeybind } from "@/shell/commands/tooltip-keybind"
import { StatusPopover } from "@/shell/status/status-popover"
import { TitlebarRight } from "@/shell/titlebar/right-slot"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { SessionHeaderActions, type SessionHeaderActionsState } from "./session-header-actions"
export function SessionHeader() {
const command = useCommand()
const language = useLanguage()
const settings = useSettings()
const { view } = useSessionLayout()
const isDesktop = createMediaQuery("(min-width: 768px)")
const actions = createMemo<SessionHeaderActionsState>(() => ({
reviewLabel: language.t("command.review.toggle"),
reviewKeybind: reviewTooltipKeybind(command),
reviewVisible: isDesktop(),
reviewOpened: view().reviewPanel.opened(),
onReviewToggle: () => view().reviewPanel.toggle(),
}))
return (
<>
<TitlebarRight>
@@ -35,7 +23,9 @@ export function SessionHeader() {
</Tooltip>
</Show>
</TitlebarRight>
<SessionHeaderActions state={actions()} />
<Show when={isDesktop() && !view().reviewPanel.opened()}>
<div class="size-7 shrink-0" aria-hidden />
</Show>
</>
)
}
+13 -2
View File
@@ -28,6 +28,7 @@ import { SessionContextTab } from "./files/session-context-tab"
import { createSessionTimelineInteraction } from "./timeline/interaction"
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
import { SessionIdentityHeader } from "./session-identity-header"
import { SessionReviewToggle } from "./header/session-header-actions"
import { createAnimatedPresence } from "@/runtime/animated-presence"
const SessionMobileFiles = lazy(async () => {
@@ -274,10 +275,19 @@ export function SessionScreen(props: { session: SessionModel }) {
<>
<div class="flex-1 min-h-0 flex flex-col gap-2 px-2 pb-[var(--shell-bottom-inset,8px)] pt-[var(--shell-top-inset,8px)]">
<div ref={screen.panel.ref} class="relative flex-1 min-h-0 flex flex-col md:flex-row gap-2">
{/* Keep the control outside panel animations; the terminal's 52px header includes a 1px divider. */}
<Show when={isDesktop() && messagesReady() && session.identity.params.id}>
<div
class="absolute end-3 top-0 z-30 flex items-center"
classList={{ "h-[51px]": sideTerminalVisible(), "h-12": !sideTerminalVisible() }}
data-slot="session-review-toggle"
>
<SessionReviewToggle />
</div>
</Show>
<div
classList={{
"@container relative z-10 min-w-0 shrink-0 flex flex-col min-h-0 h-full flex-1 md:flex-none transition-[width]":
true,
"@container relative z-10 min-w-0 shrink-0 flex flex-col min-h-0 h-full flex-1 md:flex-none transition-[width]": true,
"duration-[240ms] ease-[cubic-bezier(0.22,1,0.36,1)] will-change-[width] motion-reduce:transition-none":
!screen.size.active() && sidePresence.animate(),
"transition-none": screen.size.active() || !sidePresence.animate(),
@@ -408,6 +418,7 @@ export function SessionScreen(props: { session: SessionModel }) {
present={store.sideTerminalPresent}
animate={sidePresence.animate() || sideMotion().animateTerminal}
contentHeight={screen.side.terminal.contentHeight()}
reserveReviewToggle={!screen.side.region.open()}
/>
</div>
</div>
+51 -40
View File
@@ -45,6 +45,7 @@ export function TerminalPanel(
contentHeight?: string
embedded?: boolean
animate?: boolean
reserveReviewToggle?: boolean
} = {},
) {
const terminal = useTerminal()
@@ -249,7 +250,10 @@ export function TerminalPanel(
when={terminal.ready() || store.surfaces.length > 0}
fallback={
<div class="flex flex-col h-full pointer-events-none">
<div class="h-10 flex items-center gap-2 px-2 border-b border-border-weaker-base bg-v2-background-bg-base overflow-hidden">
<div
class="h-10 flex items-center gap-2 px-2 border-b border-border-weaker-base bg-v2-background-bg-base overflow-hidden"
classList={{ "pe-12": props.reserveReviewToggle }}
>
<For each={handoff()}>
{(title) => (
<div class="px-2 py-1 rounded-md bg-surface-base text-14-regular text-text-weak truncate max-w-40">
@@ -291,46 +295,53 @@ export function TerminalPanel(
}}
>
<div class="flex flex-col h-full">
<Tabs
variant="panel"
value={terminal.active()}
onChange={(id) => terminal.open(id)}
class="!h-[52px] !flex-none"
>
<Tabs.List
ref={tabList}
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
const active = document.activeElement
if (event.target === active) return
if (active instanceof HTMLInputElement && event.currentTarget.contains(active)) active.blur()
}}
<div class="h-[52px] shrink-0 flex border-b border-border-weaker-base">
<Tabs
variant="panel"
value={terminal.active()}
onChange={(id) => terminal.open(id)}
class="!h-full min-w-0 !flex-1"
>
<For each={all()}>
{(pty, index) => <SortableTerminalTab terminal={pty} index={index()} onClose={close} />}
</For>
<div class="h-full flex items-center justify-center">
<Tooltip
value={
<>
{language.t("command.terminal.new")}
<Show when={newTerminalKeybind().length > 0}>
<Keybind keys={newTerminalKeybind()} variant="neutral" />
</Show>
</>
}
placement="bottom"
class="flex items-center"
>
<IconButton
icon={<Icon name="plus-small" size="large" />}
variant="ghost"
onClick={() => terminal.new({ focus: true })}
aria-label={language.t("command.terminal.new")}
/>
</Tooltip>
</div>
</Tabs.List>
</Tabs>
<Tabs.List
ref={tabList}
class="!border-b-0"
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
const active = document.activeElement
if (event.target === active) return
if (active instanceof HTMLInputElement && event.currentTarget.contains(active)) active.blur()
}}
>
<For each={all()}>
{(pty, index) => <SortableTerminalTab terminal={pty} index={index()} onClose={close} />}
</For>
<div class="h-full flex items-center justify-center">
<Tooltip
value={
<>
{language.t("command.terminal.new")}
<Show when={newTerminalKeybind().length > 0}>
<Keybind keys={newTerminalKeybind()} variant="neutral" />
</Show>
</>
}
placement="bottom"
class="flex items-center"
>
<IconButton
icon={<Icon name="plus-small" size="large" />}
variant="ghost"
onClick={() => terminal.new({ focus: true })}
aria-label={language.t("command.terminal.new")}
/>
</Tooltip>
</div>
</Tabs.List>
</Tabs>
{/* Reserve outside the scroll viewport so overflowing tabs cannot cover the toggle. */}
<Show when={props.reserveReviewToggle}>
<div class="w-12 shrink-0" aria-hidden />
</Show>
</div>
<div class="flex-1 min-h-0 relative">
<For each={store.surfaces}>
{(surface) => (
+33
View File
@@ -1,6 +1,7 @@
export * as SessionRunnerLLM from "./llm.js"
import { Message } from "@opencode-ai/ai"
import { and, desc, eq, sql } from "drizzle-orm"
import { Cause, Effect, Exit, FiberMap, Layer } from "effect"
import { Database } from "../../database/database.js"
import { Bus } from "../../bus.js"
@@ -15,6 +16,7 @@ import { SessionModelTransport } from "../model-transport.js"
import { SessionMessage } from "../message.js"
import { SessionSchema } from "../schema.js"
import { SessionStore } from "../store.js"
import { SessionMessageTable } from "../sql.js"
import { SessionTitle } from "../title.js"
import { DrainResult, Service, type Interface } from "./index.js"
import { Snapshot } from "../../snapshot.js"
@@ -59,6 +61,7 @@ const layer = Layer.effect(
if (promotable === "steer" && pending.delivery === "queue" && !control) return DrainResult.Complete()
}
yield* plugins.awaitActivation
yield* settleStaleCompactions(sessionID)
yield* settleStaleToolCalls(sessionID)
const advanceToStep = Effect.fn("SessionRunner.advanceToStep")(() =>
@@ -276,6 +279,36 @@ const layer = Layer.effect(
}
})
const settleStaleCompactions = Effect.fn("SessionRunner.settleStaleCompactions")(function* (
sessionID: SessionSchema.ID,
) {
// A process death skips compaction finalizers. Include orphans behind a
// completed checkpoint, and settle newest first to match event projection.
const rows = yield* db
.select()
.from(SessionMessageTable)
.where(
and(
eq(SessionMessageTable.session_id, sessionID),
eq(SessionMessageTable.type, "compaction"),
sql`json_extract(${SessionMessageTable.data}, '$.status') = 'running'`,
),
)
.orderBy(desc(SessionMessageTable.seq))
.all()
.pipe(Effect.orDie)
for (const row of rows) {
const message = yield* SessionHistory.decodeMessageRow(row)
if (message.type !== "compaction") continue
yield* bus.publish(SessionEvent.Compaction.Failed, {
sessionID,
reason: message.reason,
inputID: message.id,
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
})
}
})
const settleStaleToolCalls = Effect.fn("SessionRunner.settleStaleToolCalls")(function* (
sessionID: SessionSchema.ID,
) {
+25 -2
View File
@@ -69,12 +69,16 @@ async function createRegistryFixture(directory: string) {
await Bun.$`tar -czf package.tgz package`.cwd(root)
tarballs.set(version, await Bun.file(path.join(root, "package.tgz")).bytes())
}
const state = { latest: "1.0.0" }
const state = { latest: "1.0.0", audits: 0 }
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(request) {
const url = new URL(request.url)
if (url.pathname.startsWith("/-/npm/v1/security/")) {
state.audits++
return Response.json({})
}
if (decodeURIComponent(url.pathname) === "/@fixture/registry-plugin")
return Response.json({
name: "@fixture/registry-plugin",
@@ -97,7 +101,7 @@ async function createRegistryFixture(directory: string) {
await fs.mkdir(root, { recursive: true })
await Bun.write(
path.join(root, ".npmrc"),
`@fixture:registry=${server.url}\ncache=${path.join(directory, "npm-cache")}\nfetch-retries=0\naudit=false\n`,
`registry=${server.url}\n@fixture:registry=${server.url}\ncache=${path.join(directory, "npm-cache")}\nfetch-retries=0\naudit=true\n`,
)
return root
},
@@ -359,6 +363,25 @@ describe("Npm.resolve", () => {
})
describe("Npm.check and Npm.update", () => {
test("installs and updates without requesting registry audits", async () => {
await using tmp = await tmpdir()
await using registry = await createRegistryFixture(tmp.path)
const cache = path.join(tmp.path, "cache")
const spec = "@fixture/registry-plugin@latest"
await registry.configure(cache, spec)
await Effect.gen(function* () {
const npm = yield* Npm.Service
expect((yield* npm.add(spec)).version).toBe("1.0.0")
expect(registry.state.audits).toBe(0)
registry.state.latest = "1.1.0"
expect((yield* npm.update(spec)).version).toBe("1.1.0")
expect(registry.state.audits).toBe(0)
expect((yield* npm.resolve(spec)).version).toBe("1.1.0")
}).pipe(Effect.scoped, Effect.provide(npmLayer(cache)), Effect.runPromise)
})
test("checks a mutable registry target without mutation and explicitly updates it", async () => {
await using tmp = await tmpdir()
await using registry = await createRegistryFixture(tmp.path)
+4
View File
@@ -4,6 +4,10 @@ import path from "path"
import { Global } from "@opencode-ai/util/global"
describe("Core test environment", () => {
test("disables public npm security audits", () => {
expect(process.env.NPM_CONFIG_AUDIT).toBe("false")
})
test("isolates global home and XDG roots", () => {
const home = process.env.OPENCODE_TEST_HOME
expect(home).toBeDefined()
+1
View File
@@ -1 +1,2 @@
process.env.OPENCODE_DB = ":memory:"
process.env.NPM_CONFIG_AUDIT = "false"
+77
View File
@@ -3472,6 +3472,83 @@ describe("SessionRunnerLLM", () => {
expect(userTexts(s.requests[1])).toEqual(["Start working", "Recover with this"])
})
scenario("settles abandoned compactions before continuing after a process crash", function* (s) {
yield* s.runPrompt("History before the crash")
const first = SessionMessage.ID.create()
const completed = SessionMessage.ID.create()
const last = SessionMessage.ID.create()
yield* s.bus.publish(SessionEvent.Compaction.Started, {
sessionID,
reason: "manual",
inputID: first,
recent: "",
})
yield* s.bus.publish(SessionEvent.Compaction.Started, {
sessionID,
reason: "manual",
inputID: completed,
recent: "",
})
yield* s.bus.publish(SessionEvent.Compaction.Ended, {
sessionID,
reason: "manual",
text: "## Objective\n- Earlier completed checkpoint",
recent: "",
})
yield* s.bus.publish(SessionEvent.Compaction.Started, {
sessionID,
reason: "auto",
inputID: last,
recent: "",
})
// These starts have no terminal events, as after SIGKILL. The older orphan
// is outside model-visible history; recovery must settle it as well.
expect(
(yield* s.messages).filter((message) => message.type === "compaction" && message.status === "running"),
).toHaveLength(2)
yield* s.llm.push(TestLLM.text("Recovered response", "recovered"))
const run = yield* s.resumePaused
expect((yield* s.messages).filter((message) => message.type === "compaction").toReversed()).toMatchObject([
{ id: first, status: "failed", reason: "manual", error: { type: "compaction.interrupted" } },
{ id: completed, status: "completed", summary: "## Objective\n- Earlier completed checkpoint" },
{ id: last, status: "failed", reason: "auto", error: { type: "compaction.interrupted" } },
])
yield* run.finish
yield* s.llm.push(TestLLM.text("## Objective\n- New checkpoint", "new-summary"))
const next = yield* s.session.compact({ sessionID })
yield* s.session.wait(sessionID)
expect((yield* s.messages).find((message) => message.id === next.id)).toMatchObject({
status: "completed",
summary: "## Objective\n- New checkpoint",
})
expect(
(yield* s.messages).filter((message) => message.type === "compaction" && message.status === "running"),
).toHaveLength(0)
})
scenario("settles an abandoned compaction before delivering another manual compaction", function* (s) {
yield* s.runPrompt("History before the crash")
const previous = SessionMessage.ID.create()
yield* s.bus.publish(SessionEvent.Compaction.Started, {
sessionID,
reason: "manual",
inputID: previous,
recent: "",
})
yield* s.llm.push(TestLLM.text("## Objective\n- New checkpoint", "new-summary"))
const gate = yield* s.llm.gate
const next = yield* s.session.compact({ sessionID })
yield* gate.started
expect((yield* s.messages).filter((message) => message.type === "compaction").toReversed()).toMatchObject([
{ id: previous, status: "failed", error: { type: "compaction.interrupted" } },
{ id: next.id, status: "running" },
])
yield* gate.release
yield* s.session.wait(sessionID)
})
scenario("durably fails local tools left running by a prior process before continuing", function* (s) {
yield* s.admit("Recover interrupted tool")
yield* SessionInbox.promote(s.db, s.bus, sessionID, "steer")
@@ -0,0 +1,144 @@
import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core"
import { useTerminalDimensions } from "@opentui/solid"
import { isShellNotFoundError, type LocationRef, type ShellInfo } from "@opencode-ai/client"
import { createEffect, createMemo, createSignal, onCleanup, Show, untrack } from "solid-js"
import stripAnsi from "strip-ansi"
import { useClient } from "../context/client"
import { Keymap } from "../context/keymap"
import { useTheme } from "../context/theme"
import { useDialog } from "../ui/dialog"
const PAGE_BYTES = 64 * 1024
export function DialogShellOutput(props: { shell: ShellInfo; location: LocationRef }) {
const client = useClient()
const dialog = useDialog()
const theme = useTheme("elevated")
const dimensions = useTerminalDimensions()
const [info, setInfo] = createSignal(props.shell)
const [output, setOutput] = createSignal<string>()
const [omitted, setOmitted] = createSignal(false)
const [error, setError] = createSignal("")
const text = createMemo(() => stripAnsi(output() ?? "").replace(/\r\n?/g, "\n"))
const height = () => Math.max(3, Math.floor(dimensions().height * 0.6) - 6)
let scroll: ScrollBoxRenderable | undefined
dialog.setSize("xlarge")
dialog.setCentered(true)
createEffect(() => {
// The running-shell inventory drops exited commands. Keep this view tied to
// the opened ID and its original Location, not the list's current selection.
const id = props.shell.id
const location = { directory: props.location.directory, workspace: props.location.workspaceID }
let cursor: number | undefined
let disposed = false
let missing = false
let timer: ReturnType<typeof setTimeout> | undefined
const load = async () => {
if (untrack(info).status === "running") {
const current = await client.api.shell.get({ id, location })
if (disposed) return false
setInfo(current.data)
}
if (cursor === undefined) {
const head = await client.api.shell.output({ id, location, cursor: Number.MAX_SAFE_INTEGER })
if (disposed) return false
cursor = Math.max(0, head.data.size - PAGE_BYTES)
setOmitted(cursor > 0)
}
const page = await client.api.shell.output({ id, location, cursor, limit: PAGE_BYTES })
if (disposed) return false
cursor = page.data.cursor
setOutput((previous) => {
const next = (previous ?? "") + page.data.output
if (next.length > PAGE_BYTES) setOmitted(true)
return next.slice(-PAGE_BYTES)
})
setError("")
return cursor < page.data.size
}
const poll = () => {
void load()
.catch((cause: unknown) => {
if (disposed) return
missing = isShellNotFoundError(cause)
setError(missing ? "Shell output is no longer available." : "Unable to read shell output. Retrying…")
})
.then((more) => {
// Poll only while the viewer is open, including after exit so the final
// file flush is observed. Never overlap reads or reload earlier pages.
if (!disposed && !missing) timer = setTimeout(poll, more ? 0 : 1_000)
})
}
poll()
onCleanup(() => {
disposed = true
clearTimeout(timer)
})
})
const status = () => {
if (info().status === "running") return "Running"
if (info().status === "timeout") return "Timed out"
if (info().status === "killed") return "Killed"
return info().exit === undefined ? "Exited" : `Exited · code ${info().exit}`
}
Keymap.createLayer(() => ({
mode: "modal",
commands: [
{ bind: "up", title: "Scroll output up", group: "Shell", run: () => scroll?.scrollBy(-1) },
{ bind: "down", title: "Scroll output down", group: "Shell", run: () => scroll?.scrollBy(1) },
{ bind: "pageup", title: "Previous output page", group: "Shell", run: () => scroll?.scrollBy(-height()) },
{ bind: "pagedown", title: "Next output page", group: "Shell", run: () => scroll?.scrollBy(height()) },
{ bind: "home", title: "First loaded output", group: "Shell", run: () => scroll?.scrollTo(0) },
{ bind: "end", title: "Follow shell output", group: "Shell", run: () => scroll?.scrollTo(Infinity) },
],
}))
return (
<box paddingLeft={2} paddingRight={2} paddingBottom={1} gap={1}>
<box flexDirection="row" gap={2}>
<text fg={theme.text.default} attributes={TextAttributes.BOLD} flexGrow={1}>
Shell output
</text>
<text fg={theme.text.subdued}>{status()}</text>
<text fg={theme.text.subdued} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<text fg={theme.text.subdued} maxHeight={3} wrapMode="word">
{props.shell.command}
</text>
<Show when={omitted()}>
<text fg={theme.text.subdued}>Earlier output omitted · showing recent output</text>
</Show>
<scrollbox
id="shell-output-scroll"
ref={(value: ScrollBoxRenderable) => (scroll = value)}
height={height()}
stickyScroll
stickyStart="bottom"
scrollbarOptions={{ visible: false }}
>
<text fg={theme.text.default} wrapMode="word">
{text() ||
(output() === undefined
? "Loading output…"
: "No captured output. Output redirected to files is not shown here.")}
</text>
</scrollbox>
<Show when={error()}>
<text fg={theme.text.feedback.error.default}>{error()}</text>
</Show>
<box flexDirection="row" gap={2} flexWrap="wrap">
<text fg={theme.text.subdued}>/ scroll</text>
<text fg={theme.text.subdued}>end follow</text>
<text fg={theme.text.subdued}>esc back</text>
</box>
</box>
)
}
+1
View File
@@ -244,6 +244,7 @@ export const Definitions = {
"composer.subagent.interrupt": keybind("ctrl+d", "Interrupt subagent"),
"composer.shell.up": keybind("up", "Previous shell"),
"composer.shell.down": keybind("down", "Next shell"),
"composer.shell.select": keybind("return", "View shell output"),
"composer.shell.kill": keybind("ctrl+d", "Kill shell command"),
"composer.terminal.up": keybind("up,k", "Previous terminal"),
"composer.terminal.down": keybind("down,j", "Next terminal"),
@@ -6,6 +6,8 @@ import { useClient } from "../../../context/client"
import { useTheme } from "../../../context/theme"
import { Keymap } from "../../../context/keymap"
import { useComposerTab } from "./index"
import { useDialog } from "../../../ui/dialog"
import { DialogShellOutput } from "../../../component/dialog-shell-output"
export function ShellTab(props: { sessionID: string }) {
const data = useData()
@@ -13,6 +15,7 @@ export function ShellTab(props: { sessionID: string }) {
const theme = useTheme()
const composer = useComposerTab()
const shortcuts = Keymap.useShortcuts()
const dialog = useDialog()
const entries = createMemo(() =>
data.shell.listBySession(props.sessionID).filter((shell) => shell.status === "running"),
@@ -23,6 +26,11 @@ export function ShellTab(props: { sessionID: string }) {
const selectedEntry = createMemo(() => entries()[store.selected])
const open = () => {
const entry = selectedEntry()
if (entry) dialog.replace(() => <DialogShellOutput shell={entry} location={entry.location} />)
}
createEffect(() => {
if (store.selected >= entries().length) setStore("selected", Math.max(0, entries().length - 1))
})
@@ -42,7 +50,13 @@ export function ShellTab(props: { sessionID: string }) {
const cleanup = composer.register({
id: "shell",
label: "Shell",
hints: () => (selectedEntry() ? [{ label: "kill", shortcut: shortcuts.get("composer.shell.kill") ?? "" }] : []),
hints: () =>
selectedEntry()
? [
{ label: "output", shortcut: shortcuts.get("composer.shell.select") ?? "" },
{ label: "kill", shortcut: shortcuts.get("composer.shell.kill") ?? "" },
]
: [],
})
onCleanup(cleanup)
})
@@ -74,6 +88,12 @@ export function ShellTab(props: { sessionID: string }) {
setStore("selected", (prev) => (prev + 1) % list.length)
},
},
{
id: "composer.shell.select",
title: "View shell output",
group: "Composer",
run: open,
},
{
id: "composer.shell.kill",
title: "Kill shell command",
@@ -106,6 +126,10 @@ export function ShellTab(props: { sessionID: string }) {
active() ? theme.background.action.primary.focused : theme.background.action.primary.default
}
onMouseOver={() => setStore("selected", index())}
onMouseUp={() => {
setStore("selected", index())
open()
}}
>
<text
fg={active() ? theme.text.action.primary.focused : theme.text.action.primary.default}
@@ -11,6 +11,8 @@ import { LocationProvider } from "../../../src/context/location"
import { RouteProvider, useRoute } from "../../../src/context/route"
import { ThemeProvider } from "../../../src/context/theme"
import { Composer } from "../../../src/routes/session/composer"
import { DialogProvider } from "../../../src/ui/dialog"
import { ToastProvider } from "../../../src/ui/toast"
import { createApi, createEventStream, createFetch, directory, json } from "../../fixture/tui-client"
import { TestTuiContexts } from "../../fixture/tui-environment"
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
@@ -31,6 +33,7 @@ async function renderComposer(
const events = createEventStream()
const interrupted: string[] = []
const removed: string[] = []
const viewed: string[] = []
const ready = Promise.withResolvers<void>()
let closed = 0
let dispatch!: ReturnType<typeof Keymap.use>["dispatch"]
@@ -53,6 +56,13 @@ async function renderComposer(
})
}
const shellID = url.pathname.match(/^\/api\/shell\/([^/]+)$/)?.[1]
if (shellID && request.method === "GET") {
viewed.push(shellID)
return json({ location: { directory }, data: shells.find((shell) => shell.id === shellID) })
}
if (url.pathname.endsWith("/output")) {
return json({ location: { directory }, data: { output: "", cursor: 0, size: 0, truncated: false } })
}
if (shellID && request.method === "DELETE") {
removed.push(shellID)
return new Response(null, { status: 204 })
@@ -100,7 +110,11 @@ async function renderComposer(
<LocationProvider>
<RouteProvider initialRoute={{ type: "session", sessionID: "parent" }}>
<ThemeProvider mode="dark" source={{ discover: async () => ({}) }}>
<Content />
<ToastProvider>
<DialogProvider>
<Content />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</RouteProvider>
</LocationProvider>
@@ -119,6 +133,7 @@ async function renderComposer(
app,
interrupted,
removed,
viewed,
route: () => route.data,
dispatch: (command: string) => dispatch(command),
closed: () => closed,
@@ -154,15 +169,18 @@ test("disabled shell bindings have no component fallbacks", async () => {
const composer = await renderComposer("shell", {
"composer.shell.up": "none",
"composer.shell.down": "none",
"composer.shell.select": "none",
"composer.shell.kill": "none",
})
try {
expect(composer.app.captureCharFrame()).toContain("bun test")
composer.app.mockInput.pressArrow("up")
composer.app.mockInput.pressEnter()
composer.app.mockInput.pressKey("d", { ctrl: true })
await composer.app.renderOnce()
expect(composer.closed()).toBe(0)
expect(composer.removed).toEqual([])
expect(composer.viewed).toEqual([])
composer.app.mockInput.pressArrow("down")
composer.dispatch("composer.shell.kill")
@@ -198,6 +216,22 @@ test("ctrl+c closes the active composer", async () => {
}
})
test("shell output respects a configured binding with a focused textarea", async () => {
const composer = await renderComposer("shell", { "composer.shell.select": "ctrl+o" }, true)
try {
composer.app.mockInput.pressEnter()
await composer.app.renderOnce()
expect(composer.viewed).toEqual([])
composer.app.mockInput.pressKey("o", { ctrl: true })
await wait(() => composer.viewed.length > 0)
await composer.app.renderOnce()
expect(composer.app.captureCharFrame()).toContain("Shell output")
expect(composer.viewed).toEqual(["sh-a"])
} finally {
composer.app.renderer.destroy()
}
})
function session(id: string, title: string, parentID?: string) {
return {
id,
+7 -1
View File
@@ -15,6 +15,8 @@ import { LocationProvider, useLocation } from "../../../src/context/location"
import { RouteProvider } from "../../../src/context/route"
import { ThemeProvider } from "../../../src/context/theme"
import { Composer } from "../../../src/routes/session/composer"
import { DialogProvider } from "../../../src/ui/dialog"
import { ToastProvider } from "../../../src/ui/toast"
import { createSessionRows, type SessionRow } from "../../../src/routes/session/rows"
import { createApi, createEventStream, createFetch, directory, json, worktree } from "../../fixture/tui-client"
import { emptyThemeSource } from "../../fixture/fixture"
@@ -2020,7 +2022,11 @@ test("keeps shell state scoped to location", async () => {
<RouteProvider initialRoute={{ type: "session", sessionID: "ses_shared" }}>
<Keymap.Provider>
<ThemeProvider mode="dark" source={emptyThemeSource}>
<Composer sessionID="ses_shared" open={true} defaultTab="shell" />
<ToastProvider>
<DialogProvider>
<Composer sessionID="ses_shared" open={true} defaultTab="shell" />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</Keymap.Provider>
</RouteProvider>
@@ -0,0 +1,221 @@
/** @jsxImportSource @opentui/solid */
import { ScrollBoxRenderable } from "@opentui/core"
import { testRender } from "@opentui/solid"
import type { ShellInfo } from "@opencode-ai/client"
import { expect, test } from "bun:test"
import { createSignal, onMount } from "solid-js"
import { ConfigProvider } from "../../src/config"
import { ClientProvider } from "../../src/context/client"
import { DataProvider, useData } from "../../src/context/data"
import { Keymap } from "../../src/context/keymap"
import { RouteProvider } from "../../src/context/route"
import { ThemeProvider } from "../../src/context/theme"
import { Composer } from "../../src/routes/session/composer"
import { DialogProvider } from "../../src/ui/dialog"
import { ToastProvider } from "../../src/ui/toast"
import { emptyThemeSource, tmpdir } from "../fixture/fixture"
import { createApi, createEventStream, createFetch, json } from "../fixture/tui-client"
import { TestTuiContexts } from "../fixture/tui-environment"
import { createTuiResolvedConfig } from "../fixture/tui-runtime"
async function setup(width: number, output = "") {
const temporary = await tmpdir()
const location = { directory: `${temporary.path}/original`, workspaceID: "workspace_fixture" }
const shell: ShellInfo = {
id: "sh_fixture",
command: "render-scene --quality high",
cwd: location.directory,
shell: "/bin/sh",
file: `${temporary.path}/capture.out`,
status: "running",
metadata: { sessionID: "ses_fixture" },
time: { started: 0 },
}
const state = { output, missing: false, failure: false }
const requests: { url: URL; method: string }[] = []
const events = createEventStream()
const envelope = (data: unknown) => json({ location, data })
const api = createApi(
createFetch((url, request) => {
if (!url.pathname.startsWith("/api/shell")) return undefined
requests.push({ url, method: request.method })
if (url.pathname === "/api/shell") return envelope([shell])
if (state.missing)
return json({ _tag: "ShellNotFoundError", id: shell.id, message: "Shell not found" }, { status: 404 })
if (state.failure) return new Response("Unavailable", { status: 503 })
if (url.pathname === `/api/shell/${shell.id}`) return envelope(shell)
const bytes = Buffer.from(state.output)
const cursor = Math.min(Number(url.searchParams.get("cursor") ?? 0), bytes.length)
const end = Math.min(cursor + Number(url.searchParams.get("limit") ?? 65536), bytes.length)
return envelope({
output: bytes.subarray(cursor, end).toString(),
cursor: end,
size: bytes.length,
truncated: false,
})
}, events).fetch,
)
function Shells() {
const data = useData()
const [open, setOpen] = createSignal(true)
onMount(() => void data.shell.sync(location))
return <Composer sessionID="ses_fixture" open={open()} defaultTab="shell" onClose={() => setOpen(false)} />
}
const app = await testRender(
() => (
<TestTuiContexts directory={temporary.path} paths={{ state: temporary.path }}>
<ConfigProvider config={createTuiResolvedConfig({ session: { terminal: false } })}>
<RouteProvider initialRoute={{ type: "session", sessionID: "ses_fixture" }}>
<ClientProvider api={api}>
<DataProvider directory={temporary.path}>
<ThemeProvider mode={width === 40 ? "light" : "dark"} source={emptyThemeSource}>
<Keymap.Provider>
<ToastProvider>
<DialogProvider>
<Shells />
</DialogProvider>
</ToastProvider>
</Keymap.Provider>
</ThemeProvider>
</DataProvider>
</ClientProvider>
</RouteProvider>
</ConfigProvider>
</TestTuiContexts>
),
{ width, height: 30, kittyKeyboard: true },
)
app.renderer.start()
await app.waitForFrame((frame) => frame.includes(shell.command))
return {
...app,
state,
shell,
location,
requests,
events,
async [Symbol.asyncDispose]() {
app.renderer.destroy()
await temporary[Symbol.asyncDispose]()
},
}
}
test.each([40, 100])("shell output opens, follows, scrolls, and survives exit at %s columns", async (width) => {
await using app = await setup(width, Array.from({ length: 50 }, (_, i) => `Frame ${i + 1}\n`).join(""))
expect(app.captureCharFrame()).toContain("output")
app.mockInput.pressEnter()
await app.waitForFrame((frame) => frame.includes("Shell output") && frame.includes("Frame 50"))
const scroll = app.renderer.root.findDescendantById("shell-output-scroll")
if (!(scroll instanceof ScrollBoxRenderable)) throw new Error("Output scrollbox missing")
expect(scroll.scrollTop).toBeGreaterThan(0)
app.mockInput.pressKey("HOME")
await app.waitForFrame((frame) => frame.includes("Frame 1\n") || /Frame 1\s/.test(frame))
expect(scroll.scrollTop).toBe(0)
app.state.output += "Frame 51\n"
await app.waitFor(
() =>
app.requests.some(
(request) => request.url.searchParams.get("cursor") === String(Buffer.byteLength(app.state.output)),
),
{ maxPasses: 150 },
)
expect(scroll.scrollTop).toBe(0)
app.mockInput.pressKey("END")
await app.waitForFrame((frame) => frame.includes("Frame 51"))
app.shell.status = "exited"
app.shell.exit = 0
app.events.emit({
id: "evt_exit",
created: 0,
type: "shell.exited",
location: app.location,
data: { id: app.shell.id, exit: 0, status: "exited" },
})
await app.waitForFrame((frame) => frame.includes("code 0"), { maxPasses: 100 })
const metadataReads = app.requests.filter((request) => request.url.pathname === `/api/shell/${app.shell.id}`).length
// Terminal metadata can arrive before the capture's final flush.
app.state.output += "\u001b[32mRender complete\u001b[0m\r\n"
await app.waitForFrame((frame) => frame.includes("Render complete") && frame.includes("code 0"), { maxPasses: 100 })
expect(app.requests.filter((request) => request.url.pathname === `/api/shell/${app.shell.id}`)).toHaveLength(
metadataReads,
)
expect(app.captureCharFrame()).not.toContain("[32m")
expect(app.requests.every((request) => request.method === "GET")).toBe(true)
const reads = app.requests.filter((request) => request.url.pathname !== "/api/shell")
expect(reads.every((request) => request.url.searchParams.get("location[directory]") === app.location.directory)).toBe(
true,
)
expect(
reads.every((request) => request.url.searchParams.get("location[workspace]") === app.location.workspaceID),
).toBe(true)
app.mockInput.pressEscape()
await app.waitForFrame((frame) => !frame.includes("Shell output") && frame.includes("No shell commands"))
const count = app.requests.length
await Bun.sleep(1100)
expect(app.requests).toHaveLength(count)
})
test("empty output explains redirection, retries errors, and preserves output after removal", async () => {
await using app = await setup(100)
app.mockInput.pressEnter()
await app.waitForFrame((frame) => frame.includes("No captured output") && frame.includes("redirected"))
app.state.failure = true
await app.waitForFrame((frame) => frame.includes("Retrying"), { maxPasses: 100 })
app.state.failure = false
app.state.output = "Recovered output\n"
await app.waitForFrame((frame) => frame.includes("Recovered output") && !frame.includes("Retrying"), {
maxPasses: 100,
})
app.state.missing = true
await app.waitForFrame((frame) => frame.includes("no longer available"), { maxPasses: 100 })
expect(app.captureCharFrame()).toContain("Recovered output")
const count = app.requests.length
await Bun.sleep(1100)
expect(app.requests).toHaveLength(count)
})
test.each([40, 100])("mouse-wheel scrolling pauses and resumes output following at %s columns", async (width) => {
await using app = await setup(width, Array.from({ length: 50 }, (_, i) => `Frame ${i + 1}\n`).join(""))
app.mockInput.pressEnter()
await app.waitForFrame((frame) => frame.includes("Shell output") && frame.includes("Frame 50"))
const scroll = app.renderer.root.findDescendantById("shell-output-scroll")
if (!(scroll instanceof ScrollBoxRenderable)) throw new Error("Output scrollbox missing")
const bottom = scroll.scrollTop
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "up")
await app.waitFor(() => scroll.scrollTop < bottom)
const paused = scroll.scrollTop
const height = scroll.scrollHeight
app.state.output += "Frame 51\n"
await app.waitFor(() => scroll.scrollHeight > height, { maxPasses: 100 })
expect(scroll.scrollTop).toBe(paused)
expect(app.captureCharFrame()).toContain("Shell output")
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "down")
await app.mockMouse.scroll(scroll.viewport.x + 2, scroll.viewport.y + 2, "down")
await app.waitFor(() => scroll.scrollTop === scroll.scrollHeight - scroll.viewport.height)
const followed = scroll.scrollTop
app.state.output += "Frame 52\n"
await app.waitForFrame((frame) => frame.includes("Frame 52"), { maxPasses: 100 })
expect(scroll.scrollTop).toBeGreaterThan(followed)
expect(scroll.scrollTop).toBe(scroll.scrollHeight - scroll.viewport.height)
})
test("large captures open at a bounded tail and clicking a shell opens the viewer", async () => {
await using app = await setup(100, "old output\n".repeat(20000) + "Latest frame\n")
const row = app
.captureCharFrame()
.split("\n")
.findIndex((line) => line.includes(app.shell.command))
await app.mockMouse.click(6, row)
await app.waitForFrame((frame) => frame.includes("Latest frame") && frame.includes("Earlier output omitted"))
const reads = app.requests.filter((request) => request.url.pathname.endsWith("/output"))
expect(reads[0]?.url.searchParams.get("cursor")).toBe(String(Number.MAX_SAFE_INTEGER))
expect(reads[1]?.url.searchParams.get("cursor")).toBe(String(Buffer.byteLength(app.state.output) - 65536))
expect(reads[1]?.url.searchParams.get("limit")).toBe("65536")
})
@@ -9,6 +9,7 @@
overflow: hidden;
}
[data-component="split-button-v2"].session-review-v2-open-in-app,
[data-component="split-button-v2"]:is(:hover, :has([data-component="split-button-v2-menu-trigger"][data-expanded])) {
box-shadow: inset 0 0 0 1px var(--v2-border-border-muted);
}
@@ -1,4 +1,5 @@
import { Icon } from "@opencode-ai/ui/icon"
import { AppIcon } from "@opencode-ai/ui/app-icon"
import { SplitButton, SplitButtonAction, SplitButtonMenuTrigger } from "./split-button"
export default {
@@ -29,3 +30,16 @@ export const Disabled = {
</SplitButton>
),
}
export const OpenIn = {
render: () => (
<SplitButton class="session-review-v2-open-in-app">
<SplitButtonAction aria-label="Open in Finder">
<AppIcon id="finder" />
</SplitButtonAction>
<SplitButtonMenuTrigger aria-label="Open options">
<Icon name="chevron-down" size="small" />
</SplitButtonMenuTrigger>
</SplitButton>
),
}
+6 -2
View File
@@ -210,8 +210,12 @@ const layer = Layer.effect(
Effect.gen(function* () {
const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"))
const add = input.add ?? []
const npmOptions = yield* NpmConfig.load(input.config ?? input.dir)
const options = input.update ? { ...npmOptions, preferOnline: true, noGitRevCache: true } : npmOptions
const options = {
...(yield* NpmConfig.load(input.config ?? input.dir)),
...(input.update ? { preferOnline: true, noGitRevCache: true } : {}),
// Audit reports are unused here, but Arborist waits for them before completing an install.
audit: false,
}
const arborist = new Arborist({
...options,
path: input.dir,
@@ -317,8 +317,13 @@ The retired `diff.toggle`, `diff.expand`, `diff.expand_all`, `diff.collapse`, an
| `composer.subagent.interrupt` | `ctrl+d` | Interrupt subagent |
| `composer.shell.up` | `up` | Previous shell |
| `composer.shell.down` | `down` | Next shell |
| `composer.shell.select` | `return` | View shell output |
| `composer.shell.kill` | `ctrl+d` | Kill shell command |
Select a running command in the **Shell** tab and press **Enter**, or click it, to view captured stdout and stderr.
Use **↑/↓**, **Page Up/Down**, or **Home** to scroll, **End** to follow new output, and **Esc** to return without stopping the command.
The viewer shows recent output and stays open after exit; output redirected to a file is not included.
## Dialogs And Autocomplete
| ID | Default | Description |
+88
View File
@@ -0,0 +1,88 @@
import { Effect, Stream } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
const label = process.env.DEMO_LABEL ?? "AFTER"
// Run from the repository root with `opencode-drive run script/drive/shell-output.ts`.
// Set OPENCODE_DEV to an immutable base worktree and DEMO_LABEL=BEFORE for comparison.
// Only the conversation is simulated; shell execution and output reads are real.
export default OpenCodeDriver.use(
{
opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() },
keepArtifacts: true,
tui: { recording: true, keypressOverlay: true, viewport: { cols: 90, rows: 30 } },
config: { autoupdate: false, username: "Demo" },
tuiConfig: { theme: { name: "opencode", mode: "dark" }, animations: false, tabs: { enabled: false } },
project: {
git: true,
files: {
"README.md": "# Shell output demo\nDeterministic real shell output.\n",
"render-scene.sh": [
"#!/bin/sh",
"i=1",
'while [ "$i" -le 40 ]; do printf "Frame %02d: rendered successfully\\n" "$i"; i=$((i+1)); done',
"while [ ! -f continue ]; do sleep 0.1; done",
'while [ "$i" -le 48 ]; do printf "Frame %02d: rendered successfully\\n" "$i"; i=$((i+1)); sleep 0.25; done',
"while [ ! -f finish ]; do sleep 0.1; done",
"printf 'Diagnostics: no errors\\n' >&2",
"printf 'Render complete: 48 frames saved.\\n'",
].join("\n"),
},
},
},
({ ui, llm, tui, opencode, artifacts }) =>
Effect.gen(function* () {
const recording = tui.recording
if (!recording) return yield* Effect.fail(new Error("Recording required"))
yield* llm.serve(() => Stream.make(Llm.text("Ready to inspect the render job.")))
yield* ui.submit("Inspect the render job.")
yield* ui.waitFor("Ready to inspect the render job.")
const sessions = yield* opencode.session.list({ limit: 1, order: "desc" })
const session = sessions.data[0]
if (!session) return yield* Effect.fail(new Error("Session missing"))
yield* opencode.session.rename({ sessionID: session.id, title: "Shell output demo" })
yield* opencode.shell.create({ command: "sh render-scene.sh", timeout: 0, metadata: { sessionID: session.id } })
yield* ui.arrow("down")
yield* ui.arrow("right")
yield* ui.waitFor("sh render-scene.sh")
yield* recording.mark(`${label}: select a running shell`)
yield* Effect.sleep(1000)
yield* ui.enter()
yield* ui.waitFor(label === "AFTER" ? "Frame 40: rendered successfully" : "sh render-scene.sh")
yield* Effect.sleep(1000)
yield* recording.mark(`${label}: Enter ${label === "AFTER" ? "opens live output" : "does nothing"}`)
console.log("opened:", yield* ui.screenshot(`${label.toLowerCase()}-opened`))
yield* Effect.promise(() => Bun.write(`${artifacts}/files/continue`, "go"))
if (label === "AFTER") yield* ui.waitFor("Frame 48: rendered successfully")
yield* Effect.sleep(2800)
yield* ui.press("home")
yield* ui.waitFor(label === "AFTER" ? "Frame 01: rendered successfully" : "sh render-scene.sh")
yield* recording.mark(`${label}: ${label === "AFTER" ? "Home scrolls to earlier output" : "no output to scroll"}`)
yield* Effect.sleep(1500)
console.log("scrolled:", yield* ui.screenshot(`${label.toLowerCase()}-scrolled`))
yield* ui.press("end")
yield* ui.waitFor(label === "AFTER" ? "Frame 48: rendered successfully" : "sh render-scene.sh")
yield* recording.mark(`${label}: ${label === "AFTER" ? "End follows the latest output" : "no output to follow"}`)
yield* Effect.sleep(1000)
yield* Effect.promise(() => Bun.write(`${artifacts}/files/finish`, "go"))
yield* ui.waitFor(label === "AFTER" ? "Render complete: 48 frames saved." : "No shell commands")
if (label === "AFTER") yield* ui.waitFor("Exited · code 0")
yield* Effect.sleep(1600)
yield* recording.mark(
`${label}: ${label === "AFTER" ? "result stays open after exit" : "finished shell disappears"}`,
)
console.log("exited:", yield* ui.screenshot(`${label.toLowerCase()}-exited`))
yield* Effect.sleep(2000)
yield* ui.resize({ cols: 40, rows: 24 })
yield* Effect.sleep(500)
console.log("narrow:", yield* ui.screenshot(`${label.toLowerCase()}-narrow`))
yield* ui.resize({ cols: 90, rows: 30 })
yield* Effect.sleep(500)
yield* ui.press("escape")
if (label === "AFTER") yield* ui.waitFor("No shell commands")
yield* recording.mark(`${label}: Esc back`)
yield* Effect.sleep(1000)
console.log("back:", yield* ui.screenshot(`${label.toLowerCase()}-back`))
return console.log("video:", yield* recording.finish())
}),
)