diff --git a/packages/tui/src/config/keybind.ts b/packages/tui/src/config/keybind.ts index 2f80c60eadc..fee781a279e 100644 --- a/packages/tui/src/config/keybind.ts +++ b/packages/tui/src/config/keybind.ts @@ -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"), diff --git a/packages/tui/src/feature-plugins/prompt/footer.tsx b/packages/tui/src/feature-plugins/prompt/footer.tsx index d5e38b0a38b..f87be8c9fb9 100644 --- a/packages/tui/src/feature-plugins/prompt/footer.tsx +++ b/packages/tui/src/feature-plugins/prompt/footer.tsx @@ -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: { - - {shortcut("agent.cycle")} agents + + {shortcut("agent.cycle")}{" "} + agents - - {shortcut("command.palette.show")} commands + + {shortcut("command.palette.show")}{" "} + commands diff --git a/packages/tui/src/feature-plugins/system/diff-viewer.tsx b/packages/tui/src/feature-plugins/system/diff-viewer.tsx index 35fcf5fe609..f49e400a84a 100644 --- a/packages/tui/src/feature-plugins/system/diff-viewer.tsx +++ b/packages/tui/src/feature-plugins/system/diff-viewer.tsx @@ -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 }>("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 ( + 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(() => ( + + updateMemory((draft) => { + draft.bases[key] = ref + }) + } + /> + )) + }} + /> + ) +} +function DiffRoute(props: { + context: Plugin.Context + data?: { mode?: DiffMode; sessionID?: string; returnRoute?: Route } +}) { + const dimensions = useTerminalDimensions() return ( - 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(() => ( - - 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" })} /> ) @@ -298,6 +309,7 @@ export function DiffViewerContent(props: { unavailable?: boolean loadImage?: (file: string, signal: AbortSignal) => Promise 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(storedView(props.preferences?.view)) const view = createMemo(() => @@ -339,8 +357,6 @@ export function DiffViewerContent(props: { const [selectedHunk, setSelectedHunk] = createSignal() const [pendingPatchScrollFileIndex, setPendingPatchScrollFileIndex] = createSignal() - 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(() => ) + dialog.show(() => ( + + )) dialog.set({ size: "medium", centered: true }) } - const HelpShortcut = (props: { compact?: boolean }) => ( + const HelpShortcut = (props: { compact?: boolean; label?: string; muted?: boolean }) => ( {(shortcut) => ( {props.compact ? "?" : shortcut()} - help + {props.label ?? "help"} )} @@ -800,13 +834,15 @@ export function DiffViewerContent(props: { })) return ( - + - + { // The fixed edge belongs to the visible card, not the tree selection. edge.onLifecyclePass = () => { @@ -936,16 +974,9 @@ export function DiffViewerContent(props: { return ( registerPatchNode(entry.fileIndex, element)}> 0}> - + - + 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} > @@ -996,17 +1027,9 @@ export function DiffViewerContent(props: { - + + + @@ -1075,8 +1098,43 @@ export function DiffViewerContent(props: { - - + + {/* The footer sits on the terminal background, eased in by a half-cell like the prompt. */} + + + + { + if (event.button !== MouseButton.LEFT) return + if (!props.panel?.focused) props.panel?.focus() + }} + > + {props.context.keymap.shortcuts("pane.focus.left")[0] ?? ""} + focus prompt + + + + + + + + + + @@ -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) => ( + + ) + return ( + + {half(props.surface, props.inset)} + {half(props.card)} + {half(props.surface, props.inset)} + + ) +} + +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) => ( + + + + ), + }) context.ui.router.register({ name: ROUTE, - render: () => , + render: ({ data }) => , }) context.ui.slot({ append: "app", render: () => }) }, diff --git a/packages/tui/test/cli/tui/diff-viewer.test.tsx b/packages/tui/test/cli/tui/diff-viewer.test.tsx index 69820f215cc..0786cc49da2 100644 --- a/packages/tui/test/cli/tui/diff-viewer.test.tsx +++ b/packages/tui/test/cli/tui/diff-viewer.test.tsx @@ -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 diff --git a/packages/tui/test/config-v2.test.tsx b/packages/tui/test/config-v2.test.tsx index ae59c8f7bca..8f6b917ed19 100644 --- a/packages/tui/test/config-v2.test.tsx +++ b/packages/tui/test/config-v2.test.tsx @@ -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 }) diff --git a/packages/tui/test/session-panel.test.tsx b/packages/tui/test/session-panel.test.tsx new file mode 100644 index 00000000000..b75c1aff2eb --- /dev/null +++ b/packages/tui/test/session-panel.test.tsx @@ -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": "h", + "pane.focus.right": "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> + +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)]) +}