From 2f35b877bf7ffd749d9f004a6413ad305295dadf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Tue, 1 Dec 2026 19:15:17 +0000 Subject: [PATCH] TUI: full-height display pane, narrow fallback, images tab, compact transcript The display pane is a column of the root now: it stands at the right over the terminal's full height, beside the prompt and the status bar, from 80 columns (layout.ts decides both columns' widths from the terminal's width alone). Below that it is no longer silently absent: the status bar names the key, and alt+d puts the display in the transcript's place and back. An images tab shows what view_image viewed, what show showed and what was attached, drawn by OpenTUI's own image renderable (kitty graphics where the terminal is found to support them, sixel, else blocks); `images: auto|on|off`. The transcript has two views over the same items: full, and compact, where a round of tool calls is one line and a failure or a refusal always has its own. `transcript: auto|full|compact`, alt+t, /transcript. The pane gets a session header, a tab bar that fits its width, clickable tabs and rows of known width; the status bar has a short form for a narrow column, and the welcome box's hints and the prompt's placeholder no longer wrap inside a phrase. Co-Authored-By: Claude Fable 5.2 --- schema/config.schema.json | 20 +- src/config/schema.ts | 4 +- src/config/settings.ts | 4 +- src/session/commands.ts | 2 +- src/tui/app.tsx | 260 ++++++--- src/tui/commands.ts | 30 +- src/tui/components/display_pane.tsx | 788 ++++++++++++++++------------ src/tui/components/messages.tsx | 249 +++++++-- src/tui/components/prompt.tsx | 6 +- src/tui/components/status.tsx | 56 +- src/tui/components/welcome.tsx | 18 +- src/tui/context.ts | 2 + src/tui/displays.ts | 95 +++- src/tui/layout.ts | 139 +++++ src/tui/state.ts | 7 +- src/tui/transcript.ts | 151 ++++++ tests/displays.test.ts | 78 +++ tests/layout.test.ts | 87 +++ tests/png.ts | 41 ++ tests/transcript.test.ts | 85 +++ tests/tui/displays.test.tsx | 311 ++++++++++- tests/tui/harness.tsx | 4 +- 22 files changed, 1903 insertions(+), 534 deletions(-) create mode 100644 src/tui/layout.ts create mode 100644 src/tui/transcript.ts create mode 100644 tests/layout.test.ts create mode 100644 tests/png.ts create mode 100644 tests/transcript.test.ts diff --git a/schema/config.schema.json b/schema/config.schema.json index 508dc16..8f33054 100644 --- a/schema/config.schema.json +++ b/schema/config.schema.json @@ -81,9 +81,27 @@ ] }, "displays": { - "description": "Side display pane showing live agent activity, files read, diffs, and bash output on wide terminals. Default true; Alt+D or /display toggles it.", + "description": "The display pane: live agent activity, files read, diffs, command output and pictures, at the right over the terminal's full height from 80 columns; on a narrower terminal Alt+D opens it in the transcript's place. Default true; Alt+D or /display toggles it.", "type": "boolean" }, + "images": { + "description": "Pictures in the display's images tab (what view_image viewed, what was shown, what you attached): auto (default) — drawn the best way the terminal is found to support: the kitty graphics protocol (kitty, Ghostty), sixel, else coloured blocks; on — the kitty graphics protocol whatever was detected (a multiplexer with passthrough); off — never drawn: the name, size and path only.", + "type": "string", + "enum": [ + "auto", + "on", + "off" + ] + }, + "transcript": { + "description": "How the conversation is drawn: full — every tool call on its own line, a change with its diff; compact — a round of tool calls as one line (count, kinds, time; failures and refusals always said), a change as a stat line, the detail in the display pane; auto (default) — compact while the display pane stands beside it, full otherwise. Alt+T or /transcript switches.", + "type": "string", + "enum": [ + "auto", + "full", + "compact" + ] + }, "personality": { "description": "How the agent talks: concise, pragmatic, optimistic, funny, formal, socratic, custom (personality_custom's text), or empty for none (the default). The same presets as the LLeMbas web UI; appended last to the system prompt, under \"## Personality\".", "anyOf": [ diff --git a/src/config/schema.ts b/src/config/schema.ts index 2bcb108..9f851ae 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -247,7 +247,9 @@ export const Config = z.strictObject({ paste: z.enum(["placeholder", "full"]).optional().describe("A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path."), kitty_clipboard: z.boolean().optional().describe("true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in."), icons: z.enum(["emoji", "plain"]).optional().describe("emoji (default), or plain: one-column symbols for a terminal font that has no emoji."), - displays: z.boolean().optional().describe("Side display pane showing live agent activity, files read, diffs, and bash output on wide terminals. Default true; Alt+D or /display toggles it."), + displays: z.boolean().optional().describe("The display pane: live agent activity, files read, diffs, command output and pictures, at the right over the terminal's full height from 80 columns; on a narrower terminal Alt+D opens it in the transcript's place. Default true; Alt+D or /display toggles it."), + images: z.enum(["auto", "on", "off"]).optional().describe("Pictures in the display's images tab (what view_image viewed, what was shown, what you attached): auto (default) — drawn the best way the terminal is found to support: the kitty graphics protocol (kitty, Ghostty), sixel, else coloured blocks; on — the kitty graphics protocol whatever was detected (a multiplexer with passthrough); off — never drawn: the name, size and path only."), + transcript: z.enum(["auto", "full", "compact"]).optional().describe("How the conversation is drawn: full — every tool call on its own line, a change with its diff; compact — a round of tool calls as one line (count, kinds, time; failures and refusals always said), a change as a stat line, the detail in the display pane; auto (default) — compact while the display pane stands beside it, full otherwise. Alt+T or /transcript switches."), personality: z .enum(PERSONALITIES) .or(z.literal("")) diff --git a/src/config/settings.ts b/src/config/settings.ts index bd73233..603348c 100644 --- a/src/config/settings.ts +++ b/src/config/settings.ts @@ -62,7 +62,9 @@ export const SETTINGS: SettingDef[] = [ { key: "paste", kind: "enum", values: ["placeholder", "full"], agent: true, scopes: USER, fallback: "placeholder", hint: "a long paste or a pasted image in the prompt box: a placeholder, or shown in full" }, { key: "kitty_clipboard", kind: "boolean", agent: false, scopes: USER, fallback: "false", hint: "over SSH in kitty, ctrl+v asks the terminal for the image on its clipboard" }, { key: "icons", kind: "enum", values: ["emoji", "plain"], agent: true, scopes: USER, fallback: "emoji" }, - { key: "displays", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "side display pane on wide terminals (Alt+D or /display toggles)" }, + { key: "displays", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "the display pane beside the conversation (Alt+D or /display toggles)" }, + { key: "images", kind: "enum", values: ["auto", "on", "off"], agent: true, scopes: USER, fallback: "auto", hint: "pictures in the display's images tab: auto — as the terminal supports (kitty graphics, sixel, blocks); on — kitty graphics always; off — text only" }, + { key: "transcript", kind: "enum", values: ["auto", "full", "compact"], agent: true, scopes: USER, fallback: "auto", hint: "the conversation: full, compact (tool rounds grouped), or auto — compact beside the display pane (Alt+T or /transcript)" }, { key: "notify", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "bell and desktop notification when a reply finishes or the agent waits for you while the terminal is not focused" }, { key: "mouse", kind: "boolean", agent: true, scopes: ["global"], reload: true, fallback: "true" }, { key: "compaction.auto_at", kind: "number", agent: true, scopes: ALL, fallback: "0.85" }, diff --git a/src/session/commands.ts b/src/session/commands.ts index 7402826..3956f68 100644 --- a/src/session/commands.ts +++ b/src/session/commands.ts @@ -40,7 +40,7 @@ export const TUI_COMMAND_NAMES = [ "agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "pages", "review", "changelog", "init", "release", "tasks", "decisions", "decide", "jobs", "sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context", "compact", "memory", "skills", "skill", "personality", "voice", "speak", "mcp", "login", "logout", "settings", "usage", "kb", "theme", "skin", "terminal", - "icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command", "reports", "display", "displays", + "icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command", "reports", "display", "displays", "transcript", ] as const /** The built-ins that work without a screen of their own. Descriptions as the TUI's (a test). */ diff --git a/src/tui/app.tsx b/src/tui/app.tsx index bdf3fc3..ea08044 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -1,7 +1,8 @@ import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core" import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/solid" -import { createEffect, createMemo, createSignal, onCleanup, Show } from "solid-js" +import { createEffect, createMemo, createSignal, on, onCleanup, Show } from "solid-js" import { stricterMode, type App as Runtime } from "../app.ts" +import { basename, resolve } from "node:path" import { isLocal } from "../config/paths.ts" import type { Mode } from "../config/schema.ts" import { levelLabel, type Level } from "../provider/effort.ts" @@ -9,8 +10,10 @@ import { teamLabel } from "../session/commands.ts" import { COMMANDS, findCommand, type CommandCtx } from "./commands.ts" import { Dialog, type DialogSpec } from "./components/dialog.tsx" import { DisplayPane } from "./components/display_pane.tsx" -import { Messages } from "./components/messages.tsx" -import { cycleTab, DISPLAY_MIN_WIDTH, effectiveTab, extractBash, extractChanges, extractFiles, initialNav, resetFollow, stepEntry, type DisplayNavState } from "./displays.ts" +import { Messages, rowId } from "./components/messages.tsx" +import { cycleTab, effectiveTab, extractBash, extractChanges, extractFiles, extractImages, freshImage, initialNav, isImagePath, resetFollow, stepEntry, type DisplayNavState, type DisplayTab } from "./displays.ts" +import { placeDisplay, STATUS_FULL_WIDTH, transcriptMode, type TranscriptSetting } from "./layout.ts" +import { groupRounds, rowIdOf } from "./transcript.ts" import { PermissionPrompt } from "./components/permission.tsx" import { copiedMessage, copyText, isRemote } from "./clipboard.ts" import { QuestionCard } from "./components/question.tsx" @@ -115,6 +118,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => setThemeSignal(loadTheme(theme().name, icons).theme) } if (e.key === "displays") setDisplaysEnabled(e.value !== false) + if (e.key === "transcript") setTranscript((e.value as TranscriptSetting | undefined) ?? "auto") refresh() }) app.settings.checks.set("theme", (v) => { @@ -132,9 +136,55 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => let quitArmed = 0 const dims = useTerminalDimensions() - const showDisplays = () => displaysEnabled() && !entered() && dims().width >= DISPLAY_MIN_WIDTH - const displayWidth = () => Math.max(42, Math.min(84, Math.floor(dims().width * 0.44))) - const ctx: Ctx = { app, view, theme, md, thought, dims } + // Where the display stands is decided from the terminal's width alone (layout.ts): beside the + // conversation over the full height, in its place on a narrow terminal, or not at all. + const [zoomed, setZoomed] = createSignal(false) + const placement = createMemo(() => placeDisplay({ width: dims().width, enabled: displaysEnabled(), zoomed: zoomed() })) + const showDisplays = () => placement().mode === "side" || placement().mode === "zoom" + const [transcript, setTranscript] = createSignal(app.loaded.config.transcript ?? "auto") + const compactWanted = createMemo(() => transcriptMode(transcript(), placement().mode) === "compact") + // What is drawn follows what is wanted one step behind, so the place in the scrollbox can be + // read off the old rows before they go and found again among the new ones. + const [compact, setCompact] = createSignal(compactWanted()) + const ctx: Ctx = { app, view, theme, md, thought, dims, compact } + /** The left column's own size: what stands in it (cards, the prompt) measures itself by this, + * never by the terminal, which the pane shares. */ + const leftDims = createMemo(() => ({ width: placement().left, height: dims().height })) + const leftCtx: Ctx = { ...ctx, dims: leftDims } + /** The transcript's rows change (full ↔ compact): the row at the top stays the row at the top; + * at the bottom it stays at the bottom. Nothing is run again — both are views of the same items. */ + const switchTranscript = (toCompact: boolean) => { + const box = scroll + let target: string | undefined + let bottom = true + if (box) { + bottom = box.scrollTop + box.viewport.height >= box.scrollHeight - 1 + if (!bottom) { + const top = box.content.getChildren().find((r) => r.id.startsWith("row-") && r.height > 0 && r.y + r.height > box.viewport.y) + const id = top?.id.slice(4) + // A call inside a round is found again as its round, and a round as its first call. + if (id) target = toCompact ? (rowIdOf(groupRounds(view.state.items, { showReasoning: view.state.showReasoning })).get(id) ?? id) : id + } + } + setCompact(toCompact) + if (!box) return + let set: number | undefined + const place = () => { + if (box.isDestroyed || scroll !== box) return + // The person scrolled meanwhile: their place now. + if (set !== undefined && box.scrollTop !== set) return + if (bottom) box.scrollTo(box.scrollHeight) + else { + const row = target ? box.content.findDescendantById(rowId(target)) : undefined + if (row) box.scrollTo(Math.max(0, row.y - box.content.y)) + } + set = box.scrollTop + } + // After the new rows are laid out — and again once markdown, parsed off the main thread, has + // its heights. + for (const ms of [30, 150, 400]) setTimeout(place, ms) + } + createEffect(on(compactWanted, (want) => want !== compact() && switchTranscript(want), { defer: true })) // Background jobs: the view's list is the registry's at the start and on every session change // (resume, /new), then follows the `job` events. @@ -304,29 +354,24 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => openJob: (id) => setJobPanel(id), enterJob, setDisplays(action) { - if (action === "toggle") { - const next = !displaysEnabled() - setDisplaysEnabled(next) - return next - ? dims().width < DISPLAY_MIN_WIDTH - ? `side display enabled (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it; now ${dims().width})` - : "side display shown (Alt+↑↓ tabs · Alt+←→ entry · Alt+PgUp/Dn scroll · Alt+D hide)" - : "side display hidden (Alt+D or /display on to show)" - } + if (action === "toggle") return toggleDisplay() if (action === "off") { setDisplaysEnabled(false) - return "side display hidden" + setZoomed(false) + return "display off (alt+d or /display on brings it back)" } setDisplaysEnabled(true) - if (action !== "on") { - setDisplayNav((n) => ({ ...n, tab: action, pinned: action !== "live" })) - return dims().width < DISPLAY_MIN_WIDTH - ? `side display tab: ${action} (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it)` - : `side display: ${action}` - } - return dims().width < DISPLAY_MIN_WIDTH - ? `side display enabled (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it)` - : "side display shown" + // Too narrow for two columns: it opens in the transcript's place. + setZoomed(true) + if (action !== "on") selectTab(action) + const what = action === "on" ? "display" : `display: ${action}` + return placement().mode === "side" ? `${what} (alt+↑↓ tabs · alt+←→ entry · alt+pgup/pgdn scroll · alt+d hide)` : `${what} — in the transcript's place on this narrow terminal (alt+d: back to the transcript)` + }, + setTranscript(to) { + if (to !== "toggle") setTranscript(to) + else setTranscript(compact() ? "full" : "compact") + const now = transcriptMode(transcript(), placement().mode) + return transcript() === "auto" ? `transcript: auto — ${now} now (compact while the display stands beside it)` : `transcript: ${now} (alt+t switches · /transcript auto follows the display)` }, copy: (text: string) => copy(text), renderer, @@ -346,6 +391,25 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => }, } + const selectTab = (tab: DisplayTab) => setDisplayNav((n) => ({ ...n, tab, pinned: tab !== "live" })) + /** Alt+D and a bare /display. Beside the conversation: shown ↔ hidden. Too narrow for that: + * the display in the transcript's place ↔ the transcript (the status bar says it is there). */ + function toggleDisplay(): string { + if (!displaysEnabled()) { + setDisplaysEnabled(true) + setZoomed(true) + return placement().mode === "side" ? "display shown" : "display (alt+d: back to the transcript)" + } + if (placement().mode === "side") { + setDisplaysEnabled(false) + setZoomed(false) + return "display hidden (alt+d shows it)" + } + const next = !zoomed() + setZoomed(next) + return next ? "display (alt+d: back to the transcript)" : "transcript (alt+d: the display)" + } + const files = new FileIndex(app.project.root) const custom = () => customCommands(app.trusted ? app.project.dir : undefined) // A skill is also a command, /, unless a built-in or custom command has the name @@ -372,7 +436,8 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => // `drawn`: what this transcript shows — the box as it looked, a paste placeholder in place of // its text. Only here: the session's title, the `prompt` event and everything a server // mirrors get `shown`, which holds the words themselves. - view.user(drawn) + // A picture that was attached is in the display's images tab, by where it is on this disk. + view.user(drawn, atts.filter((a) => isImagePath(a.path)).map((a) => resolve(app.engine.o.toolCtx.cwd, a.path))) setDisplayNav((n) => resetFollow(n)) if (atts.length) view.info(`attached ${atts.map((a) => (a.image ? `${a.path} (image)` : a.text.includes("not attached") ? `${a.path} (not attached: ${/not attached: ([^)]*)/.exec(a.text)?.[1]})` : a.path)).join(", ")}`) if (given?.attachments.length) view.info(`attached ${given.attachments.map((a) => a.name).join(", ")}`) @@ -588,25 +653,32 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => const alt = Boolean(key.meta || (key as { option?: boolean }).option) if (alt && !key.ctrl && !dialog() && !jobPanel()) { if (key.name === "d") { - const next = !displaysEnabled() - setDisplaysEnabled(next) - flash(next ? (dims().width < DISPLAY_MIN_WIDTH ? `display on (needs ${DISPLAY_MIN_WIDTH}+ cols)` : "side display shown") : "side display hidden") + flash(toggleDisplay()) + return key.preventDefault() + } + if (key.name === "t") { + cmd.setTranscript!("toggle") + flash(`transcript: ${transcriptMode(transcript(), placement().mode)}`) return key.preventDefault() } if (showDisplays()) { if (key.name === "up" || key.name === "down") { - setDisplayNav((n) => cycleTab(n, key.name === "up" ? -1 : 1)) + // From the tab that is showing — which may be one the pane went to by itself. + const shown = effectiveTab(displayNav(), Boolean(view.state.pending?.preview?.diff), freshImage(view.state.items)) + setDisplayNav((n) => cycleTab({ ...n, tab: shown }, key.name === "up" ? -1 : 1)) return key.preventDefault() } if (key.name === "left" || key.name === "right") { - const tab = effectiveTab(displayNav(), Boolean(view.state.pending?.preview?.diff)) + const tab = effectiveTab(displayNav(), Boolean(view.state.pending?.preview?.diff), freshImage(view.state.items)) if (tab !== "live") { const count = tab === "files" ? extractFiles(view.state.items).length : tab === "changes" ? extractChanges(view.state.items, view.state.pending).length - : extractBash(view.state.items).length + : tab === "images" + ? extractImages(view.state.items, (x) => x).length + : extractBash(view.state.items).length setDisplayNav((n) => stepEntry(n, tab, key.name === "left" ? -1 : 1, count)) } return key.preventDefault() @@ -718,56 +790,92 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => renderer.on("selection", onSelection) onCleanup(() => renderer.off("selection", onSelection)) + // The display's header: the session's own words, which the short status bar beside it leaves out. + const sessionWords = () => ({ model: model(), mode: mode(), effort: effort(), spend: spend(), where: `${isLocal() ? "local " : ""}${basename(app.project.root)}${branch() ? `@${branch()}` : ""}` }) + const pane = (o: { width: number; height: number; zoomed?: boolean }) => ( + (displayScroll = r)} session={sessionWords} /> + ) + // The display in the transcript's place takes the rows the bottom stack leaves: measured, since + // the stack's height is its contents'. + const [zoomRows, setZoomRows] = createSignal(0) + return ( - - - (scroll = r)} + {/* A row: the left column — the conversation and everything under it — and the display + pane at the right, over the terminal's full height: beside the prompt and the status bar too. */} + + + + (scroll = r)} + flexGrow={1} + stickyScroll + stickyStart="bottom" + viewportOptions={{ paddingRight: 1 }} + verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }} + > + + + + } + > + {(id: string) => (scroll = r)} />} + + } + > + 0 && h !== zoomRows()) setTimeout(() => setZoomRows(h), 0) + }} > - - - - - setDisplayNav((n) => ({ ...n, tab, pinned: tab !== "live" }))} - scrollRef={(r) => (displayScroll = r)} - /> + 0}>{pane({ width: placement().left, height: zoomRows(), zoomed: true })} + + + + + + + + + + + + + + + + + !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} remote={() => isRemote(renderer as never)} terminal={terminal} note={(text, warn) => (warn ? view.info(text, "warn") : text.length > 60 ? view.info(text) : flash(text))} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> + (rev(), share.label())} + spend={spend} + team={teamWord} + mcp={() => (rev(), mcpWord(app.mcp.servers.values()))} + short={() => placement().left < STATUS_FULL_WIDTH} + hint={() => (placement().mode === "tucked" ? "alt+d display" : "")} + /> - } - > - {(id: string) => (scroll = r)} />} - - - - - - - - - - - - - - - - - !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} remote={() => isRemote(renderer as never)} terminal={terminal} note={(text, warn) => (warn ? view.info(text, "warn") : text.length > 60 ? view.info(text) : flash(text))} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> - (rev(), share.label())} spend={spend} team={teamWord} mcp={() => (rev(), mcpWord(app.mcp.servers.values()))} /> - + + + {pane({ width: placement().pane, height: dims().height })} setDialog(undefined)} /> diff --git a/src/tui/commands.ts b/src/tui/commands.ts index c4d808c..be1a303 100644 --- a/src/tui/commands.ts +++ b/src/tui/commands.ts @@ -74,7 +74,10 @@ export interface CommandCtx extends Ctx { /** Enter a subagent job: its transcript in place of the session's, the prompt box sends to it. */ enterJob(id: string): void /** Control the side display pane (on/off/toggle or select a tab). */ - setDisplays?(action: "toggle" | "on" | "off" | "live" | "files" | "changes" | "bash"): string + setDisplays?(action: "toggle" | "on" | "off" | "live" | "files" | "changes" | "bash" | "images"): string + /** Which transcript is drawn: full, compact, auto (compact beside the display) — or the other + * of the two that is showing. Returns what to say. */ + setTranscript?(to: "auto" | "full" | "compact" | "toggle"): string } export interface Command { @@ -90,7 +93,8 @@ const HELP_KEYS = [ "esc stop the model · ctrl+g continue (after a stop, or to keep going) · ctrl+c clear, twice to quit · ctrl+d (empty box) quit", "/jobs background jobs: enter opens one (a subagent: esc back, type to message it), k stops it · ctrl+b moves the running command to the background", "shift+tab cycle mode (manual → edit → plan) · ctrl+r show reasoning · ctrl+o expand tool output", - "alt+d toggle side display · alt+↑/↓ switch display tab (live/files/changes/bash) · alt+←/→ entry · alt+pgup/pgdn scroll display", + "alt+d the display (beside the conversation; on a narrow terminal in its place) · alt+↑/↓ its tab (live/files/changes/bash/images) · alt+←/→ entry · alt+pgup/pgdn scroll it · click a tab, wheel over it", + "alt+t transcript full ↔ compact (compact: a round of tool calls is one line, the detail in the display)", "pgup/pgdn scroll half a screen · ctrl+↑/↓ three lines · the mouse wheel · ↑ in an empty box takes back a message waiting to go in", ] @@ -200,16 +204,28 @@ export const COMMANDS: Command[] = [ { name: "display", aliases: ["displays"], - args: "[on|off|live|files|changes|bash]", - description: "toggle or switch the side display pane (live activity, files, changes, bash)", + args: "[on|off|live|files|changes|bash|images]", + description: "the display pane: show or hide it, or open one of its tabs (live activity, files, changes, bash, images)", run(c, arg) { - if (!c.setDisplays) return c.view.info("side displays are not available here", "warn") + if (!c.setDisplays) return c.view.info("the display is not available here", "warn") const a = arg.trim().toLowerCase() if (!a) return c.view.info(c.setDisplays("toggle")) - if (a === "on" || a === "off" || a === "live" || a === "files" || a === "changes" || a === "bash") { + if (a === "on" || a === "off" || a === "live" || a === "files" || a === "changes" || a === "bash" || a === "images") { return c.view.info(c.setDisplays(a)) } - c.view.info("usage: /display [on|off|live|files|changes|bash]", "warn") + c.view.info("usage: /display [on|off|live|files|changes|bash|images] — pictures are drawn as the `images` setting says (auto, on, off: /settings)", "warn") + }, + }, + { + name: "transcript", + args: "[auto|full|compact]", + description: "the conversation in full, or compact (a round of tool calls as one line) — auto: compact beside the display", + run(c, arg) { + if (!c.setTranscript) return c.view.info("the transcript cannot be switched here", "warn") + const a = arg.trim().toLowerCase() + if (!a) return c.view.info(c.setTranscript("toggle")) + if (a === "auto" || a === "full" || a === "compact") return c.view.info(c.setTranscript(a)) + c.view.info("usage: /transcript [auto|full|compact]", "warn") }, }, { diff --git a/src/tui/components/display_pane.tsx b/src/tui/components/display_pane.tsx index c3e1b79..10a532a 100644 --- a/src/tui/components/display_pane.tsx +++ b/src/tui/components/display_pane.tsx @@ -1,5 +1,11 @@ +import { readFileSync, statSync } from "node:fs" +import { basename } from "node:path" import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core" +import { useRenderer } from "@opentui/solid" import { createEffect, createMemo, createSignal, For, Match, onCleanup, Show, Switch } from "solid-js" +import { MAX_PASTE_BYTES, sniffImage } from "../../project/image.ts" +import { imageSize } from "../../provider/tokens.ts" +import { absPath } from "../../tool/tool.ts" import { useTui } from "../context.ts" import { buildLiveSnapshot, @@ -8,20 +14,30 @@ import { extractBash, extractChanges, extractFiles, + extractImages, + fitImage, + freshImage, + imageProtocol, resolveIndex, type DisplayNavState, type DisplayTab, + type ImageEntry, } from "../displays.ts" +import { clipEnd, paneHints, tabCells, type TabSpec } from "../layout.ts" +import { num } from "../locale.ts" import { filetypeOf } from "./messages.tsx" +import { contextWords } from "./status.tsx" -const TAB_LABEL: Record = { - live: "Live", - files: "Files", - changes: "Changes", - bash: "Bash", +const TAB_NAMES: Record = { + live: ["Live", "Live", "L"], + files: ["Files", "Files", "F"], + changes: ["Changes", "Chg", "C"], + bash: ["Bash", "Bash", "B"], + images: ["Images", "Img", "I"], } const PLAN_MARK: Record = { todo: "☐", doing: "▸", done: "☑", dropped: "✗" } +const SOURCE_WORD: Record = { viewed: "viewed", shown: "shown", attached: "attached" } function toolStatusGlyph(status: string): string { if (status === "running") return "◐" @@ -30,16 +46,49 @@ function toolStatusGlyph(status: string): string { return "✓" } +const sizeWords = (n: number) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`) + +/** A picture's bytes as they are on disk now, believed only by their own signature — or why it + * cannot be drawn. Nothing but these bytes ever goes to the terminal for a picture: no text of the + * model's, and no path or address handed on for something else to fetch. */ +export function readPicture(path: string): { bytes: Uint8Array; size: number; px?: { width: number; height: number } } | { error: string; size?: number } { + let size: number + try { + const st = statSync(path) + if (!st.isFile()) return { error: "not a file" } + size = st.size + } catch { + return { error: "no longer on disk" } + } + if (size > MAX_PASTE_BYTES) return { error: `over ${MAX_PASTE_BYTES / 1e6} MB — not drawn`, size } + let bytes: Uint8Array + try { + bytes = new Uint8Array(readFileSync(path)) + } catch { + return { error: "cannot be read", size } + } + if (!sniffImage(bytes)) return { error: "not a PNG, JPEG, GIF or WebP by its bytes", size } + return { bytes, size, px: imageSize(bytes) } +} + +/** The display pane. Every row has a known size: `width` and `height` are the pane's own cells + * (layout.ts), the header, tab bar, sub-header and key line are one or two rows each, and the body + * takes what is left. `zoomed`: it stands in the transcript's place on a narrow terminal. */ export function DisplayPane(p: { width: number + height: number + zoomed?: boolean nav: () => DisplayNavState onSelectTab: (tab: DisplayTab) => void scrollRef?: (r: ScrollBoxRenderable) => void + /** The session's words for the header: its model, mode and effort; where it works; the month's spend. */ + session?: () => { model: string; mode: string; effort: string; where: string; spend: string } }) { const { theme, view, app } = useTui() + const renderer = useRenderer() const c = () => theme().colors - // Tick once per second while busy so elapsed times and live progress stay fresh. + // Tick while busy so elapsed times and live progress stay fresh. const [now, setNow] = createSignal(Date.now()) createEffect(() => { if (view.state.phase === "idle" && !view.state.jobs.some((j) => j.state === "running")) return @@ -50,8 +99,10 @@ export function DisplayPane(p: { const files = createMemo(() => extractFiles(view.state.items)) const changes = createMemo(() => extractChanges(view.state.items, view.state.pending)) const bash = createMemo(() => extractBash(view.state.items)) + const images = createMemo(() => extractImages(view.state.items, (path) => absPath(path, app.engine.o.toolCtx as Parameters[1]))) const hasProposed = createMemo(() => Boolean(view.state.pending?.preview?.diff)) - const activeTab = createMemo(() => effectiveTab(p.nav(), hasProposed())) + const hasFresh = createMemo(() => freshImage(view.state.items)) + const activeTab = createMemo(() => effectiveTab(p.nav(), hasProposed(), hasFresh())) const live = createMemo(() => buildLiveSnapshot(view.state, now())) const teamMembers = createMemo(() => { @@ -60,384 +111,435 @@ export function DisplayPane(p: { return tree.filter((m) => m.manager !== null) }) - const counts = () => ({ - files: files().length, - changes: changes().length, - bash: bash().length, - }) - const fileIdx = () => resolveIndex(p.nav(), "files", files().length) const changeIdx = () => resolveIndex(p.nav(), "changes", changes().length) const bashIdx = () => resolveIndex(p.nav(), "bash", bash().length) + const imageIdx = () => resolveIndex(p.nav(), "images", images().length) const currentFile = () => (fileIdx() >= 0 ? files()[fileIdx()] : undefined) const currentChange = () => (changeIdx() >= 0 ? changes()[changeIdx()] : undefined) const currentBash = () => (bashIdx() >= 0 ? bash()[bashIdx()] : undefined) + const currentImage = () => (imageIdx() >= 0 ? images()[imageIdx()] : undefined) - const subHeader = () => { + // ── sizes: everything below is derived from the pane's own width and height ── + /** Columns inside the pane: its border (beside the transcript) and one column of padding each side. */ + const inner = () => Math.max(1, p.width - (p.zoomed ? 0 : 1) - 2) + /** Two header rows where there is room for them, one on a short terminal. */ + const headRows = () => (p.height >= 16 ? 2 : 1) + /** Rows the body has: the pane less its header, tab bar, sub-header and key line. */ + const bodyRows = () => Math.max(1, p.height - headRows() - 3) + + const cells = createMemo(() => + tabCells( + inner(), + DISPLAY_TABS.map((tab) => ({ + id: tab, + names: TAB_NAMES[tab], + count: tab === "live" ? 0 : tab === "files" ? files().length : tab === "changes" ? changes().length : tab === "bash" ? bash().length : images().length, + mark: tab === "changes" && hasProposed() ? "●" : tab === "live" && view.state.phase !== "idle" ? "◉" : undefined, + })), + ), + ) + + const subHeader = (): { left: string; right: string; warn: boolean } => { const tab = activeTab() - if (tab === "live") { - return { - left: live().statusLine, - right: p.nav().pinned ? "pinned" : "auto-follow", - warn: Boolean(live().waiting), - } - } + if (tab === "live") return { left: live().statusLine, right: p.nav().pinned ? "pinned" : "auto", warn: Boolean(live().waiting) } if (tab === "files") { const f = currentFile() if (!f) return { left: "No files read yet", right: "0/0", warn: false } - return { - left: `${f.title}${f.subtitle ? ` · ${f.subtitle}` : ""}`, - right: `${fileIdx() + 1}/${files().length}`, - warn: f.status === "error" || f.status === "denied", - } + return { left: `${f.title}${f.subtitle ? ` · ${f.subtitle}` : ""}`, right: `${fileIdx() + 1}/${files().length}`, warn: f.status === "error" || f.status === "denied" } } if (tab === "changes") { const ch = currentChange() if (!ch) return { left: "No file changes yet", right: "0/0", warn: false } - return { - left: `${ch.title}${ch.subtitle ? ` · ${ch.subtitle}` : ""}`, - right: `${changeIdx() + 1}/${changes().length}`, - warn: ch.status === "proposed" || ch.status === "error" || ch.status === "denied", - } + return { left: `${ch.title}${ch.subtitle ? ` · ${ch.subtitle}` : ""}`, right: `${changeIdx() + 1}/${changes().length}`, warn: ch.status === "proposed" || ch.status === "error" || ch.status === "denied" } + } + if (tab === "images") { + const im = currentImage() + if (!im) return { left: "No pictures yet", right: "0/0", warn: false } + return { left: `${basename(im.path)} · ${SOURCE_WORD[im.source]}`, right: `${imageIdx() + 1}/${images().length}`, warn: false } } const b = currentBash() if (!b) return { left: "No bash commands yet", right: "0/0", warn: false } - return { - left: `$ ${b.title}${b.subtitle ? ` · ${b.subtitle}` : ""}`, - right: `${bashIdx() + 1}/${bash().length}`, - warn: b.status === "error" || b.status === "denied", - } + return { left: `$ ${b.title}${b.subtitle ? ` · ${b.subtitle}` : ""}`, right: `${bashIdx() + 1}/${bash().length}`, warn: b.status === "error" || b.status === "denied" } + } + /** The counter's own columns; the rest of the row is the title's. */ + const rightWidth = () => Math.min(inner(), Bun.stringWidth(subHeader().right)) + const leftWidth = () => Math.max(0, inner() - rightWidth() - 1) + + // Diff width inside the body (its padding and the scrollbar's column taken off). + const diffWidth = () => Math.max(8, inner() - 1) + + // ── the session header ── + const head = () => p.session?.() ?? { model: "", mode: "", effort: "", where: "", spend: "" } + const headLine = () => [head().model, head().mode, head().effort].filter(Boolean).join(" · ") + const ctxLine = () => { + const ctx = contextWords(view.state, true) + const tokens = view.taskTokens().n + void now() + return [ctx.text, view.state.rate ? `${Math.round(view.state.rate)} tok/s` : "", view.state.phase !== "idle" && tokens ? `${num(tokens)} out` : "", head().spend, head().where].filter(Boolean).join(" · ") + } + const ctxColor = () => { + const level = contextWords(view.state, true).level + return level === "critical" ? c().statusCritical : level === "bad" ? c().statusBad : level === "warn" ? c().statusWarn : level === "good" ? c().statusGood : c().muted } - // Diff width inside the pane (minus left border, padding and scrollbar). - const diffWidth = () => Math.max(20, p.width - 5) + // ── pictures ── + const setting = () => app.loaded.config.images + const [settingRev, setSettingRev] = createSignal(0) + onCleanup(app.bus.on((e) => e.type === "setting" && e.key === "images" && setSettingRev((n) => n + 1))) + const protocol = () => (settingRev(), imageProtocol(setting())) + const picture = createMemo(() => { + const im = activeTab() === "images" ? currentImage() : undefined + return im ? { entry: im, ...readPicture(im.path) } : undefined + }) + const [drawError, setDrawError] = createSignal() + createEffect(() => (picture(), setDrawError(undefined))) + /** A cell's height over its width, from the terminal's pixel size when it said one. */ + const cellAspect = () => { + const r = (renderer as unknown as { resolution?: { width: number; height: number } | null }).resolution + const w = renderer.width + const h = renderer.height + return r && r.width > 0 && r.height > 0 && w > 0 && h > 0 ? r.height / h / (r.width / w) : 2 + } + /** The picture's box: what the body leaves under its two lines of words, the aspect kept. */ + const box = () => { + const pic = picture() + const px = pic && "bytes" in pic ? pic.px : undefined + return px ? fitImage(px, inner(), Math.max(1, bodyRows() - 3), cellAspect()) : { width: inner(), height: Math.max(1, bodyRows() - 3) } + } + const pictureWords = () => { + const pic = picture() + if (!pic) return "" + const px = "bytes" in pic && pic.px ? `${num(pic.px.width)}×${num(pic.px.height)}` : "" + return [px, pic.size !== undefined ? sizeWords(pic.size) : "", "error" in pic ? pic.error : (drawError() ?? "")].filter(Boolean).join(" · ") + } - return ( - - {/* Tab bar */} - - - - {(tab, i) => { - const isActive = () => activeTab() === tab - const count = () => (tab === "live" ? 0 : counts()[tab]) - const dot = () => (tab === "changes" && hasProposed() ? " ●" : tab === "live" && view.state.phase !== "idle" ? " ◉" : "") - const label = () => `${TAB_LABEL[tab]}${tab !== "live" && count() > 0 ? ` (${count()})` : ""}${dot()}` - return ( - <> - 0}> - {" "} - - - {` ${label()} `} - - - ) - }} - + const rows = () => ( + <> + {/* Session header */} + + + {headLine() || " "} + 1}> + + {clipEnd(ctxLine(), inner()) || " "} + + - {/* Sub-header */} - - - {subHeader().left} - - - {" "}{subHeader().right} - + {/* Tab bar: one box per tab, each as wide as its label, so a click lands on a known cell */} + + + {(cell) => { + const tab = cell.id as DisplayTab + const isActive = () => activeTab() === tab + const waiting = () => tab === "changes" && hasProposed() + return ( + p.onSelectTab(tab)}> + + {cell.text} + + + ) + }} + + + + {/* Sub-header: what is shown, and which of how many */} + + + {/* A sentence is cut at its end; a path or a command keeps both ends. */} + + {activeTab() === "live" ? clipEnd(subHeader().left, leftWidth()) : subHeader().left} + + + + + {subHeader().right} + + {/* Body */} - p.scrollRef?.(r)} - flexGrow={1} - scrollX={false} - stickyScroll={activeTab() === "bash"} - stickyStart={activeTab() === "bash" ? "bottom" : "top"} - viewportOptions={{ paddingLeft: 1, paddingRight: 1 }} - verticalScrollbarOptions={{ trackOptions: { backgroundColor: c().panel, foregroundColor: c().dim } }} - > - - - - {/* Waiting banner */} - - - - {`Waiting: ${live().waiting!.title}`} - - - {live().waiting!.detail} - - - - - {/* Currently running tools */} - 0}> - - - Running now - - - {(t) => ( - - - ◐ - {t.name} - {t.title ? ` ${t.title}` : ""} - - - {(ch) => ( - - {" ↳ "} - {ch.name} - {ch.title ? ` ${ch.title}` : ""} - - )} - - - )} - - - - - {/* Live thinking preview */} - - - - {live().thinkingStreaming ? "Thinking live" : "Last thought"} - - - - {live().thinkingTail} - - - - - - {/* Active plan */} - - - - {live().plan!.head} - - - {(line) => ( - - {` ${PLAN_MARK[line.status] ?? "•"} ${line.text}`} - - )} - - - - - {/* Subagents & background jobs */} - 0 || teamMembers().length > 0}> - - - Agents & jobs - - - {(m) => ( - - {" ● "} - {m.name} - {` (${m.role}) · ${m.state}`} - - )} - - - {(j) => ( - - - {" "} - {j.state === "running" ? "◐" : j.state === "error" ? "✗" : "✓"}{" "} - - {j.id} - {` ${j.label}`} - {` · ${j.detail}`} - - )} - - - - - {/* Recent tool activity */} - 0}> - - - Recent activity - - - {(t) => ( - - - {` ${toolStatusGlyph(t.status)} `} - - {t.name} - {t.title ? ` ${t.title}` : ""} - {t.detail ? ` · ${t.detail}` : ""} - - )} - - - - - {/* Latest preview */} - - - - {`Latest ${live().latestPreview!.kind}: ${live().latestPreview!.title}`} - - - - {live().latestPreview!.body} - - - - - - - - Live agent activity, thinking, files read, diffs, and bash output will appear here as the agent works. - - - - - - + - No files read in this session yet. - + + No pictures in this session yet: what view_image views, and images you attach with @, appear here. + } > - + + {picture()!.entry.title} + + + {clipEnd(pictureWords(), inner()) || " "} + + + {picture()!.entry.path} + {protocol() ? "" : "\n(pictures are off: images: off)"} + + } + > + + setDrawError(`not drawn: ${e instanceof Error ? e.message : String(e)}`.split("\n")[0]!)} + /> + + + + } + > + p.scrollRef?.(r)} + flexGrow={1} + scrollX={false} + stickyScroll={activeTab() === "bash"} + stickyStart={activeTab() === "bash" ? "bottom" : "top"} + viewportOptions={{ paddingLeft: 1, paddingRight: 1 }} + verticalScrollbarOptions={{ trackOptions: { backgroundColor: c().panel, foregroundColor: c().dim } }} + > + + + + {/* Waiting banner */} + + + + {`Waiting: ${live().waiting!.title}`} + + + {live().waiting!.detail} + + + + + {/* Currently running tools */} + 0}> + + + Running now + + + {(t) => ( + + + ◐ + {t.name} + {t.title ? ` ${t.title}` : ""} + + + {(ch) => ( + + {" ↳ "} + {ch.name} + {ch.title ? ` ${ch.title}` : ""} + + )} + + + )} + + + + + {/* Live thinking preview */} + + + + {live().thinkingStreaming ? "Thinking live" : "Last thought"} + + + + {live().thinkingTail} + + + + + + {/* Active plan */} + + + + {live().plan!.head} + + + {(line) => ( + + {` ${PLAN_MARK[line.status] ?? "•"} ${line.text}`} + + )} + + + + + {/* Subagents & background jobs */} + 0 || teamMembers().length > 0}> + + + Agents & jobs + + + {(m) => ( + + {" ● "} + {m.name} + {` (${m.role}) · ${m.state}`} + + )} + + + {(j) => ( + + + {" "} + {j.state === "running" ? "◐" : j.state === "error" ? "✗" : "✓"}{" "} + + {j.id} + {` ${j.label}`} + {` · ${j.detail}`} + + )} + + + + + {/* Recent tool activity */} + 0}> + + + Recent activity + + + {(t) => ( + + {` ${toolStatusGlyph(t.status)} `} + {t.name} + {t.title ? ` ${t.title}` : ""} + {t.detail ? ` · ${t.detail}` : ""} + + )} + + + + + {/* Latest preview */} + + + + {`Latest ${live().latestPreview!.kind}: ${live().latestPreview!.title}`} + + + + {live().latestPreview!.body} + + + + + + + + Live agent activity, thinking, files read, diffs, command output and pictures appear here as the agent works. + + + + + + + No files read in this session yet.}> {currentFile()!.body} - - - + + - - - No file changes in this session yet. - - } - > - - - - Proposed change — waiting for your answer - - - - {currentChange()!.diff} + + No file changes in this session yet.}> + + + + Proposed change — waiting for your answer - } - > - - - - - - - - - No bash commands run in this session yet. + + + {currentChange()!.diff} + + } + > + + - } - > - - - {`$ ${currentBash()!.command}`} - - - {currentBash()!.output} - - - - - - + + - {/* Footer key hints */} + + No bash commands run in this session yet.}> + + + {`$ ${currentBash()!.command}`} + + + {currentBash()!.output} + + + + + + + + + {/* Key line */} - - Alt+↑↓ tabs · Alt+←→ entry · Alt+PgUp/Dn scroll · Alt+D hide + + {paneHints(inner(), p.zoomed) || " "} + + ) + // In the transcript's place it has no border: the column is its own. (A border colour alone + // would draw one, so the two boxes are written out.) + if (p.zoomed) + return ( + + {rows()} + + ) + return ( + + {rows()} ) } diff --git a/src/tui/components/messages.tsx b/src/tui/components/messages.tsx index 22f795a..a946f4b 100644 --- a/src/tui/components/messages.tsx +++ b/src/tui/components/messages.tsx @@ -1,18 +1,19 @@ import { TextAttributes } from "@opentui/core" -import { createEffect, createSignal, For, Match, onCleanup, Show, Switch } from "solid-js" +import { createEffect, createMemo, createSignal, For, Match, onCleanup, Show, Switch } from "solid-js" import { duration } from "../../duration.ts" import { estimateTokens } from "../../provider/tokens.ts" import { useTui } from "../context.ts" import type { Item } from "../state.ts" import { clipDiff } from "../diffclip.ts" -import { blockOf, callDuration, callTitle, drawnBlock, type CallState } from "../../session/display.ts" +import { callTitle } from "../../session/display.ts" import { num } from "../locale.ts" import { NOTICES } from "../notices.ts" import { pageNote, splitPages } from "../../pages/fence.ts" +import { callAfter, groupRounds, patchStats, roundLine, roundTrouble, summarize, undrawn, type Round } from "../transcript.ts" +import { clipEnd } from "../layout.ts" -/** A call the transcript does not draw: a plan change (the panel above the prompt follows it) or a - * tool the spec marks hidden — under its former name too (a stored session's `todo`). */ -const undrawn = (name: string) => !drawnBlock(blockOf(name)) +/** A row's id in the scrollbox, so the same place can be found again when the view changes. */ +export const rowId = (id: string) => `row-${id}` const FILETYPES: Record = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", mjs: "javascript", md: "markdown", zig: "zig" } export const filetypeOf = (diff: string) => FILETYPES[/^\+\+\+ \S*\.(\w+)/m.exec(diff)?.[1] ?? ""] @@ -72,7 +73,7 @@ function AssistantMessage(p: { item: Extract }) { * and tokens, nothing else (the task's are on the line at the bottom). The tokens are the * provider's count when the step had this one thought, else an estimate (~). Ctrl+R opens a * finished thought. */ -function Reasoning(p: { item: Extract }) { +function Reasoning(p: { item: Extract; tight?: boolean }) { const { theme, thought, view } = useTui() const [now, setNow] = createSignal(Date.now()) createEffect(() => { @@ -87,7 +88,7 @@ function Reasoning(p: { item: Extract }) { const dots = () => ".".repeat(1 + (Math.floor((now() - p.item.started) / 400) % 3)) const line = () => (p.item.streaming ? `Thinking${dots()}` : p.item.ms !== undefined ? `Thought for ${duration(p.item.ms)} · ${tokens()}` : `Thought · ${tokens()}`) return ( - + {line()} @@ -107,19 +108,19 @@ export function jobWords(j: { state: string; started: number; ended?: number; ex return `${j.state}${j.state !== "lost" && j.exit !== undefined && j.exit !== null && j.exit !== 0 ? ` (exit ${j.exit})` : ""} · ${took}` } -function ToolLine(p: { item: Extract }) { +/** `brief` (the compact transcript): the call's line alone — no diff and no output under it + * unless ctrl+o opened them, and of a subagent's lines only the newest. */ +function ToolLine(p: { item: Extract; brief?: boolean }) { const { theme, view } = useTui() const c = () => theme().colors const emoji = () => (p.item.status === "denied" ? theme().icons.denied : (theme().toolEmoji[p.item.name] ?? (p.item.name.startsWith("mcp__") ? theme().icons.mcp : theme().icons.other))) // One title for a call, in every state (display.md §1); what its result adds comes after it. const title = () => p.item.title ?? callTitle(p.item.args) ?? "" - const state = (): CallState => (p.item.status === "error" ? "failed" : p.item.status) /** After the title: the facts, a failure's or a refusal's first line, and how long it took — * never for a call that is running (a mark) or was denied (it did not run). */ - const after = () => { - if (state() === "running") return "…" - return [...(p.item.facts ?? []), ...(p.item.note ? [p.item.note] : []), ...[callDuration(state(), p.item.ms)].filter((x): x is string => !!x)].join(" · ") - } + const after = () => callAfter(p.item) + const open = () => !p.brief || view.state.expandTools + const children = () => (p.brief && !view.state.expandTools ? (p.item.children ?? []).slice(-2) : (p.item.children ?? [])) const tail = () => (p.item.output ?? "").trimEnd().split("\n").slice(-12).join("\n") // Short in the transcript, whole with ctrl+o; always a diff the renderer can parse. const shown = () => (view.state.expandTools ? { diff: p.item.diff ?? "", hidden: 0 } : clipDiff(p.item.diff ?? "", 24)) @@ -143,7 +144,7 @@ function ToolLine(p: { item: Extract }) { {` ${jobWords(p.item.job!)}`} - + {(ch) => ( {" "}{theme().branding.toolPrefix} @@ -153,7 +154,7 @@ function ToolLine(p: { item: Extract }) { )} - + 0}> @@ -277,38 +278,202 @@ function EndLine(p: { item: Extract }) { ) } -export function Messages() { +/** One item as the full transcript draws it. */ +function ItemRow(p: { item: Item; compact?: boolean }) { + const { view } = useTui() + const item = p.item + return ( + + + } /> + + + } /> + + + } tight={p.compact} /> + + ).name)}> + } /> + + + } /> + + + } /> + + + } /> + + + } /> + + + } /> + + + ) +} + +/** A multi-file diff in the compact transcript: its title and a stat line per file. */ +function DiffStats(p: { item: Extract }) { + const { theme } = useTui() + const c = () => theme().colors + return ( + + + {p.item.title} + + {(f) => } + + ) +} + +/** `path +12 −3`: a change without its diff (display.md §2's facts; the minus is U+2212). */ +function StatLine(p: { path: string; added: number; removed: number }) { + const { theme } = useTui() + const c = () => theme().colors + return ( + + {" "} + {p.path} + {` +${num(p.added)}`} + {` −${num(p.removed)}`} + + ) +} + +/** The most stat lines a round shows before it says how many more there are. */ +const ROUND_CHANGES = 4 + +/** A tool round in the compact transcript. One call is its own line. Several are one line — + * `▸ 7 tools · read ×3 · bash ×2 · edit ×2 · 14.0s` — and under it only what must not be missed: + * every failure and every refusal with its first line, every call still running, each change as + * a stat line. Ctrl+O opens the round into its calls as the full transcript draws them. */ +function RoundRow(p: { round: () => Round | undefined }) { + const { theme, view, dims } = useTui() + const c = () => theme().colors + /** The columns a line of the row has: the column it stands in, less the transcript's own + * padding and scrollbar and the row's indent — known, so nothing is cut in the middle. */ + const width = () => Math.max(8, dims().width - 3) + const trouble = () => roundTrouble(sum()) + const troubleWidth = () => (trouble().failed ? trouble().failed.length + 3 : 0) + (trouble().denied ? trouble().denied.length + 3 : 0) + const tools = () => p.round()?.tools ?? [] + const sum = createMemo(() => summarize({ tools: tools() })) + const title = (t: Extract) => t.title ?? callTitle(t.args) ?? "" + const jobs = () => tools().filter((t) => t.job && t.job.state === "running") + return ( + 1} fallback={{(t) => }}> + + + {sum().running.length ? "◐ " : "▸ "} + {roundLine(sum(), width() - 2 - troubleWidth())} + {trouble().failed ? ` · ${trouble().failed}` : ""} + {trouble().denied ? ` · ${trouble().denied}` : ""} + + + {(t) => } + + } + > + {(ch) => } + ROUND_CHANGES}> + + {` … ${sum().changes.length - ROUND_CHANGES} more change${sum().changes.length - ROUND_CHANGES === 1 ? "" : "s"} (ctrl+o)`} + + + + {(t) => ( + + {t.status === "denied" ? " ⊘ " : " ✗ "} + {t.name} + {clipEnd(`${title(t) ? ` ${title(t)}` : ""}${callAfter(t) ? ` · ${callAfter(t)}` : ""}`, width() - 6 - t.name.length)} + + )} + + + {(t) => ( + + {" ◐ "} + {t.name} + {title(t) ? ` ${title(t)}` : ""} + {t.children?.length ? ` · ${t.children[t.children.length - 1]!.name} ${t.children[t.children.length - 1]!.title}` : " …"} + + )} + + + {(t) => ( + + {" → "} + {t.job!.id} + {` (${t.job!.agent ? `${t.job!.agent}: ` : ""}${t.job!.description})`} + {` ${jobWords(t.job!)}`} + + )} + + + + + ) +} + +/** The compact transcript: the same items, tool rounds grouped (transcript.ts). */ +function CompactMessages() { + const { view } = useTui() + const rows = createMemo(() => groupRounds(view.state.items, { showReasoning: view.state.showReasoning })) + const rounds = createMemo(() => new Map(rows().flatMap((r) => (r.kind === "round" ? [[r.id, r] as const] : [])))) + // One object per round for as long as it exists, so a round that grows is updated, not redrawn. + type Ref = { round: string } + const refs = new Map() + const list = createMemo(() => { + for (const id of refs.keys()) if (!rounds().has(id)) refs.delete(id) + return rows().map((r): Item | Ref => { + if (r.kind === "item") return r.item + let ref = refs.get(r.id) + if (!ref) refs.set(r.id, (ref = { round: r.id })) + return ref + }) + }) + return ( + + {(row) => + "round" in row ? ( + + rounds().get(row.round)} /> + + ) : ( + + + + ) + } + + ) +} + +function FullMessages() { const { view } = useTui() return ( {(item) => ( - - - } /> - - - } /> - - - } /> - - ).name)}> - } /> - - - } /> - - - } /> - - - } /> - - - } /> - - + + + )} ) } + +/** The conversation, full or compact (`compact` of the context: the `transcript` setting, and + * whether the display pane stands beside it). Both are views over the same items. */ +export function Messages() { + const { compact } = useTui() + return ( + }> + + + ) +} diff --git a/src/tui/components/prompt.tsx b/src/tui/components/prompt.tsx index f2158ea..a850966 100644 --- a/src/tui/components/prompt.tsx +++ b/src/tui/components/prompt.tsx @@ -8,6 +8,7 @@ import { escapeMention } from "../../project/attach.ts" import fuzzysort from "fuzzysort" import { createMemo, createSignal, For, onCleanup, Show } from "solid-js" import type { FileIndex } from "../../project/files.ts" +import { firstFit } from "../layout.ts" import { useTui } from "../context.ts" import { History } from "../history.ts" import { imageLabel, pasteLabel, Placeholders, type BoxSnapshot } from "../paste.ts" @@ -82,7 +83,7 @@ export function Prompt(p: { * itself binds ctrl+b (move left) and would keep the key. */ onBackground?: () => void }) { - const { theme, app } = useTui() + const { theme, app, dims } = useTui() const c = () => theme().colors const history = new History() // How a paste placeholder looks: the theme's label colour, on the menu's background. @@ -349,7 +350,8 @@ export function Prompt(p: { textColor={c().prompt} focusedTextColor={c().prompt} cursorColor={c().accent} - placeholder={p.busy() ? "working… (enter adds a message to it; esc stops)" : "Ask · / commands · @ files · !shell"} + // The longest form that fits the box: a placeholder that wraps makes the box two rows. + placeholder={firstFit(dims().width - 4, p.busy() ? ["working… (enter adds a message to it; esc stops)", "working… (esc stops)", "working…"] : ["Ask · / commands · @ files · !shell", "Ask · / · @ · !", "Ask"])} placeholderColor={c().dim} keyBindings={[ { name: "return", action: "submit" }, diff --git a/src/tui/components/status.tsx b/src/tui/components/status.tsx index 0002065..ae09adf 100644 --- a/src/tui/components/status.tsx +++ b/src/tui/components/status.tsx @@ -2,6 +2,7 @@ import { basename } from "node:path" import { Show } from "solid-js" import { isLocal } from "../../config/paths.ts" import { useTui } from "../context.ts" +import { clipEnd } from "../layout.ts" const MODE_LABEL = { manual: "manual", edit: "edit", auto: "AUTO", plan: "plan" } as const @@ -18,27 +19,44 @@ export function jobsWord(jobs: { state: string; unread: number; unseen?: boolean return `${running} job${running === 1 ? "" : "s"}${news ? "!" : ""}` } +/** The context's words and how full it is: `ctx 12.0k/33k 37%` — or, `short`, `ctx 37%` (`ctx + * 12.0k` where the window is not known). `level` picks the colour. */ +export function contextWords(state: { usage?: { input: number; output: number; estimated?: boolean }; used?: number; context?: number }, full = true): { text: string; level: "none" | "plain" | "good" | "warn" | "bad" | "critical" } { + const u = state.usage + if (!u) return { text: "ctx —", level: "none" } + const used = state.used ?? u.input + u.output + const total = state.context + if (!total) return { text: `ctx ${fmtTokens(used)}${u.estimated ? "~" : ""}`, level: "plain" } + const pct = Math.round((used / total) * 100) + const level = pct >= 90 ? "critical" : pct >= 75 ? "bad" : pct >= 50 ? "warn" : "good" + return { text: full ? `ctx ${fmtTokens(used)}${u.estimated ? "~" : ""}/${fmtTokens(total)} ${pct}%` : `ctx ${pct}%${u.estimated ? "~" : ""}`, level } +} + /** One line: mode · model · effort on the left; the jobs, context use and where on the right — or, * for a moment, a flash (a copy) in their place. The jobs word sits on the right, which is never * truncated: at 80 columns a long project name cuts the left short, and a running job is the one * thing that must stay visible. */ -export function StatusBar(p: { mode: () => string; model: () => string; effort: () => string; branch?: string; voice?: () => string; flash?: () => string | undefined; remote?: () => string; spend?: () => string; team?: () => string; mcp?: () => { text: string; warn: boolean } }) { - const { theme, view, app } = useTui() +/** `short`: the bar is narrow (a column beside the display pane, a small terminal) — the right side + * keeps what must stay in sight (the jobs, how full the context is, `local`) and leaves the rest + * to the pane's header and the welcome box. `hint`: a word of the display's (a narrow terminal: + * that there is one, and the key that opens it). */ +export function StatusBar(p: { mode: () => string; model: () => string; effort: () => string; branch?: string; voice?: () => string; flash?: () => string | undefined; remote?: () => string; spend?: () => string; team?: () => string; mcp?: () => { text: string; warn: boolean }; short?: () => boolean; hint?: () => string }) { + const { theme, view, app, dims } = useTui() const c = () => theme().colors + /** The bar's columns inside its padding. A flash never runs past them, and takes the whole bar + * when the two sides would not both fit. */ + const room = () => Math.max(1, dims().width - 2) + const flashOnly = () => !!p.flash?.() && Bun.stringWidth(p.flash()!) + 22 > room() const modeColor = () => ({ manual: c().statusText, edit: c().statusGood, auto: c().statusCritical, plan: c().info })[p.mode() as keyof typeof MODE_LABEL] ?? c().statusText + const short = () => p.short?.() === true const ctx = () => { - const u = view.state.usage - if (!u) return { text: "ctx —", color: c().statusDim } - const used = view.state.used ?? u.input + u.output - const total = view.state.context - if (!total) return { text: `ctx ${fmtTokens(used)}${u.estimated ? "~" : ""}`, color: c().statusText } - const pct = Math.round((used / total) * 100) - const color = pct >= 90 ? c().statusCritical : pct >= 75 ? c().statusBad : pct >= 50 ? c().statusWarn : c().statusGood - return { text: `ctx ${fmtTokens(used)}${u.estimated ? "~" : ""}/${fmtTokens(total)} ${pct}%`, color } + const w = contextWords(view.state, !short()) + const color = { none: c().statusDim, plain: c().statusText, good: c().statusGood, warn: c().statusWarn, bad: c().statusBad, critical: c().statusCritical }[w.level] + return { text: w.text, color } } return ( - + {MODE_LABEL[p.mode() as keyof typeof MODE_LABEL] ?? p.mode()} · {p.model()} @@ -50,20 +68,20 @@ export function StatusBar(p: { mode: () => string; model: () => string; effort: when={p.flash?.()} fallback={ - {p.team?.() ? `${p.team()} · ` : ""} - {p.mcp?.().text ? `${p.mcp!().text} · ` : ""} + {p.hint?.() ? `${p.hint()} · ` : ""} + {!short() && p.team?.() ? `${p.team()} · ` : ""} + {!short() && p.mcp?.().text ? `${p.mcp!().text} · ` : ""} {jobsWord(view.state.jobs) ? `${jobsWord(view.state.jobs)} · ` : ""} - {view.state.rate ? `${Math.round(view.state.rate)} tok/s · ` : ""} - {p.spend?.() ? `${p.spend()} · ` : ""} + {!short() && view.state.rate ? `${Math.round(view.state.rate)} tok/s · ` : ""} + {!short() && p.spend?.() ? `${p.spend()} · ` : ""} {ctx().text} - · - {isLocal() ? "local " : ""} - {basename(app.project.root)}{p.branch ? `@${p.branch}` : ""} + {isLocal() ? " · local" : ""} + {short() ? "" : `${isLocal() ? " " : " · "}${basename(app.project.root)}${p.branch ? `@${p.branch}` : ""}`} } > - {p.flash!()} + {clipEnd(p.flash?.() ?? "", room())} diff --git a/src/tui/components/welcome.tsx b/src/tui/components/welcome.tsx index 0be6666..4755827 100644 --- a/src/tui/components/welcome.tsx +++ b/src/tui/components/welcome.tsx @@ -1,8 +1,10 @@ import { TextAttributes } from "@opentui/core" -import { Show } from "solid-js" +import { For, Show } from "solid-js" import { VERSION } from "../../version.ts" import { useTui } from "../context.ts" +const HINTS = ["enter send", "shift+enter newline", "shift+tab mode", "/help"] + export function Welcome() { const { theme, app } = useTui() const c = () => theme().colors @@ -25,9 +27,17 @@ export function Welcome() { This project is not trusted: its .agent config, commands and servers are ignored. /trust to change that. - - enter send · shift+enter newline · shift+tab mode · /help - + {/* Each hint is one piece that never breaks: in a narrow column the row wraps between hints, + not inside one. */} + + + {(hint, i) => ( + + {i() < HINTS.length - 1 ? `${hint} ·` : hint} + + )} + + ) } diff --git a/src/tui/context.ts b/src/tui/context.ts index 31b8ccc..f22f0f1 100644 --- a/src/tui/context.ts +++ b/src/tui/context.ts @@ -13,6 +13,8 @@ export interface Ctx { /** Terminal size, from ONE resize subscription in Root: per-item subscriptions leaked listeners * (and Node's warning about them printed over the screen). */ dims: () => { width: number; height: number } + /** The compact transcript is drawn (tool rounds grouped); unset: the full one. */ + compact?: () => boolean } export const TuiContext = createContext() diff --git a/src/tui/displays.ts b/src/tui/displays.ts index e3b1d0e..3b5234d 100644 --- a/src/tui/displays.ts +++ b/src/tui/displays.ts @@ -1,5 +1,7 @@ // Side display pane state & extractors (inspired by LiNA's displays, extended with a real-time -// "Live" activity view so you can always see what the agent is doing right now). +// "Live" activity view so you can always see what the agent is doing right now). Where the pane +// stands, and how wide, is layout.ts. +import { extname } from "node:path" import { duration } from "../duration.ts" import { open as planOpen, summary as planSummary } from "../plan/plan.ts" import { callDuration, callTitle } from "../session/display.ts" @@ -8,11 +10,10 @@ import { diffStat } from "../tool/write.ts" import { num } from "./locale.ts" import type { Item, Pending, ViewState } from "./state.ts" -export const DISPLAY_TABS = ["live", "files", "changes", "bash"] as const +export const DISPLAY_TABS = ["live", "files", "changes", "bash", "images"] as const export type DisplayTab = (typeof DISPLAY_TABS)[number] -/** Minimum terminal width to show the side-by-side display pane cleanly. */ -export const DISPLAY_MIN_WIDTH = 100 +export type ListTab = Exclude /** Cap displayed text per entry so huge reads/outputs stay snappy in the terminal. */ const MAX_BODY_CHARS = 40_000 @@ -44,6 +45,16 @@ export interface BashEntry { status: "running" | "done" | "error" | "denied" } +/** A picture of the session: one a tool viewed or showed, or one the person attached. `path` is + * where it is on this disk — the only thing ever read to draw it. */ +export interface ImageEntry { + id: string + /** The path as it was written (the call's argument, the mention). */ + title: string + path: string + source: "viewed" | "shown" | "attached" +} + export interface ActivityRow { id: string name: string @@ -68,6 +79,10 @@ export interface LiveSnapshot { const CHANGE_TOOLS = new Set(["edit", "write", "multiedit", "apply_patch"]) const FILE_TOOLS = new Set(["read", "show"]) +const IMAGE_TOOLS: Record = { view_image: "viewed", show: "shown" } +/** What the terminal can be given as a picture (project/image.ts IMAGE_TYPES), by the name alone. */ +const IMAGE_EXT = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]) +export const isImagePath = (path: string) => IMAGE_EXT.has(extname(path).toLowerCase()) function argStr(args: unknown, key: string): string { if (!args || typeof args !== "object") return "" @@ -97,10 +112,12 @@ export function extractFiles(items: readonly Item[]): FileEntry[] { for (const it of items) { if (it.kind !== "tool" || !FILE_TOOLS.has(it.name)) continue const path = argStr(it.args, "path") || argStr(it.args, "file_path") || it.title || it.name - const bits = [...(it.facts ?? []), ...(it.note ? [it.note] : [])] + // A picture that was shown is in the images tab. + if (it.name === "show" && isImagePath(path)) continue + const bits = [...(it.name === "show" ? ["shown"] : []), ...(it.facts ?? []), ...(it.note ? [it.note] : [])] const dur = callDuration(it.status === "error" ? "failed" : it.status, it.ms) if (dur) bits.push(dur) - if (it.status === "running") bits.unshift("reading…") + if (it.status === "running") bits.unshift(it.name === "show" ? "showing…" : "reading…") const body = it.output ? clipHead(it.output) : it.status === "running" ? "(reading file…)" : it.note || "(no content)" out.push({ id: it.id, @@ -113,6 +130,55 @@ export function extractFiles(items: readonly Item[]): FileEntry[] { return out } +/** The session's pictures, oldest first: what `view_image` viewed and `show` showed (finished + * calls only — one that failed or was refused read nothing), and what the person attached to a + * prompt. `abs`: the call's path as the tool read it. */ +export function extractImages(items: readonly Item[], abs: (path: string) => string): ImageEntry[] { + const out: ImageEntry[] = [] + for (const it of items) { + if (it.kind === "user") { + for (const [i, path] of (it.images ?? []).entries()) out.push({ id: `${it.id}.${i}`, title: path, path: abs(path), source: "attached" }) + continue + } + if (it.kind !== "tool" || it.status !== "done") continue + const source = IMAGE_TOOLS[it.name] + const path = argStr(it.args, "path") + if (!source || !path || !isImagePath(path)) continue + out.push({ id: it.id, title: path, path: abs(path), source }) + } + return out +} + +/** Whether the newest call of the session is a picture a tool just viewed or showed: the pane + * then shows it by itself, until the agent does something else. */ +export function freshImage(items: readonly Item[]): boolean { + for (let i = items.length - 1; i >= 0; i--) { + const it = items[i]! + if (it.kind === "user") return false + if (it.kind !== "tool") continue + return it.status === "done" && it.name in IMAGE_TOOLS && isImagePath(argStr(it.args, "path")) + } + return false +} + +/** How pictures are drawn, from the `images` setting: `auto` — the best the terminal is known to + * do (kitty's graphics protocol, sixel, else coloured blocks; the renderer asks the terminal); + * `on` — kitty's protocol whatever was detected; `off` — not drawn: name, size and path only. */ +export function imageProtocol(setting: "auto" | "on" | "off" | undefined): "auto" | "kitty" | undefined { + if (setting === "off") return undefined + return setting === "on" ? "kitty" : "auto" +} + +/** A picture's box in cells inside `width` × `height` cells, its aspect kept. `cellAspect`: a + * cell's height over its width in pixels (2 when the terminal did not say). */ +export function fitImage(px: { width: number; height: number }, width: number, height: number, cellAspect = 2): { width: number; height: number } { + if (px.width <= 0 || px.height <= 0 || width <= 0 || height <= 0) return { width: 0, height: 0 } + // The picture's width in cells for one row of height. + const aspect = (px.width / px.height) * (cellAspect > 0 ? cellAspect : 2) + const rows = Math.min(height, width / aspect) + return { width: Math.max(1, Math.min(width, Math.round(rows * aspect))), height: Math.max(1, Math.min(height, Math.round(rows))) } +} + /** Extract applied/denied/proposed file changes for the `changes` display tab. */ export function extractChanges(items: readonly Item[], pending?: Pending): ChangeEntry[] { const out: ChangeEntry[] = [] @@ -300,21 +366,24 @@ export interface DisplayNavState { /** True when the user manually navigated tabs or older entries; pauses auto-switching until reset. */ pinned: boolean /** 0-based selected index per list tab; -1 means "follow newest". */ - index: Record, number> + index: Record } export function initialNav(): DisplayNavState { - return { tab: "live", pinned: false, index: { files: -1, changes: -1, bash: -1 } } + return { tab: "live", pinned: false, index: { files: -1, changes: -1, bash: -1, images: -1 } } } -/** Resolve which tab is active right now: auto-jumps to `changes` when a proposed diff awaits approval (unless pinned). */ -export function effectiveTab(nav: DisplayNavState, hasProposedDiff: boolean): DisplayTab { +/** Resolve which tab is active right now. Unless the person pinned one, the pane goes by itself to + * `changes` while a proposed diff awaits approval, and to `images` while a picture a tool just + * viewed is the newest thing that happened. */ +export function effectiveTab(nav: DisplayNavState, hasProposedDiff: boolean, hasFreshImage = false): DisplayTab { if (!nav.pinned && hasProposedDiff) return "changes" + if (!nav.pinned && hasFreshImage) return "images" return nav.tab } /** Resolve the 0-based entry index for a list tab (clamped, defaulting to newest when -1). */ -export function resolveIndex(nav: DisplayNavState, tab: Exclude, count: number): number { +export function resolveIndex(nav: DisplayNavState, tab: ListTab, count: number): number { if (count <= 0) return -1 const raw = nav.index[tab] if (raw < 0 || raw >= count) return count - 1 @@ -329,7 +398,7 @@ export function cycleTab(nav: DisplayNavState, dir: -1 | 1): DisplayNavState { } /** Move between entries in the active list tab (`dir`: -1 for Alt+Left, +1 for Alt+Right). */ -export function stepEntry(nav: DisplayNavState, tab: Exclude, dir: -1 | 1, count: number): DisplayNavState { +export function stepEntry(nav: DisplayNavState, tab: ListTab, dir: -1 | 1, count: number): DisplayNavState { if (count <= 0) return nav const cur = resolveIndex(nav, tab, count) const next = Math.max(0, Math.min(count - 1, cur + dir)) @@ -344,5 +413,5 @@ export function stepEntry(nav: DisplayNavState, tab: Exclude /** Return to live auto-follow (called when a new user prompt starts). */ export function resetFollow(nav: DisplayNavState): DisplayNavState { - return { tab: "live", pinned: false, index: { ...nav.index, files: -1, changes: -1, bash: -1 } } + return { tab: "live", pinned: false, index: { ...nav.index, files: -1, changes: -1, bash: -1, images: -1 } } } diff --git a/src/tui/layout.ts b/src/tui/layout.ts new file mode 100644 index 0000000..bc2566f --- /dev/null +++ b/src/tui/layout.ts @@ -0,0 +1,139 @@ +// Where the display goes, by the terminal's width alone — decided here, as numbers, so that +// nothing on the screen lines up by coincidence: the left column (transcript, cards, prompt, +// status bar) and the display pane each get a width that is known before anything is drawn. + +/** Side by side from this many columns. */ +export const SIDE_MIN_WIDTH = 80 +/** The pane is this share of the terminal, within its floor and ceiling. */ +export const PANE_SHARE = 0.44 +export const PANE_MIN_WIDTH = 32 +export const PANE_MAX_WIDTH = 84 +/** The left column never gets less than this beside a pane. */ +export const LEFT_MIN_WIDTH = 44 +/** Under this width a status bar shows its short form. */ +export const STATUS_FULL_WIDTH = 80 + +export type Placement = + /** Switched off: no pane, and nothing says there is one. */ + | { mode: "off"; left: number; pane: 0 } + /** Side by side: the pane at the right over the terminal's full height. */ + | { mode: "side"; left: number; pane: number } + /** Too narrow for two columns, the display opened: it stands where the transcript was. */ + | { mode: "zoom"; left: number; pane: number } + /** Too narrow, the transcript showing: the status bar says a display exists and how to open it. */ + | { mode: "tucked"; left: number; pane: 0 } + +/** `enabled`: the display is switched on. `zoomed`: on a narrow terminal, the person opened it. */ +export function placeDisplay(o: { width: number; enabled: boolean; zoomed: boolean }): Placement { + const width = Math.max(1, Math.floor(o.width)) + if (!o.enabled) return { mode: "off", left: width, pane: 0 } + if (width >= SIDE_MIN_WIDTH) { + const share = Math.max(PANE_MIN_WIDTH, Math.min(PANE_MAX_WIDTH, Math.floor(width * PANE_SHARE))) + const pane = Math.min(share, width - LEFT_MIN_WIDTH) + return { mode: "side", left: width - pane, pane } + } + return o.zoomed ? { mode: "zoom", left: width, pane: width } : { mode: "tucked", left: width, pane: 0 } +} + +export type TranscriptSetting = "auto" | "full" | "compact" + +/** Which transcript is drawn: `auto` is compact while the display stands beside it, full otherwise + * (switched off, too narrow, or opened in the transcript's place). */ +export function transcriptMode(setting: TranscriptSetting | undefined, placement: Placement["mode"]): "full" | "compact" { + if (setting === "full" || setting === "compact") return setting + return placement === "side" ? "compact" : "full" +} + +export interface TabSpec { + id: string + /** Its full name, a shorter one, and one letter. */ + names: [long: string, short: string, letter: string] + /** Entries in it; 0 or undefined shows none. */ + count?: number + /** A mark after the name (something waits, something runs). */ + mark?: string +} + +export interface TabCell { + id: string + /** The label as drawn, one space each side included. */ + text: string + /** Its width in columns. */ + width: number +} + +const cols = (s: string) => Bun.stringWidth(s) +const countWord = (n: number | undefined) => (!n ? "" : n > 99 ? "99+" : String(n)) + +/** The tab bar for a row of `width` columns: the longest form of the labels that fits — full + * names with counts, short names, letters with counts, letters alone — one column between tabs. + * The last form is cut to the row if even that is too wide, so the bar never runs past it. */ +export function tabCells(width: number, tabs: readonly TabSpec[]): TabCell[] { + const forms: ((t: TabSpec) => string)[] = [ + (t) => `${t.names[0]}${countWord(t.count) ? ` (${countWord(t.count)})` : ""}${t.mark ? ` ${t.mark}` : ""}`, + (t) => `${t.names[1]}${countWord(t.count) ? ` ${countWord(t.count)}` : ""}${t.mark ? ` ${t.mark}` : ""}`, + (t) => `${t.names[2]}${countWord(t.count)}${t.mark ?? ""}`, + (t) => t.names[2], + ] + let cells: TabCell[] = [] + for (const form of forms) { + cells = tabs.map((t) => { + const text = ` ${form(t)} ` + return { id: t.id, text, width: cols(text) } + }) + if (rowWidth(cells) <= width) return cells + } + // Narrower than five letters: as many whole tabs as fit. + const out: TabCell[] = [] + for (const c of cells) { + if (rowWidth([...out, c]) > width) break + out.push(c) + } + return out +} + +/** A row of cells with one column between them. */ +export function rowWidth(cells: readonly { width: number }[]): number { + return cells.reduce((n, c) => n + c.width, 0) + Math.max(0, cells.length - 1) +} + +/** The tab under column `x` of the bar (0 = the first cell's first column), if any. */ +export function tabAt(cells: readonly TabCell[], x: number): string | undefined { + let at = 0 + for (const c of cells) { + if (x >= at && x < at + c.width) return c.id + at += c.width + 1 + } + return undefined +} + +/** The pane's key line, in the longest form that fits `width`. `zoomed`: the display stands in the + * transcript's place, and alt+d goes back to it. */ +export function paneHints(width: number, zoomed = false): string { + const back = zoomed ? "transcript" : "hide" + const forms = [ + `alt+↑↓ tabs · alt+←→ entry · alt+pgup/pgdn scroll · alt+d ${back}`, + `alt+↑↓ tabs · alt+←→ entry · alt+d ${back}`, + `alt ↑↓ tab · ←→ item · d ${back}`, + `alt+d ${back}`, + ] + return forms.find((f) => cols(f) <= width) ?? "" +} + +/** The first of `forms` that fits `width` columns; the last one when none does. */ +export function firstFit(width: number, forms: readonly string[]): string { + return forms.find((f) => cols(f) <= width) ?? forms[forms.length - 1] ?? "" +} + +/** Text cut to `width` columns at its end, with an ellipsis — for a sentence, where OpenTUI's own + * `truncate` (which elides the middle) is wrong. */ +export function clipEnd(text: string, width: number): string { + if (width <= 0) return "" + if (cols(text) <= width) return text + let out = "" + for (const ch of text) { + if (cols(out + ch) > width - 1) break + out += ch + } + return `${out.trimEnd()}…` +} diff --git a/src/tui/state.ts b/src/tui/state.ts index cde5694..b839fc1 100644 --- a/src/tui/state.ts +++ b/src/tui/state.ts @@ -27,7 +27,8 @@ const resultFacts = (name: string, title: string | undefined, result: { title?: export type Item = /** `mid`: sent while the agent worked, and given to it at a step boundary. `machine`: the harness * said it (a job's note), not the person. */ - | { kind: "user"; id: string; text: string; mid?: boolean; machine?: boolean } + /** `images`: the pictures attached to it, as paths on this disk (the display's images tab). */ + | { kind: "user"; id: string; text: string; mid?: boolean; machine?: boolean; images?: string[] } /** `pages`: the page fences in the text (harness pages.md), by where each starts — its title, * and where it was saved when it could be. */ | { kind: "assistant"; id: string; text: string; streaming: boolean; pages?: Record } @@ -458,8 +459,8 @@ export function createView(bus: Bus) { taskTokens(): { n: number; estimated: boolean } { return { n: taskTokens + Math.ceil(liveChars / CHARS_PER_TOKEN), estimated: liveChars > 0 } }, - user(text: string) { - set(produce((s) => void s.items.push({ kind: "user", id: nextId(), text }))) + user(text: string, images?: string[]) { + set(produce((s) => void s.items.push({ kind: "user", id: nextId(), text, ...(images?.length ? { images } : {}) }))) set({ phase: "waiting", busySince: Date.now() }) }, /** A report read here (harness reports.md): its title and where it came from as a line, then diff --git a/src/tui/transcript.ts b/src/tui/transcript.ts new file mode 100644 index 0000000..ac39ebc --- /dev/null +++ b/src/tui/transcript.ts @@ -0,0 +1,151 @@ +// The compact transcript: the same items as the full one, grouped. A tool round — the calls +// between two pieces of text — is one row; what the calls returned is in the display pane. +// Pure: a view over the items, which it never changes. +import { duration } from "../duration.ts" +import { blockOf, callDuration, callTitle, diffCounts, drawnBlock } from "../session/display.ts" +import type { Item } from "./state.ts" + +export type ToolItem = Extract +export type ReasoningItem = Extract + +/** A call the transcript does not draw: a plan change (the panel follows it) or a tool the spec + * marks hidden — under its former name too. */ +export const undrawn = (name: string) => !drawnBlock(blockOf(name)) + +/** One round: its calls in order, and the finished thoughts between them (folded into the row). */ +export interface Round { + kind: "round" + /** The first call's id: the same from the round's first call to its last. */ + id: string + tools: ToolItem[] + thoughts: ReasoningItem[] +} + +export type Row = { kind: "item"; item: Item } | Round + +/** The items as rows. Consecutive drawn calls are one round; a finished thought between two calls + * of a round is folded into it. A thought still streaming, one before the round's first call, and + * every thought while `showReasoning` is on, is a row of its own — and ends the round before it. + * Undrawn calls are no row and end nothing. */ +export function groupRounds(items: readonly Item[], o: { showReasoning?: boolean } = {}): Row[] { + const rows: Row[] = [] + let round: Round | undefined + // Thoughts after the round's last call so far: folded in only if another call follows. + let trailing: ReasoningItem[] = [] + const close = () => { + for (const t of trailing) rows.push({ kind: "item", item: t }) + trailing = [] + round = undefined + } + for (const item of items) { + if (item.kind === "tool") { + if (undrawn(item.name)) continue + if (!round) { + round = { kind: "round", id: item.id, tools: [], thoughts: [] } + rows.push(round) + } + round.thoughts.push(...trailing) + trailing = [] + round.tools.push(item) + continue + } + if (item.kind === "reasoning" && round && !item.streaming && !o.showReasoning) { + trailing.push(item) + continue + } + close() + rows.push({ kind: "item", item }) + } + close() + return rows +} + +/** Which row an item is drawn in: its own id, or its round's — to find the same place again + * after the view changes. */ +export function rowIdOf(rows: readonly Row[]): Map { + const map = new Map() + for (const r of rows) { + if (r.kind === "item") map.set(r.item.id, r.item.id) + else for (const it of [...r.tools, ...r.thoughts]) map.set(it.id, r.id) + } + return map +} + +export interface RoundSummary { + count: number + /** The tools by name, in the order each first appears. */ + kinds: { name: string; n: number }[] + /** Every finished call's time together; undefined when none was measured (a stored session). */ + ms?: number + running: ToolItem[] + failed: ToolItem[] + denied: ToolItem[] + /** Finished changes, one per call that has a diff: `path`, `+added −removed`. */ + changes: { id: string; path: string; added: number; removed: number }[] +} + +const titleOf = (t: ToolItem) => t.title ?? callTitle(t.args) ?? "" + +export function summarize(round: Pick): RoundSummary { + const kinds: { name: string; n: number }[] = [] + let ms: number | undefined + const changes: RoundSummary["changes"] = [] + for (const t of round.tools) { + const k = kinds.find((x) => x.name === t.name) + if (k) k.n++ + else kinds.push({ name: t.name, n: 1 }) + if (t.ms !== undefined && t.status !== "running") ms = (ms ?? 0) + t.ms + if (t.diff && t.status === "done") { + const stat = diffCounts(t.diff) + changes.push({ id: t.id, path: titleOf(t) || t.name, added: stat.added, removed: stat.removed }) + } + } + return { + count: round.tools.length, + kinds, + ...(ms !== undefined ? { ms } : {}), + running: round.tools.filter((t) => t.status === "running"), + failed: round.tools.filter((t) => t.status === "error"), + denied: round.tools.filter((t) => t.status === "denied"), + changes, + } +} + +/** What is said beside the round's line in its own colour: `2 failed`, `1 denied`. */ +export function roundTrouble(s: RoundSummary): { failed: string; denied: string } { + return { failed: s.failed.length ? `${s.failed.length} failed` : "", denied: s.denied.length ? `${s.denied.length} denied` : "" } +} + +/** The round's one line, without its mark: `7 tools · read ×3 · bash ×2 · edit ×2 · 14.0s`. + * Failures and refusals are not in it: they are said beside it (`roundTrouble`), and each gets a + * line of its own under it — never only a number. `width`: the columns the line may take; the + * count and the time always stay, and of the kinds as many as fit, then `…`. */ +export function roundLine(s: RoundSummary, width = Infinity): string { + const sep = " · " + const count = `${s.count} tool${s.count === 1 ? "" : "s"}` + // The same writing as a single call's time (display.md §2): durations are not locale numbers. + const took = s.ms !== undefined && !s.running.length ? duration(s.ms) : "" + const kinds = s.kinds.map((k) => (k.n > 1 ? `${k.name} ×${k.n}` : k.name)) + const line = (shown: string[], more: boolean) => [count, ...shown, ...(more ? ["…"] : []), took].filter(Boolean).join(sep) + for (let n = kinds.length; n > 0; n--) { + const text = line(kinds.slice(0, n), n < kinds.length) + if (Bun.stringWidth(text) <= width) return text + } + return line([], kinds.length > 0 && Bun.stringWidth(line([], true)) <= width) +} + +/** What a call adds after its title in one line: its facts, a failure's or refusal's first line, + * how long it took (never for a call that is running or was denied). */ +export function callAfter(t: ToolItem): string { + if (t.status === "running") return "…" + const state = t.status === "error" ? "failed" : t.status + return [...(t.facts ?? []), ...(t.note ? [t.note] : []), ...[callDuration(state, t.ms)].filter((x): x is string => !!x)].join(" · ") +} + +/** A multi-file patch (/diff) as stat lines, one per file. */ +export function patchStats(patch: string): { path: string; added: number; removed: number }[] { + return patch + .split(/^(?=diff --git )/m) + .filter((f) => f.startsWith("diff --git")) + .map((f) => ({ path: /^diff --git a\/(.+?) b\//.exec(f)?.[1] ?? "?", ...diffCounts(f) })) +} diff --git a/tests/displays.test.ts b/tests/displays.test.ts index d942c06..f1e4e76 100644 --- a/tests/displays.test.ts +++ b/tests/displays.test.ts @@ -6,6 +6,10 @@ import { extractBash, extractChanges, extractFiles, + extractImages, + fitImage, + freshImage, + imageProtocol, initialNav, resetFollow, resolveIndex, @@ -118,3 +122,77 @@ test("DisplayNav auto-jumps to changes on proposed diff, respects pinning, and r expect(nav.pinned).toBe(false) expect(effectiveTab(nav, true)).toBe("changes") }) + +test("the session's pictures: finished view_image and show calls, and what was attached — in order, by path", () => { + const abs = (p: string) => (p.startsWith("/") ? p : `/work/${p}`) + const items: Item[] = [ + { kind: "user", id: "u1", text: "look", images: ["/work/in/a.png"] }, + { kind: "tool", id: "t1", name: "view_image", args: { path: "shots/one.PNG" }, status: "done" }, + // Not pictures: a failed view, one refused, one still running, a shown text file, a read. + { kind: "tool", id: "t2", name: "view_image", args: { path: "gone.png" }, status: "error" }, + { kind: "tool", id: "t3", name: "view_image", args: { path: "secret.png" }, status: "denied" }, + { kind: "tool", id: "t4", name: "view_image", args: { path: "later.png" }, status: "running" }, + { kind: "tool", id: "t5", name: "show", args: { path: "notes.md" }, status: "done", output: "Shown to the user: notes.md." }, + { kind: "tool", id: "t6", name: "read", args: { path: "pic.png" }, status: "done" }, + { kind: "tool", id: "t7", name: "show", args: { path: "chart.webp" }, status: "done" }, + ] + expect(extractImages(items, abs)).toEqual([ + { id: "u1.0", title: "/work/in/a.png", path: "/work/in/a.png", source: "attached" }, + { id: "t1", title: "shots/one.PNG", path: "/work/shots/one.PNG", source: "viewed" }, + { id: "t7", title: "chart.webp", path: "/work/chart.webp", source: "shown" }, + ]) + // A shown picture is in images, not in files; a shown text file is in files, and says so. + const files = extractFiles(items) + expect(files.map((f) => f.title)).toEqual(["notes.md", "pic.png"]) + expect(files[0]!.subtitle).toContain("shown") +}) + +test("the pane goes to a picture by itself only while it is the newest thing a tool did, and never over a pinned tab", () => { + const view = (id: string): Item => ({ kind: "tool", id, name: "view_image", args: { path: "a.png" }, status: "done" }) + const bash: Item = { kind: "tool", id: "b", name: "bash", args: { command: "ls" }, status: "done" } + expect(freshImage([view("1")])).toBe(true) + expect(freshImage([view("1"), { kind: "assistant", id: "a", text: "A cat.", streaming: false }])).toBe(true) + // The agent went on to something else; a new prompt; a view still running. + expect(freshImage([view("1"), bash])).toBe(false) + expect(freshImage([view("1"), { kind: "user", id: "u", text: "next" }])).toBe(false) + expect(freshImage([{ ...view("1"), status: "running" } as Item])).toBe(false) + // What the person attached does not move the pane. + expect(freshImage([{ kind: "user", id: "u", text: "see", images: ["/a.png"] }])).toBe(false) + + const nav = initialNav() + expect(effectiveTab(nav, false, true)).toBe("images") + // A change waiting for an answer comes first. + expect(effectiveTab(nav, true, true)).toBe("changes") + expect(effectiveTab({ ...nav, tab: "bash", pinned: true }, true, true)).toBe("bash") + expect(effectiveTab(nav, false, false)).toBe("live") + // The images tab is one of the tabs: alt+↑ from live reaches it, alt+←→ walks it. + expect(cycleTab(nav, -1).tab).toBe("images") + expect(resolveIndex(nav, "images", 3)).toBe(2) + expect(stepEntry(nav, "images", -1, 3).index.images).toBe(1) + expect(resetFollow(stepEntry(nav, "images", -1, 3)).index.images).toBe(-1) +}) + +test("images: auto leaves the protocol to what the terminal is found to do, on asks for kitty graphics, off draws nothing", () => { + expect(imageProtocol(undefined)).toBe("auto") + expect(imageProtocol("auto")).toBe("auto") + expect(imageProtocol("on")).toBe("kitty") + expect(imageProtocol("off")).toBeUndefined() +}) + +test("a picture's box keeps its aspect inside the cells it is given", () => { + // Cells twice as tall as wide: 64×32 px is four cells wide for each row. + expect(fitImage({ width: 64, height: 32 }, 48, 26)).toEqual({ width: 48, height: 12 }) + expect(fitImage({ width: 100, height: 400 }, 48, 20)).toEqual({ width: 10, height: 20 }) + // The terminal's own cell size, where it says one (10×22 px cells). + expect(fitImage({ width: 800, height: 600 }, 40, 30, 2.2)).toEqual({ width: 40, height: 14 }) + for (const px of [{ width: 1, height: 5000 }, { width: 5000, height: 1 }, { width: 640, height: 480 }]) + for (let w = 1; w <= 90; w += 7) + for (let h = 1; h <= 60; h += 5) { + const box = fitImage(px, w, h) + expect(box.width).toBeGreaterThanOrEqual(1) + expect(box.width).toBeLessThanOrEqual(w) + expect(box.height).toBeGreaterThanOrEqual(1) + expect(box.height).toBeLessThanOrEqual(h) + } + expect(fitImage({ width: 0, height: 10 }, 10, 10)).toEqual({ width: 0, height: 0 }) +}) diff --git a/tests/layout.test.ts b/tests/layout.test.ts new file mode 100644 index 0000000..f471ee7 --- /dev/null +++ b/tests/layout.test.ts @@ -0,0 +1,87 @@ +// Where the display stands and what its rows hold, by the width alone (src/tui/layout.ts). +import { expect, test } from "bun:test" +import { clipEnd, firstFit, LEFT_MIN_WIDTH, PANE_MAX_WIDTH, PANE_MIN_WIDTH, paneHints, placeDisplay, rowWidth, SIDE_MIN_WIDTH, tabAt, tabCells, transcriptMode, type TabSpec } from "../src/tui/layout.ts" + +test("the display stands beside the conversation from 80 columns, each column within its floor", () => { + for (let width = SIDE_MIN_WIDTH; width <= 400; width++) { + const p = placeDisplay({ width, enabled: true, zoomed: false }) + expect(p.mode).toBe("side") + // The two columns are the terminal, exactly. + expect(p.left + p.pane).toBe(width) + expect(p.pane).toBeGreaterThanOrEqual(PANE_MIN_WIDTH) + expect(p.pane).toBeLessThanOrEqual(PANE_MAX_WIDTH) + expect(p.left).toBeGreaterThanOrEqual(LEFT_MIN_WIDTH) + } + expect(placeDisplay({ width: 80, enabled: true, zoomed: false })).toEqual({ mode: "side", left: 45, pane: 35 }) + expect(placeDisplay({ width: 120, enabled: true, zoomed: false })).toEqual({ mode: "side", left: 68, pane: 52 }) + expect(placeDisplay({ width: 300, enabled: true, zoomed: false }).pane).toBe(PANE_MAX_WIDTH) + // Being zoomed means nothing where there is room for both. + expect(placeDisplay({ width: 120, enabled: true, zoomed: true }).mode).toBe("side") +}) + +test("too narrow for two columns: the display is tucked away or stands in the transcript's place — never silently nothing", () => { + for (let width = 1; width < SIDE_MIN_WIDTH; width++) { + expect(placeDisplay({ width, enabled: true, zoomed: false })).toEqual({ mode: "tucked", left: width, pane: 0 }) + expect(placeDisplay({ width, enabled: true, zoomed: true })).toEqual({ mode: "zoom", left: width, pane: width }) + } + expect(placeDisplay({ width: 60, enabled: false, zoomed: true })).toEqual({ mode: "off", left: 60, pane: 0 }) + expect(placeDisplay({ width: 200, enabled: false, zoomed: false })).toEqual({ mode: "off", left: 200, pane: 0 }) +}) + +test("transcript: auto is compact only while the display stands beside it; a choice holds everywhere", () => { + expect(transcriptMode(undefined, "side")).toBe("compact") + expect(transcriptMode("auto", "side")).toBe("compact") + for (const mode of ["off", "tucked", "zoom"] as const) expect(transcriptMode("auto", mode)).toBe("full") + for (const mode of ["off", "tucked", "zoom", "side"] as const) { + expect(transcriptMode("full", mode)).toBe("full") + expect(transcriptMode("compact", mode)).toBe("compact") + } +}) + +const TABS: TabSpec[] = [ + { id: "live", names: ["Live", "Live", "L"], mark: "◉" }, + { id: "files", names: ["Files", "Files", "F"], count: 12 }, + { id: "changes", names: ["Changes", "Chg", "C"], count: 3, mark: "●" }, + { id: "bash", names: ["Bash", "Bash", "B"], count: 140 }, + { id: "images", names: ["Images", "Img", "I"] }, +] + +test("the tab bar takes the longest labels that fit and never runs past its row", () => { + expect(tabCells(80, TABS).map((c) => c.text)).toEqual([" Live ◉ ", " Files (12) ", " Changes (3) ● ", " Bash (99+) ", " Images "]) + expect(tabCells(48, TABS).map((c) => c.text)).toEqual([" Live ◉ ", " Files 12 ", " Chg 3 ● ", " Bash 99+ ", " Img "]) + // The narrowest pane (29 columns inside): letters, with their counts and marks. + expect(tabCells(29, TABS).map((c) => c.text)).toEqual([" L◉ ", " F12 ", " C3● ", " B99+ ", " I "]) + expect(tabCells(24, TABS).map((c) => c.text)).toEqual([" L ", " F ", " C ", " B ", " I "]) + for (let width = 1; width <= 120; width++) { + const cells = tabCells(width, TABS) + expect(rowWidth(cells)).toBeLessThanOrEqual(width) + // From the narrowest pane there is, every tab is there. + if (width >= PANE_MIN_WIDTH - 3) expect(cells.length).toBe(TABS.length) + for (const c of cells) expect(c.width).toBe(Bun.stringWidth(c.text)) + } +}) + +test("a click finds the tab under it, and the gap between two tabs is no tab", () => { + const cells = tabCells(80, TABS) + expect(tabAt(cells, 0)).toBe("live") + expect(tabAt(cells, cells[0]!.width - 1)).toBe("live") + expect(tabAt(cells, cells[0]!.width)).toBeUndefined() + expect(tabAt(cells, cells[0]!.width + 1)).toBe("files") + expect(tabAt(cells, rowWidth(cells) - 1)).toBe("images") + expect(tabAt(cells, rowWidth(cells))).toBeUndefined() +}) + +test("the key line and a clipped sentence fit the columns they are given", () => { + for (let width = 0; width <= 100; width++) { + expect(Bun.stringWidth(paneHints(width))).toBeLessThanOrEqual(width) + expect(Bun.stringWidth(paneHints(width, true))).toBeLessThanOrEqual(width) + expect(Bun.stringWidth(clipEnd("Waiting for approval: bash — 日本語 too", width))).toBeLessThanOrEqual(width) + } + // The narrowest pane still says how to leave it. + expect(paneHints(PANE_MIN_WIDTH - 3)).toContain("d hide") + expect(paneHints(60, true)).toContain("alt+d transcript") + expect(clipEnd("short", 10)).toBe("short") + expect(clipEnd("a sentence that is too long", 12)).toBe("a sentence…") + expect(firstFit(20, ["a rather long form of it", "a short form", "x"])).toBe("a short form") + expect(firstFit(0, ["long", "x"])).toBe("x") +}) diff --git a/tests/png.ts b/tests/png.ts new file mode 100644 index 0000000..e554b64 --- /dev/null +++ b/tests/png.ts @@ -0,0 +1,41 @@ +// A PNG made in the test: no picture is kept in the repository. +import { deflateSync } from "node:zlib" + +const CRC = (() => { + const t = new Uint32Array(256) + for (let n = 0; n < 256; n++) { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + t[n] = c >>> 0 + } + return t +})() +function crc32(b: Uint8Array): number { + let c = 0xffffffff + for (const x of b) c = CRC[(c ^ x) & 0xff]! ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 +} +function chunk(type: string, data: Uint8Array): Uint8Array { + const out = new Uint8Array(12 + data.length) + const v = new DataView(out.buffer) + v.setUint32(0, data.length) + out.set(Buffer.from(type, "ascii"), 4) + out.set(data, 8) + v.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length))) + return out +} + +/** An RGB PNG of `width` × `height`; `at` gives each pixel's colour. */ +export function png(width: number, height: number, at: (x: number, y: number) => [number, number, number] = (x, y) => [(x * 255) / width, (y * 255) / height, 128]): Uint8Array { + const raw = new Uint8Array(height * (1 + width * 3)) + for (let y = 0; y < height; y++) { + const row = y * (1 + width * 3) + for (let x = 0; x < width; x++) raw.set(at(x, y).map((n) => Math.max(0, Math.min(255, Math.round(n)))), row + 1 + x * 3) + } + const head = new Uint8Array(13) + const v = new DataView(head.buffer) + v.setUint32(0, width) + v.setUint32(4, height) + head.set([8, 2, 0, 0, 0], 8) + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", head), chunk("IDAT", new Uint8Array(deflateSync(raw))), chunk("IEND", new Uint8Array(0))]) +} diff --git a/tests/transcript.test.ts b/tests/transcript.test.ts new file mode 100644 index 0000000..192123f --- /dev/null +++ b/tests/transcript.test.ts @@ -0,0 +1,85 @@ +// The compact transcript's grouping (src/tui/transcript.ts): a pure view over the items. +import { expect, test } from "bun:test" +import type { Item } from "../src/tui/state.ts" +import { groupRounds, patchStats, roundLine, roundTrouble, rowIdOf, summarize, type Round } from "../src/tui/transcript.ts" + +const tool = (id: string, name: string, o: Partial> = {}): Item => ({ kind: "tool", id, name, args: {}, status: "done", ...o }) +const text = (id: string): Item => ({ kind: "assistant", id, text: "words", streaming: false }) +const thought = (id: string, streaming = false): Item => ({ kind: "reasoning", id, text: "hm", streaming, started: 0, ms: 100 }) +const shape = (items: Item[], o?: { showReasoning?: boolean }) => groupRounds(items, o).map((r) => (r.kind === "round" ? `[${r.tools.map((t) => t.id).join(",")}${r.thoughts.length ? `|${r.thoughts.map((t) => t.id).join(",")}` : ""}]` : r.item.id)) + +test("the calls between two pieces of text are one round; text, a prompt, a notice end it", () => { + const items: Item[] = [{ kind: "user", id: "u1", text: "go" }, text("a1"), tool("t1", "read"), tool("t2", "read"), tool("t3", "bash"), text("a2"), tool("t4", "edit"), { kind: "notice", id: "n1", text: "x", level: "info" }, tool("t5", "bash"), text("a3")] + expect(shape(items)).toEqual(["u1", "a1", "[t1,t2,t3]", "a2", "[t4]", "n1", "[t5]", "a3"]) + // The items are not changed, and grouping twice gives the same rows. + const before = JSON.stringify(items) + expect(shape(items)).toEqual(shape(items)) + expect(JSON.stringify(items)).toBe(before) +}) + +test("a finished thought between two calls is folded into the round; one before it, after it, or still streaming is a row", () => { + expect(shape([thought("r0"), tool("t1", "read"), thought("r1"), tool("t2", "bash"), thought("r2"), text("a1")])).toEqual(["r0", "[t1,t2|r1]", "r2", "a1"]) + // Thinking now: the round ends where the thought begins, and the thought shows. + expect(shape([tool("t1", "read"), thought("r1", true)])).toEqual(["[t1]", "r1"]) + // Opened with ctrl+r, every thought is a row of its own. + expect(shape([tool("t1", "read"), thought("r1"), tool("t2", "bash")], { showReasoning: true })).toEqual(["[t1]", "r1", "[t2]"]) +}) + +test("a call the transcript does not draw is no row and ends no round", () => { + expect(shape([tool("t1", "read"), tool("p1", "plan_update"), tool("t2", "bash")])).toEqual(["[t1,t2]"]) + expect(shape([tool("p1", "plan_write")])).toEqual([]) +}) + +test("every item is found again in its row: itself, or its round", () => { + const rows = groupRounds([text("a1"), tool("t1", "read"), thought("r1"), tool("t2", "bash"), text("a2")]) + const map = rowIdOf(rows) + expect([...map]).toEqual([["a1", "a1"], ["t1", "t1"], ["t2", "t1"], ["r1", "t1"], ["a2", "a2"]]) +}) + +const round = (tools: Item[]): Pick => ({ tools: tools as Round["tools"] }) +const DIFF = "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1,1 +1,2 @@\n-old\n+new\n+more\n" + +test("a round's line: the count, the kinds in order with ×n, the time together", () => { + const s = summarize(round([tool("1", "read", { ms: 400 }), tool("2", "bash", { ms: 9000 }), tool("3", "read", { ms: 100 }), tool("4", "edit", { ms: 2500, diff: DIFF, title: "src/a.ts" }), tool("5", "read", { ms: 0 }), tool("6", "bash", { ms: 1000 }), tool("7", "edit", { ms: 1000, diff: DIFF, title: "src/b.ts" })])) + expect(roundLine(s)).toBe("7 tools · read ×3 · bash ×2 · edit ×2 · 14.0s") + expect(s.changes).toEqual([ + { id: "4", path: "src/a.ts", added: 2, removed: 1 }, + { id: "7", path: "src/b.ts", added: 2, removed: 1 }, + ]) + expect(roundTrouble(s)).toEqual({ failed: "", denied: "" }) + expect(roundLine(summarize(round([tool("1", "bash", { ms: 61_000 })])))).toBe("1 tool · bash · 1m 01s") + // A stored session kept no durations: none is made up. + expect(roundLine(summarize(round([tool("1", "read"), tool("2", "read")])))).toBe("2 tools · read ×2") +}) + +test("a failure and a refusal are never inside a number only: each is counted beside the line and listed", () => { + const s = summarize(round([tool("1", "read", { ms: 10 }), tool("2", "bash", { status: "error", ms: 20, note: "exit 3" }), tool("3", "bash", { status: "denied", note: "denied by a rule" }), tool("4", "edit", { status: "error", ms: 5, diff: DIFF })])) + expect(roundTrouble(s)).toEqual({ failed: "2 failed", denied: "1 denied" }) + expect(s.failed.map((t) => t.id)).toEqual(["2", "4"]) + expect(s.denied.map((t) => t.id)).toEqual(["3"]) + // A change that failed is not a change. + expect(s.changes).toEqual([]) +}) + +test("a running call stays in sight, and the round has no total until it ends", () => { + const s = summarize(round([tool("1", "read", { ms: 10 }), tool("2", "bash", { status: "running" })])) + expect(s.running.map((t) => t.id)).toEqual(["2"]) + expect(roundLine(s)).toBe("2 tools · read · bash") +}) + +test("the line fits the columns it is given: the count and the time stay, the kinds give way", () => { + const s = summarize(round([tool("1", "read", { ms: 400 }), tool("2", "bash", { ms: 9000 }), tool("3", "grep", { ms: 100 }), tool("4", "edit", { ms: 2500 }), tool("5", "web_fetch", { ms: 2000 })])) + expect(roundLine(s, 80)).toBe("5 tools · read · bash · grep · edit · web_fetch · 14.0s") + expect(roundLine(s, 40)).toBe("5 tools · read · bash · grep · … · 14.0s") + expect(roundLine(s, 20)).toBe("5 tools · … · 14.0s") + expect(roundLine(s, 16)).toBe("5 tools · 14.0s") + for (let width = 16; width <= 80; width++) expect(Bun.stringWidth(roundLine(s, width))).toBeLessThanOrEqual(width) +}) + +test("a multi-file patch as stat lines", () => { + const patch = `diff --git a/a.txt b/a.txt\n--- a/a.txt\n+++ b/a.txt\n@@ -1,1 +1,2 @@\n-x\n+y\n+z\ndiff --git a/d/b.txt b/d/b.txt\n--- a/d/b.txt\n+++ b/d/b.txt\n@@ -1,2 +1,1 @@\n-one\n-two\n+one\n` + expect(patchStats(patch)).toEqual([ + { path: "a.txt", added: 2, removed: 1 }, + { path: "d/b.txt", added: 1, removed: 2 }, + ]) +}) diff --git a/tests/tui/displays.test.tsx b/tests/tui/displays.test.tsx index d209721..3635369 100644 --- a/tests/tui/displays.test.tsx +++ b/tests/tui/displays.test.tsx @@ -1,37 +1,310 @@ +// The display pane in the real Root: where it stands at each width, its tabs, the compact +// transcript beside it, pictures. import { afterEach, expect, test } from "bun:test" -import { delta, toolCall } from "../fake-provider.ts" +import { writeFileSync } from "node:fs" +import { join } from "node:path" +import { delta, toolCall, usage } from "../fake-provider.ts" +import { png } from "../png.ts" import { tui } from "./harness.tsx" let t: Awaited> | undefined afterEach(() => t?.stop()) -test("side display shows live activity, files, changes, and toggles with /display", async () => { - t = await tui( - [ - { chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "hello.txt" }))] }, - { chunks: [delta({ content: "Read hello.txt." }, "stop")] }, - ], - { width: 120, height: 35 }, - "displays: true\n", - ) - expect(t.frame()).toContain("Live") - expect(t.frame()).toContain("Files") - expect(t.frame()).toContain("Changes") - expect(t.frame()).toContain("Bash") +const lines = () => t!.frame().split("\n") +/** Whether every row of the terminal has the pane's border in column `x`. */ +const borderOnEveryRow = (x: number) => lines().slice(0, -1).every((row) => row[x] === "│") +/** A round of five calls: one refused by a rule, one edit that fails, one command that exits 3. */ +const ROUND = [ + { + chunks: [ + delta({ content: "Let me look." }), + toolCall(0, "c1", "grep", '{"pattern":"hello","path":"."}'), + toolCall(1, "c2", "read", '{"path":"hello.txt"}'), + toolCall(2, "c3", "bash", '{"command":"exit 3","description":"Fail on purpose"}'), + toolCall(3, "c4", "bash", '{"command":"git push origin main","description":"Push"}'), + toolCall(4, "c5", "edit", '{"path":"hello.txt","old":"hello world","new":"hello there\\nworld"}'), + usage(9000, 50), + ], + }, + { chunks: [delta({ content: "All done." }), usage(12000, 5)] }, +] +const AUTO = "displays: true\nmode: auto\npermission:\n bash:\n 'git push *': deny\n" + +test("the pane stands at the right over the terminal's full height — beside the prompt and the status bar", async () => { + t = await tui([{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "hello.txt" }))] }, { chunks: [delta({ content: "Read hello.txt." }, "stop")] }], { width: 120, height: 35 }, "displays: true\n") await t.input.typeText("read hello.txt") t.input.pressEnter() expect(await t.until("Read hello.txt.")).toBe(true) + const rows = lines() + // One border column on every row of the terminal: the pane cuts the prompt and the status bar. + const at = 68 + expect(rows.length - 1).toBe(35) + expect(borderOnEveryRow(at)).toBe(true) + // The session header at the top, the key line on the last row — beside the status bar. + expect(rows[0]!.slice(at)).toContain("fake/coder · manual · low") + expect(rows[34]!.slice(0, at)).toContain("manual · fake/coder") + expect(rows[34]!.slice(at)).toContain("alt+d hide") + expect(rows[33]!.slice(0, at)).toContain("Ask · / commands") expect(t.frame()).toContain("Files (1)") - // Switch to Files tab via /display files + // A tab by name: the file's text. await t.input.typeText("/display files") t.input.pressEnter() - expect(await t.until("hello world")).toBe(true) + expect(await t.until("1: hello world")).toBe(true) + expect(t.frame()).toContain("1/1") - // Hide side display via /display off + // Off: the conversation has the whole width again. await t.input.typeText("/display off") t.input.pressEnter() - expect(await t.until("side display hidden")).toBe(true) - expect(t.frame()).not.toContain("Alt+↑↓ tabs") + expect(await t.until("display off")).toBe(true) + expect(borderOnEveryRow(at)).toBe(false) + expect(lines()[34]).toContain("lembas-tui-") +}) + +test("at 80 columns the pane is still beside the conversation, and each column holds its rows", async () => { + t = await tui(ROUND, { width: 80, height: 24 }, AUTO) + await t.input.typeText("do things") + t.input.pressEnter() + expect(await t.until("All done.")).toBe(true) + await t.settle(200) + const rows = lines() + expect(borderOnEveryRow(45)).toBe(true) + // The tab bar in its narrow form, every tab there; the short status bar keeps mode, model, context. + expect(rows.some((r) => / L +F1 +C1 +B2 +I /.test(r.slice(45)))).toBe(true) + expect(rows[23]!.slice(0, 45)).toMatch(/AUTO · fake\/coder · low +ctx 37% $/) + expect(rows[23]!.slice(45)).toContain("d hide") + // The prompt box is one row: nothing of it wrapped in the narrow column. + expect(rows[22]!.slice(0, 45)).toContain("❯ Ask") + expect(rows[21]!.slice(0, 45)).toMatch(/^─+$/) +}) + +test("too narrow for two columns: the status bar says there is a display, alt+d opens it in the transcript's place and brings the transcript back", async () => { + t = await tui(ROUND, { width: 70, height: 24 }, AUTO) + await t.input.typeText("do things") + t.input.pressEnter() + expect(await t.until("All done.")).toBe(true) + // Not beside it — and not silently nothing: the status bar names the key. + expect(t.frame()).not.toContain("Recent activity") + expect(lines()[23]).toContain("alt+d display") + // The full transcript: there is no display beside it. + expect(t.frame()).toMatch(/bash +exit 3 · exit 3/) + + t.input.pressKey("d", { meta: true }) + expect(await t.until("Recent activity")).toBe(true) + await t.settle(200) + let rows = lines() + // The display where the transcript was; the prompt and the status bar stay. + expect(t.frame()).not.toContain("Let me look.") + expect(rows[0]).toContain("fake/coder · auto · low") + expect(rows.some((r) => r.includes("alt+d transcript"))).toBe(true) + expect(rows[22]).toContain("❯ Ask") + expect(rows[23]).toContain("AUTO · fake/coder") + + t.input.pressKey("d", { meta: true }) + expect(await t.until("Let me look.")).toBe(true) + expect(t.frame()).not.toContain("Recent activity") + // Once the word that said so has gone, the status bar names the key again. + expect(await t.until("alt+d display")).toBe(true) + + // /display off: no display, and nothing says there is one. + await t.input.typeText("/display off") + t.input.pressEnter() + expect(await t.until("display off")).toBe(true) + await t.settle(300) + expect(lines()[23]).not.toContain("alt+d display") + expect(lines()[23]).toContain("ctx 37%") +}) + +test("beside the display the transcript is compact: a round is one line, failures and refusals are never hidden; alt+t and /transcript switch, ctrl+o opens", async () => { + t = await tui(ROUND, { width: 120, height: 36 }, AUTO) + await t.input.typeText("do things") + t.input.pressEnter() + expect(await t.until("All done.")).toBe(true) + await t.settle(200) + const left = () => lines().map((r) => r.slice(0, 68)).join("\n") + // One line for the round: count, kinds, time — the failures and the refusal counted beside it… + expect(left()).toMatch(/▸ 5 tools · bash ×2 · grep · .*\d+\.\ds · 1 failed · 1 denied/) + // …and each said in a line of its own; the change that went through as its stat. + expect(left()).toMatch(/✗ bash exit 3 · exit 3 · \d+\.\ds/) + expect(left()).toMatch(/⊘ bash git push origin main · Denied/) + expect(left()).toMatch(/ hello\.txt \+2 −1/) + expect(left()).not.toContain("hello there") + // No call that went well has a line of its own. + expect(left()).not.toMatch(/grep +hello · 1 hit/) + + // alt+t: the full transcript, every call on its line. + t.input.pressKey("t", { meta: true }) + expect(await t.until("transcript: full")).toBe(true) + await t.settle(200) + expect(left()).toMatch(/grep +hello · 1 hit · \d+\.\ds/) + expect(left()).toMatch(/bash +exit 3 · exit 3 · \d+\.\ds ✗/) + expect(left()).not.toContain("5 tools") + + // /transcript auto: compact again, since the display is beside it. + await t.input.typeText("/transcript auto") + t.input.pressEnter() + expect(await t.until("transcript: auto — compact now")).toBe(true) + await t.settle(200) + expect(left()).toContain("▸ 5 tools") + + // ctrl+o opens the round into its calls. + t.input.pressKey("o", { ctrl: true }) + await t.settle(200) + expect(left()).toContain("▸ 5 tools") + expect(left()).toMatch(/grep +hello · 1 hit · \d+\.\ds/) + t.input.pressKey("o", { ctrl: true }) + await t.settle(200) + + // The display hidden: auto is the full transcript. + t.input.pressKey("d", { meta: true }) + await t.settle(300) + expect(t.frame()).not.toContain("5 tools") + expect(t.frame()).toMatch(/grep +hello · 1 hit · \d+\.\ds/) + // Nothing ran again for any of it. + expect(t.fake.requests.length).toBe(2) +}) + +test("a single call is its own line in the compact transcript, a change as its stat — the diff is in the display", async () => { + t = await tui( + [ + { chunks: [toolCall(0, "r1", "read", '{"path":"hello.txt"}')] }, + { chunks: [delta({ content: "Now the change." }), toolCall(0, "e1", "edit", '{"path":"hello.txt","old":"hello world","new":"hello there\\nworld"}')] }, + { chunks: [delta({ content: "Changed it." })] }, + ], + { width: 120, height: 36 }, + "displays: true\nmode: auto\n", + ) + await t.input.typeText("change it") + t.input.pressEnter() + expect(await t.until("Changed it.")).toBe(true) + await t.settle(200) + const left = lines().map((r) => r.slice(0, 68)).join("\n") + expect(left).toMatch(/edit +hello\.txt · \+2 −1 · \d+\.\ds/) + // Not inline… + expect(left).not.toContain("hello there") + // …but in the display: the change, counted, as a diff. + await t.input.typeText("/display changes") + t.input.pressEnter() + expect(await t.until("hello there")).toBe(true) + const right = lines().map((r) => r.slice(68)).join("\n") + expect(right).toContain("1/1") + expect(right).toContain("hello there") +}) + +test("switching the transcript keeps the place: the bottom stays the bottom, a row scrolled to stays in sight", async () => { + const script = Array.from({ length: 12 }, (_, i) => [ + { chunks: [delta({ content: `Looking at part ${i}.` }), toolCall(0, `a${i}`, "read", '{"path":"hello.txt"}'), toolCall(1, `b${i}`, "grep", '{"pattern":"hello","path":"."}')] }, + { chunks: [delta({ content: `Part ${i} is fine.` })] }, + ]).flat() + t = await tui(script, { width: 120, height: 30 }, "displays: true\nmode: auto\n") + for (let i = 0; i < 12; i++) { + await t.input.typeText(`part ${i}`) + t.input.pressEnter() + expect(await t.until(`Part ${i} is fine.`)).toBe(true) + } + const left = () => lines().map((r) => r.slice(0, 68)).join("\n") + // At the bottom: the newest reply stays in sight both ways. + t.input.pressKey("t", { meta: true }) + await t.settle(700) + expect(left()).toContain("Part 11 is fine.") + t.input.pressKey("t", { meta: true }) + await t.settle(700) + expect(left()).toContain("Part 11 is fine.") + // Scrolled up: what is at the top stays in sight when the rows change under it. + for (let i = 0; i < 6; i++) t.input.pressKey("\x1b[5~") + await t.settle(300) + const top = /Looking at part (\d+)\./.exec(left())?.[1] + expect(top).toBeDefined() + expect(left()).not.toContain("Part 11 is fine.") + t.input.pressKey("t", { meta: true }) + await t.settle(700) + expect(left()).toContain(`Looking at part ${top}.`) + expect(left()).not.toContain("Part 11 is fine.") + t.input.pressKey("t", { meta: true }) + await t.settle(700) + expect(left()).toContain(`Looking at part ${top}.`) +}, 60_000) + +test("the mouse: a click on a tab opens it, the wheel over the pane scrolls the pane", async () => { + t = await tui([{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "long.txt" }))] }, { chunks: [delta({ content: "Read it." }, "stop")] }], { width: 120, height: 30 }, "displays: true\nmode: auto\n") + writeFileSync(join(t.cwd, "long.txt"), Array.from({ length: 200 }, (_, i) => `line number ${i + 1}`).join("\n") + "\n") + await t.input.typeText("read long.txt") + t.input.pressEnter() + expect(await t.until("Read it.")).toBe(true) + const rows = lines() + const y = rows.findIndex((r) => r.includes("Files (1)")) + const x = rows[y]!.indexOf("Files (1)") + await t.setup.mockMouse.click(x + 1, y) + expect(await t.until("1: line number 1")).toBe(true) + expect(t.frame()).not.toContain("line number 40") + // The wheel over the pane moves the pane, not the conversation. + for (let i = 0; i < 12; i++) await t.setup.mockMouse.scroll(90, 15, "down") + await t.settle(300) + expect(t.frame()).not.toContain("1: line number 1\n") + expect(lines().some((r) => /\d+: line number \d+/.test(r.slice(68)) && !/ [1-9]: line/.test(r.slice(68)))).toBe(true) + expect(lines().map((r) => r.slice(0, 68)).join("\n")).toContain("Read it.") + // A click on Live goes back. + const y2 = lines().findIndex((r) => r.slice(68).includes(" Live ")) + await t.setup.mockMouse.click(lines()[y2]!.indexOf(" Live ", 68) + 2, y2) + expect(await t.until("Recent activity")).toBe(true) +}) + +test("pictures: what view_image views opens in the images tab by itself and is drawn; one that was attached is listed; images: off draws none", async () => { + t = await tui( + [ + { chunks: [toolCall(0, "v1", "view_image", '{"path":"shot.png"}')] }, + { chunks: [delta({ content: "A gradient." })] }, + { chunks: [delta({ content: "Seen both." })] }, + ], + { width: 120, height: 36 }, + "displays: true\nmode: auto\n", + { vision: true }, + ) + writeFileSync(join(t.cwd, "shot.png"), png(64, 32)) + writeFileSync(join(t.cwd, "other.png"), png(20, 20, () => [200, 40, 40])) + await t.input.typeText("look at shot.png") + t.input.pressEnter() + expect(await t.until("A gradient.")).toBe(true) + await t.settle(400) + const right = () => lines().map((r) => r.slice(68)).join("\n") + // The pane went to the picture by itself: its name, how it got here, its size — and the picture, + // which a terminal without a graphics protocol gets as coloured blocks. + expect(right()).toContain("shot.png · viewed") + expect(right()).toContain("1/1") + expect(right()).toContain("64×32") + expect(right()).toMatch(/[▀▄█▌▐▖▗▘▙▚▛▜▝▞▟]/) + + // A new prompt goes back to Live; a picture attached with @ is the second entry. + await t.input.typeText("@other.png as well") + t.input.pressEnter() + expect(await t.until("Seen both.")).toBe(true) + expect(right()).toContain("Recent activity") + await t.input.typeText("/display images") + t.input.pressEnter() + expect(await t.until("other.png · attached")).toBe(true) + expect(right()).toContain("2/2") + // alt+← is the one before. + t.input.pressArrow("left", { meta: true }) + expect(await t.until("shot.png · viewed")).toBe(true) + expect(right()).toContain("1/2") + + // images: off — the words stay, nothing is drawn. + t.app.settings.set("images", "off") + await t.settle(300) + expect(right()).toContain("shot.png · viewed") + expect(right()).toContain("pictures are off") + expect(right()).not.toMatch(/[▀▄█▌▐▖▗▘▙▚▛▜▝▞▟]/) +}) + +test("a file that is no picture by its bytes is never handed to the terminal", async () => { + t = await tui([{ chunks: [delta({ content: "ok" })] }], { width: 120, height: 30 }, "displays: true\n") + writeFileSync(join(t.cwd, "fake.png"), "\x1b_Ga=d\x1b\\ not a picture\n") + await t.input.typeText("@fake.png is one") + t.input.pressEnter() + expect(await t.until("ok")).toBe(true) + await t.input.typeText("/display images") + t.input.pressEnter() + expect(await t.until("fake.png · attached")).toBe(true) + expect(t.frame()).toContain("not a PNG, JPEG, GIF or WebP by its bytes") }) diff --git a/tests/tui/harness.tsx b/tests/tui/harness.tsx index 85898eb..7587560 100644 --- a/tests/tui/harness.tsx +++ b/tests/tui/harness.tsx @@ -11,12 +11,12 @@ import { DEFAULT_THEME } from "../../src/tui/theme.ts" import { fakeProvider, type Scripted } from "../fake-provider.ts" /** The whole TUI in OpenTUI's test renderer, against a scripted endpoint. */ -export async function tui(script: Scripted[], size = { width: 100, height: 30 }, extraConfig = "", o: { store?: boolean } = {}) { +export async function tui(script: Scripted[], size = { width: 100, height: 30 }, extraConfig = "", o: { store?: boolean; vision?: boolean } = {}) { const fake = fakeProvider(script) mkdirSync(paths.config, { recursive: true }) writeFileSync( join(paths.config, "connections.yaml"), - `connections:\n fake:\n type: webui\n url: ${fake.url}\n models:\n fake/coder: { context: 32768, efforts: [low, high], effort: low }\n fake/other: { context: 8192 }\n`, + `connections:\n fake:\n type: webui\n url: ${fake.url}\n models:\n fake/coder: { context: 32768, efforts: [low, high], effort: low${o.vision ? ", vision: true" : ""} }\n fake/other: { context: 8192 }\n`, { mode: 0o600 }, ) const disp = /^\s*displays:/m.test(extraConfig) ? "" : "displays: false\n"