feat(ruflo-console): an AI terminal with sessions, live streaming and a codex+claude swarm; neon materialise and glitch (0.6.0)

- Sessions: each agent keeps a conversation per project, so a follow-up carries the context.
  - codex: by its thread id, via `codex exec --json` then `codex exec resume <id> --json`, read-only throughout.
  - claude: by a session id the console picks, via `--session-id` then `--resume`, in plan mode with $1 a turn.
  - Ids are saved per project, and only id-shaped strings come back.
- Streaming (stream.ts):
  - codex JSON events show commands, file changes, tools and the answer.
  - claude stream-json types the answer out from deltas, shows tool calls, and counts the cost.
  - If a run ends with events but no answer drawn, the terminal says the format may have changed.
- Concurrency: codex and claude run side by side.
  - The swarm harness (v) sends one question to both, and their lines are tagged.
  - s stops all runs.
- Confirm once per session: the first message shows the exact command(s), and Enter again runs them. After that the session is live and Enter sends. /new or o starts over. ruflo commands are still asked every time.
- Scrollback wraps to the pane instead of truncating.
- Neon boot: each tube materialises out of random letters as it strikes, and the lit sign now and then glitches (a row slips, cells flash to noise).

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ruv committed 2026-10-02 15:50:04 -04:00
1 parent fbeada07e6
commit f45c6712c1
13 files changed
+697 -188

No files matched your search

