Merge remote-tracking branch 'origin/round/display' into round/merge
# Conflicts: # CHANGELOG.md # src/tui/state.ts
This commit is contained in:
25 files changed
+2091
-545
No files matched your search
@@ -111,6 +111,46 @@ All notable changes to LLeMbas CLI. The format follows
|
||||
file is replaced in one step.
|
||||
- `serve --stdio` gives up a connection whose client sends a line of more than 64 MB without
|
||||
ending it, instead of reading it into memory.
|
||||
- **Pictures in the display, by themselves.** A new **Images** tab shows what the agent views
|
||||
with `view_image`, what `show` shows when it is a picture, and the images you attach or paste
|
||||
(`@shot.png`) — the newest first, `Alt+←/→` through the others. The pane goes to a picture a
|
||||
tool has just viewed without being asked (unless you pinned a tab) and back to Live when the
|
||||
agent moves on. Pictures are drawn with the **kitty graphics protocol** where the terminal is
|
||||
found to support it (kitty, Ghostty — the terminal is asked, nothing is configured), with sixel
|
||||
where that is what it has, and as coloured blocks anywhere else, inside tmux included. Setting
|
||||
`images: auto | on | off` (default `auto`; `on` asks for kitty graphics whatever was detected,
|
||||
`off` shows the name, size and path only).
|
||||
- **Two transcripts: full and compact.** Compact groups a round of tool calls into one line —
|
||||
`▸ 7 tools · read ×3 · bash ×2 · edit ×2 · 14.0s` — with every failure and every refusal still
|
||||
on a line of its own, a running call in sight while it runs, and a change as a stat line
|
||||
(`src/a.ts +12 −3`) instead of its diff: the detail is in the display. Setting
|
||||
`transcript: auto | full | compact`; `auto` (the default) is compact while the display stands
|
||||
beside the conversation and full when it does not. `Alt+T` or `/transcript [auto|full|compact]`
|
||||
switches; `Ctrl+O` opens the rounds. Switching keeps your place and runs nothing again.
|
||||
- **The display has a header and a mouse.** Its first rows say the session's model, mode and
|
||||
effort, how full the context is, the rate, the month's spend and the project. A click on a tab
|
||||
opens it, the wheel over the pane scrolls the pane, and every list tab counts its entries
|
||||
(`3/12`). Files that `show` showed are listed under Files.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The display pane is the full height of the terminal.** It stands at the right from the first
|
||||
row to the last, beside the prompt and the status bar, instead of ending above them.
|
||||
- **The display no longer needs a wide terminal.** It stands beside the conversation from 80
|
||||
columns (it needed 100, and below that showed nothing and said nothing). On a narrower terminal
|
||||
the status bar says `alt+d display`, and `Alt+D` — or `/display` — puts the display in the
|
||||
transcript's place and brings the transcript back; the prompt and the status bar stay.
|
||||
- The status bar has a short form for a narrow column (mode, model, jobs, context); what it
|
||||
leaves out is in the display's header.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The display's tab bar, title line and key line no longer run past a narrow pane or lose their
|
||||
middle: each takes the longest form that fits its row.
|
||||
- The welcome box's key hints and the prompt box's placeholder no longer break in the middle of a
|
||||
phrase in a narrow column; a placeholder that wrapped left the prompt box two rows high.
|
||||
- A word in the status bar that is longer than the bar is cut to it instead of running over the
|
||||
mode and the model.
|
||||
|
||||
## [2.0.0-beta.17] — 2026-11-27
|
||||
|
||||
|
||||
@@ -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": [
|
||||
|
||||
+5
-1
@@ -10,6 +10,9 @@ import { delta, fakeProvider, toolCall, usage } from "../tests/fake-provider.ts"
|
||||
|
||||
export interface Driver {
|
||||
screen(): string[]
|
||||
/** What is in one cell, by column and row — where a row's text cannot say (a wide character
|
||||
* before it shifts every index after it). */
|
||||
cell(x: number, y: number): string
|
||||
/** Rows that are continuations of the row above: something was wider than the terminal. */
|
||||
wrapped(): number[]
|
||||
type(s: string): Promise<void>
|
||||
@@ -42,6 +45,7 @@ export async function drive(opts: { cols: number; rows: number; bin?: string; ho
|
||||
}
|
||||
return {
|
||||
screen,
|
||||
cell: (x, y) => term.buffer.active.getLine(y)?.getCell(x)?.getChars() ?? "",
|
||||
wrapped: () => Array.from({ length: opts.rows }, (_, y) => y).filter((y) => term.buffer.active.getLine(y)?.isWrapped),
|
||||
async type(s) {
|
||||
for (const ch of s) {
|
||||
@@ -93,7 +97,7 @@ if (import.meta.main) {
|
||||
])
|
||||
const d = await drive({ cols, rows, home, cwd, bin: binAt > 0 ? process.argv[binAt + 1] : undefined })
|
||||
const show = (label: string) => console.log(`\n=== ${label}\n` + d.screen().map((l) => l.trimEnd()).join("\n"))
|
||||
await d.waitFor("shift+tab mode · /help")
|
||||
await d.waitFor("shift+tab mode")
|
||||
show("start")
|
||||
await d.type("greet me")
|
||||
await d.key("\r")
|
||||
|
||||
+114
-5
@@ -6,7 +6,9 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { delta, fakeProvider, toolCall, usage } from "../tests/fake-provider.ts"
|
||||
import { drive, fakeHome } from "./drive.ts"
|
||||
import { placeDisplay } from "../src/tui/layout.ts"
|
||||
import { png } from "../tests/png.ts"
|
||||
import { drive, fakeHome, type Driver } from "./drive.ts"
|
||||
|
||||
const bin = resolve(process.argv[2] ?? "dist/lembas")
|
||||
const home = mkdtempSync(join(tmpdir(), "lembas-smoke-"))
|
||||
@@ -21,6 +23,10 @@ const run = (args: string[], cwd = home) => {
|
||||
return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() }
|
||||
}
|
||||
|
||||
/** Whether the display pane's border is in column `x` on every row of the terminal. */
|
||||
const borderOnEveryRow = (d: Driver, x: number, rows: number) => Array.from({ length: rows }, (_, y) => d.cell(x, y)).every((c) => c === "│")
|
||||
const BLOCKS = /[▀▄█▌▐▖▗▘▙▚▛▜▝▞▟]/
|
||||
|
||||
// 1. --version
|
||||
const v = run(["--version"])
|
||||
check("--version", v.code === 0 && /^\d+\.\d+\.\d+/.test(v.out), v.err)
|
||||
@@ -103,7 +109,7 @@ for (const [cols, rows] of [
|
||||
// A fresh directory opens with the first-run question; trust it (the default), then work.
|
||||
const firstRun = await d.waitFor("Trust this directory?")
|
||||
await d.key("\r")
|
||||
const drawn = await d.waitFor("shift+tab mode · /help")
|
||||
const drawn = await d.waitFor("shift+tab mode")
|
||||
await d.type("make a file")
|
||||
await d.key("\r")
|
||||
const asked = await d.waitFor("Allow once")
|
||||
@@ -112,11 +118,21 @@ for (const [cols, rows] of [
|
||||
await Bun.sleep(200)
|
||||
const screen = d.screen()
|
||||
const wrapped = d.wrapped()
|
||||
// The display pane: a column at the right over every row — beside the prompt and the status bar.
|
||||
const place = placeDisplay({ width: cols, enabled: true, zoomed: false })
|
||||
const fullHeight = place.mode === "side" && borderOnEveryRow(d, place.left, rows)
|
||||
const keyLine = Array.from({ length: cols - place.left }, (_, i) => d.cell(place.left + i, rows - 1) || " ").join("")
|
||||
const promptRow = Array.from({ length: place.left }, (_, i) => d.cell(i, rows - 2) || " ").join("")
|
||||
await d.key("\x03")
|
||||
await d.key("\x03")
|
||||
const code = await d.close()
|
||||
f.stop()
|
||||
const file = await Bun.file(join(cwd, "out.txt")).text().catch(() => "")
|
||||
check(
|
||||
`TUI ${cols}x${rows}: the display pane stands beside the conversation, the prompt and the status bar, over the full height`,
|
||||
fullHeight && keyLine.includes("hide") && promptRow.includes("❯") && screen.some((l) => l.includes("Recent activity")),
|
||||
`placement=${JSON.stringify(place)} fullHeight=${fullHeight} keyLine=${JSON.stringify(keyLine)} promptRow=${JSON.stringify(promptRow)}\n${screen.join("\n")}`,
|
||||
)
|
||||
check(
|
||||
`TUI ${cols}x${rows}: first run → prompt → approval → answer → quit`,
|
||||
firstRun && drawn && asked && answered && file === "smoke\n" && code === 0,
|
||||
@@ -126,6 +142,99 @@ for (const [cols, rows] of [
|
||||
check(`TUI ${cols}x${rows}: status bar on the last row`, (screen[rows - 1] ?? "").includes("manual · fake/coder"), screen[rows - 1] ?? "")
|
||||
}
|
||||
|
||||
// 3a. too narrow for two columns (70×24): the display is not silently absent — the status bar
|
||||
// names the key, alt+d puts it in the transcript's place (the prompt and the status bar stay) and
|
||||
// alt+d again brings the transcript back.
|
||||
{
|
||||
const { fake: f, home: h, cwd } = fakeHome([
|
||||
{ chunks: [delta({ content: "Reading it." }), toolCall(0, "c1", "read", '{"path":"hello.txt"}'), usage(900, 40)] },
|
||||
{ chunks: [delta({ content: "It says hello." }), usage(1200, 20)] },
|
||||
])
|
||||
const d = await drive({ cols: 70, rows: 24, bin, home: h, cwd })
|
||||
await d.waitFor("Trust this directory?")
|
||||
await d.key("\r")
|
||||
await d.waitFor("shift+tab mode")
|
||||
await d.type("read it")
|
||||
await d.key("\r")
|
||||
const answered = await d.waitFor("It says hello.")
|
||||
const named = await d.waitFor("alt+d display")
|
||||
const tucked = !d.screen().some((l) => l.includes("Recent activity"))
|
||||
await d.key("\x1bd")
|
||||
const opened = (await d.waitFor("Recent activity")) && (await d.waitFor("alt+d transcript"))
|
||||
await Bun.sleep(200)
|
||||
const zoom = d.screen()
|
||||
const inPlace = !zoom.some((l) => l.includes("It says hello.")) && (zoom[22] ?? "").includes("❯") && (zoom[23] ?? "").includes("manual · fake/coder") && d.cell(0, 0) !== "│"
|
||||
const wrapped = d.wrapped()
|
||||
await d.key("\x1bd")
|
||||
const back = (await d.waitFor("It says hello.")) && !d.screen().some((l) => l.includes("Recent activity"))
|
||||
await d.key("\x03")
|
||||
await d.key("\x03")
|
||||
const code = await d.close()
|
||||
f.stop()
|
||||
check(
|
||||
"TUI 70x24: no room beside the conversation — the status bar names the display, alt+d opens it in the transcript's place and back",
|
||||
answered && named && tucked && opened && inPlace && back && code === 0,
|
||||
`answered=${answered} named=${named} tucked=${tucked} opened=${opened} inPlace=${inPlace} back=${back} exit=${code}\n${zoom.join("\n")}`,
|
||||
)
|
||||
check("TUI 70x24: the display in the transcript's place is no wider than the terminal", wrapped.length === 0, `wrapped rows: ${wrapped.join(", ")}`)
|
||||
}
|
||||
|
||||
// 3c. compact and full, and a picture, at 120×40: beside the display a round of calls is one line;
|
||||
// alt+t shows every call on its own line and back; a picture attached with @ is drawn in the
|
||||
// images tab — OpenTUI's native image decoder inside the compiled binary (blocks: this terminal
|
||||
// has no graphics protocol).
|
||||
{
|
||||
const { fake: f, home: h, cwd } = fakeHome([
|
||||
{ chunks: [delta({ content: "Looking." }), toolCall(0, "c1", "read", '{"path":"hello.txt"}'), toolCall(1, "c2", "grep", '{"pattern":"hello","path":"."}'), usage(900, 40)] },
|
||||
{ chunks: [delta({ content: "Both say hello." }), usage(1200, 20)] },
|
||||
// Twice: the session's title is asked of the model too.
|
||||
{ chunks: [delta({ content: "A picture, noted." }), usage(1300, 20)] },
|
||||
{ chunks: [delta({ content: "A picture, noted." }), usage(1300, 20)] },
|
||||
])
|
||||
writeFileSync(join(cwd, "shot.png"), png(64, 32))
|
||||
const d = await drive({ cols: 120, rows: 40, bin, home: h, cwd })
|
||||
await d.waitFor("Trust this directory?")
|
||||
await d.key("\r")
|
||||
await d.waitFor("shift+tab mode")
|
||||
await d.type("look")
|
||||
await d.key("\r")
|
||||
const answered = await d.waitFor("Both say hello.")
|
||||
const left = () => d.screen().map((l) => l.slice(0, 68))
|
||||
const compact = (await d.waitFor("▸ 2 tools · read · grep")) && !left().some((l) => /read +hello\.txt/.test(l))
|
||||
await d.key("\x1bt")
|
||||
await d.waitFor("transcript: full")
|
||||
await Bun.sleep(300)
|
||||
const full = left().some((l) => /read +hello\.txt/.test(l)) && left().some((l) => /grep +hello/.test(l)) && !left().some((l) => l.includes("2 tools"))
|
||||
const fullScreen = d.screen()
|
||||
await d.key("\x1bt")
|
||||
const again = await d.waitFor("▸ 2 tools · read · grep")
|
||||
await d.type("@shot.png what is this ")
|
||||
await d.key("\r")
|
||||
const noted = await d.waitFor("A picture, noted.")
|
||||
await d.type("/display images")
|
||||
await d.key("\r")
|
||||
const listed = await d.waitFor("shot.png · attached")
|
||||
await Bun.sleep(500)
|
||||
const picture = d.screen()
|
||||
const drawn = picture.some((l) => BLOCKS.test(l.slice(68))) && picture.some((l) => l.includes("64×32"))
|
||||
const wrapped = d.wrapped()
|
||||
await d.key("\x03")
|
||||
await d.key("\x03")
|
||||
const code = await d.close()
|
||||
const modes = d.modes()
|
||||
f.stop()
|
||||
check(
|
||||
"TUI 120x40: beside the display a tool round is one line; alt+t shows every call and back",
|
||||
answered && compact && full && again,
|
||||
`answered=${answered} compact=${compact} full=${full} again=${again}\n${fullScreen.join("\n")}`,
|
||||
)
|
||||
check(
|
||||
"TUI 120x40: an attached picture is drawn in the images tab (the native decoder inside the binary)",
|
||||
noted && listed && drawn && wrapped.length === 0 && code === 0 && modes.mouse === "none" && !modes.altScreen,
|
||||
`noted=${noted} listed=${listed} drawn=${drawn} wrapped=${wrapped.join(",")} exit=${code} modes=${JSON.stringify(modes)}\n${picture.join("\n")}`,
|
||||
)
|
||||
}
|
||||
|
||||
// 3b. jobs, at 80×24: a command the model starts in the background is counted in the status bar;
|
||||
// /jobs opens the list (the row fits the terminal) and esc closes it; quitting with it running asks
|
||||
// first, and y stops it and leaves.
|
||||
@@ -137,7 +246,7 @@ for (const [cols, rows] of [
|
||||
const d = await drive({ cols: 80, rows: 24, bin, home: h, cwd })
|
||||
await d.waitFor("Trust this directory?")
|
||||
await d.key("\r")
|
||||
await d.waitFor("shift+tab mode · /help")
|
||||
await d.waitFor("shift+tab mode")
|
||||
await d.type("start a server")
|
||||
await d.key("\r")
|
||||
const asked = await d.waitFor("Allow once")
|
||||
@@ -218,7 +327,7 @@ for (const [cols, rows] of [
|
||||
await d.key("\r")
|
||||
// The new program draws its welcome box again, with the conversation loaded under it.
|
||||
await Bun.sleep(300)
|
||||
const back = await d.waitFor("shift+tab mode · /help")
|
||||
const back = await d.waitFor("shift+tab mode")
|
||||
// The new program's next request carries the conversation from before the reload.
|
||||
await d.type("again")
|
||||
await d.key("\r")
|
||||
@@ -252,7 +361,7 @@ for (const [cols, rows] of [
|
||||
const d = await drive({ cols: 100, rows: 30, bin, home: h, cwd, args: ["-l"], env: { HOME: h, TMPDIR: tmp, XDG_CONFIG_HOME: join(h, ".config"), XDG_DATA_HOME: join(h, ".local/share"), XDG_STATE_HOME: join(h, ".local/state") } })
|
||||
const firstRun = await d.waitFor("Trust this directory?")
|
||||
await d.key("\r")
|
||||
const drawn = await d.waitFor("shift+tab mode · /help", 15000)
|
||||
const drawn = await d.waitFor("shift+tab mode", 15000)
|
||||
await d.type("make a file")
|
||||
await d.key("\r")
|
||||
const asked = await d.waitFor("Allow once")
|
||||
|
||||
@@ -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(""))
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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). */
|
||||
|
||||
+186
-78
@@ -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<TranscriptSetting>(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.
|
||||
@@ -306,29 +356,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,
|
||||
@@ -348,6 +393,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, /<its name>, unless a built-in or custom command has the name
|
||||
@@ -374,7 +438,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(", ")}`)
|
||||
@@ -590,33 +655,40 @@ 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()
|
||||
}
|
||||
if (key.name === "pageup" || key.name === "pagedown" || key.name === "[" || key.name === "]") {
|
||||
const up = key.name === "pageup" || key.name === "["
|
||||
const step = Math.max(1, Math.floor((displayScroll?.height || 10) / 2))
|
||||
displayScroll?.scrollBy(up ? -step : step)
|
||||
// The images tab has nothing to scroll, and the box of the tab before it is gone.
|
||||
if (displayScroll && !displayScroll.isDestroyed) displayScroll.scrollBy(up ? -Math.max(1, Math.floor((displayScroll.height || 10) / 2)) : Math.max(1, Math.floor((displayScroll.height || 10) / 2)))
|
||||
return key.preventDefault()
|
||||
}
|
||||
}
|
||||
@@ -720,56 +792,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 }) => (
|
||||
<DisplayPane width={o.width} height={o.height} zoomed={o.zoomed} nav={displayNav} onSelectTab={selectTab} scrollRef={(r) => (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 (
|
||||
<TuiContext.Provider value={ctx}>
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
<Show
|
||||
when={entered()}
|
||||
keyed
|
||||
fallback={
|
||||
<box flexDirection="row" flexGrow={1}>
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => (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. */}
|
||||
<box flexDirection="row" width="100%" height="100%">
|
||||
<TuiContext.Provider value={leftCtx}>
|
||||
<box flexDirection="column" width={placement().left} height="100%" flexShrink={0}>
|
||||
<Show
|
||||
when={placement().mode === "zoom"}
|
||||
fallback={
|
||||
<Show
|
||||
when={entered()}
|
||||
keyed
|
||||
fallback={
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => (scroll = r)}
|
||||
flexGrow={1}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
viewportOptions={{ paddingRight: 1 }}
|
||||
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
|
||||
>
|
||||
<Welcome />
|
||||
<Messages />
|
||||
</scrollbox>
|
||||
}
|
||||
>
|
||||
{(id: string) => <SubagentView id={id} view={childViews.get(id)!} scrollRef={(r) => (scroll = r)} />}
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
<box
|
||||
flexGrow={1}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
viewportOptions={{ paddingRight: 1 }}
|
||||
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
|
||||
flexDirection="column"
|
||||
onSizeChange={function (this: { height: number }) {
|
||||
const h = this.height
|
||||
// After this layout pass, not inside it.
|
||||
if (h > 0 && h !== zoomRows()) setTimeout(() => setZoomRows(h), 0)
|
||||
}}
|
||||
>
|
||||
<Welcome />
|
||||
<Messages />
|
||||
</scrollbox>
|
||||
<Show when={showDisplays()}>
|
||||
<DisplayPane
|
||||
width={displayWidth()}
|
||||
nav={displayNav}
|
||||
onSelectTab={(tab) => setDisplayNav((n) => ({ ...n, tab, pinned: tab !== "live" }))}
|
||||
scrollRef={(r) => (displayScroll = r)}
|
||||
/>
|
||||
<Show when={zoomRows() > 0}>{pane({ width: placement().left, height: zoomRows(), zoomed: true })}</Show>
|
||||
</box>
|
||||
</Show>
|
||||
<box flexShrink={0} flexDirection="column">
|
||||
<PlanPanel />
|
||||
<Show when={view.state.pending}>
|
||||
<PermissionPrompt pending={view.state.pending!} />
|
||||
</Show>
|
||||
<Show when={view.state.question && !view.state.pending}>
|
||||
<QuestionCard pending={view.state.question!} />
|
||||
</Show>
|
||||
<Show when={view.state.plan && !view.state.pending && !view.state.question}>
|
||||
<PlanCard pending={view.state.plan!} />
|
||||
</Show>
|
||||
<Show when={busy() && !view.state.pending && !view.state.question && !view.state.plan}>
|
||||
<Spinner />
|
||||
</Show>
|
||||
<Queued />
|
||||
<Prompt focused={() => !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} />
|
||||
<StatusBar
|
||||
mode={mode}
|
||||
model={model}
|
||||
effort={effort}
|
||||
branch={branch()}
|
||||
voice={voiceStatus}
|
||||
flash={flashText}
|
||||
remote={() => (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" : "")}
|
||||
/>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
{(id: string) => <SubagentView id={id} view={childViews.get(id)!} scrollRef={(r) => (scroll = r)} />}
|
||||
</Show>
|
||||
<box flexShrink={0} flexDirection="column">
|
||||
<PlanPanel />
|
||||
<Show when={view.state.pending}>
|
||||
<PermissionPrompt pending={view.state.pending!} />
|
||||
</Show>
|
||||
<Show when={view.state.question && !view.state.pending}>
|
||||
<QuestionCard pending={view.state.question!} />
|
||||
</Show>
|
||||
<Show when={view.state.plan && !view.state.pending && !view.state.question}>
|
||||
<PlanCard pending={view.state.plan!} />
|
||||
</Show>
|
||||
<Show when={busy() && !view.state.pending && !view.state.question && !view.state.plan}>
|
||||
<Spinner />
|
||||
</Show>
|
||||
<Queued />
|
||||
<Prompt focused={() => !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} />
|
||||
<StatusBar mode={mode} model={model} effort={effort} branch={branch()} voice={voiceStatus} flash={flashText} remote={() => (rev(), share.label())} spend={spend} team={teamWord} mcp={() => (rev(), mcpWord(app.mcp.servers.values()))} />
|
||||
</box>
|
||||
</box>
|
||||
</TuiContext.Provider>
|
||||
<Show when={placement().mode === "side"}>{pane({ width: placement().pane, height: dims().height })}</Show>
|
||||
<Show when={dialog()}>
|
||||
<Dialog spec={dialog()!} close={() => setDialog(undefined)} />
|
||||
</Show>
|
||||
|
||||
+23
-7
@@ -75,7 +75,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 {
|
||||
@@ -91,7 +94,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",
|
||||
]
|
||||
|
||||
@@ -201,16 +205,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")
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+450
-343
@@ -1,5 +1,11 @@
|
||||
import { readFileSync, statSync } from "node:fs"
|
||||
import { basename, relative } 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<DisplayTab, string> = {
|
||||
live: "Live",
|
||||
files: "Files",
|
||||
changes: "Changes",
|
||||
bash: "Bash",
|
||||
const TAB_NAMES: Record<DisplayTab, TabSpec["names"]> = {
|
||||
live: ["Live", "Live", "L"],
|
||||
files: ["Files", "Files", "F"],
|
||||
changes: ["Changes", "Chg", "C"],
|
||||
bash: ["Bash", "Bash", "B"],
|
||||
images: ["Images", "Img", "I"],
|
||||
}
|
||||
|
||||
const PLAN_MARK: Record<string, string> = { todo: "☐", doing: "▸", done: "☑", dropped: "✗" }
|
||||
const SOURCE_WORD: Record<ImageEntry["source"], string> = { 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<typeof absPath>[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,440 @@ 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<string>()
|
||||
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) }
|
||||
}
|
||||
/** A path as it reads from the project: inside it, from its root. */
|
||||
const shownPath = (path: string) => {
|
||||
const rel = relative(app.project.root, path)
|
||||
return rel && !rel.startsWith("..") ? rel : path
|
||||
}
|
||||
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 (
|
||||
<box
|
||||
width={p.width}
|
||||
flexShrink={0}
|
||||
flexDirection="column"
|
||||
border={["left"]}
|
||||
borderColor={hasProposed() ? c().warn : c().border}
|
||||
backgroundColor={c().panel}
|
||||
>
|
||||
{/* Tab bar */}
|
||||
<box
|
||||
height={1}
|
||||
flexShrink={0}
|
||||
flexDirection="row"
|
||||
justifyContent="space-between"
|
||||
paddingLeft={1}
|
||||
paddingRight={1}
|
||||
backgroundColor={c().menu}
|
||||
>
|
||||
<text wrapMode="none" truncate>
|
||||
<For each={DISPLAY_TABS}>
|
||||
{(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 (
|
||||
<>
|
||||
<Show when={i() > 0}>
|
||||
<span style={{ fg: c().dim }}>{" "}</span>
|
||||
</Show>
|
||||
<span
|
||||
style={{
|
||||
fg: isActive() ? c().panel : tab === "changes" && hasProposed() ? c().warn : c().muted,
|
||||
bg: isActive() ? (tab === "changes" && hasProposed() ? c().warn : c().accent) : undefined,
|
||||
attributes: isActive() ? TextAttributes.BOLD : 0,
|
||||
}}
|
||||
>
|
||||
{` ${label()} `}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
const rows = () => (
|
||||
<>
|
||||
{/* Session header */}
|
||||
<box height={headRows()} flexShrink={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
|
||||
<text height={1} wrapMode="none" truncate fg={c().statusStrong}>
|
||||
{headLine() || " "}
|
||||
</text>
|
||||
<Show when={headRows() > 1}>
|
||||
<text height={1} wrapMode="none" fg={ctxColor()}>
|
||||
{clipEnd(ctxLine(), inner()) || " "}
|
||||
</text>
|
||||
</Show>
|
||||
</box>
|
||||
|
||||
{/* Sub-header */}
|
||||
<box
|
||||
height={1}
|
||||
flexShrink={0}
|
||||
flexDirection="row"
|
||||
justifyContent="space-between"
|
||||
paddingLeft={1}
|
||||
paddingRight={1}
|
||||
border={["bottom"]}
|
||||
borderColor={c().border}
|
||||
>
|
||||
<text wrapMode="none" truncate fg={subHeader().warn ? c().warn : c().title}>
|
||||
{subHeader().left}
|
||||
</text>
|
||||
<text wrapMode="none" fg={c().dim}>
|
||||
{" "}{subHeader().right}
|
||||
</text>
|
||||
{/* Tab bar: one box per tab, each as wide as its label, so a click lands on a known cell */}
|
||||
<box height={1} flexShrink={0} flexDirection="row" gap={1} paddingLeft={1} paddingRight={1} backgroundColor={c().menu}>
|
||||
<For each={cells()}>
|
||||
{(cell) => {
|
||||
const tab = cell.id as DisplayTab
|
||||
const isActive = () => activeTab() === tab
|
||||
const waiting = () => tab === "changes" && hasProposed()
|
||||
return (
|
||||
<box width={cell.width} height={1} flexShrink={0} backgroundColor={isActive() ? (waiting() ? c().warn : c().accent) : c().menu} onMouseDown={() => p.onSelectTab(tab)}>
|
||||
<text wrapMode="none" fg={isActive() ? c().panel : waiting() ? c().warn : c().muted} attributes={isActive() ? TextAttributes.BOLD : 0}>
|
||||
{cell.text}
|
||||
</text>
|
||||
</box>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</box>
|
||||
|
||||
{/* Sub-header: what is shown, and which of how many */}
|
||||
<box height={1} flexShrink={0} flexDirection="row" justifyContent="space-between" paddingLeft={1} paddingRight={1}>
|
||||
<box width={leftWidth()} height={1} flexShrink={0}>
|
||||
{/* A sentence is cut at its end; a path or a command keeps both ends. */}
|
||||
<text wrapMode="none" truncate fg={subHeader().warn ? c().warn : c().title}>
|
||||
{activeTab() === "live" ? clipEnd(subHeader().left, leftWidth()) : subHeader().left}
|
||||
</text>
|
||||
</box>
|
||||
<box width={rightWidth()} height={1} flexShrink={0}>
|
||||
<text wrapMode="none" fg={c().dim}>
|
||||
{subHeader().right}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
{/* Body */}
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => 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 } }}
|
||||
>
|
||||
<Switch>
|
||||
<Match when={activeTab() === "live"}>
|
||||
<box flexDirection="column" gap={1} paddingTop={1}>
|
||||
{/* Waiting banner */}
|
||||
<Show when={live().waiting}>
|
||||
<box border borderStyle="rounded" borderColor={c().warn} paddingLeft={1} paddingRight={1} flexDirection="column">
|
||||
<text fg={c().warn} attributes={TextAttributes.BOLD} wrapMode="word">
|
||||
{`Waiting: ${live().waiting!.title}`}
|
||||
</text>
|
||||
<text fg={c().text} wrapMode="word">
|
||||
{live().waiting!.detail}
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Currently running tools */}
|
||||
<Show when={live().activeTools.length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().accent} attributes={TextAttributes.BOLD}>
|
||||
Running now
|
||||
</text>
|
||||
<For each={live().activeTools}>
|
||||
{(t) => (
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<text wrapMode="word">
|
||||
<span style={{ fg: c().accent }}>◐ </span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
|
||||
</text>
|
||||
<For each={t.children ?? []}>
|
||||
{(ch) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" ↳ "}</span>
|
||||
<span style={{ fg: c().label }}>{ch.name}</span>
|
||||
<span style={{ fg: ch.isError ? c().error : c().muted }}>{ch.title ? ` ${ch.title}` : ""}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Live thinking preview */}
|
||||
<Show when={live().thinkingTail}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().reasoning} attributes={TextAttributes.BOLD}>
|
||||
{live().thinkingStreaming ? "Thinking live" : "Last thought"}
|
||||
</text>
|
||||
<box paddingLeft={1}>
|
||||
<text fg={c().reasoning} attributes={TextAttributes.ITALIC} wrapMode="word">
|
||||
{live().thinkingTail}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Active plan */}
|
||||
<Show when={live().plan}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().label} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
|
||||
{live().plan!.head}
|
||||
</text>
|
||||
<For each={live().plan!.lines}>
|
||||
{(line) => (
|
||||
<text
|
||||
wrapMode="word"
|
||||
fg={line.status === "doing" ? c().accent : line.status === "done" ? c().dim : c().text}
|
||||
>
|
||||
{` ${PLAN_MARK[line.status] ?? "•"} ${line.text}`}
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Subagents & background jobs */}
|
||||
<Show when={live().jobs.length > 0 || teamMembers().length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().info} attributes={TextAttributes.BOLD}>
|
||||
Agents & jobs
|
||||
</text>
|
||||
<For each={teamMembers()}>
|
||||
{(m) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: m.state === "working" ? c().accent : c().dim }}>{" ● "}</span>
|
||||
<span style={{ fg: c().label }}>{m.name}</span>
|
||||
<span style={{ fg: c().muted }}>{` (${m.role}) · ${m.state}`}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
<For each={live().jobs}>
|
||||
{(j) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: j.state === "running" ? c().accent : j.state === "error" ? c().error : c().dim }}>
|
||||
{" "}
|
||||
{j.state === "running" ? "◐" : j.state === "error" ? "✗" : "✓"}{" "}
|
||||
</span>
|
||||
<span style={{ fg: c().label }}>{j.id}</span>
|
||||
<span style={{ fg: c().text }}>{` ${j.label}`}</span>
|
||||
<span style={{ fg: c().dim }}>{` · ${j.detail}`}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Recent tool activity */}
|
||||
<Show when={live().recentTools.length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().title} attributes={TextAttributes.BOLD}>
|
||||
Recent activity
|
||||
</text>
|
||||
<For each={live().recentTools}>
|
||||
{(t) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: t.status === "error" ? c().error : t.status === "denied" ? c().warn : c().statusGood }}>
|
||||
{` ${toolStatusGlyph(t.status)} `}
|
||||
</span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
|
||||
<span style={{ fg: c().dim }}>{t.detail ? ` · ${t.detail}` : ""}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Latest preview */}
|
||||
<Show when={live().latestPreview && live().activeTools.length === 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().muted} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
|
||||
{`Latest ${live().latestPreview!.kind}: ${live().latestPreview!.title}`}
|
||||
</text>
|
||||
<box paddingLeft={1}>
|
||||
<text fg={c().muted} wrapMode="char">
|
||||
{live().latestPreview!.body}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
<Show
|
||||
when={
|
||||
!live().waiting &&
|
||||
live().activeTools.length === 0 &&
|
||||
!live().thinkingTail &&
|
||||
!live().plan &&
|
||||
live().jobs.length === 0 &&
|
||||
live().recentTools.length === 0
|
||||
}
|
||||
>
|
||||
<text fg={c().muted} wrapMode="word">
|
||||
Live agent activity, thinking, files read, diffs, and bash output will appear here as the agent works.
|
||||
</text>
|
||||
</Show>
|
||||
</box>
|
||||
</Match>
|
||||
|
||||
<Match when={activeTab() === "files"}>
|
||||
<Show
|
||||
when={activeTab() !== "images"}
|
||||
fallback={
|
||||
<box flexGrow={1} flexDirection="column" paddingLeft={1} paddingRight={1}>
|
||||
<Show
|
||||
when={currentFile()}
|
||||
when={picture()}
|
||||
fallback={
|
||||
<box paddingTop={1}>
|
||||
<text fg={c().muted}>No files read in this session yet.</text>
|
||||
</box>
|
||||
<text fg={c().muted} wrapMode="word">
|
||||
No pictures in this session yet: what view_image views, and images you attach with @, appear here.
|
||||
</text>
|
||||
}
|
||||
>
|
||||
<box flexDirection="column" paddingTop={1}>
|
||||
<text height={1} wrapMode="none" truncate fg={c().text}>
|
||||
{shownPath(picture()!.entry.path)}
|
||||
</text>
|
||||
<text height={1} wrapMode="none" fg={"error" in picture()! || drawError() ? c().warn : c().muted}>
|
||||
{clipEnd(pictureWords(), inner()) || " "}
|
||||
</text>
|
||||
<Show
|
||||
when={protocol() && "bytes" in picture()! && !drawError()}
|
||||
fallback={
|
||||
<text fg={c().muted} wrapMode="char">
|
||||
{picture()!.entry.path}
|
||||
{protocol() ? "" : "\n(pictures are off: images: off)"}
|
||||
</text>
|
||||
}
|
||||
>
|
||||
<box height={1} flexShrink={0} />
|
||||
<image
|
||||
source={(picture() as { bytes: Uint8Array }).bytes}
|
||||
width={box().width}
|
||||
height={box().height}
|
||||
flexShrink={0}
|
||||
fit="fit"
|
||||
protocol={protocol()!}
|
||||
onError={(e: unknown) => setDrawError(`not drawn: ${e instanceof Error ? e.message : String(e)}`.split("\n")[0]!)}
|
||||
/>
|
||||
</Show>
|
||||
</Show>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => 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 } }}
|
||||
>
|
||||
<Switch>
|
||||
<Match when={activeTab() === "live"}>
|
||||
<box flexDirection="column" gap={1}>
|
||||
{/* Waiting banner */}
|
||||
<Show when={live().waiting}>
|
||||
<box border borderStyle="rounded" borderColor={c().warn} paddingLeft={1} paddingRight={1} flexDirection="column">
|
||||
<text fg={c().warn} attributes={TextAttributes.BOLD} wrapMode="word">
|
||||
{`Waiting: ${live().waiting!.title}`}
|
||||
</text>
|
||||
<text fg={c().text} wrapMode="word">
|
||||
{live().waiting!.detail}
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Currently running tools */}
|
||||
<Show when={live().activeTools.length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().accent} attributes={TextAttributes.BOLD}>
|
||||
Running now
|
||||
</text>
|
||||
<For each={live().activeTools}>
|
||||
{(t) => (
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<text wrapMode="word">
|
||||
<span style={{ fg: c().accent }}>◐ </span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
|
||||
</text>
|
||||
<For each={t.children ?? []}>
|
||||
{(ch) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" ↳ "}</span>
|
||||
<span style={{ fg: c().label }}>{ch.name}</span>
|
||||
<span style={{ fg: ch.isError ? c().error : c().muted }}>{ch.title ? ` ${ch.title}` : ""}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Live thinking preview */}
|
||||
<Show when={live().thinkingTail}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().reasoning} attributes={TextAttributes.BOLD}>
|
||||
{live().thinkingStreaming ? "Thinking live" : "Last thought"}
|
||||
</text>
|
||||
<box paddingLeft={1}>
|
||||
<text fg={c().reasoning} attributes={TextAttributes.ITALIC} wrapMode="word">
|
||||
{live().thinkingTail}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Active plan */}
|
||||
<Show when={live().plan}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().label} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
|
||||
{live().plan!.head}
|
||||
</text>
|
||||
<For each={live().plan!.lines}>
|
||||
{(line) => (
|
||||
<text wrapMode="word" fg={line.status === "doing" ? c().accent : line.status === "done" ? c().dim : c().text}>
|
||||
{` ${PLAN_MARK[line.status] ?? "•"} ${line.text}`}
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Subagents & background jobs */}
|
||||
<Show when={live().jobs.length > 0 || teamMembers().length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().info} attributes={TextAttributes.BOLD}>
|
||||
Agents & jobs
|
||||
</text>
|
||||
<For each={teamMembers()}>
|
||||
{(m) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: m.state === "working" ? c().accent : c().dim }}>{" ● "}</span>
|
||||
<span style={{ fg: c().label }}>{m.name}</span>
|
||||
<span style={{ fg: c().muted }}>{` (${m.role}) · ${m.state}`}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
<For each={live().jobs}>
|
||||
{(j) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: j.state === "running" ? c().accent : j.state === "error" ? c().error : c().dim }}>
|
||||
{" "}
|
||||
{j.state === "running" ? "◐" : j.state === "error" ? "✗" : "✓"}{" "}
|
||||
</span>
|
||||
<span style={{ fg: c().label }}>{j.id}</span>
|
||||
<span style={{ fg: c().text }}>{` ${j.label}`}</span>
|
||||
<span style={{ fg: c().dim }}>{` · ${j.detail}`}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Recent tool activity */}
|
||||
<Show when={live().recentTools.length > 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().title} attributes={TextAttributes.BOLD}>
|
||||
Recent activity
|
||||
</text>
|
||||
<For each={live().recentTools}>
|
||||
{(t) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: t.status === "error" ? c().error : t.status === "denied" ? c().warn : c().statusGood }}>{` ${toolStatusGlyph(t.status)} `}</span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
|
||||
<span style={{ fg: c().dim }}>{t.detail ? ` · ${t.detail}` : ""}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
{/* Latest preview */}
|
||||
<Show when={live().latestPreview && live().activeTools.length === 0}>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().muted} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
|
||||
{`Latest ${live().latestPreview!.kind}: ${live().latestPreview!.title}`}
|
||||
</text>
|
||||
<box paddingLeft={1}>
|
||||
<text fg={c().muted} wrapMode="char">
|
||||
{live().latestPreview!.body}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
<Show when={!live().waiting && live().activeTools.length === 0 && !live().thinkingTail && !live().plan && live().jobs.length === 0 && live().recentTools.length === 0}>
|
||||
<text fg={c().muted} wrapMode="word">
|
||||
Live agent activity, thinking, files read, diffs, command output and pictures appear here as the agent works.
|
||||
</text>
|
||||
</Show>
|
||||
</box>
|
||||
</Match>
|
||||
|
||||
<Match when={activeTab() === "files"}>
|
||||
<Show when={currentFile()} fallback={<text fg={c().muted}>No files read in this session yet.</text>}>
|
||||
<text fg={c().text} wrapMode="char">
|
||||
{currentFile()!.body}
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
</Match>
|
||||
</Show>
|
||||
</Match>
|
||||
|
||||
<Match when={activeTab() === "changes"}>
|
||||
<Show
|
||||
when={currentChange()}
|
||||
fallback={
|
||||
<box paddingTop={1}>
|
||||
<text fg={c().muted}>No file changes in this session yet.</text>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
<box flexDirection="column" paddingTop={1}>
|
||||
<Show when={currentChange()!.status === "proposed"}>
|
||||
<text fg={c().warn} attributes={TextAttributes.BOLD}>
|
||||
Proposed change — waiting for your answer
|
||||
</text>
|
||||
</Show>
|
||||
<Show
|
||||
when={currentChange()!.diff.includes("@@") || currentChange()!.diff.includes("--- ")}
|
||||
fallback={
|
||||
<text fg={c().text} wrapMode="char">
|
||||
{currentChange()!.diff}
|
||||
<Match when={activeTab() === "changes"}>
|
||||
<Show when={currentChange()} fallback={<text fg={c().muted}>No file changes in this session yet.</text>}>
|
||||
<box flexDirection="column">
|
||||
<Show when={currentChange()!.status === "proposed"}>
|
||||
<text fg={c().warn} attributes={TextAttributes.BOLD} wrapMode="word">
|
||||
Proposed change — waiting for your answer
|
||||
</text>
|
||||
}
|
||||
>
|
||||
<diff
|
||||
width={diffWidth()}
|
||||
diff={currentChange()!.diff}
|
||||
view="unified"
|
||||
filetype={filetypeOf(currentChange()!.diff)}
|
||||
showLineNumbers
|
||||
wrapMode="char"
|
||||
fg={c().text}
|
||||
addedBg={c().diffAddedBg}
|
||||
removedBg={c().diffRemovedBg}
|
||||
contextBg={c().diffContextBg}
|
||||
addedSignColor={c().diffAddedSign}
|
||||
removedSignColor={c().diffRemovedSign}
|
||||
lineNumberFg={c().lineNumber}
|
||||
lineNumberBg={c().diffContextBg}
|
||||
/>
|
||||
</Show>
|
||||
</box>
|
||||
</Show>
|
||||
</Match>
|
||||
|
||||
<Match when={activeTab() === "bash"}>
|
||||
<Show
|
||||
when={currentBash()}
|
||||
fallback={
|
||||
<box paddingTop={1}>
|
||||
<text fg={c().muted}>No bash commands run in this session yet.</text>
|
||||
</Show>
|
||||
<Show
|
||||
when={currentChange()!.diff.includes("@@") || currentChange()!.diff.includes("--- ")}
|
||||
fallback={
|
||||
<text fg={c().text} wrapMode="char">
|
||||
{currentChange()!.diff}
|
||||
</text>
|
||||
}
|
||||
>
|
||||
<diff
|
||||
width={diffWidth()}
|
||||
diff={currentChange()!.diff}
|
||||
view="unified"
|
||||
filetype={filetypeOf(currentChange()!.diff)}
|
||||
showLineNumbers
|
||||
wrapMode="char"
|
||||
fg={c().text}
|
||||
addedBg={c().diffAddedBg}
|
||||
removedBg={c().diffRemovedBg}
|
||||
contextBg={c().diffContextBg}
|
||||
addedSignColor={c().diffAddedSign}
|
||||
removedSignColor={c().diffRemovedSign}
|
||||
lineNumberFg={c().lineNumber}
|
||||
lineNumberBg={c().diffContextBg}
|
||||
/>
|
||||
</Show>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
<box flexDirection="column" paddingTop={1} gap={1}>
|
||||
<text fg={c().accent} wrapMode="char">
|
||||
{`$ ${currentBash()!.command}`}
|
||||
</text>
|
||||
<text fg={currentBash()!.status === "error" ? c().error : c().text} wrapMode="char">
|
||||
{currentBash()!.output}
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
</Match>
|
||||
</Switch>
|
||||
</scrollbox>
|
||||
</Show>
|
||||
</Match>
|
||||
|
||||
{/* Footer key hints */}
|
||||
<Match when={activeTab() === "bash"}>
|
||||
<Show when={currentBash()} fallback={<text fg={c().muted}>No bash commands run in this session yet.</text>}>
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text fg={c().accent} wrapMode="char">
|
||||
{`$ ${currentBash()!.command}`}
|
||||
</text>
|
||||
<text fg={currentBash()!.status === "error" ? c().error : c().text} wrapMode="char">
|
||||
{currentBash()!.output}
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
</Match>
|
||||
</Switch>
|
||||
</scrollbox>
|
||||
</Show>
|
||||
|
||||
{/* Key line */}
|
||||
<box height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={c().menu}>
|
||||
<text fg={c().dim} wrapMode="none" truncate>
|
||||
Alt+↑↓ tabs · Alt+←→ entry · Alt+PgUp/Dn scroll · Alt+D hide
|
||||
<text fg={c().dim} wrapMode="none">
|
||||
{paneHints(inner(), p.zoomed) || " "}
|
||||
</text>
|
||||
</box>
|
||||
</>
|
||||
)
|
||||
// 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 (
|
||||
<box width={p.width} height={p.height} flexShrink={0} flexDirection="column" backgroundColor={c().panel}>
|
||||
{rows()}
|
||||
</box>
|
||||
)
|
||||
return (
|
||||
<box width={p.width} height={p.height} flexShrink={0} flexDirection="column" border={["left"]} borderColor={hasProposed() ? c().warn : c().border} backgroundColor={c().panel}>
|
||||
{rows()}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
+207
-42
@@ -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<string, string> = { 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<Item, { kind: "assistant" }> }) {
|
||||
* 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<Item, { kind: "reasoning" }> }) {
|
||||
function Reasoning(p: { item: Extract<Item, { kind: "reasoning" }>; tight?: boolean }) {
|
||||
const { theme, thought, view } = useTui()
|
||||
const [now, setNow] = createSignal(Date.now())
|
||||
createEffect(() => {
|
||||
@@ -87,7 +88,7 @@ function Reasoning(p: { item: Extract<Item, { kind: "reasoning" }> }) {
|
||||
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 (
|
||||
<box paddingLeft={2} marginTop={1} flexDirection="column">
|
||||
<box paddingLeft={2} marginTop={p.tight ? 0 : 1} flexDirection="column">
|
||||
<text fg={theme().colors.reasoning} attributes={TextAttributes.ITALIC} wrapMode="none" truncate>
|
||||
{line()}
|
||||
</text>
|
||||
@@ -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<Item, { kind: "tool" }> }) {
|
||||
/** `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<Item, { kind: "tool" }>; 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<Item, { kind: "tool" }> }) {
|
||||
<span style={{ fg: p.item.job!.state === "running" ? c().accent : p.item.job!.state === "error" || p.item.job!.state === "lost" ? c().error : c().dim }}>{` ${jobWords(p.item.job!)}`}</span>
|
||||
</text>
|
||||
</Show>
|
||||
<For each={p.item.children ?? []}>
|
||||
<For each={children()}>
|
||||
{(ch) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" "}{theme().branding.toolPrefix} </span>
|
||||
@@ -153,7 +154,7 @@ function ToolLine(p: { item: Extract<Item, { kind: "tool" }> }) {
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
<Show when={p.item.diff}>
|
||||
<Show when={p.item.diff && open()}>
|
||||
<box paddingLeft={4} paddingRight={1} flexDirection="column">
|
||||
<WrappedDiff patch={shown().diff} filetype={filetypeOf(p.item.diff!)} />
|
||||
<Show when={shown().hidden > 0}>
|
||||
@@ -277,38 +278,202 @@ function EndLine(p: { item: Extract<Item, { kind: "end" }> }) {
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<Switch>
|
||||
<Match when={item.kind === "user"}>
|
||||
<UserMessage item={item as Extract<Item, { kind: "user" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "assistant"}>
|
||||
<AssistantMessage item={item as Extract<Item, { kind: "assistant" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "reasoning"}>
|
||||
<Reasoning item={item as Extract<Item, { kind: "reasoning" }>} tight={p.compact} />
|
||||
</Match>
|
||||
<Match when={item.kind === "tool" && !undrawn((item as Extract<Item, { kind: "tool" }>).name)}>
|
||||
<ToolLine item={item as Extract<Item, { kind: "tool" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "notice"}>
|
||||
<Notice item={item as Extract<Item, { kind: "notice" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "diff" && p.compact && !view.state.expandTools}>
|
||||
<DiffStats item={item as Extract<Item, { kind: "diff" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "diff"}>
|
||||
<DiffBlock item={item as Extract<Item, { kind: "diff" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "end"}>
|
||||
<EndLine item={item as Extract<Item, { kind: "end" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "error"}>
|
||||
<ErrorLine item={item as Extract<Item, { kind: "error" }>} />
|
||||
</Match>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
|
||||
/** A multi-file diff in the compact transcript: its title and a stat line per file. */
|
||||
function DiffStats(p: { item: Extract<Item, { kind: "diff" }> }) {
|
||||
const { theme } = useTui()
|
||||
const c = () => theme().colors
|
||||
return (
|
||||
<box flexDirection="column" paddingLeft={1} marginTop={1}>
|
||||
<text fg={c().title} wrapMode="none" truncate>
|
||||
{p.item.title}
|
||||
</text>
|
||||
<For each={patchStats(p.item.patch)}>{(f) => <StatLine path={f.path} added={f.added} removed={f.removed} />}</For>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
/** `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 (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" "}</span>
|
||||
<span style={{ fg: c().text }}>{p.path}</span>
|
||||
<span style={{ fg: c().diffAddedSign }}>{` +${num(p.added)}`}</span>
|
||||
<span style={{ fg: c().diffRemovedSign }}>{` −${num(p.removed)}`}</span>
|
||||
</text>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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<Item, { kind: "tool" }>) => t.title ?? callTitle(t.args) ?? ""
|
||||
const jobs = () => tools().filter((t) => t.job && t.job.state === "running")
|
||||
return (
|
||||
<Show when={tools().length > 1} fallback={<For each={tools()}>{(t) => <ToolLine item={t} brief />}</For>}>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: sum().running.length ? c().accent : c().dim }}>{sum().running.length ? "◐ " : "▸ "}</span>
|
||||
<span style={{ fg: c().label }}>{roundLine(sum(), width() - 2 - troubleWidth())}</span>
|
||||
<span style={{ fg: c().error }}>{trouble().failed ? ` · ${trouble().failed}` : ""}</span>
|
||||
<span style={{ fg: c().warn }}>{trouble().denied ? ` · ${trouble().denied}` : ""}</span>
|
||||
</text>
|
||||
<Show
|
||||
when={!view.state.expandTools}
|
||||
fallback={
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<For each={tools()}>{(t) => <ToolLine item={t} />}</For>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
<For each={sum().changes.slice(0, ROUND_CHANGES)}>{(ch) => <StatLine path={ch.path} added={ch.added} removed={ch.removed} />}</For>
|
||||
<Show when={sum().changes.length > ROUND_CHANGES}>
|
||||
<text fg={c().muted} wrapMode="none" truncate>
|
||||
{` … ${sum().changes.length - ROUND_CHANGES} more change${sum().changes.length - ROUND_CHANGES === 1 ? "" : "s"} (ctrl+o)`}
|
||||
</text>
|
||||
</Show>
|
||||
<For each={[...sum().failed, ...sum().denied]}>
|
||||
{(t) => (
|
||||
<text wrapMode="none">
|
||||
<span style={{ fg: t.status === "denied" ? c().warn : c().error }}>{t.status === "denied" ? " ⊘ " : " ✗ "}</span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: t.status === "denied" ? c().warn : c().error }}>{clipEnd(`${title(t) ? ` ${title(t)}` : ""}${callAfter(t) ? ` · ${callAfter(t)}` : ""}`, width() - 6 - t.name.length)}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
<For each={sum().running}>
|
||||
{(t) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().accent }}>{" ◐ "}</span>
|
||||
<span style={{ fg: c().label }}>{t.name}</span>
|
||||
<span style={{ fg: c().text }}>{title(t) ? ` ${title(t)}` : ""}</span>
|
||||
<span style={{ fg: c().dim }}>{t.children?.length ? ` · ${t.children[t.children.length - 1]!.name} ${t.children[t.children.length - 1]!.title}` : " …"}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
<For each={jobs()}>
|
||||
{(t) => (
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" → "}</span>
|
||||
<span style={{ fg: c().label }}>{t.job!.id}</span>
|
||||
<span style={{ fg: c().muted }}>{` (${t.job!.agent ? `${t.job!.agent}: ` : ""}${t.job!.description})`}</span>
|
||||
<span style={{ fg: c().accent }}>{` ${jobWords(t.job!)}`}</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
</box>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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<string, Ref>()
|
||||
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 (
|
||||
<For each={list()}>
|
||||
{(row) =>
|
||||
"round" in row ? (
|
||||
<box id={rowId(row.round)} flexDirection="column" flexShrink={0}>
|
||||
<RoundRow round={() => rounds().get(row.round)} />
|
||||
</box>
|
||||
) : (
|
||||
<box id={rowId(row.id)} flexDirection="column" flexShrink={0}>
|
||||
<ItemRow item={row} compact />
|
||||
</box>
|
||||
)
|
||||
}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
function FullMessages() {
|
||||
const { view } = useTui()
|
||||
return (
|
||||
<For each={view.state.items}>
|
||||
{(item) => (
|
||||
<Switch>
|
||||
<Match when={item.kind === "user"}>
|
||||
<UserMessage item={item as Extract<Item, { kind: "user" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "assistant"}>
|
||||
<AssistantMessage item={item as Extract<Item, { kind: "assistant" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "reasoning"}>
|
||||
<Reasoning item={item as Extract<Item, { kind: "reasoning" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "tool" && !undrawn((item as Extract<Item, { kind: "tool" }>).name)}>
|
||||
<ToolLine item={item as Extract<Item, { kind: "tool" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "notice"}>
|
||||
<Notice item={item as Extract<Item, { kind: "notice" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "diff"}>
|
||||
<DiffBlock item={item as Extract<Item, { kind: "diff" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "end"}>
|
||||
<EndLine item={item as Extract<Item, { kind: "end" }>} />
|
||||
</Match>
|
||||
<Match when={item.kind === "error"}>
|
||||
<ErrorLine item={item as Extract<Item, { kind: "error" }>} />
|
||||
</Match>
|
||||
</Switch>
|
||||
<box id={rowId(item.id)} flexDirection="column" flexShrink={0}>
|
||||
<ItemRow item={item} />
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<Show when={compact?.()} fallback={<FullMessages />}>
|
||||
<CompactMessages />
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
@@ -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" },
|
||||
|
||||
@@ -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 (
|
||||
<box height={1} flexDirection="row" justifyContent="space-between" backgroundColor={c().panel} paddingLeft={1} paddingRight={1}>
|
||||
<text wrapMode="none" truncate>
|
||||
<text wrapMode="none" truncate visible={!flashOnly()}>
|
||||
<span style={{ fg: modeColor() }}>{MODE_LABEL[p.mode() as keyof typeof MODE_LABEL] ?? p.mode()}</span>
|
||||
<span style={{ fg: c().statusDim }}> · </span>
|
||||
<span style={{ fg: c().statusStrong }}>{p.model()}</span>
|
||||
@@ -50,20 +68,20 @@ export function StatusBar(p: { mode: () => string; model: () => string; effort:
|
||||
when={p.flash?.()}
|
||||
fallback={
|
||||
<text wrapMode="none">
|
||||
<span style={{ fg: c().info }}>{p.team?.() ? `${p.team()} · ` : ""}</span>
|
||||
<span style={{ fg: p.mcp?.().warn ? c().statusWarn : c().statusDim }}>{p.mcp?.().text ? `${p.mcp!().text} · ` : ""}</span>
|
||||
<span style={{ fg: c().info }}>{p.hint?.() ? `${p.hint()} · ` : ""}</span>
|
||||
<span style={{ fg: c().info }}>{!short() && p.team?.() ? `${p.team()} · ` : ""}</span>
|
||||
<span style={{ fg: p.mcp?.().warn ? c().statusWarn : c().statusDim }}>{!short() && p.mcp?.().text ? `${p.mcp!().text} · ` : ""}</span>
|
||||
<span style={{ fg: jobsWord(view.state.jobs).endsWith("!") ? c().statusWarn : c().statusText }}>{jobsWord(view.state.jobs) ? `${jobsWord(view.state.jobs)} · ` : ""}</span>
|
||||
<span style={{ fg: c().statusDim }}>{view.state.rate ? `${Math.round(view.state.rate)} tok/s · ` : ""}</span>
|
||||
<span style={{ fg: c().statusText }}>{p.spend?.() ? `${p.spend()} · ` : ""}</span>
|
||||
<span style={{ fg: c().statusDim }}>{!short() && view.state.rate ? `${Math.round(view.state.rate)} tok/s · ` : ""}</span>
|
||||
<span style={{ fg: c().statusText }}>{!short() && p.spend?.() ? `${p.spend()} · ` : ""}</span>
|
||||
<span style={{ fg: ctx().color }}>{ctx().text}</span>
|
||||
<span style={{ fg: c().statusDim }}> · </span>
|
||||
<span style={{ fg: c().info }}>{isLocal() ? "local " : ""}</span>
|
||||
<span style={{ fg: c().statusDim }}>{basename(app.project.root)}{p.branch ? `@${p.branch}` : ""}</span>
|
||||
<span style={{ fg: c().info }}>{isLocal() ? " · local" : ""}</span>
|
||||
<span style={{ fg: c().statusDim }}>{short() ? "" : `${isLocal() ? " " : " · "}${basename(app.project.root)}${p.branch ? `@${p.branch}` : ""}`}</span>
|
||||
</text>
|
||||
}
|
||||
>
|
||||
<text wrapMode="none" fg={c().statusGood}>
|
||||
{p.flash!()}
|
||||
{clipEnd(p.flash?.() ?? "", room())}
|
||||
</text>
|
||||
</Show>
|
||||
</box>
|
||||
|
||||
@@ -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.
|
||||
</text>
|
||||
</Show>
|
||||
<text fg={c().dim} wrapMode="word">
|
||||
enter send · shift+enter newline · shift+tab mode · /help
|
||||
</text>
|
||||
{/* Each hint is one piece that never breaks: in a narrow column the row wraps between hints,
|
||||
not inside one. */}
|
||||
<box flexDirection="row" flexWrap="wrap" columnGap={1}>
|
||||
<For each={HINTS}>
|
||||
{(hint, i) => (
|
||||
<text fg={c().dim} wrapMode="none" flexShrink={0}>
|
||||
{i() < HINTS.length - 1 ? `${hint} ·` : hint}
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
@@ -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<Ctx>()
|
||||
|
||||
+82
-13
@@ -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<DisplayTab, "live">
|
||||
|
||||
/** 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<string, ImageEntry["source"]> = { 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<Exclude<DisplayTab, "live">, number>
|
||||
index: Record<ListTab, number>
|
||||
}
|
||||
|
||||
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<DisplayTab, "live">, 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<DisplayTab, "live">, 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<DisplayTab, "live">
|
||||
|
||||
/** 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 } }
|
||||
}
|
||||
@@ -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()}…`
|
||||
}
|
||||
+12
-5
@@ -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<number, SavedPage> }
|
||||
@@ -145,6 +146,8 @@ export interface ViewState {
|
||||
// What the model was given beside the words typed — attachments, and a session note
|
||||
// (session/prefix.ts) — is not shown as typed.
|
||||
const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || t.startsWith("<editor>\n") || t.startsWith("<terminal>\n") || isNote(t) }
|
||||
/** An attached picture as the model was told of it: `<image path="…"/>`, the whole part. */
|
||||
const IMAGE_ATTACHMENT = /^<image path="([^"]+)"\/>$/gm
|
||||
/** Running first, then by start — the registry's order. */
|
||||
const byRunning = (a: JobInfo, b: JobInfo) => Number(b.state === "running") - Number(a.state === "running") || a.started - b.started
|
||||
let seq = 0
|
||||
@@ -458,8 +461,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
|
||||
@@ -535,9 +538,13 @@ export function createView(bus: Bus) {
|
||||
else if (m.role === "user" && m.parts[0]?.type === "text" && stripMark(m.parts[0].text).mark)
|
||||
// A job's note given mid-turn: without its mark, as a steer is shown.
|
||||
items.push({ kind: "user", id: nextId(), text: stripMark(m.parts[0].text).body.trim(), mid: true, machine: true })
|
||||
else if (m.role === "user")
|
||||
else if (m.role === "user") {
|
||||
// What was typed; attachments (@files, ! output) went to the model but are not shown again.
|
||||
items.push({ kind: "user", id: nextId(), text: m.parts.filter((p, i) => p.type === "text" && (i === 0 || !ATTACHMENT.test(p.text))).map((p) => (p.type === "text" ? p.text : "")).join("\n") })
|
||||
// A picture that was attached is remembered by its path, as the attachment named it
|
||||
// (project/attach.ts), for the display's images tab.
|
||||
const images = m.parts.flatMap((p) => (p.type === "text" ? [...p.text.matchAll(IMAGE_ATTACHMENT)].map((x) => x[1]!) : []))
|
||||
items.push({ kind: "user", id: nextId(), text: m.parts.filter((p, i) => p.type === "text" && (i === 0 || !ATTACHMENT.test(p.text))).map((p) => (p.type === "text" ? p.text : "")).join("\n"), ...(images.length ? { images } : {}) })
|
||||
}
|
||||
else if (m.role === "assistant") {
|
||||
for (const p of m.parts) {
|
||||
if (p.type === "text" && p.text.trim()) {
|
||||
|
||||
@@ -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<Item, { kind: "tool" }>
|
||||
export type ReasoningItem = Extract<Item, { kind: "reasoning" }>
|
||||
|
||||
/** 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<string, string> {
|
||||
const map = new Map<string, string>()
|
||||
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<Round, "tools">): 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) }))
|
||||
}
|
||||
+92
-1
@@ -6,12 +6,17 @@ import {
|
||||
extractBash,
|
||||
extractChanges,
|
||||
extractFiles,
|
||||
extractImages,
|
||||
fitImage,
|
||||
freshImage,
|
||||
imageProtocol,
|
||||
initialNav,
|
||||
resetFollow,
|
||||
resolveIndex,
|
||||
stepEntry,
|
||||
} from "../src/tui/displays.ts"
|
||||
import type { Item, Pending, ViewState } from "../src/tui/state.ts"
|
||||
import { Bus } from "../src/bus/index.ts"
|
||||
import { createView, type Item, type Pending, type ViewState } from "../src/tui/state.ts"
|
||||
|
||||
function baseState(overrides: Partial<ViewState> = {}): ViewState {
|
||||
return {
|
||||
@@ -118,3 +123,89 @@ 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 })
|
||||
})
|
||||
|
||||
test("a stored session's attached pictures are found again by the path the attachment named", () => {
|
||||
const view = createView(new Bus())
|
||||
view.load([
|
||||
{ role: "user", parts: [{ type: "text", text: "what is this @shots/a.png" }, { type: "text", text: '<image path="shots/a.png"/>' }, { type: "image", mime: "image/png", data: "" }, { type: "text", text: '<image path="b.png">(not attached: this model has no vision)</image>' }] },
|
||||
{ role: "assistant", parts: [{ type: "text", text: "A cat." }] },
|
||||
] as never)
|
||||
expect(extractImages(view.state.items, (p) => `/work/${p}`)).toEqual([{ id: expect.any(String) as never, title: "shots/a.png", path: "/work/shots/a.png", source: "attached" }])
|
||||
// What the person typed is shown as before: the attachment's text is not.
|
||||
const user = view.state.items[0]!
|
||||
expect(user.kind === "user" && user.text).toBe("what is this @shots/a.png")
|
||||
})
|
||||
@@ -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")
|
||||
})
|
||||
@@ -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))])
|
||||
}
|
||||
@@ -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<Extract<Item, { kind: "tool" }>> = {}): 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<Round, "tools"> => ({ 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 },
|
||||
])
|
||||
})
|
||||
+292
-19
@@ -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<ReturnType<typeof tui>> | 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")
|
||||
})
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user