From 5122dcf10fcea893f46d166e89f5985a1b76eaa4 Mon Sep 17 00:00:00 2001 From: ruv Date: Fri, 2 Oct 2026 16:36:27 -0400 Subject: [PATCH] feat(ruflo-console): a scrollable, framed AI terminal and a clickable console MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Terminal: - The conversation is a window that scrolls: ▲ older, ▼ newer, ⤓ end by mouse, or /up /down /end from the field. - While scrolled up, new output waits below and is counted (⤓ N new). - Each turn is framed: ╭─ you → agent, ├─ agent, then a gutter in that agent's colour, closed by ╰─ ✓ 3 s · $0.012. - Light markdown: headings bold, bullets as •, fenced code framed and tinted. - Long answers wrap at word boundaries. - A question can be clicked to put it back in the field. - While an agent writes back, a spinner shows; the input sits under its own rule. - Clickable: - Every band part opens the console on its view, with the keys (approvals, swarm, terminal, events, claims, cost). - The Wildcat NETWORKS names are links. - The main menu's status-bar facts are links. Co-Authored-By: RuFlo --- plugins/ruflo-console/hooks/bindings.ts | 23 +++ plugins/ruflo-console/hooks/harness.ts | 30 ++-- plugins/ruflo-console/hooks/register.ts | 6 +- plugins/ruflo-console/hooks/state.ts | 10 +- plugins/ruflo-console/hooks/views/bar.ts | 51 ++++-- plugins/ruflo-console/hooks/views/common.ts | 2 +- plugins/ruflo-console/hooks/views/menu.ts | 23 ++- plugins/ruflo-console/hooks/views/pane.ts | 9 +- plugins/ruflo-console/hooks/views/terminal.ts | 154 ++++++++++++------ plugins/ruflo-console/tests/band.spec.ts | 2 +- plugins/ruflo-console/tests/behaviour.test.ts | 18 ++ plugins/ruflo-console/tests/terminal.spec.ts | 32 +++- 12 files changed, 274 insertions(+), 86 deletions(-) diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts index 6530018b78..a045386615 100644 --- a/plugins/ruflo-console/hooks/bindings.ts +++ b/plugins/ruflo-console/hooks/bindings.ts @@ -148,6 +148,16 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps return } + // /up /down /end scroll the conversation from the field (it holds the keys, so PgUp would only type). + const move = { '/up': 12, '/down': -12, '/end': -state.terminal.scroll }[text.trim()] + + if (move !== undefined) { + state.terminal.draft = '' + actions.term.scroll(move) + + return + } + // /codex /claude /swarm /ruflo switch harness from the field, which holds the keys (its hotkeys would type). const pick = HARNESSES.find(entry => text.trim() === `/${entry.id}`) @@ -199,8 +209,21 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps fresh: () => newSession(state, host), clear: () => { state.terminal.lines = [] + state.terminal.scroll = 0 + state.terminal.unseen = 0 host.invalidate() }, + scroll: by => { + state.terminal.scroll = Math.max(0, state.terminal.scroll + by) + if (state.terminal.scroll === 0) state.terminal.unseen = 0 + host.invalidate() + }, + // A click on an earlier question puts it back in the field, ready to edit or send again. + reuse: text => { + state.terminal.draft = text + host.invalidate() + if (state.pane.isFocused) void host.focus(PANE_ID, 'term-input').catch(() => undefined) + }, // A menu entry elsewhere (x.ruv.io) opens the terminal with its command typed, not run: Enter twice runs it. load: (id, text) => { state.terminal.harness = id diff --git a/plugins/ruflo-console/hooks/harness.ts b/plugins/ruflo-console/hooks/harness.ts index e147ba1545..e5b2c7f760 100644 --- a/plugins/ruflo-console/hooks/harness.ts +++ b/plugins/ruflo-console/hooks/harness.ts @@ -73,8 +73,14 @@ export function termText(line: string, max = 400, trim = true): string { return out.length <= max ? out : `${out.slice(0, max - 1)}…` } +/** Appends one line; while the person has scrolled up, the window stays put and the new line is counted instead. */ +function add(state: State, line: TermLine): void { + push(state.terminal.lines, line, TERM_MAX_LINES) + if (state.terminal.scroll > 0) state.terminal.unseen += 1 +} + function note(state: State, kind: TermLine['kind'], text: string, from?: AgentId): void { - for (const line of text.split('\n')) push(state.terminal.lines, { kind, text: termText(line), ...(from !== undefined && { from }) }, TERM_MAX_LINES) + for (const line of text.split('\n')) add(state, { kind, text: termText(line), ...(from !== undefined && { from }) }) } const persist = (state: State, host: Host) => void host.storeSet(termStoreKeyOf(state.cwd), state.terminal.sessions).catch(() => undefined) @@ -124,11 +130,13 @@ export function harnessSpec(state: State, host: Host, text: string): ActionSpec export function send(state: State, host: Host, text: string): void { const harness = harnessOf(state.terminal.harness) const prompt = text.trim().slice(0, MAX_PROMPT) - const isMany = harness.agents.length > 1 - note(state, 'in', `${harness.label}> ${prompt}`) + // A new question brings the window back to the tail, so its answer is seen streaming in. + state.terminal.scroll = 0 + state.terminal.unseen = 0 + note(state, 'in', prompt, harness.agents.length === 1 ? harness.agents[0] : undefined) - for (const agent of harness.agents) void runAgent(state, host, agent, prompt, isMany) + for (const agent of harness.agents) void runAgent(state, host, agent, prompt) } /** Forgets the picked harness's sessions: the next question starts new ones (and is asked first). */ @@ -144,9 +152,10 @@ export function newSession(state: State, host: Host): void { host.invalidate() } -async function runAgent(state: State, host: Host, agent: AgentId, prompt: string, isTagged: boolean): Promise { +async function runAgent(state: State, host: Host, agent: AgentId, prompt: string): Promise { const term = state.terminal - const tag = isTagged ? agent : undefined + // Every line names its agent: the screen draws each answer in that agent's colour, tagged where several talk. + const tag = agent const startedAtMs = Date.now() const secs = () => `${Math.round((Date.now() - startedAtMs) / 1000)} s` // claude takes the session id the console picks; it counts once the CLI reports the session started. @@ -176,8 +185,8 @@ async function runAgent(state: State, host: Host, agent: AgentId, prompt: string parts.forEach((part, i) => { if (i > 0 || open === null) { - open = { kind: 'out', text: '', ...(tag !== undefined && { from: tag }) } - push(term.lines, open, TERM_MAX_LINES) + open = { kind: 'out', text: '', from: tag } + add(state, open) } open.text = termText(open.text + part, 2_000, false) }) @@ -215,6 +224,7 @@ async function runAgent(state: State, host: Host, agent: AgentId, prompt: string const partial = { stdout: '', stderr: '' } term.runs.set(agent, { label: agent, startedAtMs, stop }) + note(state, 'head', agent, tag) host.invalidate() const take = (from: 'stdout' | 'stderr', line: string) => { @@ -249,10 +259,10 @@ async function runAgent(state: State, host: Host, agent: AgentId, prompt: string if (claudeId !== undefined && !sawSession) delete term.sessions.claude // A stream read to its end with events but no answer drawn: the CLI's format moved, and silence would hide it. if (parse !== null && !isStopped && !isAnswered && ended === null) note(state, 'err', `no answer read from ${events} ${agent} event${events === 1 ? '' : 's'}: has its --json format changed?`, tag) - note(state, 'sys', isStopped ? `stopped after ${secs()}` : (ended ?? (result.code === 0 ? `✓ ${secs()}` : `✗ exit ${result.code ?? result.signal ?? '?'} · ${secs()}`)), tag) + note(state, 'end', isStopped ? `stopped after ${secs()}` : (ended ?? (result.code === 0 ? `✓ ${secs()}` : `✗ exit ${result.code ?? result.signal ?? '?'} · ${secs()}`)), tag) } catch (error) { if (claudeId !== undefined && !sawSession) delete term.sessions.claude - note(state, 'sys', isStopped ? `stopped after ${secs()}` : `✗ ${argv[0]}: ${error instanceof Error ? error.message : String(error)} (is it installed and on PATH?)`, tag) + note(state, 'end', isStopped ? `stopped after ${secs()}` : `✗ ${argv[0]}: ${error instanceof Error ? error.message : String(error)} (is it installed and on PATH?)`, tag) } finally { cap.cancel() term.runs.delete(agent) diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts index 2965dfce06..2581b49b40 100644 --- a/plugins/ruflo-console/hooks/register.ts +++ b/plugins/ruflo-console/hooks/register.ts @@ -178,7 +178,11 @@ export const register: Register = (on, raw: PluginOptions) => { bound.markFrame(e.requestId, e.props.isWorking && mark !== null) - return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open(false)) + // A click on a part opens the console on its view, with the keys, so the person can act there at once. + return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open(false), view => { + bound.setView(view) + void bound.open(true) + }) }) /** The band's mark pulses during a turn: a redraw at its start, and the loop stopped at its end, whatever redraws. */ diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts index b938cc908c..03cd2da70f 100644 --- a/plugins/ruflo-console/hooks/state.ts +++ b/plugins/ruflo-console/hooks/state.ts @@ -115,10 +115,11 @@ export type HarnessId = 'codex' | 'claude' | 'ruflo' | 'swarm' export type AgentId = Exclude /** - * One line of the terminal's scrollback: what was asked (`in`), what came back, a tool the agent used (`tool`), or + * One line of the terminal's scrollback: what was asked (`in`), an agent starting its answer (`head`), what came back, + * a tool it used (`tool`), how its turn ended (`end`), or * the console's own note (`sys`); `from` names the agent when more than one is talking. */ -export type TermLine = { kind: 'in' | 'out' | 'err' | 'sys' | 'tool'; text: string; from?: AgentId } +export type TermLine = { kind: 'in' | 'head' | 'out' | 'err' | 'sys' | 'tool' | 'end'; text: string; from?: AgentId } /** A conversation kept per project: codex's thread id, claude's session id, so a follow-up resumes it. */ export type TermSessions = { codex?: string; claude?: string } @@ -198,6 +199,9 @@ export type State = { /** Turns and spend this session, as the agents reported them. */ turns: { codex: number; claude: number } costUsd: number + /** Screen rows scrolled up from the newest (0 follows the tail), and how many lines arrived while scrolled up. */ + scroll: number + unseen: number /** The text the last Enter asked about: Enter on the same text again confirms it. */ asked: { key: string; label: string } | null } @@ -242,7 +246,7 @@ export function newState(raw: PluginOptions | undefined): State { isActing: false, isRefreshing: false, barDrawnAtMs: 0, - terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, asked: null }, + terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null }, timers: new Map(), stats: { renders: [], refreshes: [], frames: [] }, } diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.ts index 719ca9cc8b..2f05f35df5 100644 --- a/plugins/ruflo-console/hooks/views/bar.ts +++ b/plugins/ruflo-console/hooks/views/bar.ts @@ -9,12 +9,13 @@ import type { RenderElement } from 'claude-code' import { alertsOf, approvalsOf } from '../data/alerts' import { agentLabels } from '../data/parse' -import type { State } from '../state' +import type { State, ViewId } from '../state' import { ago, clip, type Kit } from './common' export const BAR_KEY = 'mark' -export type BarPart = { text: string; tone: 'attention' | 'live' | 'plain' } +/** One part of the band: its words, how loud, and the view a click on it opens. */ +export type BarPart = { text: string; tone: 'attention' | 'live' | 'plain'; go?: ViewId } /** How long an event counts as "now" on the band. */ const FRESH_MS = 60_000 @@ -34,10 +35,10 @@ function workingParts(state: State, nowMs: number): BarPart[] { const what = task !== undefined ? ` on ${clip(task.description || task.type, 40)}` : ' working' const span = state.statusLog.get(agent.id)?.at(-1)?.atMs - return { text: `▶ ${labels.get(agent.id) ?? agent.type}${what}${since(span, nowMs)}`, tone: 'live' as const } + return { text: `▶ ${labels.get(agent.id) ?? agent.type}${what}${since(span, nowMs)}`, tone: 'live' as const, go: 'swarm' as const } }) - if (busy.length > 2) parts.push({ text: `+${busy.length - 2} more working`, tone: 'live' }) + if (busy.length > 2) parts.push({ text: `+${busy.length - 2} more working`, tone: 'live', go: 'swarm' }) return parts } @@ -55,24 +56,24 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] { const approvals = approvalsOf(state).length const alerts = alertsOf(state, nowMs, state.loadedAtMs).filter(alert => alert.level !== 'info').length - if (approvals > 0) parts.push({ text: `${approvals} to approve (q)`, tone: 'attention' }) - if (alerts > 0) parts.push({ text: `⚠ ${alerts} alert${alerts === 1 ? '' : 's'}`, tone: 'attention' }) + if (approvals > 0) parts.push({ text: `${approvals} to approve (q)`, tone: 'attention', go: 'approvals' }) + if (alerts > 0) parts.push({ text: `⚠ ${alerts} alert${alerts === 1 ? '' : 's'}`, tone: 'attention', go: 'overview' }) // What is happening now: agents at work, the AI terminal's runs, and the newest event while it is fresh. parts.push(...workingParts(state, nowMs)) - for (const [agent, run] of state.terminal.runs) parts.push({ text: `💻 ${agent} answering${since(run.startedAtMs, nowMs)}`, tone: 'live' }) + for (const [agent, run] of state.terminal.runs) parts.push({ text: `💻 ${agent} answering${since(run.startedAtMs, nowMs)}`, tone: 'live', go: 'terminal' }) const latest = state.events.at(-1) const isFresh = latest !== undefined && nowMs - latest.atMs < FRESH_MS - if (isFresh) parts.push({ text: `${clip(latest.text, 44)} ·${since(latest.atMs, nowMs)} ago`, tone: 'plain' }) + if (isFresh) parts.push({ text: `${clip(latest.text, 44)} ·${since(latest.atMs, nowMs)} ago`, tone: 'plain', go: 'events' }) // Nothing moving: say so, with how many agents stand ready and when something last happened. if (!parts.some(part => part.tone === 'live') && !isFresh && snap?.swarm != null) { const ready = snap.agents.length - parts.push({ text: `${ready > 0 ? `idle · ${ready} agent${ready === 1 ? '' : 's'} ready` : 'swarm, no agents'}${latest !== undefined ? ` · last activity${since(latest.atMs, nowMs)} ago` : ''}`, tone: 'plain' }) + parts.push({ text: `${ready > 0 ? `idle · ${ready} agent${ready === 1 ? '' : 's'} ready` : 'swarm, no agents'}${latest !== undefined ? ` · last activity${since(latest.atMs, nowMs)} ago` : ''}`, tone: 'plain', go: 'swarm' }) } // Standing context last: claims held, this session's spend. @@ -81,10 +82,10 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] { if (claims.length > 0) { const stealable = claims.filter(claim => claim.isStealable).length - parts.push({ text: `${claims.length} claim${claims.length === 1 ? '' : 's'}${stealable > 0 ? ` (${stealable} stealable)` : ''}`, tone: 'plain' }) + parts.push({ text: `${claims.length} claim${claims.length === 1 ? '' : 's'}${stealable > 0 ? ` (${stealable} stealable)` : ''}`, tone: 'plain', go: 'claims' }) } - if (state.usage?.costUsd !== undefined && state.usage.costUsd >= 0.01) parts.push({ text: `${money(state.usage.costUsd)} this session`, tone: 'plain' }) + if (state.usage?.costUsd !== undefined && state.usage.costUsd >= 0.01) parts.push({ text: `${money(state.usage.costUsd)} this session`, tone: 'plain', go: 'cost' }) return parts } @@ -94,7 +95,11 @@ export function barText(state: State, nowMs: number = Date.now()): string { return ['ruflo', ...barParts(state, nowMs).map(part => part.text)].join(' · ') } -export function barView(kit: Kit, state: State, columns: number, mark: RenderElement | null, onOpen: () => void): RenderElement { +/** + * The band. Each part is a link: a click opens the console on the view it is about (approvals, the swarm, the + * terminal, the event stream, claims, cost). `onGo` opens the console there; `onOpen` opens it as it was. + */ +export function barView(kit: Kit, state: State, columns: number, mark: RenderElement | null, onOpen: () => void, onGo?: (view: ViewId) => void): RenderElement { // A stale marketplace clone is one of the alerts, so it already turns the band's attention part on. const parts = barParts(state) let room = Math.max(8, columns - (state.pane.isOpen ? 4 : 22)) @@ -102,12 +107,24 @@ export function barView(kit: Kit, state: State, columns: number, mark: RenderEle room -= 5 - for (const part of parts) { - const words = ` · ${part.text}` + for (const [i, part] of parts.entries()) { + const words = part.text - if (room <= 3) break - children.push(kit.Text({ wrap: 'truncate-end', ...(part.tone === 'attention' ? { color: 'warning' } : part.tone === 'live' ? { color: 'success' } : { dimColor: true }), children: clip(words, room) })) - room -= words.length + if (room <= 6) break + children.push(kit.Text({ dimColor: true, children: ' · ' })) + + const go = part.go + + // Attention and live parts keep their colour; a part with somewhere to go is a button to it. + if (go !== undefined && onGo !== undefined && part.tone === 'plain') { + children.push(kit.Button({ key: `band-${i}`, label: clip(words, room - 3), plain: true, dimColor: true, onPress: () => onGo(go) })) + } else if (go !== undefined && onGo !== undefined) { + children.push(kit.Button({ key: `band-${i}`, label: clip(words, room - 3), plain: true, onPress: () => onGo(go) })) + } else { + children.push(kit.Text({ wrap: 'truncate-end', ...(part.tone === 'attention' ? { color: 'warning' } : part.tone === 'live' ? { color: 'success' } : { dimColor: true }), children: clip(words, room - 3) })) + } + + room -= words.length + 3 } if (!state.pane.isOpen) children.push(kit.Text({ children: ' ' }), kit.Button({ key: 'open-console', label: 'open console', plain: true, onPress: onOpen })) diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts index b1b063e35b..93ec6e1c05 100644 --- a/plugins/ruflo-console/hooks/views/common.ts +++ b/plugins/ruflo-console/hooks/views/common.ts @@ -40,7 +40,7 @@ export type Actions = { /** The terminal view: pick a harness, follow the field, ask to run its text, stop the run, clear the scrollback. */ /** The main menu's prompt: a key or a name takes the person to that area. */ menu: (text: string) => void - term: { harness: (id: HarnessId) => void; draft: (text: string) => void; submit: (text: string) => void; stop: () => void; fresh: () => void; clear: () => void; load: (id: HarnessId, text: string) => void } + term: { harness: (id: HarnessId) => void; draft: (text: string) => void; submit: (text: string) => void; stop: () => void; fresh: () => void; clear: () => void; load: (id: HarnessId, text: string) => void; /** Moves the window up (positive) or down by screen rows. */ scroll: (by: number) => void; /** Puts an earlier question back in the field. */ reuse: (text: string) => void } } export type Ctx = { diff --git a/plugins/ruflo-console/hooks/views/menu.ts b/plugins/ruflo-console/hooks/views/menu.ts index ef4041805c..dd90881539 100644 --- a/plugins/ruflo-console/hooks/views/menu.ts +++ b/plugins/ruflo-console/hooks/views/menu.ts @@ -122,9 +122,10 @@ export function menuView(ctx: Ctx): RenderElement { // The status bar under the box: the line, then what is live in this project, then how long the board has been open. const online = mmss(nowMs - (state.pane.bootAtMs > 0 ? state.pane.bootAtMs : state.loadedAtMs)) - const facts = barParts(state, nowMs).map(part => part.text) - const status = [state.snapshot?.isRufloProject === true ? 'Registered' : 'Unregistered', 'ANSI-BBS', '115200·N81 FDX', ...facts.slice(0, 3)].join(' │ ') + const facts = barParts(state, nowMs).slice(0, 3) + const line = ` ${state.snapshot?.isRufloProject === true ? 'Registered' : 'Unregistered'} │ ANSI-BBS │ 115200·N81 FDX` const right = ` Online ${online} ` + let room = Math.max(4, ctx.columns - right.length - line.length) rows.push(text(ctx, ' ')) rows.push( @@ -133,7 +134,23 @@ export function menuView(ctx: Ctx): RenderElement { backgroundColor: isBbs() ? '#8b1a1a' : undefined, key: 'menu-status', children: [ - ctx.kit.Text({ bold: true, color: '#ffd319', wrap: 'truncate-end', children: clip(` ${status}`, Math.max(4, ctx.columns - right.length)).padEnd(Math.max(0, ctx.columns - right.length)) }), + ctx.kit.Text({ bold: true, color: '#ffd319', children: line }), + // The live facts are links: a click goes to the view each is about. + ...facts.flatMap((part, i) => { + if (room <= 6) return [] + + const label = clip(part.text, room - 3) + + room -= label.length + 3 + + return [ + ctx.kit.Text({ bold: true, color: '#ffd319', children: ' │ ' }), + part.go !== undefined + ? ctx.kit.Button({ key: `status-${i}`, label, plain: true, onPress: () => ctx.act.view(part.go as ViewId) }) + : ctx.kit.Text({ bold: true, color: '#ffd319', children: label }), + ] + }), + ctx.kit.Box({ flexGrow: 1, key: 'status-gap', children: [ctx.kit.Text({ children: ' ' })] }), ctx.kit.Text({ bold: true, color: '#ffd319', children: right }), ], }), diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts index c6f33fdf4e..3f6f9e1628 100644 --- a/plugins/ruflo-console/hooks/views/pane.ts +++ b/plugins/ruflo-console/hooks/views/pane.ts @@ -26,6 +26,9 @@ import { terminalView } from './terminal' import { xruvView } from './xruv' export const NARROW = 44 + +/** The networks the Wildcat strip names, each with the view a click on it opens. */ +const NETWORKS: readonly (readonly [string, ViewId])[] = [['x.ruv.io', 'xruv'], ['relay.ruv.io', 'xruv'], ['agentbbs', 'federation'], ['mcp', 'plugins'], ['claude code', 'terminal']] /** Width from which every tab spells its name beside its emoji (the 1-9 row is about 128 columns with names). */ const WIDE_TABS = 140 @@ -186,9 +189,13 @@ function wildcat(ctx: Ctx): { strip: RenderElement[]; art: RenderElement[] } { ctx.kit.Text({ color: THEME.info, children: 'x.ruv.io ' }), ctx.kit.Text({ bold: true, color: THEME.ok, children: clip('AGENTS WELCOME.', Math.max(4, ctx.columns - 16)) }), ], 'welcome'), + // Each network is a link to the view that shows it. row(ctx, [ ctx.kit.Text({ color: THEME.head, children: 'NETWORKS: ' }), - ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip('x.ruv.io * relay.ruv.io * agentbbs * mcp * claude code', Math.max(4, ctx.columns - 10)) }), + ...NETWORKS.flatMap(([name, view], i) => [ + ...(i > 0 ? [ctx.kit.Text({ color: THEME.info, dimColor: true, children: ' * ' })] : []), + ctx.kit.Button({ key: `net-${view}-${i}`, label: name, plain: true, onPress: () => ctx.act.view(view) }), + ]), ], 'networks'), ], art: art !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(art.toRaster('title'))] : [], diff --git a/plugins/ruflo-console/hooks/views/terminal.ts b/plugins/ruflo-console/hooks/views/terminal.ts index 8bdc4cf1be..fb1ba95d77 100644 --- a/plugins/ruflo-console/hooks/views/terminal.ts +++ b/plugins/ruflo-console/hooks/views/terminal.ts @@ -2,18 +2,15 @@ import type { RenderElement } from 'claude-code' import { HARNESSES, harnessOf, isLive } from '../harness' import type { AgentId, TermLine } from '../state' -import { button, col, row, rule, text, THEME, type Ctx } from './common' +import { button, clip, col, row, rule, text, THEME, type Ctx } from './common' -/** Screen rows of scrollback under the picker: the newest, wrapped to the pane, so an answer reads like a chat. */ +/** Screen rows of conversation when the pane's height is unknown; a known height gives the window what is left. */ export const TERM_ROWS = 18 -const TAG: Record = { - codex: { text: 'codex ', color: '#00afd7' }, - claude: { text: 'claude', color: '#d7af00' }, - ruflo: { text: 'ruflo ', color: '#d7005f' }, -} +const COLOR: Record = { codex: '#00afd7', claude: '#d7af00', ruflo: '#d7005f' } +const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' -/** A line folded to the pane's width, so a long answer wraps instead of being cut at the edge. */ +/** A line folded to the window's width, so a long answer wraps instead of being cut at the edge. */ function fold(line: string, width: number): string[] { if (line.length <= width) return [line === '' ? ' ' : line] @@ -33,18 +30,78 @@ function fold(line: string, width: number): string[] { return out } +/** One screen row of the conversation: a gutter in the agent's colour, then the text in its style. */ +type ScreenRow = { gutter: string; gutterColor: string; text: string; style: Record; reuse?: string } + /** - * The second terminal: pick a harness (c codex, l claude, v swarm = both, u ruflo) and talk to it. Each agent keeps - * its conversation per project, so a follow-up carries the context; the first message of a session is asked (Enter - * shows the command, Enter again runs it), later ones go as you press Enter. Answers type out as they stream in, with - * the tools each agent runs; s stops, o starts a new session, z clears the screen. + * The conversation as screen rows. Each question opens a framed turn (╭─ you), each agent's answer runs down a gutter + * in its colour (├─ codex … │ … ╰─ ✓ 3 s · $0.01), with a light reading of markdown: headings bold, bullets as •, and + * fenced code framed and tinted. Tool calls are dim ⚙ rows. A question's rows can be clicked to ask it again. + */ +export function screenOf(lines: readonly TermLine[], width: number): ScreenRow[] { + const rows: ScreenRow[] = [] + const inFence = new Map() + + for (const line of lines) { + const color = line.from !== undefined ? COLOR[line.from] : THEME.head + const at = (gutter: string, body: string, style: Record = {}, reuse?: string) => { + for (const part of fold(body, width)) rows.push({ gutter, gutterColor: color, text: part, style, ...(reuse !== undefined && { reuse }) }) + } + + switch (line.kind) { + case 'in': + rows.push({ gutter: ' ', gutterColor: color, text: ' ', style: {} }) + rows.push({ gutter: '╭─ ', gutterColor: THEME.head, text: `you${line.from !== undefined ? ` → ${line.from}` : ''}`, style: { bold: true, color: THEME.head } }) + at('│ ', line.text, { bold: true }, line.text) + break + case 'head': + rows.push({ gutter: '├─ ', gutterColor: color, text: line.text, style: { bold: true, color } }) + break + case 'out': { + const key = line.from ?? '' + const isFence = /^\s*```/.test(line.text) + + if (isFence) { + inFence.set(key, !(inFence.get(key) ?? false)) + rows.push({ gutter: '│ ', gutterColor: color, text: inFence.get(key) === true ? `┌┄ ${line.text.replace(/`/g, '').trim() || 'code'}` : '└┄', style: { dimColor: true } }) + } else if (inFence.get(key) === true) { + at('│ ', `┆ ${line.text}`, { color: THEME.info }) + } else if (/^\s*#{1,6}\s/.test(line.text)) { + at('│ ', line.text.replace(/^\s*#{1,6}\s/, ''), { bold: true, color }) + } else { + at('│ ', line.text.replace(/^(\s*)[-*]\s/, '$1• ')) + } + break + } + case 'tool': + // The stream gives each tool row its own mark (⚙ $ ✎ 🔎 ☐); output under a command arrives indented. + at('│ ', line.text, { dimColor: true, color: THEME.info }) + break + case 'err': + at('│ ', `! ${line.text.trim()}`, { color: THEME.warn }) + break + case 'end': + rows.push({ gutter: '╰─ ', gutterColor: color, text: line.text, style: line.text.startsWith('✗') ? { color: THEME.bad } : { color: THEME.ok } }) + break + default: + at(' ', line.text, { dimColor: true, italic: true }) + } + } + + return rows +} + +/** + * The AI terminal: pick a harness, type, and talk. The conversation scrolls in a window (▲ older, ▼ newer, ⤓ end, or + * /up /down /end in the field); while scrolled up, new output waits below and is counted instead of pulling the view + * down. Each agent keeps its session per project, so follow-ups carry the context; the first message of a session + * shows its command and Enter again runs it. Answers stream in as they are written. */ export function terminalView(ctx: Ctx): RenderElement { const { state, nowMs } = ctx const term = state.terminal const harness = harnessOf(term.harness) - const running = [...term.runs.entries()].map(([agent, run]) => `${agent} ${Math.round((nowMs - run.startedAtMs) / 1000)}s`) - const rows: RenderElement[] = [rule(ctx, 'Harness', running.length > 0 ? `answering: ${running.join(' · ')}` : term.costUsd > 0 ? `$${term.costUsd.toFixed(2)} this session` : 'idle')] + const rows: RenderElement[] = [rule(ctx, 'Harness', term.costUsd > 0 ? `$${term.costUsd.toFixed(2)} this session` : 'pick one, or /codex /claude /swarm /ruflo')] rows.push( ctx.kit.Box({ @@ -54,13 +111,12 @@ export function terminalView(ctx: Ctx): RenderElement { children: HARNESSES.map(entry => entry.id === term.harness ? ctx.kit.Box({ key: `term-${entry.id}`, children: [ctx.kit.Text({ bold: true, color: THEME.head, children: `[${entry.key}: ${entry.label.toUpperCase()}]` })] }) - : ctx.kit.Button({ key: `term-${entry.id}`, label: entry.label, hotkey: entry.key, plain: true, dimColor: true, onPress: () => ctx.act.term.harness(entry.id) }), + : ctx.kit.Button({ key: `term-${entry.id}`, label: entry.label, hotkey: entry.key, onPress: () => ctx.act.term.harness(entry.id) }), ), }), ) rows.push(text(ctx, ` ${harness.about}`, { color: THEME.info })) - // Where each conversation stands: new, or resuming a thread with so many turns behind it. const sessions = harness.agents .filter((agent): agent is 'codex' | 'claude' => agent !== 'ruflo') .map(agent => { @@ -70,42 +126,53 @@ export function terminalView(ctx: Ctx): RenderElement { }) if (sessions.length > 0) rows.push(text(ctx, ` ${sessions.join(' ')}`, { dimColor: true })) - rows.push(rule(ctx, 'Screen', `${term.lines.length} lines`)) - const width = Math.max(10, ctx.columns - 8) - const screen: { line: TermLine; text: string; isFirst: boolean }[] = [] + // The window: the newest screen rows, or `scroll` rows up from them. + const width = Math.max(10, ctx.columns - 6) + const screen = screenOf(term.lines, width) + const height = state.pane.rows > 0 ? Math.max(8, Math.min(48, state.pane.rows - 26)) : TERM_ROWS + const maxScroll = Math.max(0, screen.length - height) + const scroll = Math.min(term.scroll, maxScroll) + const start = Math.max(0, screen.length - height - scroll) + const shown = screen.slice(start, start + height) - for (const line of term.lines) fold(line.text, width).forEach((part, i) => screen.push({ line, text: part, isFirst: i === 0 })) + rows.push(rule(ctx, 'Conversation', screen.length === 0 ? 'empty' : `rows ${start + 1}–${start + shown.length} of ${screen.length}`)) - if (screen.length === 0) { - rows.push(text(ctx, ` nothing yet: type below and press Enter. The first message of a session shows its command; Enter again runs it.`, { dimColor: true })) + if (shown.length === 0) rows.push(text(ctx, ' nothing yet: type below and press Enter. The first message of a session shows its command; Enter again runs it.', { dimColor: true })) + + for (const [i, entry] of shown.entries()) { + const body = entry.reuse !== undefined + ? ctx.kit.Button({ key: `term-reuse-${start + i}`, label: clip(entry.text, width), plain: true, onPress: () => ctx.act.term.reuse(entry.reuse as string) }) + : ctx.kit.Text({ wrap: 'truncate-end', ...entry.style, children: clip(entry.text, width) }) + + rows.push(row(ctx, [ctx.kit.Text({ color: entry.gutterColor, children: entry.gutter }), body], `term-row-${start + i}`)) } - for (const { line, text: shown, isFirst } of screen.slice(-TERM_ROWS)) { - const props = line.kind === 'in' ? { bold: true, color: THEME.head } : line.kind === 'err' ? { color: THEME.warn } : line.kind === 'sys' ? { dimColor: true, italic: true } : line.kind === 'tool' ? { color: THEME.info, dimColor: true } : {} - const tag = line.from !== undefined ? TAG[line.from] : undefined + // Live: each agent still answering, with a spinner that turns only while it writes back. + for (const [agent, run] of term.runs) { + const secs = Math.round((nowMs - run.startedAtMs) / 1000) - rows.push( - row(ctx, [ - ctx.kit.Text({ bold: true, color: tag?.color ?? THEME.info, children: tag === undefined ? '' : isFirst ? `${tag.text}│ ` : ' │ ' }), - ctx.kit.Text({ wrap: 'truncate-end', ...props, children: shown }), - ]), - ) + rows.push(text(ctx, `${SPIN[Math.floor(nowMs / 100) % SPIN.length]} ${agent} is answering · ${secs}s`, { color: COLOR[agent] })) } - if (term.runs.size > 0) { - // Data, not decoration: the cursor blinks only while an agent is writing back. - rows.push(text(ctx, Math.floor(nowMs / 500) % 2 === 0 ? '█' : ' ', { color: THEME.ok })) - } - - rows.push(text(ctx, ' ')) + // Scrolling, by mouse or from the field. + rows.push( + row(ctx, [ + ...(scroll < maxScroll ? [button(ctx, 'term-up', '▲ older', () => ctx.act.term.scroll(height - 2))] : []), + ...(scroll > 0 ? [button(ctx, 'term-down', '▼ newer', () => ctx.act.term.scroll(-(height - 2))), button(ctx, 'term-end', term.unseen > 0 ? `⤓ ${term.unseen} new` : '⤓ end', () => ctx.act.term.scroll(-scroll))] : []), + ...(term.runs.size > 0 ? [button(ctx, 'term-stop', '■ Stop', ctx.act.term.stop)] : []), + ...(harness.id !== 'ruflo' ? [button(ctx, 'term-new', '✚ New session', ctx.act.term.fresh)] : []), + button(ctx, 'term-clear', '⌫ Clear', ctx.act.term.clear), + ]), + ) + rows.push(rule(ctx, `Ask ${harness.label}`, isLive(state) ? 'live: Enter sends' : 'Enter shows the command, Enter again runs it')) if (ctx.kit.Input !== undefined) { rows.push( ctx.kit.Input({ key: 'term-input', - label: harness.label, - placeholder: harness.id === 'ruflo' ? 'a ruflo command: swarm status, memory search -q auth …' : isLive(state) ? `follow up with ${harness.label}… (/new starts over)` : `ask ${harness.label} about this project…`, + label: '›', + placeholder: harness.id === 'ruflo' ? 'a ruflo command: swarm status, memory search -q auth …' : isLive(state) ? `follow up with ${harness.label}…` : `ask ${harness.label} about this project…`, value: term.draft, submitLabel: isLive(state) ? 'send' : 'ask', onInput: value => ctx.act.term.draft(value), @@ -116,14 +183,7 @@ export function terminalView(ctx: Ctx): RenderElement { rows.push(text(ctx, 'this surface has no text field: the terminal needs Claude Code in a terminal', { dimColor: true })) } - rows.push( - row(ctx, [ - ...(term.runs.size > 0 ? [button(ctx, 'term-stop', 'Stop', ctx.act.term.stop, { hotkey: 's' })] : []), - ...(harness.id !== 'ruflo' ? [button(ctx, 'term-new', 'New session', ctx.act.term.fresh, { hotkey: 'o' })] : []), - button(ctx, 'term-clear', 'Clear', ctx.act.term.clear, { hotkey: 'z' }), - text(ctx, isLive(state) ? ' live: Enter sends · /codex /claude /swarm /ruflo switch · /new' : ' Enter shows the command, Enter again runs it · /codex /claude /swarm /ruflo switch', { dimColor: true }), - ]), - ) + rows.push(text(ctx, ' /codex /claude /swarm /ruflo switch · /new starts over · /up /down /end scroll · click a question to ask it again', { dimColor: true })) return col(ctx, rows, 'terminal') } diff --git a/plugins/ruflo-console/tests/band.spec.ts b/plugins/ruflo-console/tests/band.spec.ts index 2bd00ea657..21a499b780 100644 --- a/plugins/ruflo-console/tests/band.spec.ts +++ b/plugins/ruflo-console/tests/band.spec.ts @@ -65,7 +65,7 @@ describe('band', () => { it('a stale marketplace clone shows as an alert, not as a separate word', async () => { const state = await capturedState(['ruflo-core', 'ruflo-swarm']) - expect(barParts(state, 0).find(part => part.text.startsWith('⚠'))).toEqual({ text: '⚠ 1 alert', tone: 'attention' }) + expect(barParts(state, 0).find(part => part.text.startsWith('⚠'))).toEqual({ text: '⚠ 1 alert', tone: 'attention', go: 'overview' }) expect(barText(state, 0)).not.toContain('STALE') }) diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.ts index 81ce7e4a3b..e216bb554e 100644 --- a/plugins/ruflo-console/tests/behaviour.test.ts +++ b/plugins/ruflo-console/tests/behaviour.test.ts @@ -247,6 +247,24 @@ describe('behaviour', () => { expect(world.blits.length).toBe(stopped) }) + test('the band is clickable: a part opens the console on the view it is about, with the keys', { options: { boot: false } }, async ($, on) => { + fakeRuflo().register(on, {}) + const world = worldOf(on, RUFLO_FILES) + + mock.clock(on) + on('ui.render', () => ({ type: 'Text', children: ['engine'] }) as never) + await $.session.start(SESSION) + await $.command.run(command('status')) + + const band = await $.ui.mount({ ...BAND, plugin: PLUGIN }) + + // The first part is "3 to approve (q)". + await band.press({ key: 'band-0' }) + expect(world.openArgs.at(-1)).toMatchObject({ id: 'ruflo-console', focus: true }) + expect(world.stored.get('ruflo-console/ui:/work')).toMatchObject({ view: 'approvals' }) + await band.unmount() + }) + test('on the desktop surface, which has no Raster, every picture becomes a text line and the tree is accepted', { options: { boot: false } }, async ($, on) => { worldOf(on, RUFLO_FILES) mock.clock(on) diff --git a/plugins/ruflo-console/tests/terminal.spec.ts b/plugins/ruflo-console/tests/terminal.spec.ts index a93027d91a..d89aee59f8 100644 --- a/plugins/ruflo-console/tests/terminal.spec.ts +++ b/plugins/ruflo-console/tests/terminal.spec.ts @@ -10,6 +10,7 @@ import { argvOf, harnessSpec, isLive, newSession, send, termText, whyNotRun } fr import type { Host } from '../hooks/host' import { newState, restoreSessions, type State } from '../hooks/state' import { claudeParser, codexEvent, eventOf, type Sink } from '../hooks/stream' +import { screenOf } from '../hooks/views/terminal' type Chunk = { stream: 'stdout' | 'stderr'; text: string } @@ -117,7 +118,7 @@ describe('terminal sessions', () => { send(state, host, 'where is auth?') await settled(state) - expect(shown(state)).toEqual(['in:codex> where is auth?', 'tool:$ rg -n auth src', 'out:Auth lives in src/auth.ts.', expect.stringMatching(/^sys:✓ \d+ s · 940 tokens$/)]) + expect(shown(state)).toEqual(['codex in:where is auth?', 'codex head:codex', 'codex tool:$ rg -n auth src', 'codex out:Auth lives in src/auth.ts.', expect.stringMatching(/^codex end:✓ \d+ s · 940 tokens$/)]) expect(state.terminal.sessions.codex).toBe('01a0fe1f-b077-7793-9612-f134bd61bc85') expect(stored.get('ruflo-console/term:/work')).toEqual({ codex: '01a0fe1f-b077-7793-9612-f134bd61bc85' }) expect(state.terminal.turns.codex).toBe(1) @@ -132,7 +133,7 @@ describe('terminal sessions', () => { send(state, host, 'hi') await settled(state) - expect(shown(state)).toEqual(['in:claude> hi', 'out:Hello there', 'out:second', 'tool:⚙ Read src/auth.ts', expect.stringMatching(/^sys:✓ \d+ s · \$0\.012$/)]) + expect(shown(state)).toEqual(['claude in:hi', 'claude head:claude', 'claude out:Hello there', 'claude out:second', 'claude tool:⚙ Read src/auth.ts', expect.stringMatching(/^claude end:✓ \d+ s · \$0\.012$/)]) expect(state.terminal.sessions.claude).toBe('6b1c2d3e-0000-4000-8000-000000000001') expect(state.terminal.costUsd).toBeCloseTo(0.0123) }) @@ -186,6 +187,33 @@ describe('terminal sessions', () => { }) }) +describe('terminal screen', () => { + it('frames each turn, reads light markdown, and lets a question be clicked to ask again', () => { + const rows = screenOf( + [ + { kind: 'in', text: 'explain auth', from: 'claude' }, + { kind: 'head', text: 'claude', from: 'claude' }, + { kind: 'out', text: '## Auth', from: 'claude' }, + { kind: 'out', text: '- tokens expire', from: 'claude' }, + { kind: 'out', text: '```ts', from: 'claude' }, + { kind: 'out', text: 'const a = 1', from: 'claude' }, + { kind: 'out', text: '```', from: 'claude' }, + { kind: 'end', text: '✓ 3 s', from: 'claude' }, + ], + 60, + ) + + expect(rows.map(entry => `${entry.gutter}${entry.text}`)).toEqual([' ', '╭─ you → claude', '│ explain auth', '├─ claude', '│ Auth', '│ • tokens expire', '│ ┌┄ ts', '│ ┆ const a = 1', '│ └┄', '╰─ ✓ 3 s']) + expect(rows[2]?.reuse).toBe('explain auth') + }) + + it('wraps a long answer at word boundaries instead of cutting it', () => { + const rows = screenOf([{ kind: 'out', text: 'one two three four five six seven', from: 'codex' }], 14) + + expect(rows.map(entry => entry.text)).toEqual(['one two three', 'four five six', 'seven']) + }) +}) + describe('x.ruv.io registry probe', () => { it('asks the network only with federationNetwork on, and keeps the join steps and rooms as capped data', () => { expect(registryProbe.isNetwork).toBe(true)