@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, an x.ruv.io federation board, a second terminal for codex, claude and the ruflo CLI (each run confirmed), agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a; no network by default.",
"version": "0.5.0",
"version": "0.6.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
+30 -4
View File
@@ -4,7 +4,7 @@
*/
import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot } from './actions'
import { EVENT_KINDS } from './data/events'
import { harnessSpec, whyNotRun } from './harness'
import { harnessSpec, isLive, newSession, send, whyNotRun } from './harness'
import { plain } from './data/parse'
import type { Host } from './host'
import { filterPalette, paletteEntries } from './palette'
@@ -132,12 +132,35 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
draft: text => {
state.terminal.draft = text
},
// Enter asks: the confirm row shows the exact command. Enter again on the same text runs it, as a terminal
// would; the field keeps the keys throughout (Esc would hand them back to the prompt). y and n work too.
// In a live session Enter sends, as in a chat. Otherwise Enter asks: the confirm row shows the exact command,
// and Enter again on the same text runs it (the field keeps the keys throughout; y and n work too).
// `/new` in the field starts a fresh session.
submit: text => {
const key = `${state.terminal.harness}\u0000${text.trim()}`
const asked = state.terminal.asked
if (text.trim() === '/new') {
state.terminal.draft = ''
newSession(state, host)
return
}
if (isLive(state)) {
const why = whyNotRun(state, text)
if (why !== null) {
runner.ask(null, why)
return
}
state.terminal.draft = ''
send(state, host, text)
return
}
if (asked !== null && asked.key === key && state.pending?.label === asked.label) {
state.terminal.asked = null
state.terminal.draft = ''
@@ -153,7 +176,10 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
runner.ask(spec, whyNotRun(state, text) ?? 'nothing to run')
state.terminal.asked = spec !== null ? { key, label: spec.label } : null
},
stop: () => state.terminal.running?.stop(),
stop: () => {
for (const run of state.terminal.runs.values()) run.stop()
},
fresh: () => newSession(state, host),
clear: () => {
state.terminal.lines = []
host.invalidate()
+1 -1
View File
@@ -106,7 +106,7 @@ export const HELP = [
'',
'Pane keys (while it holds the keyboard: /ruflo opens it with the keys, or click it; ctrl+x tab reaches the band, not the pane)',
' 0 main menu · 1-9 views · g timeline · q approvals · e events · m missions · w x.ruv.io · i terminal · p palette · x actions for the selection',
' terminal: c codex · l claude · u ruflo · in the field Enter shows the command, Enter again runs it · s stop · z clear',
' terminal: c codex · l claude · v swarm (both) · u ruflo · sessions remember the conversation per project; the first message asks, then Enter sends · /new or o new session · s stop · z clear',
' j/k select · d drill in · b back · r refresh · h help · f event filter · y/n confirm',
' Esc: a pane /ruflo opened closes; one that opened by itself (panel=auto) only hands the keys back. ✕ or /ruflo close closes either',
' (? and Enter cannot be pane hotkeys in this Claude Code build: use h, and d to drill in)',
+40 -1
View File
@@ -120,6 +120,32 @@ function power(tube: Tube, age: number, isAnimated: boolean): number {
return 0.9 + 0.1 * Math.sin(age / 210 + tube.seed)
}
const NOISE = '#%@$&*+=?!/\\<>[]{}01'
/**
* Now and then, once the sign is lit, a glitch: for ~110 ms one row slips one or two cells sideways and a few of its
* cells flash to random letters, the way a bad line garbles an ANSI screen.
*/
function glitch(grid: Grid, age: number): void {
const slot = Math.floor(age / 110)
if (age < 1_600 || hash(slot, 97) % 11 !== 0) return
const y = 1 + (hash(slot, 3) % (grid.rows - 2))
const shift = hash(slot, 5) % 2 === 0 ? 1 + (hash(slot, 9) % 2) : -1 - (hash(slot, 9) % 2)
const row = grid.cells.slice(y * grid.columns * 3, (y + 1) * grid.columns * 3)
for (let x = 0; x < grid.columns; x++) {
const from = Math.min(grid.columns - 1, Math.max(0, x - shift))
const at = (y * grid.columns + x) * 3
grid.cells[at] = row[from * 3] ?? 0x20
grid.cells[at + 1] = row[from * 3 + 1] ?? 0
grid.cells[at + 2] = row[from * 3 + 2] ?? 0
if (hash(x, slot) % 9 === 0 && grid.cells[at] !== 0x20) grid.cells[at] = NOISE.codePointAt(hash(slot, x) % NOISE.length) ?? 0x23
}
}
/** The wall behind the sign: bricks a row tall in a running bond, teal on the left warming to rose on the right. */
function wall(x: number, y: number, columns: number): number {
const base = mix(0x0f2f38, 0x3a1230, x / Math.max(1, columns - 1))
@@ -159,15 +185,28 @@ export function neonPicture(columns: number, age: number, isAnimated: boolean):
}
}
for (const cell of SIGN.cells) {
const frame = Math.floor(age / 60)
for (const [i, cell] of SIGN.cells.entries()) {
const level = levels[cell.tube] ?? 0
const color = SIGN.tubes[cell.tube]?.color ?? 0xffffff
const at = (cell.y * columns + cell.x + left) * 3
const under = grid.cells[at + 2] ?? 0
// Animated, each cell of a tube resolves at its own moment after the strike: until then it is a random letter
// flickering in the tube's colour, the image-to-ASCII materialise.
const resolveAt = (SIGN.tubes[cell.tube]?.strikeMs ?? 0) + (hash(i, 7) % 520)
const isResolving = isAnimated && age >= resolveAt - 520 && age < resolveAt
if (isResolving) {
grid.set(cell.x + left, cell.y, NOISE[hash(i, frame) % NOISE.length] as string, mix(CORE[color] ?? 0xffffff, color, (hash(frame, i) % 100) / 100))
continue
}
grid.set(cell.x + left, cell.y, cell.ch, level <= 0.05 ? UNLIT : mix(UNLIT, CORE[color] ?? 0xffffff, Math.min(1, level)), level <= 0.05 || cell.ch === '~' ? under : mix(under, color, Math.min(1, level)))
}
if (isAnimated) glitch(grid, age)
// The hardware stays dark: clips over the frame, wires up and down off the panel.
for (const cx of SIGN.clips) {
for (const [y, wireY] of [[1, 0], [9, 10]] as const) {
+182 -90
View File
@@ -1,126 +1,207 @@
/**
* The terminal view's second terminal: a line of text sent to another harness (codex, claude, or one ruflo CLI
* command), its output streamed into a scrollback. Each harness is a fixed argv; the person's text reaches a model
* harness on stdin, never as an argument, so it cannot be read as a flag, and the ruflo harness splits it into words
* with no shell. A run costs money, so it is asked like any other change: y runs it, n drops it.
* The terminal view's second terminal: a conversation with codex or claude (or both at once, the swarm), or one ruflo
* CLI command. Each agent keeps a session per project, so a follow-up resumes the conversation: codex by its thread
* id (`codex exec resume`), claude by a session id the console picks (`--session-id`, then `--resume`). Their JSON
* streams are read as they arrive (stream.ts), so the answer types out and each tool call shows as it runs.
*
* Starting or resuming a session costs money, so it is asked once (Enter shows the command, Enter again runs it);
* after that the session is live for this Claude Code session and Enter sends. A ruflo command is asked every time.
* The person's text reaches an agent on stdin, never as an argument, so it cannot be read as a flag.
*/
import type { ActionSpec } from './actions'
import type { Host } from './host'
import { CLI_PREFIXES, push, type HarnessId, type State, type TermLine } from './state'
import { CLI_PREFIXES, push, termStoreKeyOf, type AgentId, type HarnessId, type State, type TermLine } from './state'
import { claudeParser, codexEvent, eventOf, type Sink } from './stream'
export const TERM_MAX_LINES = 400
/** The engine kills a spawned child only when the loop ends: the console ends it at ten minutes, as `run` would. */
export const TERM_MAX_LINES = 600
/** The engine ends a spawned child only when its loop ends: the console ends a run at ten minutes. */
export const RUN_CAP_MS = 10 * 60_000
const MAX_PROMPT = 4_000
const MAX_PROMPT = 8_000
export type Harness = {
id: HarnessId
/** The picker's hotkey in the terminal view. */
key: string
label: string
/** What it runs and what it may do, in the words the view shows. */
about: string
argv: (state: State, text: string) => readonly string[] | null
/** True: the text goes on stdin; false: it is part of the argv. */
isStdin: boolean
}
export type Harness = { id: HarnessId; key: string; label: string; about: string; agents: readonly AgentId[] }
export const HARNESSES: readonly Harness[] = [
{
id: 'codex',
key: 'c',
label: 'codex',
about: 'codex exec in a read-only sandbox: reads this project, writes nothing · billed to your OpenAI plan',
argv: () => ['codex', 'exec', '--sandbox', 'read-only', '--skip-git-repo-check', '-'],
isStdin: true,
},
{
id: 'claude',
key: 'l',
label: 'claude',
about: 'claude -p in plan mode, at most $1 a run: answers, edits nothing · billed to your Claude plan',
argv: () => ['claude', '-p', '--permission-mode', 'plan', '--max-budget-usd', '1'],
isStdin: true,
},
{
id: 'ruflo',
key: 'u',
label: 'ruflo',
about: 'one ruflo CLI command, split on spaces with no shell (swarm status, memory search -q auth) · local unless it reaches out',
argv: (state, text) => {
const words = text.split(/\s+/).filter(word => word !== '')
return words.length === 0 || words.length > 40 ? null : [...CLI_PREFIXES[state.options.cli], ...words]
},
isStdin: false,
},
{ id: 'codex', key: 'c', label: 'codex', about: 'codex exec, read-only sandbox, one thread per project · billed to your OpenAI plan', agents: ['codex'] },
{ id: 'claude', key: 'l', label: 'claude', about: 'claude -p in plan mode, at most $1 a turn, one session per project · billed to your Claude plan', agents: ['claude'] },
{ id: 'swarm', key: 'v', label: 'swarm', about: 'codex and claude together: one question to both, answering side by side in their own sessions', agents: ['codex', 'claude'] },
{ id: 'ruflo', key: 'u', label: 'ruflo', about: 'one ruflo CLI command, split on spaces with no shell (swarm status, memory search -q auth) · asked each time', agents: ['ruflo'] },
]
export const harnessOf = (id: HarnessId): Harness => HARNESSES.find(harness => harness.id === id) ?? (HARNESSES[0] as Harness)
/** A v4 UUID for a new claude session (not a secret: it only names the conversation). */
function uuid(): string {
const hex = Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16))
hex[12] = '4'
hex[16] = ((parseInt(hex[16] as string, 16) & 0x3) | 0x8).toString(16)
return `${hex.slice(0, 8).join('')}-${hex.slice(8, 12).join('')}-${hex.slice(12, 16).join('')}-${hex.slice(16, 20).join('')}-${hex.slice(20).join('')}`
}
/** The argv for one agent's next turn: a new session, or the saved one resumed. */
export function argvOf(state: State, agent: AgentId, text: string): readonly string[] | null {
const session = agent === 'ruflo' ? undefined : state.terminal.sessions[agent]
switch (agent) {
case 'codex':
return session === undefined
? ['codex', 'exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-']
: ['codex', 'exec', 'resume', '--json', '--skip-git-repo-check', '-c', 'sandbox_mode="read-only"', session, '-']
case 'claude':
return ['claude', '-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--permission-mode', 'plan', '--max-budget-usd', '1', ...(session === undefined ? [] : ['--resume', session])]
case 'ruflo': {
const words = text.split(/\s+/).filter(word => word !== '')
return words.length === 0 || words.length > 40 ? null : [...CLI_PREFIXES[state.options.cli], ...words]
}
}
}
/**
* One line of a harness's output as the scrollback keeps it: ANSI sequences, control and bidirectional characters
* gone, tabs as two spaces, indentation kept (unlike `plain`, which folds whitespace for one-line facts).
* One line of an agent's output as the scrollback keeps it: ANSI sequences, control and bidirectional characters
* gone, tabs as two spaces, indentation kept. `trim` false keeps a trailing space (a token typed mid-sentence).
*/
export function termText(line: string, max = 400): string {
export function termText(line: string, max = 400, trim = true): string {
const cleaned = line
.replace(/\u001b\][^\u0007\u001b]*(\u0007|\u001b\\)/g, '')
.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '')
.replace(/\t/g, ' ')
.replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g, '')
.trimEnd()
const out = trim ? cleaned.trimEnd() : cleaned
return cleaned.length <= max ? cleaned : `${cleaned.slice(0, max - 1)}…`
return out.length <= max ? out : `${out.slice(0, max - 1)}…`
}
function note(state: State, kind: TermLine['kind'], text: string): void {
for (const line of text.split('\n')) push(state.terminal.lines, { kind, text: termText(line) }, TERM_MAX_LINES)
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)
}
/** Why the field's text cannot be asked now, or null when it can. */
const persist = (state: State, host: Host) => void host.storeSet(termStoreKeyOf(state.cwd), state.terminal.sessions).catch(() => undefined)
/** Why the field's text cannot be sent now, or null when it can. */
export function whyNotRun(state: State, text: string): string | null {
if (state.terminal.running !== null) return `${state.terminal.running.label} is still running: stop it first (s)`
const harness = harnessOf(state.terminal.harness)
const busy = harness.agents.find(agent => state.terminal.runs.has(agent))
if (text.trim() === '') return 'type something first'
if (harnessOf(state.terminal.harness).argv(state, text.trim()) === null) return 'that is not one ruflo command (1 to 40 words)'
if (busy !== undefined) return `${busy} is still answering: wait, or stop it (s)`
if (harness.id === 'ruflo' && argvOf(state, 'ruflo', text.trim()) === null) return 'that is not one ruflo command (1 to 40 words)'
return null
}
/** The confirm-gated ask for the field's text, or null (see `whyNotRun`). */
/** True when the text can go straight to the agents: every one of them has a session the person said yes to. */
export const isLive = (state: State): boolean => {
const agents = harnessOf(state.terminal.harness).agents
return agents.every(agent => agent !== 'ruflo' && state.terminal.isLive[agent])
}
/** The confirm-gated ask that opens (or resumes) the harness's sessions with this text, or null (see `whyNotRun`). */
export function harnessSpec(state: State, host: Host, text: string): ActionSpec | null {
if (whyNotRun(state, text) !== null) return null
const harness = harnessOf(state.terminal.harness)
const prompt = text.trim().slice(0, MAX_PROMPT)
const argv = whyNotRun(state, prompt) === null ? harness.argv(state, prompt) : null
if (argv === null) return null
const input = harness.isStdin ? prompt : undefined
const short = termText(prompt.replace(/\s+/g, ' '), 48)
const plans = harness.agents.map(agent => ({ agent, argv: argvOf(state, agent, prompt) ?? [] }))
const verb = harness.agents.every(agent => agent !== 'ruflo' && state.terminal.sessions[agent] !== undefined) ? 'resume' : 'start'
return {
label: `ask ${harness.label}: ${short}`,
args: argv,
shows: `${argv.join(' ')}${input !== undefined ? ' (your text on stdin)' : ''}`,
label: harness.id === 'ruflo' ? `ruflo ${termText(prompt.replace(/\s+/g, ' '), 48)}` : `${verb} a ${harness.label} session: ${termText(prompt.replace(/\s+/g, ' '), 40)}`,
args: plans[0]?.argv ?? [],
shows: plans.map(plan => `${plan.argv.join(' ')}${plan.agent === 'ruflo' ? '' : ' (your text on stdin)'}`).join(' & '),
expect: 'its output in the terminal',
run: () => runHarness(state, host, harness.label, argv, prompt, input),
run: async () => {
for (const agent of harness.agents) if (agent !== 'ruflo') state.terminal.isLive[agent] = true
send(state, host, prompt)
},
}
}
/** Runs one harness command, streaming each line it writes into the scrollback; s stops it, and so does the cap. */
export async function runHarness(state: State, host: Host, label: string, argv: readonly string[], prompt: string, input: string | undefined): Promise<void> {
/** Sends the text to every agent of the picked harness at once; each streams into the shared scrollback. */
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}`)
for (const agent of harness.agents) void runAgent(state, host, agent, prompt, isMany)
}
/** Forgets the picked harness's sessions: the next question starts new ones (and is asked first). */
export function newSession(state: State, host: Host): void {
for (const agent of harnessOf(state.terminal.harness).agents) {
if (agent === 'ruflo') continue
delete state.terminal.sessions[agent]
state.terminal.isLive[agent] = false
}
note(state, 'sys', `── new ${state.terminal.harness} session: the next question starts fresh ──`)
persist(state, host)
host.invalidate()
}
async function runAgent(state: State, host: Host, agent: AgentId, prompt: string, isTagged: boolean): Promise<void> {
const term = state.terminal
const tag = isTagged ? agent : undefined
const startedAtMs = Date.now()
const secs = () => `${Math.round((Date.now() - startedAtMs) / 1000)} s`
const partial = { out: '', err: '' }
let isStopped = false
// claude takes the session id the console picks; it counts once the CLI reports the session started.
const claudeId = agent === 'claude' && term.sessions.claude === undefined ? uuid() : undefined
const base = argvOf(state, agent, prompt)
note(state, 'in', `${label}> ${prompt}`)
if (base === null) return
const argv = claudeId === undefined ? base : [...base, '--session-id', claudeId]
const parse = agent === 'codex' ? codexEvent : agent === 'claude' ? claudeParser() : null
let open: TermLine | null = null
let sawSession = false
let isStopped = false
let ended: string | null = null
let events = 0
let isAnswered = false
const sink: Sink = {
line: (kind, text) => {
open = null
if (kind === 'out') isAnswered = true
note(state, kind, text, tag)
},
type: text => {
const parts = text.split('\n')
isAnswered = true
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.text = termText(open.text + part, 2_000, false)
})
},
session: id => {
sawSession = true
if (agent !== 'ruflo' && term.sessions[agent] !== id) {
term.sessions[agent] = id
persist(state, host)
}
},
done: ({ costUsd, tokens, isError, message }) => {
if (agent === 'codex' || agent === 'claude') term.turns[agent] += 1
if (costUsd !== undefined) term.costUsd += costUsd
ended = isError === true ? `✗ ${message ?? 'failed'}` : `✓ ${secs()}${costUsd !== undefined ? ` · $${costUsd.toFixed(3)}` : ''}${tokens !== undefined ? ` · ${tokens.toLocaleString('en-US')} tokens` : ''}`
},
}
let stream: ReturnType<Host['spawn']>
try {
stream = host.spawn(argv, input)
stream = host.spawn(argv, agent === 'ruflo' ? undefined : prompt)
} catch (error) {
note(state, 'sys', `${argv[0]} did not start: ${error instanceof Error ? error.message : String(error)}`)
note(state, 'err', `${argv[0]} did not start: ${error instanceof Error ? error.message : String(error)}`, tag)
host.invalidate()
return
@@ -131,39 +212,50 @@ export async function runHarness(state: State, host: Host, label: string, argv:
void stream.return(undefined as never).catch(() => undefined)
}
const cap = host.after(RUN_CAP_MS, stop)
const partial = { stdout: '', stderr: '' }
state.terminal.running = { label, startedAtMs, stop }
term.runs.set(agent, { label: agent, startedAtMs, stop })
host.invalidate()
const flush = () => {
for (const kind of ['out', 'err'] as const) {
if (partial[kind] !== '') note(state, kind, partial[kind])
partial[kind] = ''
const take = (from: 'stdout' | 'stderr', line: string) => {
if (from === 'stderr' || parse === null) {
// codex and claude write progress to stderr; only a line that reads as an error is worth a row.
if (parse === null || /error|denied|not found|invalid/i.test(line)) sink.line(from === 'stderr' ? 'err' : 'out', line)
return
}
const event = eventOf(line)
if (event !== null) {
events += 1
parse(event, sink)
}
}
try {
for await (const chunk of stream) {
const kind = chunk.stream === 'stderr' ? 'err' : 'out'
const lines = (partial[kind] + chunk.text).split('\n')
const lines = (partial[chunk.stream] + chunk.text).split('\n')
partial[kind] = lines.pop() ?? ''
for (const line of lines) push(state.terminal.lines, { kind, text: termText(line) }, TERM_MAX_LINES)
partial[chunk.stream] = lines.pop() ?? ''
for (const line of lines) if (line.trim() !== '' || parse === null) take(chunk.stream, line)
host.invalidate()
}
flush()
for (const from of ['stdout', 'stderr'] as const) if (partial[from].trim() !== '') take(from, partial[from])
const result = await stream.result
note(state, 'sys', isStopped ? `stopped after ${secs()}` : result.signal !== null ? `ended by ${result.signal} after ${secs()}` : `exit ${result.code ?? '?'} · ${secs()}`)
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)
} catch (error) {
flush()
note(state, 'sys', isStopped ? `stopped after ${secs()}` : `${argv[0]}: ${error instanceof Error ? error.message : String(error)} (is it installed and on PATH?)`)
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)
} finally {
cap.cancel()
state.terminal.running = null
term.runs.delete(agent)
host.invalidate()
}
}
+2 -1
View File
@@ -6,7 +6,7 @@ import { plain } from './data/parse'
import { dispatch } from './dispatch'
import { markPicture } from './gfx/pictures'
import type { Host } from './host'
import { newState, PANE_ID, restore, storeKeyOf } from './state'
import { newState, PANE_ID, restore, restoreSessions, storeKeyOf, termStoreKeyOf } from './state'
import { BAR_KEY, barView } from './views/bar'
import type { Kit } from './views/common'
import { picturesOf } from './views/frames'
@@ -94,6 +94,7 @@ export const register: Register = (on, raw: PluginOptions) => {
// Kept for good (ADR-406: no command is removed or renamed): `/ruflo-console` is the same command as `/ruflo`.
bound.registerCommand({ name: 'ruflo-console', description: 'Same as /ruflo: the ruflo console', argumentHint: '[view|palette|help]' }).catch(() => undefined),
bound.storeGet(storeKeyOf(e.cwd)).then(value => restore(state, value), () => undefined),
bound.storeGet(termStoreKeyOf(e.cwd)).then(value => restoreSessions(state, value), () => undefined),
bound.rufloTools().then(counted => void (state.rufloTools = counted), () => undefined),
])
control.start()
+40 -8
View File
@@ -36,7 +36,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'events', key: 'e', label: 'Events', short: 'Evt', icon: '📡', blurb: 'every swarm, claim, memory and mod event as it happens (f filters them)', rows: 26 },
{ id: 'missions', key: 'm', label: 'Missions', short: 'Msn', icon: '🎯', blurb: 'ADR-406 missions: the plan, task dependencies, acceptance and budget (observe only)', rows: 26 },
{ id: 'xruv', key: 'w', label: 'x.ruv.io', short: 'XRV', icon: '🛸', blurb: 'the open agent federation: what it offers, how to join, its channels and who is on', rows: 34 },
{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'a second terminal: ask codex, claude or the ruflo CLI, each run confirmed, its output streamed', rows: 32 },
{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'an AI terminal: codex, claude or both, each a session that remembers the conversation, streamed live', rows: 32 },
]
export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }
@@ -109,11 +109,21 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
/** A mutating action waiting for the person's second press; `shows` is the command line when it is not a ruflo one. */
export type Pending = { label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string }
/** The harnesses the terminal view can ask. */
export type HarnessId = 'codex' | 'claude' | 'ruflo'
/** The harnesses the terminal view can ask; `swarm` asks codex and claude at once. */
export type HarnessId = 'codex' | 'claude' | 'ruflo' | 'swarm'
/** What actually runs: a swarm is a codex run and a claude run side by side. */
export type AgentId = Exclude<HarnessId, 'swarm'>
/** One line of the terminal's scrollback: what was asked (`in`), what came back, or the console's own note (`sys`). */
export type TermLine = { kind: 'in' | 'out' | 'err' | 'sys'; text: string }
/**
* One line of the terminal's scrollback: what was asked (`in`), what came back, a tool the agent used (`tool`), 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 }
/** 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 }
export const termStoreKeyOf = (cwd: string): string => `ruflo-console/term:${cwd}`
/** What an action did: what ran, how it exited, whether the disk shows the change, and anything it printed to show. */
export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[] }
@@ -175,12 +185,19 @@ export type State = {
isRefreshing: boolean
/** When the band above the prompt last drew: the disk is re-read on the fast cadence only while it is seen. */
barDrawnAtMs: number
/** The terminal view: the harness picked, the field's text, the scrollback, and the run in flight. */
/** The terminal view: the harness picked, the field's text, the scrollback, and the runs in flight. */
terminal: {
harness: HarnessId
draft: string
lines: TermLine[]
running: { label: string; startedAtMs: number; stop: () => void } | null
/** One run per agent at most; codex and claude may run at the same time. */
runs: Map<AgentId, { label: string; startedAtMs: number; stop: () => void }>
/** The conversations to resume, and which of them the person has said yes to in this Claude Code session. */
sessions: TermSessions
isLive: { codex: boolean; claude: boolean }
/** Turns and spend this session, as the agents reported them. */
turns: { codex: number; claude: number }
costUsd: number
/** The text the last Enter asked about: Enter on the same text again confirms it. */
asked: { key: string; label: string } | null
}
@@ -225,7 +242,7 @@ export function newState(raw: PluginOptions | undefined): State {
isActing: false,
isRefreshing: false,
barDrawnAtMs: 0,
terminal: { harness: 'codex', draft: '', lines: [], running: null, asked: null },
terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, asked: null },
timers: new Map(),
stats: { renders: [], refreshes: [], frames: [] },
}
@@ -253,6 +270,21 @@ export function restore(state: State, value: unknown): void {
state.pane.isClosedByPerson = held.isClosedByPerson === true
}
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{7,63}$/
/** The terminal's saved conversations: only id-shaped strings come back, since each one becomes an argv element. */
export function restoreSessions(state: State, value: unknown): void {
const held = value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : {}
for (const agent of ['codex', 'claude'] as const) {
const id = held[agent]
if (typeof id === 'string' && SESSION_ID.test(id)) state.terminal.sessions[agent] = id
}
}
export const isSessionId = (id: string): boolean => SESSION_ID.test(id)
/** The BBS boot screen's span: at least BOOT_MIN_MS, longer while the first read is still out, never past BOOT_MAX_MS. */
export const BOOT_MIN_MS = 3_200
export const BOOT_MAX_MS = 6_000
+190
View File
@@ -0,0 +1,190 @@
/**
* The agents' streamed JSON, one event per line, read into what the terminal shows: the answer as it is typed, each
* tool or command the agent runs, its session id (so the next question resumes the conversation), and what the turn
* cost. `codex exec --json` and `claude -p --output-format stream-json` each have their own events; anything not
* named here is skipped. Every string is the agent's and is drawn as data.
*/
import type { TermLine } from './state'
export type Sink = {
line: (kind: TermLine['kind'], text: string) => void
/** Answer text arriving piece by piece: appended to the open answer line; a newline opens the next. */
type: (text: string) => void
session: (id: string) => void
done: (note: { costUsd?: number; tokens?: number; isError?: boolean; message?: string }) => void
}
const rec = (value: unknown): Record<string, unknown> | null => (value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null)
const str = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)
const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
const clip = (text: string, max: number): string => {
const one = text.replace(/\s+/g, ' ').trim()
return one.length <= max ? one : `${one.slice(0, max - 1)}…`
}
/** One JSON event per line; a line that is not an object is not an event. */
export function eventOf(line: string): Record<string, unknown> | null {
const text = line.trim()
if (!text.startsWith('{') || text.length > 1_000_000) return null
try {
return rec(JSON.parse(text))
} catch {
return null
}
}
/** What a tool call was about, in a few words: the command, the file, the pattern or the URL it was given. */
function about(input: unknown): string {
const args = rec(input)
if (args === null) return ''
const pick = str(args.command) ?? str(args.file_path) ?? str(args.path) ?? str(args.pattern) ?? str(args.url) ?? str(args.query) ?? str(args.description) ?? str(args.prompt)
return pick === undefined ? '' : ` ${clip(pick, 90)}`
}
/** codex exec --json: thread.started, item.started/completed (messages, commands, file changes, tools), turn.completed. */
export function codexEvent(event: Record<string, unknown>, sink: Sink): void {
const item = rec(event.item)
switch (event.type) {
case 'thread.started': {
const id = str(event.thread_id)
if (id !== undefined) sink.session(id)
return
}
case 'item.started':
if (item?.type === 'command_execution' && str(item.command) !== undefined) sink.line('tool', `$ ${clip(item.command as string, 120)}`)
return
case 'item.completed':
if (item === null) return
switch (item.type) {
case 'agent_message':
if (str(item.text) !== undefined) sink.line('out', item.text as string)
break
case 'reasoning':
if (str(item.text) !== undefined) sink.line('sys', `thinking: ${clip(item.text as string, 140)}`)
break
case 'command_execution': {
const code = num(item.exit_code)
const output = (str(item.aggregated_output) ?? '').split('\n').filter(line => line.trim() !== '')
for (const line of output.slice(-4)) sink.line('tool', ` ${line}`)
if (code !== undefined && code !== 0) sink.line('err', ` exit ${code}`)
break
}
case 'file_change':
for (const change of Array.isArray(item.changes) ? item.changes.slice(0, 8) : []) {
const entry = rec(change)
sink.line('tool', `✎ ${str(entry?.kind) ?? 'change'} ${str(entry?.path) ?? ''}`)
}
break
case 'mcp_tool_call':
sink.line('tool', `⚙ ${str(item.server) ?? 'mcp'}.${str(item.tool) ?? 'tool'}`)
break
case 'web_search':
sink.line('tool', `🔎 ${clip(str(item.query) ?? '', 100)}`)
break
case 'todo_list':
for (const todo of Array.isArray(item.items) ? item.items.slice(0, 8) : []) {
const entry = rec(todo)
sink.line('tool', `${entry?.completed === true ? '☑' : '☐'} ${clip(str(entry?.text) ?? '', 100)}`)
}
break
case 'error':
sink.line('err', clip(str(item.message) ?? 'error', 200))
break
}
return
case 'turn.completed': {
const usage = rec(event.usage)
const tokens = (num(usage?.input_tokens) ?? 0) + (num(usage?.output_tokens) ?? 0)
sink.done(tokens > 0 ? { tokens } : {})
return
}
case 'turn.failed':
sink.done({ isError: true, message: clip(str(rec(event.error)?.message) ?? 'turn failed', 200) })
return
case 'error':
sink.line('err', clip(str(event.message) ?? 'error', 200))
}
}
/**
* claude -p --output-format stream-json --include-partial-messages: system/init carries the session id, stream_event
* text deltas are the answer as it is typed, assistant messages carry the tool calls, result the cost. A message whose
* text never came as deltas (an older CLI) is written out whole when it arrives.
*/
export function claudeParser(): (event: Record<string, unknown>, sink: Sink) => void {
let hasDeltas = false
return (event, sink) => {
switch (event.type) {
case 'system': {
const id = str(event.session_id)
if (event.subtype === 'init' && id !== undefined) sink.session(id)
return
}
case 'stream_event': {
const inner = rec(event.event)
const delta = rec(inner?.delta)
if (inner?.type === 'content_block_delta' && delta?.type === 'text_delta' && typeof delta.text === 'string') {
hasDeltas = true
sink.type(delta.text)
}
return
}
case 'assistant': {
const content = rec(event.message)?.content
for (const block of Array.isArray(content) ? content : []) {
const part = rec(block)
if (part?.type === 'tool_use') sink.line('tool', `⚙ ${str(part.name) ?? 'tool'}${about(part.input)}`)
else if (part?.type === 'text' && !hasDeltas && str(part.text) !== undefined) sink.line('out', part.text as string)
}
hasDeltas = false
return
}
case 'user': {
const content = rec(event.message)?.content
for (const block of Array.isArray(content) ? content : []) {
const part = rec(block)
if (part?.type === 'tool_result' && part.is_error === true) sink.line('err', ` ${clip(typeof part.content === 'string' ? part.content : 'tool error', 160)}`)
}
return
}
case 'result': {
const cost = num(event.total_cost_usd)
sink.done({
...(cost !== undefined && { costUsd: cost }),
...(event.is_error === true && { isError: true, message: clip(str(event.result) ?? str(event.subtype) ?? 'error', 200) }),
})
}
}
}
}
+1 -1
View File
@@ -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; 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 }
}
export type Ctx = {
+70 -20
View File
@@ -1,21 +1,50 @@
import type { RenderElement } from 'claude-code'
import { HARNESSES, harnessOf } from '../harness'
import { button, clip, col, row, rule, text, THEME, type Ctx } from './common'
import { HARNESSES, harnessOf, isLive } from '../harness'
import type { AgentId, TermLine } from '../state'
import { button, col, row, rule, text, THEME, type Ctx } from './common'
/** Scrollback lines shown under the picker: the newest, so a long answer reads like a terminal's tail. */
export const TERM_ROWS = 16
/** Screen rows of scrollback under the picker: the newest, wrapped to the pane, so an answer reads like a chat. */
export const TERM_ROWS = 18
const TAG: Record<AgentId, { text: string; color: string }> = {
codex: { text: 'codex ', color: '#00afd7' },
claude: { text: 'claude', color: '#d7af00' },
ruflo: { text: 'ruflo ', color: '#d7005f' },
}
/** A line folded to the pane'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]
const out: string[] = []
let rest = line
while (rest.length > width) {
const cut = rest.lastIndexOf(' ', width)
const at = cut > width * 0.5 ? cut : width
out.push(rest.slice(0, at))
rest = rest.slice(at).replace(/^ /, '')
}
out.push(rest)
return out
}
/**
* The second terminal: pick a harness (c codex, l claude, u ruflo) and type into the field. Enter shows the exact
* command, Enter again on the same text runs it (y does too, from outside the field). Output streams in as the harness
* writes it; s stops a run, z clears the screen. While the field has focus every key types into it.
* 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.
*/
export function terminalView(ctx: Ctx): RenderElement {
const { state, nowMs } = ctx
const term = state.terminal
const harness = harnessOf(term.harness)
const rows: RenderElement[] = [rule(ctx, 'Harness', term.running !== null ? `${term.running.label} running · ${Math.round((nowMs - term.running.startedAtMs) / 1000)} s` : 'idle')]
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')]
rows.push(
ctx.kit.Box({
@@ -30,22 +59,42 @@ export function terminalView(ctx: Ctx): RenderElement {
}),
)
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 => {
const id = term.sessions[agent]
return `${agent}: ${id === undefined ? 'new session' : `session ${id.slice(0, 8)}… · ${term.turns[agent]} turn${term.turns[agent] === 1 ? '' : 's'} here`}${term.isLive[agent] ? ' · live' : ''}`
})
if (sessions.length > 0) rows.push(text(ctx, ` ${sessions.join(' ')}`, { dimColor: true }))
rows.push(rule(ctx, 'Screen', `${term.lines.length} lines`))
const tail = term.lines.slice(-TERM_ROWS)
const width = Math.max(10, ctx.columns - 8)
const screen: { line: TermLine; text: string; isFirst: boolean }[] = []
if (tail.length === 0) {
rows.push(text(ctx, ' nothing yet: type below, Enter shows the exact command, Enter again runs it', { dimColor: true }))
for (const line of term.lines) fold(line.text, width).forEach((part, i) => screen.push({ line, text: part, isFirst: i === 0 }))
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 }))
}
for (const line of tail) {
const props = line.kind === 'in' ? { bold: true, color: THEME.head } : line.kind === 'err' ? { color: THEME.warn } : line.kind === 'sys' ? { dimColor: true, italic: true } : {}
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
rows.push(ctx.kit.Text({ wrap: 'truncate-end', ...props, children: clip(line.text === '' ? ' ' : line.text, Math.max(4, ctx.columns)) }))
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 }),
]),
)
}
if (term.running !== null) {
// Data, not decoration: the cursor blinks only while a harness is writing back.
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 }))
}
@@ -56,9 +105,9 @@ export function terminalView(ctx: Ctx): RenderElement {
ctx.kit.Input({
key: 'term-input',
label: harness.label,
placeholder: harness.id === 'ruflo' ? 'a ruflo command: swarm status, memory search -q auth …' : `ask ${harness.label} about this project…`,
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…`,
value: term.draft,
submitLabel: 'ask',
submitLabel: isLive(state) ? 'send' : 'ask',
onInput: value => ctx.act.term.draft(value),
onSubmit: value => ctx.act.term.submit(value),
}),
@@ -69,9 +118,10 @@ export function terminalView(ctx: Ctx): RenderElement {
rows.push(
row(ctx, [
...(term.running !== null ? [button(ctx, 'term-stop', 'Stop', ctx.act.term.stop, { hotkey: 's' })] : []),
...(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, ' Tab or click to the field · Enter shows the command · Enter again runs it', { dimColor: true }),
text(ctx, isLive(state) ? ' live: Enter sends' : ' Enter shows the command · Enter again runs it', { dimColor: true }),
]),
)
+2 -2
View File
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
step "1. plugin.json declares ruflo-console 0.5.0"
step "1. plugin.json declares ruflo-console 0.6.0"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
&& grep -q '"version": "0.5.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
&& grep -q '"version": "0.6.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
+136 -58
View File
@@ -1,18 +1,22 @@
/**
* The terminal view's harness runner and the x.ruv.io registry probe, under vitest: what argv each harness runs, that
* the person's text never becomes a flag, how streamed output lands in the scrollback, and how a stop reads.
* The terminal view's agents and the x.ruv.io registry probe, under vitest: what argv each harness runs (a new session
* or a resumed one), that the person's text never becomes a flag, how codex's and claude's JSON streams land in the
* scrollback, that a session id is kept for the next question, that the swarm runs both agents at once, and a stop.
*/
import { describe, expect, it } from 'vitest'
import { registryProbe } from '../hooks/data/cli'
import { harnessSpec, runHarness, termText, whyNotRun } from '../hooks/harness'
import { argvOf, harnessSpec, isLive, newSession, send, termText, whyNotRun } from '../hooks/harness'
import type { Host } from '../hooks/host'
import { newState } from '../hooks/state'
import { newState, restoreSessions, type State } from '../hooks/state'
import { claudeParser, codexEvent, eventOf, type Sink } from '../hooks/stream'
type Chunk = { stream: 'stdout' | 'stderr'; text: string }
/** A spawn that yields `chunks`, then ends with `code`; `hang` keeps it open until `return()`. */
function fakeSpawn(chunks: Chunk[], code = 0, hang = false) {
const json = (value: unknown) => `${JSON.stringify(value)}\n`
/** A spawn answering each program with its own chunks; `hang` keeps a run open until `return()`. */
function fakeSpawn(script: Record<string, Chunk[]>, hang = false) {
const calls: { argv: readonly string[]; input?: string }[] = []
const spawn = (argv: readonly string[], input?: string) => {
calls.push({ argv, ...(input !== undefined && { input }) })
@@ -21,14 +25,12 @@ function fakeSpawn(chunks: Chunk[], code = 0, hang = false) {
let release: () => void = () => undefined
let isClosed = false
const stream = (async function* () {
for (const chunk of chunks) yield chunk
for (const chunk of script[argv[0] as string] ?? []) yield chunk
if (hang) await new Promise<void>(resolve => (release = resolve))
return { code, signal: null }
return { code: 0, signal: null }
})()
const result = {
then: (ok: (value: unknown) => void, fail: (error: Error) => void) => (isClosed ? fail(new Error('closed before its end')) : ok({ code, signal: null })),
}
const result = { then: (ok: (value: unknown) => void, fail: (error: Error) => void) => (isClosed ? fail(new Error('closed')) : ok({ code: 0, signal: null })) }
return Object.assign(stream, {
result,
@@ -44,67 +46,143 @@ function fakeSpawn(chunks: Chunk[], code = 0, hang = false) {
return { spawn, calls }
}
const hostWith = (spawn: Host['spawn']): Host => ({ spawn, invalidate: () => undefined, after: () => ({ cancel: () => undefined }) }) as unknown as Host
function hostWith(spawn: Host['spawn']) {
const stored = new Map<string, unknown>()
const host = { spawn, invalidate: () => undefined, after: () => ({ cancel: () => undefined }), storeSet: async (key: string, value: unknown) => void stored.set(key, JSON.parse(JSON.stringify(value))) } as unknown as Host
describe('terminal harnesses', () => {
it('codex and claude get the text on stdin, never in the argv, and run read-only', () => {
return { host, stored }
}
const settled = async (state: State) => {
for (let i = 0; i < 100 && (state.terminal.runs.size > 0 || i < 2); i++) await new Promise(resolve => setTimeout(resolve, 2))
}
const shown = (state: State) => state.terminal.lines.map(line => `${line.from ?? ''}${line.from ? ' ' : ''}${line.kind}:${line.text}`)
const CODEX = [
{ stream: 'stdout' as const, text: json({ type: 'thread.started', thread_id: '01a0fe1f-b077-7793-9612-f134bd61bc85' }) },
{ stream: 'stdout' as const, text: json({ type: 'item.started', item: { type: 'command_execution', command: 'rg -n auth src' } }) },
{ stream: 'stdout' as const, text: `${json({ type: 'item.completed', item: { type: 'agent_message', text: 'Auth lives in src/auth.ts.' } })}${json({ type: 'turn.completed', usage: { input_tokens: 900, output_tokens: 40 } })}`.slice(0, 50) },
{ stream: 'stdout' as const, text: `${json({ type: 'item.completed', item: { type: 'agent_message', text: 'Auth lives in src/auth.ts.' } })}${json({ type: 'turn.completed', usage: { input_tokens: 900, output_tokens: 40 } })}`.slice(50) },
{ stream: 'stderr' as const, text: 'Reading prompt from stdin...\n' },
]
const CLAUDE = [
{ stream: 'stdout' as const, text: json({ type: 'system', subtype: 'init', session_id: '6b1c2d3e-0000-4000-8000-000000000001' }) },
{ stream: 'stdout' as const, text: json({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Hel' } } }) },
{ stream: 'stdout' as const, text: json({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'lo \u001b[31mthere\nsecond' } } }) },
{ stream: 'stdout' as const, text: json({ type: 'assistant', message: { content: [{ type: 'text', text: 'Hello there\nsecond' }, { type: 'tool_use', name: 'Read', input: { file_path: 'src/auth.ts' } }] } }) },
{ stream: 'stdout' as const, text: json({ type: 'result', subtype: 'success', is_error: false, total_cost_usd: 0.0123, session_id: '6b1c2d3e-0000-4000-8000-000000000001' }) },
]
describe('terminal sessions', () => {
it('a new codex session reads the text from stdin; a known thread is resumed, still read-only', () => {
const state = newState({})
const host = hostWith(fakeSpawn([]).spawn)
const codex = harnessSpec(state, host, '--dangerously-bypass-approvals-and-sandbox explain')
expect(codex?.args).toEqual(['codex', 'exec', '--sandbox', 'read-only', '--skip-git-repo-check', '-'])
expect(codex?.shows).toContain('(your text on stdin)')
state.terminal.harness = 'claude'
expect(harnessSpec(state, host, 'hi')?.args).toEqual(['claude', '-p', '--permission-mode', 'plan', '--max-budget-usd', '1'])
expect(argvOf(state, 'codex', '--yolo')).toEqual(['codex', 'exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-'])
state.terminal.sessions.codex = '01a0fe1f-b077-7793-9612-f134bd61bc85'
expect(argvOf(state, 'codex', 'next')).toEqual(['codex', 'exec', 'resume', '--json', '--skip-git-repo-check', '-c', 'sandbox_mode="read-only"', '01a0fe1f-b077-7793-9612-f134bd61bc85', '-'])
expect(argvOf(state, 'claude', 'x')).not.toContain('--resume')
state.terminal.sessions.claude = '6b1c2d3e-0000-4000-8000-000000000001'
expect(argvOf(state, 'claude', 'x')?.slice(-2)).toEqual(['--resume', '6b1c2d3e-0000-4000-8000-000000000001'])
})
it('ruflo splits words onto the CLI prefix, with no shell, and refuses empty text or a run in flight', () => {
it('the first message of a session is asked; the swarm shows both commands; once live, Enter sends', async () => {
const state = newState({})
const host = hostWith(fakeSpawn([]).spawn)
const { spawn, calls } = fakeSpawn({ codex: CODEX, claude: CLAUDE })
const { host } = hostWith(spawn)
state.terminal.harness = 'swarm'
expect(isLive(state)).toBe(false)
const spec = harnessSpec(state, host, 'where is auth?')
expect(spec?.label).toBe('start a swarm session: where is auth?')
expect(spec?.shows).toContain('codex exec --json')
expect(spec?.shows).toContain('& claude -p')
await spec?.run?.()
expect(isLive(state)).toBe(true)
expect(state.terminal.runs.size).toBe(2)
await settled(state)
expect(calls.map(call => call.input)).toEqual(['where is auth?', 'where is auth?'])
expect(calls[1]?.argv).toContain('--session-id')
})
it('codex: the thread id is kept, commands and the answer show, and the turn closes with its tokens', async () => {
const state = newState({})
const { spawn } = fakeSpawn({ codex: CODEX })
const { host, stored } = hostWith(spawn)
state.cwd = '/work'
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(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)
})
it('claude: the answer types out from deltas (not twice), tool calls show, the cost is counted', async () => {
const state = newState({})
const { spawn } = fakeSpawn({ claude: CLAUDE })
const { host } = hostWith(spawn)
state.terminal.harness = 'claude'
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(state.terminal.sessions.claude).toBe('6b1c2d3e-0000-4000-8000-000000000001')
expect(state.terminal.costUsd).toBeCloseTo(0.0123)
})
it('a busy agent refuses a second question; s stops it; /new forgets the session', async () => {
const state = newState({})
const { spawn } = fakeSpawn({ codex: [] }, true)
const { host, stored } = hostWith(spawn)
state.cwd = '/work'
state.terminal.sessions.codex = '01a0fe1f-b077-7793-9612-f134bd61bc85'
send(state, host, 'long job')
await new Promise(resolve => setTimeout(resolve, 5))
expect(whyNotRun(state, 'more')).toContain('still answering')
for (const run of state.terminal.runs.values()) run.stop()
await settled(state)
expect(state.terminal.lines.at(-1)?.text).toMatch(/^stopped after \d+ s$/)
newSession(state, host)
expect(state.terminal.sessions.codex).toBeUndefined()
expect(stored.get('ruflo-console/term:/work')).toEqual({})
})
it('saved sessions come back only as id-shaped strings', () => {
const state = newState({})
restoreSessions(state, { codex: '01a0fe1f-b077-7793-9612-f134bd61bc85', claude: '--resume; rm -rf' })
expect(state.terminal.sessions).toEqual({ codex: '01a0fe1f-b077-7793-9612-f134bd61bc85' })
})
it('the ruflo harness splits words onto the CLI prefix with no shell and is asked every time', () => {
const state = newState({})
const { host } = hostWith(fakeSpawn({}).spawn)
state.terminal.harness = 'ruflo'
expect(harnessSpec(state, host, ' swarm status; rm x ')?.args).toEqual(['npx', '--offline', '-y', '@claude-flow/cli@latest', 'swarm', 'status;', 'rm', 'x'])
expect(harnessSpec(state, host, ' ')).toBeNull()
expect(isLive(state)).toBe(false)
expect(whyNotRun(state, '')).toBe('type something first')
state.terminal.running = { label: 'codex', startedAtMs: 0, stop: () => undefined }
expect(harnessSpec(state, host, 'swarm status')).toBeNull()
expect(whyNotRun(state, 'swarm status')).toContain('still running')
})
it('streams output into the scrollback by line, joining pieces split mid-line, and notes the exit', async () => {
const state = newState({})
const { spawn, calls } = fakeSpawn([
{ stream: 'stdout', text: 'hel' },
{ stream: 'stdout', text: 'lo\n indented\tline\n' },
{ stream: 'stderr', text: '\u001b[31mwarn\u001b[0m\n' },
{ stream: 'stdout', text: 'tail' },
])
it('stream readers skip what is not an event, and termText keeps indentation but drops escapes and bidi', () => {
const lines: string[] = []
const sink: Sink = { line: (kind, text) => lines.push(`${kind}:${text}`), type: text => lines.push(`type:${text}`), session: id => lines.push(`id:${id}`), done: () => lines.push('done') }
await runHarness(state, hostWith(spawn), 'codex', ['codex', 'exec', '-'], 'say hi', 'say hi')
expect(calls[0]).toEqual({ argv: ['codex', 'exec', '-'], input: 'say hi' })
expect(state.terminal.lines.map(line => `${line.kind}:${line.text}`)).toEqual(['in:codex> say hi', 'out:hello', 'out: indented line', 'err:warn', 'out:tail', expect.stringMatching(/^sys:exit 0 · \d+ s$/)])
expect(state.terminal.running).toBeNull()
})
it('a stop ends the run and says so', async () => {
const state = newState({})
const { spawn } = fakeSpawn([{ stream: 'stdout', text: 'working\n' }], 0, true)
const run = runHarness(state, hostWith(spawn), 'claude', ['claude', '-p'], 'long', 'long')
await new Promise(resolve => setTimeout(resolve, 5))
state.terminal.running?.stop()
await run
expect(state.terminal.lines.at(-1)?.text).toMatch(/^stopped after \d+ s$/)
expect(state.terminal.running).toBeNull()
})
it('termText keeps indentation but drops escapes, control and bidi characters', () => {
expect(eventOf('not json')).toBeNull()
codexEvent({ type: 'item.completed', item: { type: 'file_change', changes: [{ kind: 'update', path: 'a.ts' }] } }, sink)
claudeParser()({ type: 'assistant', message: { content: [{ type: 'text', text: 'whole' }] } }, sink)
expect(lines).toEqual(['tool:✎ update a.ts', 'out:whole'])
expect(termText(' a‮b\u0007\u001b]0;title\u0007c ')).toBe(' abc')
expect(termText('x'.repeat(500)).length).toBe(400)
})
})
+2 -1
View File
@@ -226,7 +226,8 @@ describe('views', () => {
const { text, tree } = await drawn($, 'terminal')
expect(text).toContain('[c: CODEX]')
expect(text).toContain('codex exec in a read-only sandbox')
expect(text).toContain('codex exec, read-only sandbox, one thread per project')
expect(text).toContain('codex: new session')
expect(elementsOf(tree, 'Input').map(keyOf)).toEqual(['term-input'])
expect(world.runs.some(argv => argv[0] === 'codex' || argv[0] === 'claude')).toBe(false)
})