feat(tui): render diffs in plugin panel slots (#47152)

This commit is contained in:
James Long
2026-10-14 11:26:36 -04:00
committed by GitHub
Unverified
parent c458ad72d3
commit c0d41d2b26
6 changed files with 892 additions and 122 deletions
+1
View File
@@ -85,6 +85,7 @@ export const Definitions = {
"diff.single_patch": keybind("s", "Toggle single patch view"),
"diff.switch_source": keybind("d", "Switch diff viewer source"),
"diff.toggle_view": keybind("v", "Toggle diff viewer split or unified view"),
"diff.toggle_fullscreen": keybind("f", "Toggle diff viewer full screen"),
"diff.mark_reviewed": keybind("m", "Toggle selected diff file reviewed"),
"diff.help": keybind("?,shift+?,shift+/", "Show more diff viewer shortcuts"),
@@ -2,6 +2,8 @@ import { Plugin } from "@opencode/plugin/tui"
import { createMemo, createSignal, Match, Show, Switch } from "solid-js"
import { contextUsage, formatContextUsage } from "../../util/session"
import { useTerminalDimensions } from "@opentui/solid"
import { TextAttributes } from "@opentui/core"
import { useInteractivity } from "../../context/interactivity"
import { stringWidth } from "../../util/string-width"
const money = new Intl.NumberFormat("en-US", {
@@ -47,6 +49,8 @@ export function PromptFooter(props: {
].filter((item): item is string => Boolean(item))
})
const live = createMemo(() => Boolean(subagents() || shells()))
// Prompt hints read as disabled while the session does not own input, e.g. while a side panel is focused.
const interactive = useInteractivity()
const shortcut = (id: string) => props.context.keymap.shortcuts(id)[0]
const layout = createMemo(() => {
const command = shortcut("command.palette.show")
@@ -93,14 +97,25 @@ export function PromptFooter(props: {
</box>
</Match>
<Match when={props.showDetails && layout().shortcuts}>
<text fg={props.context.theme.text.base} flexShrink={0}>
{shortcut("agent.cycle")} <span style={{ fg: props.context.theme.text.muted }}>agents</span>
<text
fg={interactive() ? props.context.theme.text.base : props.context.theme.text.formfield.disabled}
attributes={interactive() ? 0 : TextAttributes.DIM}
flexShrink={0}
>
{shortcut("agent.cycle")}{" "}
<span style={interactive() ? { fg: props.context.theme.text.muted } : {}}>agents</span>
</text>
</Match>
</Switch>
<Show when={props.showDetails && layout().shortcuts}>
<text fg={props.context.theme.text.base} wrapMode="none" flexShrink={0}>
{shortcut("command.palette.show")} <span style={{ fg: props.context.theme.text.muted }}>commands</span>
<text
fg={interactive() ? props.context.theme.text.base : props.context.theme.text.formfield.disabled}
attributes={interactive() ? 0 : TextAttributes.DIM}
wrapMode="none"
flexShrink={0}
>
{shortcut("command.palette.show")}{" "}
<span style={interactive() ? { fg: props.context.theme.text.muted } : {}}>commands</span>
</text>
</Show>
</Match>
@@ -2,11 +2,12 @@
import type { FileDiffInfo, LocationRef } from "@opencode/client"
import type { Vcs } from "@opencode/schema/vcs"
import { Plugin } from "@opencode/plugin/tui"
import type { KeymapCommand, Route } from "@opencode/plugin/tui/context"
import type { KeymapCommand, PanelInput, Route } from "@opencode/plugin/tui/context"
import {
MouseButton,
TextAttributes,
type BoxRenderable,
type RGBA,
type MouseEvent,
type ScrollBoxRenderable,
} from "@opentui/core"
@@ -23,7 +24,7 @@ import { getScrollAcceleration } from "../../util/scroll"
import { createDebouncedSignal } from "../../util/signal"
import { type DiffSource, useConfig } from "../../config"
import { locationKey } from "../../context/data"
import { useThemes } from "../../context/theme"
import { useTheme, useThemes } from "../../context/theme"
import { PatchDiff, type PatchDiffRef } from "../../component/patch-diff"
import {
allExpandedFileTreeDirectories,
@@ -81,26 +82,21 @@ const VCS_SOURCES = ["branch", "committed", "working"] as const
const needsBase = (mode: DiffMode) => mode === "branch" || mode === "committed"
function DiffViewer(props: { context: Plugin.Context }) {
const dimensions = useTerminalDimensions()
function DiffViewer(props: {
context: Plugin.Context
sessionID?: string
initialMode?: DiffMode
panel?: PanelInput
onClose: () => void
}) {
const config = useConfig()
const [memory, updateMemory] = props.context.storage.memory<{
source?: DiffMode
bases: Record<string, string>
}>("review", { initial: { bases: {} } })
const params = () => {
const route = props.context.ui.router.current()
return (route.type === "plugin" ? route.data : undefined) as
| {
mode?: DiffMode
sessionID?: string
returnRoute?: Route
}
| undefined
}
const sessionID = () => params()?.sessionID
const sessionID = () => props.sessionID
const sources = (): readonly DiffMode[] => (sessionID() ? [...VCS_SOURCES, "turn"] : VCS_SOURCES)
const initialMode = params()?.mode ?? memory.source ?? config.data.diffs?.source ?? "branch"
const initialMode = props.initialMode ?? memory.source ?? config.data.diffs?.source ?? "branch"
const [mode, setMode] = createSignal(sources().includes(initialMode) ? initialMode : "branch")
const location = createMemo(
() => {
@@ -188,52 +184,67 @@ function DiffViewer(props: { context: Plugin.Context }) {
if (!base) return "Base not reported"
return `vs ${base.name}`
}
return (
<DiffViewerContent
context={props.context}
files={result()?.files ?? []}
loading={diff.loading}
error={diff.error}
mode={mode()}
sources={sources()}
sourceDetail={sourceDetail()}
sourceBase={sourceBase()}
unavailable={mode() === "committed" && !!result() && !result()?.base}
preferences={config.data.diffs}
panel={props.panel}
loadImage={(file, signal) => props.context.client.file.read({ path: file, location: location() }, { signal })}
onPreferencesChange={(value) => {
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, ...value }
})
.catch(() => {})
}}
onClose={props.onClose}
onSwitchSource={(mode) => {
updateMemory((draft) => {
draft.source = mode
})
setMode(mode)
}}
onChooseBase={() => {
const target = { ...location() }
const key = baseKey()
if (!memory.bases[key]) void loadBase(target, key).catch(() => {})
props.context.ui.dialog.show(() => (
<DiffBaseDialog
context={props.context}
location={target}
current={memory.bases[key] ?? reportedBases().get(key)?.ref}
onSelect={(ref) =>
updateMemory((draft) => {
draft.bases[key] = ref
})
}
/>
))
}}
/>
)
}
function DiffRoute(props: {
context: Plugin.Context
data?: { mode?: DiffMode; sessionID?: string; returnRoute?: Route }
}) {
const dimensions = useTerminalDimensions()
return (
<box position="absolute" zIndex={2500} left={0} top={0} width={dimensions().width} height={dimensions().height}>
<DiffViewerContent
<DiffViewer
context={props.context}
files={result()?.files ?? []}
loading={diff.loading}
error={diff.error}
mode={mode()}
sources={sources()}
sourceDetail={sourceDetail()}
sourceBase={sourceBase()}
unavailable={mode() === "committed" && !!result() && !result()?.base}
preferences={config.data.diffs}
loadImage={(file, signal) => props.context.client.file.read({ path: file, location: location() }, { signal })}
onPreferencesChange={(value) => {
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, ...value }
})
.catch(() => {})
}}
onClose={() => props.context.ui.router.navigate(params()?.returnRoute ?? { type: "home" })}
onSwitchSource={(mode) => {
updateMemory((draft) => {
draft.source = mode
})
setMode(mode)
}}
onChooseBase={() => {
const target = { ...location() }
const key = baseKey()
if (!memory.bases[key]) void loadBase(target, key).catch(() => {})
props.context.ui.dialog.show(() => (
<DiffBaseDialog
context={props.context}
location={target}
current={memory.bases[key] ?? reportedBases().get(key)?.ref}
onSelect={(ref) =>
updateMemory((draft) => {
draft.bases[key] = ref
})
}
/>
))
}}
sessionID={props.data?.sessionID}
initialMode={props.data?.mode}
onClose={() => props.context.ui.router.navigate(props.data?.returnRoute ?? { type: "home" })}
/>
</box>
)
@@ -298,6 +309,7 @@ export function DiffViewerContent(props: {
unavailable?: boolean
loadImage?: (file: string, signal: AbortSignal) => Promise<Uint8Array>
preferences?: DiffPreferences
panel?: PanelInput
onPreferencesChange?: (value: DiffPreferences) => void
onClose: () => void
onSwitchSource: (mode: DiffMode) => void
@@ -307,19 +319,25 @@ export function DiffViewerContent(props: {
const dimensions = useTerminalDimensions()
const config = useConfig()
const dialog = props.context.ui.dialog
const theme = useThemes().current
const theme = useTheme()
const currentSyntax = useThemes().currentSyntax
const files = () => props.files
const docked = () => props.panel?.presentation === "panel"
// The side panel sits on the slot's raised surface; full screen keeps the base background.
const surface = () => (docked() ? theme.background.raised.base : theme.background.base)
// Cards are inset from the pane edges; the gaps between them run edge to edge.
const inset = () => (docked() ? 1 : 2)
const width = () => props.panel?.width ?? dimensions().width
const mode = () => props.mode
const [fileTreeEnabled, setFileTreeEnabled] = createSignal(props.preferences?.tree ?? true)
const showFileTree = createMemo(
() => dimensions().width >= 90 && showDiffViewerFileTree(fileTreeEnabled(), files().length),
() => !docked() && width() >= 90 && showDiffViewerFileTree(fileTreeEnabled(), files().length),
)
const [singlePatch, setSinglePatch] = createSignal(props.preferences?.single ?? false)
const fileTreeWidth = createMemo(() =>
Math.max(FILE_TREE_MIN_WIDTH, Math.min(FILE_TREE_MAX_WIDTH, Math.floor(dimensions().width / 4))),
Math.max(FILE_TREE_MIN_WIDTH, Math.min(FILE_TREE_MAX_WIDTH, Math.floor(width() / 4))),
)
const patchPaneWidth = createMemo(() => dimensions().width - (showFileTree() ? fileTreeWidth() : 0) - 4)
const patchPaneWidth = createMemo(() => width() - (showFileTree() ? fileTreeWidth() : 0) - (docked() ? 2 : 4))
const splitAvailable = createMemo(() => patchPaneWidth() >= MIN_SPLIT_WIDTH)
const [viewOverride, setViewOverride] = createSignal<DiffView | undefined>(storedView(props.preferences?.view))
const view = createMemo(() =>
@@ -339,8 +357,6 @@ export function DiffViewerContent(props: {
const [selectedHunk, setSelectedHunk] = createSignal<SelectedHunk | undefined>()
const [pendingPatchScrollFileIndex, setPendingPatchScrollFileIndex] = createSignal<number | undefined>()
onCleanup(() => dialog.clear())
createEffect(() => {
setExpandedFileNodes(allExpandedFileTreeDirectories(fileTree()))
setSelectedFileIndex(undefined)
@@ -548,6 +564,7 @@ export function DiffViewerContent(props: {
if (event.button !== MouseButton.RIGHT) return
event.preventDefault()
event.stopPropagation()
props.panel?.focus()
setFileMenu({ fileIndex, x: event.x, y: event.y })
}
@@ -667,7 +684,9 @@ export function DiffViewerContent(props: {
id: "diff.toggle_file_tree",
title: "Toggle diff viewer file tree",
group: "VCS",
enabled: () => !docked(),
run() {
if (docked()) return
const next = !fileTreeEnabled()
setFileTreeEnabled(next)
props.onPreferencesChange?.({ tree: next })
@@ -715,6 +734,13 @@ export function DiffViewerContent(props: {
props.onPreferencesChange?.({ view: next })
},
},
{
id: "diff.toggle_fullscreen",
title: "Toggle diff viewer full screen",
group: "VCS",
enabled: () => props.panel !== undefined,
run: () => props.panel?.toggleFullscreen(),
},
{
id: "diff.help",
title: "Show more diff viewer shortcuts",
@@ -767,16 +793,24 @@ export function DiffViewerContent(props: {
}
const openHelpDialog = () => {
dialog.show(() => <DiffViewerHelpDialog context={props.context} single={singlePatch()} />)
dialog.show(() => (
<DiffViewerHelpDialog
context={props.context}
single={singlePatch()}
fullscreen={props.panel !== undefined}
tree={!docked()}
/>
))
dialog.set({ size: "medium", centered: true })
}
const HelpShortcut = (props: { compact?: boolean }) => (
const HelpShortcut = (props: { compact?: boolean; label?: string; muted?: boolean }) => (
<Show when={helpShortcut()}>
{(shortcut) => (
<text
id="diff-help-shortcut"
fg={theme.text.base}
fg={props.muted ? theme.text.formfield.disabled : theme.text.base}
attributes={props.muted ? TextAttributes.DIM : 0}
selectable={false}
flexShrink={0}
wrapMode="none"
@@ -788,7 +822,7 @@ export function DiffViewerContent(props: {
>
{props.compact ? "?" : shortcut()}
<Show when={!props.compact}>
<span style={{ fg: theme.text.muted }}> help</span>
<span style={props.muted ? {} : { fg: theme.text.muted }}> {props.label ?? "help"}</span>
</Show>
</text>
)}
@@ -800,13 +834,15 @@ export function DiffViewerContent(props: {
}))
return (
<box width="100%" height="100%" backgroundColor={theme.background.base}>
<box width="100%" height="100%" backgroundColor={surface()}>
<Show when={!showFileTree()}>
<box
id="diff-source-header"
paddingLeft={2}
paddingRight={2}
height={1}
paddingTop={1}
paddingBottom={1}
height={3}
flexShrink={0}
flexDirection="row"
gap={1}
@@ -892,9 +928,11 @@ export function DiffViewerContent(props: {
/>
</Show>
<box flexGrow={1} minWidth={0} minHeight={0} paddingLeft={2} paddingRight={2}>
<box flexGrow={1} minWidth={0} minHeight={0}>
<box
id="diff-patch-top-edge"
marginLeft={inset()}
marginRight={inset()}
ref={(edge: BoxRenderable) => {
// The fixed edge belongs to the visible card, not the tree selection.
edge.onLifecyclePass = () => {
@@ -936,16 +974,9 @@ export function DiffViewerContent(props: {
return (
<box ref={(element: BoxRenderable) => registerPatchNode(entry.fileIndex, element)}>
<Show when={index() > 0}>
<box
height={1}
flexShrink={0}
border={["top"]}
borderColor={background()}
backgroundColor={theme.background.base}
customBorderChars={{ ...EmptyBorder, horizontal: "▄" }}
/>
<CardGap glyph="▄" card={background()} surface={surface()} inset={inset()} />
</Show>
<box backgroundColor={background()}>
<box backgroundColor={background()} marginLeft={inset()} marginRight={inset()}>
<box
id={`diff-file-header-${entry.fileIndex}`}
onMouseDown={(event) => openFileMenu(entry.fileIndex, event)}
@@ -971,7 +1002,7 @@ export function DiffViewerContent(props: {
zIndex={1}
backgroundColor={background()}
paddingLeft={1}
paddingRight={1}
paddingRight={docked() ? 0 : 1}
paddingBottom={1}
>
<box flexGrow={1} minWidth={0}>
@@ -996,17 +1027,9 @@ export function DiffViewerContent(props: {
</text>
</Show>
<Show when={reviewed()}>
<box
position="absolute"
left={0}
bottom={0}
width="100%"
height={1}
border={["bottom"]}
borderColor={background()}
backgroundColor={theme.background.base}
customBorderChars={{ ...EmptyBorder, horizontal: "▀" }}
/>
<box position="absolute" left={-inset()} right={-inset()} bottom={0} height={1}>
<CardGap glyph="▀" card={background()} surface={surface()} inset={inset()} />
</box>
</Show>
</box>
<Show when={!reviewed()}>
@@ -1075,8 +1098,43 @@ export function DiffViewerContent(props: {
</Match>
</Switch>
</box>
<Show when={!showFileTree()}>
<box position="absolute" top={0} right={0} width={1} height={1}>
<Show when={docked()}>
{/* The footer sits on the terminal background, eased in by a half-cell like the prompt. */}
<box id="diff-footer" flexShrink={0} backgroundColor={theme.background.base}>
<box
height={1}
flexShrink={0}
border={["bottom"]}
borderColor={surface()}
backgroundColor={theme.background.base}
customBorderChars={{ ...EmptyBorder, horizontal: "▀" }}
/>
<box height={1} flexShrink={0} flexDirection="row" paddingLeft={2} paddingRight={2}>
<text
fg={props.panel?.focused ? theme.background.action.primary.focused : theme.text.formfield.disabled}
attributes={props.panel?.focused ? 0 : TextAttributes.DIM}
flexGrow={1}
minWidth={0}
wrapMode="none"
truncate
selectable={false}
onMouseUp={(event) => {
if (event.button !== MouseButton.LEFT) return
if (!props.panel?.focused) props.panel?.focus()
}}
>
<span>{props.context.keymap.shortcuts("pane.focus.left")[0] ?? ""}</span>
<span style={props.panel?.focused ? { fg: theme.text.muted } : {}}> focus prompt</span>
</text>
<box flexShrink={0}>
<HelpShortcut label="see all" muted={!props.panel?.focused} />
</box>
</box>
<box height={1} flexShrink={0} />
</box>
</Show>
<Show when={!showFileTree() && !docked()}>
<box position="absolute" top={1} right={0} width={1} height={1}>
<HelpShortcut compact />
</box>
</Show>
@@ -1095,7 +1153,30 @@ export function DiffViewerContent(props: {
)
}
function DiffViewerHelpDialog(props: { context: Plugin.Context; single: boolean }) {
/** A half-row of base background between cards: the card's color over its width, the pane surface in the insets. */
function CardGap(props: { glyph: "▄" | "▀"; card: RGBA; surface: RGBA; inset: number }) {
const theme = useTheme()
const half = (color: RGBA, width?: number) => (
<box
height={1}
flexShrink={0}
{...(width === undefined ? { flexGrow: 1 } : { width })}
border={[props.glyph === "▄" ? "top" : "bottom"]}
borderColor={color}
backgroundColor={theme.background.base}
customBorderChars={{ ...EmptyBorder, horizontal: props.glyph }}
/>
)
return (
<box height={1} flexShrink={0} flexDirection="row">
{half(props.surface, props.inset)}
{half(props.card)}
{half(props.surface, props.inset)}
</box>
)
}
function DiffViewerHelpDialog(props: { context: Plugin.Context; single: boolean; fullscreen: boolean; tree: boolean }) {
const dimensions = useTerminalDimensions()
const theme = props.context.theme.surface("dialog")
const shortcut =
@@ -1133,8 +1214,11 @@ function DiffViewerHelpDialog(props: { context: Plugin.Context; single: boolean
rows: [
{ shortcut: shortcut("diff.toggle_view"), label: "Split / unified" },
{ shortcut: shortcut("diff.single_patch"), label: "All files / single file" },
{ shortcut: shortcut("diff.toggle_file_tree"), label: "Show / hide file tree" },
...(props.tree ? [{ shortcut: shortcut("diff.toggle_file_tree"), label: "Show / hide file tree" }] : []),
{ shortcut: shortcut("diff.switch_source"), label: "Switch diff source" },
...(props.fullscreen
? [{ shortcut: shortcut("diff.toggle_fullscreen"), label: "Full screen / split view" }]
: []),
{ shortcut: () => props.context.keymap.shortcuts("diff.close").join(" / "), label: "Close diff viewer" },
],
},
@@ -1203,6 +1287,13 @@ function Commands(props: { context: Plugin.Context }) {
palette: true,
run() {
const route = props.context.ui.router.current()
props.context.ui.dialog.clear()
const current = props.context.ui.panel.current()
if (route.type === "session" && current?.sessionID === route.sessionID && current.name === ROUTE) {
props.context.ui.panel.close()
return
}
if (props.context.ui.panel.open(ROUTE)) return
const returnRoute: Route =
route.type === "home"
? { type: "home" }
@@ -1222,7 +1313,6 @@ function Commands(props: { context: Plugin.Context }) {
returnRoute,
},
})
props.context.ui.dialog.clear()
},
},
],
@@ -1233,9 +1323,17 @@ function Commands(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.diffs",
setup(context) {
context.ui.slot({
append: "session.panel",
render: (panel) => (
<Show when={panel.name === ROUTE}>
<DiffViewer context={context} sessionID={panel.sessionID} panel={panel} onClose={panel.close} />
</Show>
),
})
context.ui.router.register({
name: ROUTE,
render: () => <DiffViewer context={context} />,
render: ({ data }) => <DiffRoute context={context} data={data} />,
})
context.ui.slot({ append: "app", render: () => <Commands context={context} /> })
},
+53 -20
View File
@@ -69,6 +69,28 @@ test("closing the diff viewer returns to the route it opened from", async () =>
}
})
test.each([80, 160])("standalone full-screen diff does not expose panel-only toggling at %i columns", async (width) => {
const viewer = await renderDiffViewer([], {
width,
initialRoute: {
type: "plugin",
id: "opencode.diffs",
name: "diff",
data: { sessionID: "session-1", returnRoute: startRoute, split: true },
},
})
try {
const command = viewer.commands.get("diff.toggle_fullscreen")
expect(typeof command?.enabled === "function" ? command.enabled() : command?.enabled).toBe(false)
const route = viewer.current()
viewer.app.mockInput.pressKey("f")
await viewer.app.flush()
expect(viewer.current()).toEqual(route)
} finally {
viewer.app.renderer.destroy()
}
})
test("ctrl+c closes the diff viewer without exiting the application", async () => {
const viewer = await renderDiffViewer([])
@@ -300,10 +322,13 @@ test.each([50, 80, 160])(
const header = viewer.app.renderer.root.findDescendantById("diff-source-header")!
const source = viewer.app.renderer.root.findDescendantById("diff-source-switch")!
const count = viewer.app.renderer.root.findDescendantById("diff-review-count")!
expect(header.height).toBe(1)
expect(source.y).toBe(header.y)
expect(count.y).toBe(header.y)
expect(viewer.app.captureCharFrame().split("\n")[header.y]).toMatch(/All · vs release\s+0\/1/)
// Without the file tree, the header has one row of padding above and below its title.
const padded = width < 100
expect(header.height).toBe(padded ? 3 : 1)
const title = header.y + (padded ? 1 : 0)
expect(source.y).toBe(title)
expect(count.y).toBe(title)
expect(viewer.app.captureCharFrame().split("\n")[title]).toMatch(/All · vs release\s+0\/1/)
expect(viewer.app.captureCharFrame()).not.toContain("reviewed")
expect(viewer.vcsDiffInput()).toMatchObject({ base: "refs/remotes/origin/release" })
await viewer.app.mockMouse.click(source.x, source.y)
@@ -323,7 +348,7 @@ test.each([50, 80, 160])(
await viewer.app.waitForFrame((frame) => !frame.includes("Diff source"))
viewer.commands.get("diff.mark_reviewed")!.run()
await viewer.app.flush()
expect(viewer.app.captureCharFrame().split("\n")[header.y]).toMatch(/All · vs release\s+1\/1/)
expect(viewer.app.captureCharFrame().split("\n")[title]).toMatch(/All · vs release\s+1\/1/)
await chooseSource(viewer, 2)
await viewer.app.waitForFrame((frame) => frame.includes("Uncommitted · vs HEAD"))
viewer.app.mockInput.pressKey("d")
@@ -348,18 +373,20 @@ test.each([50, 80, 100, 160])(
try {
const header = viewer.app.renderer.root.findDescendantById("diff-source-header")!
const count = viewer.app.renderer.root.findDescendantById("diff-review-count")!
const row = viewer.app.captureCharFrame().split("\n")[header.y]
expect(header.height).toBe(1)
const padded = width < 100
const title = header.y + (padded ? 1 : 0)
const row = viewer.app.captureCharFrame().split("\n")[title]
expect(header.height).toBe(padded ? 3 : 1)
expect(row).toContain("Committed · vs")
expect(row).toContain("0/1")
expect(row).not.toContain("release/very-long-comparison-branch-name-that-does-not-fit-in-the-header")
expect(count.y).toBe(header.y)
expect(count.y).toBe(title)
expect(count.x + count.width).toBeLessThanOrEqual(header.x + header.width)
const hint = viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!
if (width < 90) {
expect(hint.y).toBe(header.y)
expect(hint.y).toBe(title)
expect(hint.x).toBeGreaterThan(count.x + count.width)
expect(findScrollBox(viewer.app.renderer.root)!.viewport.y).toBeGreaterThan(header.y)
expect(findScrollBox(viewer.app.renderer.root)!.viewport.y).toBeGreaterThan(header.y + header.height - 1)
}
} finally {
viewer.app.renderer.destroy()
@@ -1015,7 +1042,7 @@ test.each([100, 160])("shared pane edges align headings and stay fixed at %i col
await viewer.app.flush()
expect(viewer.app.renderer.root.findDescendantById("diff-tree-top-edge")).toBeUndefined()
expect(viewer.app.renderer.root.findDescendantById("diff-patch-top-edge")).toBeDefined()
expect(viewer.app.captureCharFrame().split("\n")[title + 1]).toContain("file01.txt")
expect(viewer.app.captureCharFrame().split("\n")[title + 3]).toContain("file01.txt")
} finally {
viewer.app.renderer.destroy()
}
@@ -1032,7 +1059,9 @@ test.each(["dark", "light"] as const)("the pane edge matches the visible reviewe
const scroll = findScrollBox(viewer.app.renderer.root)!
const expectEdge = (file: string, collapsed = false) => {
const frame = viewer.app.captureSpans()
const edge = frame.lines[scroll.viewport.y - 1].spans.find((span) => span.width === scroll.viewport.width)!
// Full-screen cards are inset two columns from each pane edge.
const card = scroll.viewport.width - 4
const edge = frame.lines[scroll.viewport.y - 1].spans.find((span) => span.width === card)!
const page = frame.lines[scroll.viewport.y - 1].spans.at(-1)!.bg
const title = frame.lines[scroll.viewport.y].spans.find((span) => span.text.includes(file))!
expect(title, viewer.app.captureCharFrame()).toBeDefined()
@@ -1040,12 +1069,14 @@ test.each(["dark", "light"] as const)("the pane edge matches the visible reviewe
expect(edge.bg).toEqual(title.bg)
expect(edge.bg).not.toEqual(page)
expect(frame.lines[0].spans[0].bg).toEqual(frame.lines[1].spans.find((span) => span.text.includes("All"))!.bg)
const bottom = frame.lines[scroll.viewport.y + 1].spans.findLast((span) => span.text.includes("▀"))
const bottom = frame.lines[scroll.viewport.y + 1].spans.find(
(span) => span.text.includes("▀") && span.width === card,
)
if (!collapsed) {
expect(bottom).toBeUndefined()
return
}
expect(bottom?.text.trim()).toBe("▀".repeat(scroll.viewport.width))
expect(bottom?.text.trim()).toBe("▀".repeat(card))
expect(bottom?.fg).toEqual(edge.bg)
expect(bottom?.bg).toEqual(page)
}
@@ -1069,7 +1100,8 @@ test.each(["dark", "light"] as const)("the pane edge matches the visible reviewe
expectEdge("file0.txt", true)
const second = viewer.app.renderer.root.findDescendantById("diff-file-header-1")!
const frame = viewer.app.captureSpans()
expect(frame.lines[second.y - 1].spans.findLast((span) => span.text.includes("▄"))!.fg).toEqual(
// The gap's card segment sits between the two inset segments.
expect(frame.lines[second.y - 1].spans.find((span) => span.text.includes("▄") && span.width > 2)!.fg).toEqual(
frame.lines[second.y].spans.find((span) => span.text.includes("file1.txt"))!.bg,
)
@@ -1135,9 +1167,9 @@ test("compact gutter help leaves the full patch viewport available when the side
await viewer.app.flush()
const scroll = findScrollBox(viewer.app.renderer.root)!
const hint = viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!
expect(hint.y).toBe(0)
expect(hint.y).toBe(1)
expect(hint.x).toBe(159)
expect(scroll.viewport.y).toBe(2)
expect(scroll.viewport.y).toBe(4)
expect(scroll.viewport.y + scroll.viewport.height).toBe(24)
await viewer.app.mockMouse.click(hint.x, hint.y)
await viewer.app.waitForFrame((frame) => frame.includes("Diff shortcuts"))
@@ -1150,11 +1182,11 @@ test("compact gutter help leaves the full patch viewport available when the side
expect(viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!.y).toBe(21)
viewer.app.resize(80, 24)
await viewer.app.flush()
expect(viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!.y).toBe(0)
expect(viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!.y).toBe(1)
expect(viewer.app.renderer.root.findDescendantById("diff-help-shortcut")!.x).toBe(79)
expect(scroll.viewport.y + scroll.viewport.height).toBe(24)
expect(viewer.app.captureCharFrame()).not.toContain("? help")
expect(viewer.app.captureCharFrame().split("\n")[0].at(-1)).toBe("?")
expect(viewer.app.captureCharFrame().split("\n")[1].at(-1)).toBe("?")
viewer.app.mockInput.pressKey("d")
await viewer.app.waitForFrame((frame) => frame.includes("Diff source"))
viewer.app.mockInput.pressEscape()
@@ -1332,7 +1364,7 @@ test.each(["patch", "image", "fallback"] as const)(
if (!(header instanceof BoxRenderable)) throw new Error("Missing reviewed file title")
expect(header.parent?.height).toBe(header.height)
expect(header.height).toBe(2)
expect(viewer.app.captureCharFrame().split("\n")[header.y + 1].trim()).toBe("▀".repeat(header.width))
expect(viewer.app.captureCharFrame().split("\n")[header.y + 1].trim()).toBe("▀".repeat(header.width + 4))
expect(header.y).toBe(scroll.viewport.y)
expect(viewer.app.captureCharFrame()).toContain(file.file)
expect(viewer.app.captureCharFrame()).toContain("✓")
@@ -2001,6 +2033,7 @@ async function renderDiffViewer(
},
ui: {
dialog: createDialogApi(dialog, (render) => render()),
panel: { open: () => false, close: () => {}, current: () => undefined },
router: {
register(page: Page) {
if (page.name === "diff") renderDiff = page.render
+1
View File
@@ -243,6 +243,7 @@ test("centralizes named command defaults and resolves explicit none", () => {
"diff.next_hunk": "]",
"diff.previous_hunk": "[",
"diff.mark_reviewed": "m",
"diff.toggle_fullscreen": "f",
"diff.help": "?,shift+?,shift+/",
}
const config = resolve({}, { terminalSuspend: true })
+622
View File
@@ -0,0 +1,622 @@
import { expect, test } from "bun:test"
import {
DiffRenderable,
InputRenderable,
MouseButton,
type Renderable,
ScrollBoxRenderable,
TextareaRenderable,
} from "@opentui/core"
import type { FileDiffInfo, FormInfo, PermissionRequest, SessionInfo } from "@opencode/client"
import type { Config } from "../src/config"
import { createAppFixture } from "./fixture/app"
import { directory, json } from "./fixture/tui-client"
import { tmpdir } from "./fixture/fixture"
test("/diff focuses the production session panel without sending typing to the prompt", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path)
await ready(setup)
const prompt = editor(setup)
const transcript = node(setup, "msg_panel_11")
expect(setup.requests.base).toHaveLength(0)
expect(setup.requests.diff).toHaveLength(0)
await setup.mockInput.typeText("/diff")
await setup.waitForFrame((frame) => frame.includes("Open diff viewer"))
setup.mockInput.pressEnter()
await panelReady(setup)
const panel = node(setup, "session-panel")
const patches = scroll(setup)
expect(panel.width).toBeLessThan(setup.renderer.width)
expect(setup.renderer.currentFocusedEditor).toBeNull()
expect(node(setup, "msg_panel_11")).toBe(transcript)
await setup.mockInput.typeText("xyz")
setup.mockInput.pressEnter()
await setup.flush()
expect(prompt.plainText).toBe("")
expect(setup.requests.prompt).toHaveLength(0)
focus(setup, "left")
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
await setup.mockInput.typeText("fjm")
await setup.flush()
expect(prompt.plainText).toBe("fjm")
expect(panel.width).toBeLessThan(setup.renderer.width)
expect(patches.scrollTop).toBe(0)
expect(text(setup, "diff-review-count")).toBe("0/4")
focus(setup, "right")
await setup.waitFor(() => setup.renderer.currentFocusedRenderable === panel)
setup.mockInput.pressKey("j")
await setup.waitFor(() => patches.scrollTop > 0)
expect(prompt.plainText).toBe("fjm")
setup.mockInput.pressKey("q")
await setup.waitFor(() => !setup.renderer.root.findDescendantById("session-panel"))
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
expect(node(setup, "msg_panel_11")).toBe(transcript)
expect(prompt.plainText).toBe("fjm")
expect(setup.requests.prompt).toHaveLength(0)
})
test("repeated fullscreen toggles retain the viewer, transcript, scroll, and reviewed files", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path)
await ready(setup)
const prompt = editor(setup)
const transcript = node(setup, "msg_panel_11")
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
const patches = scroll(setup)
const splitWidth = panel.width
const history = descendants(setup.renderer.root).find(
(item) => item instanceof ScrollBoxRenderable && item.findDescendantById("msg_panel_11"),
)
if (!(history instanceof ScrollBoxRenderable)) throw new Error("Missing session transcript scrollbox")
history.scrollTo(4)
await setup.flush()
const historyTop = history.scrollTop
expect(historyTop).toBeGreaterThan(0)
setup.mockInput.pressKey("m")
await setup.waitForFrame(() => text(setup, "diff-review-count") === "1/4")
await setup.flush()
setup.mockInput.pressKey("n")
await setup.waitFor(() => patches.scrollTop > 0)
setup.mockInput.pressKey("j")
await setup.flush()
const top = patches.scrollTop
const header = node(setup, "diff-file-header-1")
const diffs = descendants(patches).filter((item) => item instanceof DiffRenderable)
expect(diffs).toHaveLength(3)
expect(top).toBeGreaterThan(0)
for (const fullscreen of [true, false, true, false]) {
setup.mockInput.pressKey("f")
await setup.waitFor(() => node(setup, "session-panel").width === (fullscreen ? setup.renderer.width : splitWidth))
await setup.flush()
expect(node(setup, "session-panel")).toBe(panel)
expect(scroll(setup)).toBe(patches)
expect(patches.scrollTop).toBe(top)
expect(node(setup, "diff-file-header-1")).toBe(header)
const current = descendants(patches).filter((item) => item instanceof DiffRenderable)
expect(current).toHaveLength(diffs.length)
current.forEach((item, index) => expect(item).toBe(diffs[index]))
expect(text(setup, "diff-review-count")).toBe("1/4")
expect(node(setup, "msg_panel_11")).toBe(transcript)
expect(transcript.isDestroyed).toBe(false)
expect(history.isDestroyed).toBe(false)
expect(history.scrollTop).toBe(historyTop)
expect(prompt.isDestroyed).toBe(false)
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
expect(setup.requests.base).toHaveLength(1)
expect(setup.requests.diff).toHaveLength(1)
}
setup.mockInput.pressKey("HOME")
await setup.waitForFrame((frame) => frame.includes("file00.txt") && text(setup, "diff-file-header-0").includes("✓"))
expect(text(setup, "diff-file-header-0")).toContain("✓")
expect(setup.requests.diff[0].searchParams.get("location[directory]")).toBe(directory)
expect(setup.requests.diff[0].searchParams.get("base")).toBe("refs/heads/v2")
})
test("docked tree commands leave the full-screen tree preference unchanged", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, { diffs: { tree: true } })
await ready(setup)
setup.mockInput.pressKey("F6")
await panelReady(setup)
expect(setup.renderer.root.findDescendantById("diff-files")).toBeUndefined()
setup.mockInput.pressKey("b")
await setup.flush()
expect(setup.renderer.root.findDescendantById("diff-files")).toBeUndefined()
setup.mockInput.pressKey("f")
await setup.waitFor(() => setup.renderer.root.findDescendantById("diff-files") !== undefined)
setup.mockInput.pressKey("b")
await setup.waitFor(() => setup.renderer.root.findDescendantById("diff-files") === undefined)
setup.mockInput.pressKey("f")
await setup.waitFor(() => node(setup, "session-panel").width < setup.renderer.width)
setup.mockInput.pressKey("f")
await setup.waitFor(() => node(setup, "session-panel").width === setup.renderer.width)
expect(setup.renderer.root.findDescendantById("diff-files")).toBeUndefined()
expect(setup.requests.diff).toHaveLength(1)
})
test("right-clicking an inactive diff focuses its screen-relative file menu", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path)
await ready(setup)
const prompt = editor(setup)
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
focus(setup, "left")
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
const header = node(setup, "diff-file-header-0")
await setup.mockMouse.click(header.x + 1, header.y, MouseButton.RIGHT)
await setup.waitFor(() => setup.renderer.root.findDescendantById("diff-file-menu") !== undefined)
const menu = node(setup, "diff-file-menu")
expect(menu.x).toBe(Math.min(header.x + 1, setup.renderer.width - menu.width))
expect(menu.x + menu.width).toBeLessThanOrEqual(setup.renderer.width)
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
setup.mockInput.pressEnter()
await setup.waitForFrame(() => text(setup, "diff-review-count") === "1/4")
expect(setup.renderer.root.findDescendantById("diff-file-menu")).toBeUndefined()
expect(prompt.plainText).toBe("")
})
test.each([60, 80])("a panel opened at %i columns can split after growing without remounting", async (width) => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, { width })
await ready(setup)
const prompt = editor(setup)
const transcript = node(setup, "msg_panel_11")
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
const patches = scroll(setup)
expect(panel.width).toBe(width)
setup.mockInput.pressKey("f")
await setup.flush()
expect(panel.width).toBe(width)
expect(prompt.plainText).toBe("")
setup.resize(160, 36)
await setup.flush()
const grownWidth = panel.width
setup.mockInput.pressKey("f")
await setup.waitFor(() => node(setup, "session-panel").width !== grownWidth)
expect(node(setup, "session-panel")).toBe(panel)
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width === grownWidth)
if (panel.width === setup.renderer.width) {
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width < setup.renderer.width)
}
expect(panel.x).toBeGreaterThan(0)
setup.resize(80, 36)
await setup.waitFor(() => panel.width === 80)
expect(scroll(setup)).toBe(patches)
expect(node(setup, "msg_panel_11")).toBe(transcript)
expect(prompt.isDestroyed).toBe(false)
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
expect(setup.requests.base).toHaveLength(1)
expect(setup.requests.diff).toHaveLength(1)
})
test("split eligibility uses the columns remaining beside vertical session tabs", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, {
width: 122,
tabs: { enabled: true, layout: "vertical" },
})
await ready(setup)
await setup.waitFor(() => editor(setup).x >= 42)
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
expect(panel.x).toBe(0)
expect(panel.width).toBe(122)
setup.mockInput.pressKey("f")
await setup.flush()
expect(panel.x).toBe(0)
expect(panel.width).toBe(122)
setup.resize(180, 36)
await setup.flush()
const grownWidth = panel.width
setup.mockInput.pressKey("f")
await setup.waitFor(() => node(setup, "session-panel").width !== grownWidth)
expect(node(setup, "session-panel")).toBe(panel)
expect(setup.requests.base).toHaveLength(1)
expect(setup.requests.diff).toHaveLength(1)
})
test("panel focus, scrolling, and fullscreen use customized keys", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, {
width: 240,
keybinds: {
leader: "ctrl+space",
"pane.focus.left": "<leader>h",
"pane.focus.right": "<leader>l",
"diff.toggle_fullscreen": "f7",
"diff.down": "x",
"diff.up": "z",
},
})
await ready(setup)
const prompt = editor(setup)
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
const patches = scroll(setup)
const splitWidth = panel.width
expect(text(setup, "diff-footer")).toContain("ctrl+space h focus prompt")
expect(text(setup, "diff-footer")).toContain("? see all")
setup.mockInput.pressKey("f")
setup.mockInput.pressKey("j")
focus(setup, "left")
await setup.flush()
expect(panel.width).toBe(splitWidth)
expect(patches.scrollTop).toBe(0)
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
setup.mockInput.pressKey("x")
await setup.waitForFrame(() => patches.scrollTop > 0)
setup.mockInput.pressKey("F7")
await setup.waitFor(() => panel.width === setup.renderer.width)
setup.mockInput.pressKey("F7")
await setup.waitFor(() => panel.width === splitWidth)
setup.mockInput.pressKey(" ", { ctrl: true })
setup.mockInput.pressKey("h")
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
setup.mockInput.pressKey(" ", { ctrl: true })
setup.mockInput.pressKey("l")
await setup.waitFor(() => setup.renderer.currentFocusedRenderable === panel)
expect(prompt.plainText).toBe("")
})
test.each(["none", false] as const)(
"disabled panel keys (%s) have no behavioral or hint fallbacks",
async (binding) => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, {
width: 240,
keybinds: {
"pane.focus.left": binding,
"pane.focus.right": binding,
"diff.toggle_fullscreen": binding,
"diff.down": binding,
"diff.up": binding,
"diff.next_file": binding,
"diff.previous_file": binding,
"diff.next_hunk": binding,
"diff.previous_hunk": binding,
"diff.mark_reviewed": binding,
"diff.close": binding,
"diff.help": binding,
},
})
await ready(setup)
const prompt = editor(setup)
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
const splitWidth = panel.width
const patches = scroll(setup)
await setup.mockInput.typeText("fjknpm?[]q")
focus(setup, "left")
await setup.flush()
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
expect(panel.width).toBe(splitWidth)
expect(patches.scrollTop).toBe(0)
expect(text(setup, "diff-review-count")).toBe("0/4")
expect(prompt.plainText).toBe("")
expect(setup.renderer.root.findDescendantById("diff-help-shortcut")).toBeUndefined()
expect(text(setup, "diff-footer")).not.toMatch(/ctrl\+x|see all/)
await setup.mockMouse.click(prompt.x + 1, prompt.y)
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
await setup.flush()
focus(setup, "right")
await setup.flush()
expect(setup.renderer.currentFocusedEditor).toBe(prompt)
},
)
test("Enter in the diff panel cannot approve a pending permission in either presentation", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, { permission: true })
await setup.waitForFrame((frame) => frame.includes("Permission required"))
const permissionNode = node(setup, "session.permission")
setup.mockInput.pressKey("F6")
await panelReady(setup)
const panel = node(setup, "session-panel")
const splitWidth = panel.width
setup.mockInput.pressEnter()
await setup.flush()
expect(setup.requests.permission).toHaveLength(0)
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width === setup.renderer.width)
setup.mockInput.pressEnter()
await setup.flush()
expect(setup.requests.permission).toHaveLength(0)
expect(node(setup, "session.permission")).toBe(permissionNode)
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width === splitWidth)
focus(setup, "left")
await setup.waitFor(() => setup.renderer.currentFocusedRenderable !== panel)
setup.mockInput.pressEnter()
await setup.waitFor(() => setup.requests.permission.length === 1)
expect(setup.requests.permission).toEqual([{ decision: "once" }])
})
test.each([true, false])("a form cannot capture diff keys (form already pending: %s)", async (pending) => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path, { form: pending })
await setup.waitForFrame((frame) => frame.includes(pending ? setup.form.title : "Transcript item 11"))
setup.mockInput.pressKey("F6")
await panelReady(setup)
if (!pending) {
setup.events.emit({
id: "evt_panel_form",
created: 20,
type: "form.created",
location: { directory },
data: { form: setup.form },
})
await setup.waitForFrame((frame) => frame.includes(setup.form.title))
}
const panel = node(setup, "session-panel")
const patches = scroll(setup)
const splitWidth = panel.width
setup.mockInput.pressKey("j")
await setup.waitFor(() => patches.scrollTop > 0)
setup.mockInput.pressKey("m")
await setup.waitForFrame(() => text(setup, "diff-review-count") === "1/4")
setup.mockInput.pressEnter()
await setup.flush()
expect(setup.requests.form).toHaveLength(0)
expect(setup.renderer.currentFocusedRenderable).toBe(panel)
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width === setup.renderer.width)
setup.mockInput.pressKey("f")
await setup.waitFor(() => panel.width === splitWidth)
expect(setup.requests.form).toHaveLength(0)
focus(setup, "left")
await setup.waitFor(() => setup.renderer.currentFocusedRenderable !== panel)
setup.mockInput.pressKey("x")
await setup.waitFor(() => setup.renderer.currentFocusedEditor?.plainText === "answerx")
setup.mockInput.pressEnter()
await setup.waitFor(() => setup.requests.form.length === 1)
expect(setup.requests.form).toEqual([{ answer: { target: "answerx" } }])
})
test("disabling the registered diff plugin closes its open panel and removes its bindings", async () => {
await using state = await tmpdir()
await using setup = await createSessionFixture(state.path)
await ready(setup)
const prompt = editor(setup)
const transcript = node(setup, "msg_panel_11")
setup.mockInput.pressKey("F6")
await panelReady(setup)
const patches = scroll(setup)
focus(setup, "left")
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
await setup.mockInput.typeText("/plugins")
setup.mockInput.pressEnter()
await setup.waitForFrame((frame) => frame.includes("Plugins") && frame.includes("show internal"))
setup.mockInput.pressKey("a", { ctrl: true })
await setup.waitForFrame((frame) => frame.includes("opencode.diffs"))
await setup.waitFor(() => setup.renderer.currentFocusedEditor instanceof InputRenderable)
await setup.mockInput.typeText("opencode.diffs")
await setup.waitFor(() => setup.renderer.currentFocusedEditor?.plainText === "opencode.diffs")
await setup.flush()
setup.mockInput.pressEnter()
await setup.waitFor(() => !setup.renderer.root.findDescendantById("session-panel"))
await setup.flush()
if (setup.captureCharFrame().includes("Plugins")) setup.mockInput.pressEscape()
await setup.waitFor(() => setup.renderer.currentFocusedEditor === prompt)
expect(patches.isDestroyed).toBe(true)
expect(node(setup, "msg_panel_11")).toBe(transcript)
setup.mockInput.pressKey("F6")
await setup.flush()
expect(setup.renderer.root.findDescendantById("session-panel")).toBeUndefined()
await setup.mockInput.typeText("fjm")
expect(prompt.plainText).toBe("fjm")
expect(setup.requests.base).toHaveLength(1)
expect(setup.requests.diff).toHaveLength(1)
})
const files = Array.from({ length: 4 }, (_, index) => ({
file: `src/file0${index}.txt`,
status: "modified",
additions: 1,
deletions: 1,
patch: [
`--- a/src/file0${index}.txt`,
`+++ b/src/file0${index}.txt`,
"@@ -1,30 +1,30 @@",
`-before ${index}`,
`+after ${index}`,
...Array.from({ length: 29 }, (_, line) => ` context ${index}-${line}`),
"",
].join("\n"),
})) satisfies FileDiffInfo[]
async function createSessionFixture(
state: string,
input: {
width?: number
tabs?: Config.Info["tabs"]
diffs?: Config.Info["diffs"]
keybinds?: Config.Info["keybinds"]
permission?: boolean
form?: boolean
} = {},
) {
// Drafts survive app disposal in memory, so each production app needs its own session identity.
const session = {
id: `ses_panel_${crypto.randomUUID()}`,
title: "Panel fixture",
projectID: "proj_panel",
location: { directory },
agent: "build",
model: { providerID: "fixture", id: "model" },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 12 },
} satisfies SessionInfo
const permission = {
id: `per_panel_${crypto.randomUUID()}`,
sessionID: session.id,
action: "shell",
resources: ["echo permission-fixture"],
} satisfies PermissionRequest
const form = {
id: `frm_panel_${crypto.randomUUID()}`,
sessionID: session.id,
title: "Panel form fixture",
fields: [
{
key: "target",
type: "string",
title: "Target",
options: [{ value: "staging", label: "Staging" }],
custom: true,
default: "answer",
},
],
} satisfies FormInfo
const location = { directory, project: { id: session.projectID, directory, canonical: directory } }
const requests = {
base: [] as URL[],
diff: [] as URL[],
prompt: [] as unknown[],
permission: [] as unknown[],
form: [] as unknown[],
}
const setup = await createAppFixture({
width: input.width ?? 160,
height: 36,
state,
args: { sessionID: session.id },
config: {
animations: false,
tabs: input.tabs ?? { enabled: false },
session: { sidebar: "hide" },
// Keep patch geometry stable while testing host presentation changes, not split/unified diff layout.
diffs: { tree: false, view: "unified", ...input.diffs },
keybinds: { "diff.open": "f6", ...input.keybinds },
},
fetch: async (url, request) => {
if (url.pathname === "/api/location") return json(location)
if (url.pathname === "/api/fs/list") return json({ location, data: [] })
if (url.pathname === "/api/agent")
return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
if (url.pathname === "/api/model")
return json({ location, data: [{ id: "model", providerID: "fixture", name: "Model", variants: [] }] })
if (url.pathname === "/api/provider") return json({ location, data: [{ id: "fixture", name: "Fixture" }] })
if (url.pathname === "/api/vcs") return json({ location, data: { branch: { current: "panel", default: "v2" } } })
if (url.pathname === "/api/vcs/base") {
requests.base.push(url)
return json({ location, data: { name: "v2", ref: "refs/heads/v2", source: "default" } })
}
if (url.pathname === "/api/vcs/diff") {
requests.diff.push(url)
return json({ location, data: files })
}
if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
if (url.pathname === `/api/session/${session.id}/message`)
return json({
data: Array.from({ length: 12 }, (_, index) => ({
id: `msg_panel_${String(index).padStart(2, "0")}`,
type: "user",
text: `Transcript item ${index}`,
time: { created: index + 1 },
})).toReversed(),
cursor: {},
})
if (url.pathname === `/api/session/${session.id}/inbox`) return json({ data: [] })
if (url.pathname === `/api/session/${session.id}/permission`)
return json({ data: input.permission ? [permission] : [] })
if (url.pathname === `/api/session/${session.id}/form`) return json({ data: input.form ? [form] : [] })
if (url.pathname === `/api/session/${session.id}/prompt`) {
requests.prompt.push(await request.json())
return json({ data: {} })
}
if (url.pathname === `/api/session/${session.id}/permission/${permission.id}/reply`) {
requests.permission.push(await request.json())
return new Response(null, { status: 204 })
}
if (url.pathname === `/api/session/${session.id}/form/${form.id}/reply`) {
requests.form.push(await request.json())
return new Response(null, { status: 204 })
}
return undefined
},
})
return { ...setup, requests, form }
}
type AppFixture = Awaited<ReturnType<typeof createAppFixture>>
async function ready(setup: AppFixture) {
await setup.ready
await setup.waitForFrame((frame) => frame.includes("Transcript item 11") && frame.includes("Build · Model Fixture"), {
maxPasses: 120,
})
await setup.waitFor(() => setup.renderer.currentFocusedEditor instanceof TextareaRenderable)
}
async function panelReady(setup: AppFixture) {
await setup.waitForFrame(
(frame) => frame.includes("file00.txt") && setup.renderer.currentFocusedRenderable?.id === "session-panel",
{ maxPasses: 120 },
)
await setup.flush()
}
function focus(setup: AppFixture, direction: "left" | "right") {
setup.mockInput.pressKey("x", { ctrl: true })
setup.mockInput.pressArrow(direction)
}
function node(setup: AppFixture, id: string) {
const result = setup.renderer.root.findDescendantById(id)
if (!result) throw new Error(`Missing renderable: ${id}\n${setup.captureCharFrame()}`)
return result
}
function scroll(setup: AppFixture) {
const result = node(setup, "diff-patches")
if (!(result instanceof ScrollBoxRenderable)) throw new Error("Missing diff scrollbox")
return result
}
function editor(setup: AppFixture) {
const result = setup.renderer.currentFocusedEditor
if (!(result instanceof TextareaRenderable)) throw new Error("Missing focused session prompt")
return result
}
function text(setup: AppFixture, id: string) {
const item = setup.renderer.root.findDescendantById(id)
if (!item) return ""
return setup
.captureCharFrame()
.split("\n")
.slice(item.y, item.y + item.height)
.map((line) => line.slice(item.x, item.x + item.width).trim())
.join("\n")
.trim()
}
function descendants(root: Renderable): Renderable[] {
return root.getChildren().flatMap((item) => [item, ...descendants(item)])
}