diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.ts index 0b0da93fb3..43327e13cc 100644 --- a/plugins/ruflo-console/hooks/data/parse.ts +++ b/plugins/ruflo-console/hooks/data/parse.ts @@ -19,7 +19,8 @@ export function plain(value: unknown, max = 200): string { return '' } - const cleaned = value.replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim() + // Whole ANSI sequences first (the CLI colours its output): stripping only the ESC byte left `[1m` in log lines. + const cleaned = value.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim() return cleaned.length <= max ? cleaned : `${cleaned.slice(0, Math.max(0, max - 1))}…` } @@ -305,3 +306,20 @@ export function parseHive(text: string | null): HiveInfo | null { return info } + +/** The tail of an id a person can tell apart at a glance: `agent-1790954653916-od014i` → `od014i`. */ +export function shortId(id: string): string { + const tail = id.split(/[-_:]/).pop() ?? id + + return tail.length >= 4 ? tail.slice(-6) : id.slice(-6) +} + +/** One readable label per agent: its name, else its type, with a short id only where two would read the same. */ +export function agentLabels(agents: readonly { id: string; name?: string; type: string }[]): Map { + const base = (agent: { name?: string; type: string }) => agent.name ?? agent.type + const counts = new Map() + + for (const agent of agents) counts.set(base(agent), (counts.get(base(agent)) ?? 0) + 1) + + return new Map(agents.map(agent => [agent.id, (counts.get(base(agent)) ?? 0) > 1 ? `${base(agent)}·${shortId(agent.id).slice(-4)}` : base(agent)])) +} diff --git a/plugins/ruflo-console/hooks/gfx/flow.ts b/plugins/ruflo-console/hooks/gfx/flow.ts index 8c276563fc..289a2f6478 100644 --- a/plugins/ruflo-console/hooks/gfx/flow.ts +++ b/plugins/ruflo-console/hooks/gfx/flow.ts @@ -4,7 +4,7 @@ * for an instant on the real clock. The ring is data: time left to `expiresAt` where ruflo set one, else the claim's * age on a 24 h scale; an expired claim's ring blinks. */ -import type { AgentRecord, ClaimRecord, TaskRecord } from '../data/parse' +import { shortId, type AgentRecord, type ClaimRecord, type TaskRecord } from '../data/parse' import { COLOR, Grid, mix } from './raster' export const LANES = ['open', 'claimed', 'working', 'done', 'stealable'] as const @@ -12,7 +12,7 @@ export type LaneId = (typeof LANES)[number] export const LANE_TITLES: Record = { open: 'open tasks', claimed: 'claimed', working: 'working', done: 'done', stealable: 'stealable' } -export type FlowCard = { id: string; owner: string; lane: LaneId; claimedAtMs?: number; expiresAtMs?: number; handoffTo?: string; progress?: number } +export type FlowCard = { id: string; /** What the work is, where the task store says. */ title?: string; owner: string; lane: LaneId; claimedAtMs?: number; expiresAtMs?: number; handoffTo?: string; progress?: number } const DAY = 86_400_000 const RINGS = ['○', '◔', '◑', '◕', '●'] as const @@ -27,13 +27,15 @@ export function laneOf(claim: ClaimRecord): LaneId { } /** Cards for the lanes; a handoff names its target by the agent's name where the store has one. */ -export function flowModelOf(claims: readonly ClaimRecord[], openTasks: readonly TaskRecord[], agents: readonly AgentRecord[] = []): FlowCard[] { +export function flowModelOf(claims: readonly ClaimRecord[], openTasks: readonly TaskRecord[], agents: readonly AgentRecord[] = [], tasks: readonly TaskRecord[] = openTasks): FlowCard[] { const nameOf = (id: string) => agents.find(agent => agent.id === id)?.name ?? agents.find(agent => agent.id === id)?.type ?? id + const titleOf = (id: string) => tasks.find(task => task.id === id)?.description || undefined return [ - ...openTasks.slice(0, 40).map(task => ({ id: task.id, owner: task.description || task.type, lane: 'open' as const })), + ...openTasks.slice(0, 40).map(task => ({ id: task.id, ...(task.description ? { title: task.description } : {}), owner: task.type, lane: 'open' as const })), ...claims.slice(0, 200).map(claim => ({ id: claim.issueId, + ...(titleOf(claim.issueId) !== undefined && { title: titleOf(claim.issueId) as string }), owner: claim.claimant.agentType ?? claim.claimant.name ?? claim.claimant.id, lane: laneOf(claim), ...(claim.claimedAtMs !== undefined && { claimedAtMs: claim.claimedAtMs }), @@ -67,14 +69,35 @@ export function flowRows(cards: readonly FlowCard[], maxCards = 6): number { return 1 + 2 * Math.min(maxCards, fullest) + 1 } +/** Text cut to a width with an ellipsis, so a clipped title reads as clipped. */ +function fit(text: string, width: number): string { + return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…` +} + +/** + * Column widths for the five lanes: an empty lane keeps just enough for its title; the rest of the width goes to + * the lanes that hold cards, so titles are not cut short while four lanes stand empty. + */ +export function laneWidths(cards: readonly FlowCard[], columns: number): number[] { + const counts = LANES.map(lane => cards.filter(card => card.lane === lane).length) + const narrow = LANES.map(lane => LANE_TITLES[lane].length + 5) + const busy = counts.filter(count => count > 0).length + const spare = columns - narrow.reduce((sum, w, i) => sum + ((counts[i] as number) > 0 ? 0 : w), 0) + + if (busy === 0 || spare < busy * 14) return LANES.map(() => Math.max(6, Math.floor(columns / LANES.length))) + + return counts.map((count, i) => (count > 0 ? Math.floor(spare / busy) : (narrow[i] as number))) +} + export function flowPicture(cards: readonly FlowCard[], columns: number, rows: number, nowMs: number): Grid { const grid = new Grid(columns, rows) - const width = Math.max(6, Math.floor(columns / LANES.length)) + const widths = laneWidths(cards, columns) const maxCards = Math.max(0, Math.floor((rows - 2) / 2)) const blink = Math.floor(nowMs / 500) % 2 === 0 LANES.forEach((lane, li) => { - const x0 = li * width + const x0 = widths.slice(0, li).reduce((sum, w) => sum + w, 0) + const width = widths[li] as number const inLane = cards.filter(card => card.lane === lane) const title = `${LANE_TITLES[lane]} ${inLane.length}` @@ -88,7 +111,7 @@ export function flowPicture(cards: readonly FlowCard[], columns: number, rows: n const inner = width - 3 grid.set(x0, y, ring.isExpired && blink ? ' ' : ring.glyph, ring.color) - grid.text(x0 + 2, y, card.id.slice(0, inner), lane === 'stealable' ? COLOR.warn : 0xd0d0d0) + grid.text(x0 + 2, y, fit(card.title ?? card.id, inner), lane === 'stealable' ? COLOR.warn : 0xd0d0d0) if (card.handoffTo !== undefined) { const target = `→ ${card.handoffTo}` @@ -96,7 +119,9 @@ export function flowPicture(cards: readonly FlowCard[], columns: number, rows: n grid.text(x0 + 1, y + 1, '╰─▶', COLOR.warn) grid.text(x0 + 4, y + 1, target.slice(2, 2 + inner - 3), COLOR.warn) } else { - grid.text(x0 + 2, y + 1, `${card.owner}${card.progress !== undefined && card.progress > 0 ? ` ${card.progress}%` : ''}`.slice(0, inner), COLOR.dim) + const owner = `${card.owner}${card.progress !== undefined && card.progress > 0 ? ` ${card.progress}%` : ''}` + + grid.text(x0 + 2, y + 1, fit(card.title !== undefined ? `${owner} · #${shortId(card.id)}` : owner, inner), COLOR.dim) } }) diff --git a/plugins/ruflo-console/hooks/gfx/pictures.ts b/plugins/ruflo-console/hooks/gfx/pictures.ts index 060e67b4a7..397f050155 100644 --- a/plugins/ruflo-console/hooks/gfx/pictures.ts +++ b/plugins/ruflo-console/hooks/gfx/pictures.ts @@ -10,6 +10,8 @@ export type TopoNode = { id: string; label: string; status: string; isLeader: bo export type TopoModel = { topology: string; nodes: TopoNode[] } export const PULSE_MS = 1_400 +/** How long a work-in-flight dot takes from the leader to a busy agent. */ +export const FLIGHT_MS = 1400 const isBusy = (status: string) => /busy|active|running|working/i.test(status) const isDown = (status: string) => /stop|terminat|offline|dead|error|fail/i.test(status) @@ -101,6 +103,21 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number, if (p !== undefined && q !== undefined) canvas.line(p.x, p.y, q.x, q.y, COLOR.line) } + // Work in flight: while ruflo has an agent busy, a dim amber dot keeps travelling down its edge from the leader. + // It runs only for as long as the status says busy, so it is data, not decoration; each agent has its own phase. + model.nodes.forEach((node, i) => { + const q = points[i] + + if (i === 0 || leader === undefined || q === undefined || !isBusy(node.status)) return + + const k = (((t / FLIGHT_MS + i * 0.37) % 1) + 1) % 1 + const x = leader.x + (q.x - leader.x) * k + const y = leader.y + (q.y - leader.y) * k + + canvas.dot(x, y, COLOR.warn) + canvas.dot(x + 1, y, COLOR.warn) + }) + model.nodes.forEach((node, i) => { const q = points[i] const k = node.pulseAtMs === undefined ? -1 : (t - node.pulseAtMs) / PULSE_MS @@ -128,9 +145,11 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number, const cy = Math.floor(point.y / 4) const heartbeat = node.isLeader ? Math.max(0, Math.sin(t / 260)) ** 6 : 0 const flash = node.pulseAtMs !== undefined && t - node.pulseAtMs >= 0 && t - node.pulseAtMs < PULSE_MS + 600 - const color = flash ? 0xffffff : node.isLeader ? mix(COLOR.accent, 0xffffff, heartbeat) : nodeColor(node) + // A busy agent breathes (brighter and back, about once every 2 s) so it reads as working, not just coloured. + const breath = !node.isLeader && isBusy(node.status) ? 0.45 * Math.sin(t / 330 + i) ** 2 : 0 + const color = flash ? 0xffffff : node.isLeader ? mix(COLOR.accent, 0xffffff, heartbeat) : mix(nodeColor(node), 0xffffff, breath) - grid.set(cx, cy, node.isLeader ? '★' : '●', color) + grid.set(cx, cy, node.isLeader ? '★' : isBusy(node.status) ? '◉' : '●', color) if (room >= 5 || node.isLeader) { const label = node.label.slice(0, Math.max(3, room - 1)) diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts index 8e2170a353..f10f2bed5b 100644 --- a/plugins/ruflo-console/hooks/state.ts +++ b/plugins/ruflo-console/hooks/state.ts @@ -15,20 +15,24 @@ export type ViewId = 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' * The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three * management views take letters no other control uses. `agent` is the drill-down, reached from a selection, not a tab. */ -export const VIEWS: readonly { id: ViewId; key: string; label: string; short: string; rows: number }[] = [ - { id: 'overview', key: '1', label: 'Overview', short: 'Ovr', rows: 26 }, - { id: 'swarm', key: '2', label: 'Swarm', short: 'Swm', rows: 30 }, - { id: 'claims', key: '3', label: 'Claims', short: 'Clm', rows: 30 }, - { id: 'federation', key: '4', label: 'Federation', short: 'Fed', rows: 26 }, - { id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', rows: 30 }, - { id: 'learning', key: '6', label: 'Learning', short: 'Lrn', rows: 30 }, - { id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', rows: 26 }, - { id: 'memory', key: '8', label: 'Memory', short: 'Mem', rows: 22 }, - { id: 'cost', key: '9', label: 'Cost', short: 'Cst', rows: 20 }, - { id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', rows: 24 }, - { id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', rows: 24 }, - { id: 'events', key: 'e', label: 'Events', short: 'Evt', rows: 26 }, - { id: 'missions', key: 'm', label: 'Missions', short: 'Msn', rows: 26 }, +/** + * `icon` is one terminal cell (no emoji: those are two cells wide and render unevenly), shown in the tab bar; the + * current tab adds its label, and `blurb` is the one line under the bar that says what the view is for. + */ +export const VIEWS: readonly { id: ViewId; key: string; label: string; short: string; icon: string; blurb: string; rows: number }[] = [ + { id: 'overview', key: '1', label: 'Overview', short: 'Ovr', icon: '⌂', blurb: 'what ruflo is doing here: subsystems, mods, health alerts and live activity', rows: 26 }, + { id: 'swarm', key: '2', label: 'Swarm', short: 'Swm', icon: '⁂', blurb: 'the swarm as ruflo wrote it: topology, agents at work, and the hive-mind votes', rows: 30 }, + { id: 'claims', key: '3', label: 'Claims', short: 'Clm', icon: '⚑', blurb: 'who holds which task: claim, release, hand off or steal, each after a y/n confirm', rows: 30 }, + { id: 'federation', key: '4', label: 'Federation', short: 'Fed', icon: '⇄', blurb: 'this node, its peers, keys and channels, placed by how far each is trusted', rows: 26 }, + { id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', icon: '◫', blurb: 'ruflo plugins: installed, enabled, in the marketplace clone, and loaded as mods', rows: 30 }, + { id: 'learning', key: '6', label: 'Learning', short: 'Lrn', icon: '✦', blurb: 'router picks and outcomes, and the RETRIEVE → JUDGE → DISTILL → CONSOLIDATE pipeline', rows: 30 }, + { id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', icon: '⚙', blurb: 'harness readiness by axis, the audit trend, and the flywheel champion', rows: 26 }, + { id: 'memory', key: '8', label: 'Memory', short: 'Mem', icon: '▤', blurb: 'AgentDB entries by namespace: what the swarm has stored', rows: 22 }, + { id: 'cost', key: '9', label: 'Cost', short: 'Cst', icon: '$', blurb: 'this session spend against the budget, and how fast it is burning', rows: 20 }, + { id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', icon: '◷', blurb: 'each agent busy or idle over the last minutes, beside Claude Code tool calls', rows: 24 }, + { id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', icon: '✓', blurb: 'decisions waiting for a person: votes, stealable claims, refused mods, budget', rows: 24 }, + { 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 }, ] export const AGENT_VIEW = { id: 'agent' as const, rows: 28 } diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.ts index bed3a472c1..76d1ab82df 100644 --- a/plugins/ruflo-console/hooks/views/bar.ts +++ b/plugins/ruflo-console/hooks/views/bar.ts @@ -1,49 +1,99 @@ /** * The band above the prompt: one row naming what ruflo is doing here, with a mark that pulses while Claude works. * Each part is a fact on disk or n/a; a part with nothing to say is left out rather than shown as zero. + * Parts come most-important first, so a narrow band truncates the least useful ones: what needs a person, + * then the swarm, this session's spend, claims, the router's last pick, and what was learned since load. */ import type { RenderElement } from 'claude-code' +import { alertsOf, approvalsOf } from '../data/alerts' import type { State } from '../state' import { clip, count, type Kit } from './common' export const BAR_KEY = 'mark' -/** The band's words, shortest-first droppable parts last. */ -export function barText(state: State): string { - const snap = state.snapshot - const parts = ['ruflo'] +export type BarPart = { text: string; tone: 'attention' | 'plain' } - if (snap?.swarm != null) parts.push(`${snap.swarm.topology} ${snap.agents.filter(agent => /busy|active/i.test(agent.status)).length}/${snap.swarm.agentIds.length || snap.agents.length} busy`) +/** The swarm in words: how many agents and how many are working, never "0/0". */ +function swarmText(state: State): string | null { + const snap = state.snapshot + + if (snap?.swarm == null) return null + + const total = snap.swarm.agentIds.length || snap.agents.length + + if (total === 0) return 'swarm, no agents' + + const busy = snap.agents.filter(agent => /busy|active/i.test(agent.status)).length + + return busy === 0 ? `${total} agent${total === 1 ? '' : 's'} idle` : `${busy}/${total} agents busy` +} + +/** Dollars a person reads at a glance: cents under $100, whole dollars with separators above. */ +export function money(usd: number): string { + return usd < 100 ? `$${usd.toFixed(2)}` : `$${Math.round(usd).toLocaleString('en-US')}` +} + +export function barParts(state: State, nowMs: number = Date.now()): BarPart[] { + const snap = state.snapshot + const parts: BarPart[] = [] + + // What needs a person: approvals waiting and warn/bad alerts. Info alerts (a claim held for days) stay in the pane. + 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' }) + + const swarm = swarmText(state) + + if (swarm !== null) parts.push({ text: swarm, tone: 'plain' }) + if (state.usage?.costUsd !== undefined && state.usage.costUsd >= 0.01) parts.push({ text: `${money(state.usage.costUsd)} this session`, tone: 'plain' }) const claims = snap?.claims ?? [] if (claims.length > 0) { const stealable = claims.filter(claim => claim.isStealable).length - parts.push(`${claims.length} claim${claims.length === 1 ? '' : 's'}${stealable > 0 ? ` (${stealable} stealable)` : ''}`) + parts.push({ text: `${claims.length} claim${claims.length === 1 ? '' : 's'}${stealable > 0 ? ` (${stealable} stealable)` : ''}`, tone: 'plain' }) } - if (snap?.neural?.patterns !== undefined) parts.push(`${count(snap.neural.patterns)} patterns`) - if (state.ruflo.route !== null) parts.push(`→ ${state.ruflo.route.agent}`) - if (snap?.plugins.missingFromClone.length) parts.push('marketplace STALE') - if (state.usage?.costUsd !== undefined) parts.push(`$${state.usage.costUsd.toFixed(2)}`) + if (state.ruflo.route !== null) parts.push({ text: `routed → ${state.ruflo.route.agent}`, tone: 'plain' }) - return parts.join(' · ') + // Learning shows as growth since the console loaded; the running total lives in the Learning view (6). + const patterns = state.history.patterns + + if (patterns.length > 1) { + const learned = (patterns[patterns.length - 1] as { value: number }).value - (patterns[0] as { value: number }).value + + if (learned > 0) parts.push({ text: `+${count(learned)} learned`, tone: 'plain' }) + } + + return parts +} + +/** The band's words, for `/ruflo status` and anything that wants it as one line. */ +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 { - const words = barText(state) - const room = Math.max(8, columns - (state.pane.isOpen ? 14 : 30)) + // 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)) + const children: RenderElement[] = [mark !== null ? mark : kit.Text({ color: 'claude', children: '◆ ' }), kit.Text({ dimColor: true, children: 'ruflo' })] - return kit.Box({ - flexDirection: 'row', - children: [ - ...(mark !== null ? [mark] : [kit.Text({ color: 'claude', children: '◆ ' })]), - kit.Text({ wrap: 'truncate-end', ...(state.snapshot?.plugins.missingFromClone.length ? { color: 'warning' } : { dimColor: true }), children: clip(words, room) }), - kit.Text({ children: ' ' }), - ...(state.pane.isOpen ? [] : [kit.Text({ dimColor: true, children: '/ruflo to open ' })]), - kit.Button({ key: 'open-console', label: 'console', plain: true, onPress: onOpen }), - ], - }) + room -= 5 + + for (const part of parts) { + const words = ` · ${part.text}` + + if (room <= 3) break + children.push(kit.Text({ wrap: 'truncate-end', ...(part.tone === 'attention' ? { color: 'warning' } : { dimColor: true }), children: clip(words, room) })) + room -= words.length + } + + if (!state.pane.isOpen) children.push(kit.Text({ children: ' ' }), kit.Button({ key: 'open-console', label: 'open console', plain: true, onPress: onOpen })) + + return kit.Box({ flexDirection: 'row', children }) } diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts index 1e5c0fd5fa..efbf8eca29 100644 --- a/plugins/ruflo-console/hooks/views/common.ts +++ b/plugins/ruflo-console/hooks/views/common.ts @@ -76,7 +76,7 @@ export function count(value: number | null | undefined): string { export const pct = (value: number | null | undefined): string => (value === null || value === undefined || !Number.isFinite(value) ? 'n/a' : `${Math.round(value * 100)}%`) -export function text(ctx: Ctx, children: string, props: { color?: string; bold?: boolean; dimColor?: boolean } = {}): RenderElement { +export function text(ctx: Ctx, children: string, props: { color?: string; bold?: boolean; dimColor?: boolean; italic?: boolean } = {}): RenderElement { return ctx.kit.Text({ wrap: 'truncate-end', ...props, children: clip(children, Math.max(4, ctx.columns)) }) } diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.ts index 297ce7a593..0886e27234 100644 --- a/plugins/ruflo-console/hooks/views/frames.ts +++ b/plugins/ruflo-console/hooks/views/frames.ts @@ -5,6 +5,7 @@ */ import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli' import { recentByAgent } from '../data/events' +import { agentLabels } from '../data/parse' import type { Snapshot } from '../data/snapshot' import type { Channels, Peers, Roster } from '../data/cli' import { pipelinePicture, radarPicture, samplesPicture, trendPicture, gaugePicture, type Stage } from '../gfx/charts' @@ -31,6 +32,7 @@ export function topoModelOf(snapshot: Snapshot | null, pulses: Map 0 ? snapshot.agents.filter(agent => swarm.agentIds.includes(agent.id)) : snapshot.agents + const labels = agentLabels(snapshot.agents) const leaderId = snapshot.hive?.queen ?? swarm?.id ?? 'swarm' const leaderPulse = pulses.get(leaderId) @@ -41,7 +43,7 @@ export function topoModelOf(snapshot: Snapshot | null, pulses: Map { const pulseAtMs = pulses.get(agent.id) - return { id: agent.id, label: agent.name ?? agent.type, status: agent.status, isLeader: false, ...(pulseAtMs !== undefined && { pulseAtMs }) } + return { id: agent.id, label: labels.get(agent.id) ?? agent.type, status: agent.status, isLeader: false, ...(pulseAtMs !== undefined && { pulseAtMs }) } }), ], } @@ -93,11 +95,12 @@ export function healthRowsOf(state: State): HealthRow[] { /** The timeline's lanes over the last 15 minutes: ruflo agents' observed statuses and Claude Code's tool calls. */ export function lanesOf(state: State, nowMs: number): Lane[] { const from = nowMs - TIMELINE_MS + const labels = agentLabels(state.snapshot?.agents ?? []) const agents = (state.snapshot?.agents ?? []).slice(0, 24).map(agent => { const log = state.statusLog.get(agent.id) ?? [] return { - label: agent.name ?? agent.type, + label: labels.get(agent.id) ?? agent.type, spans: log.map((entry, i) => ({ fromMs: Math.max(from, entry.atMs), toMs: log[i + 1]?.atMs ?? nowMs, busy: /busy|active|working/i.test(entry.status) })).filter(span => span.toMs >= from), ticks: [], } @@ -128,7 +131,7 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb break } case 'claims': { - const cards = flowModelOf(snapshot?.claims ?? [], openTasks(state), snapshot?.agents ?? []) + const cards = flowModelOf(snapshot?.claims ?? [], openTasks(state), snapshot?.agents ?? [], snapshot?.tasks ?? []) if (cards.length > 0) pictures.set('flow', flowPicture(cards, width, flowRows(cards), nowMs)) break diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts index aa0ae1f325..e508cfba59 100644 --- a/plugins/ruflo-console/hooks/views/pane.ts +++ b/plugins/ruflo-console/hooks/views/pane.ts @@ -23,6 +23,8 @@ import { pluginsView } from './plugins' import { swarmView } from './swarm' export const NARROW = 44 +/** Width from which the current tab spells its name beside its icon. */ +const WIDE_TABS = 110 const BODIES: Record RenderElement> = { overview: overviewView, @@ -49,21 +51,43 @@ function tabs(ctx: Ctx): RenderElement { return text(ctx, `${index < 0 ? '·' : `${index + 1}/${VIEWS.length}`} ${label} · /ruflo help`, { bold: true, color: THEME.head }) } - const isShort = ctx.columns < 132 - + // Every tab is its icon; the current one adds its name in the heading colour, so the bar reads at a glance and + // still fits a docked pane. The names are in /ruflo help and in the line under the bar. return ctx.kit.Box({ flexDirection: 'row', gap: 1, key: 'tabs', children: VIEWS.map(view => { const isCurrent = view.id === ctx.state.view || (ctx.state.view === 'agent' && view.id === ctx.state.back) - const label = isShort ? view.short : view.label - return ctx.kit.Button({ key: `tab-${view.id}`, label: isCurrent ? `${label}◂` : label, hotkey: view.key, plain: true, ...(isCurrent ? {} : { dimColor: true }), onPress: () => ctx.act.view(view.id) }) + // A Button cannot be styled, so the current tab is Text: its key is not needed, the view is already open + // (from a drill-down, b goes back). + // The dock's width is the engine's (it keeps where the divider was left): the name joins the icon only where + // the bar has room for it, and the line under the bar always leads with it. + if (isCurrent) return ctx.kit.Box({ key: `tab-${view.id}`, children: [ctx.kit.Text({ bold: true, color: THEME.head, wrap: 'truncate-end', children: ctx.columns >= WIDE_TABS ? `${view.key}:${view.icon} ${view.label}` : `${view.key}:${view.icon}` })] }) + + return ctx.kit.Button({ key: `tab-${view.id}`, label: view.icon, hotkey: view.key, plain: true, dimColor: true, onPress: () => ctx.act.view(view.id) }) }), }) } +/** One line under the tabs saying what the current view is for. */ +function blurb(ctx: Ctx): RenderElement | null { + if (ctx.columns < NARROW) return null + + const view = VIEWS.find(entry => entry.id === (ctx.state.view === 'agent' ? ctx.state.back : ctx.state.view)) + + if (view === undefined) return null + + const name = ctx.state.view === 'agent' ? 'Agent' : view.label + const about = ctx.state.view === 'agent' ? `one agent's role, task, claims, activity and logs · b goes back to ${view.label}` : view.blurb + + return row(ctx, [ + ctx.kit.Text({ bold: true, color: THEME.head, children: `${view.icon} ${name}` }), + ctx.kit.Text({ dimColor: true, italic: true, wrap: 'truncate-end', children: clip(` — ${about}`, Math.max(4, ctx.columns - name.length - 2)) }), + ], 'about') +} + function help(ctx: Ctx): RenderElement { return col(ctx, [...HELP.split('\n').map((line, i) => text(ctx, line || ' ', i === 0 ? { bold: true, color: THEME.head } : /^[A-Z]/.test(line) ? { bold: true } : { dimColor: i > 20 })), row(ctx, [button(ctx, 'help-close', 'Back', ctx.act.help, { hotkey: 'h' })])], 'help') } @@ -131,7 +155,8 @@ export function paneView(ctx: Ctx): RenderElement { const header = ctx.pictures.get('header') const isCompact = ctx.state.pane.rows > 0 && ctx.state.pane.rows < rowsOf(ctx.state.view) const title = !isCompact && header !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(header.toRaster('header'))] : [] - const parts = isCompact ? [tabs(ctx), ...(confirm !== null ? [confirm] : []), footer(ctx), body] : [...title, tabs(ctx), body, ...(confirm !== null ? [confirm] : []), footer(ctx)] + const about = blurb(ctx) + const parts = isCompact ? [tabs(ctx), ...(confirm !== null ? [confirm] : []), footer(ctx), body] : [...title, tabs(ctx), ...(about !== null ? [about] : []), body, ...(confirm !== null ? [confirm] : []), footer(ctx)] return ctx.kit.Box({ flexDirection: 'column', children: parts }) } diff --git a/plugins/ruflo-console/hooks/views/swarm.ts b/plugins/ruflo-console/hooks/views/swarm.ts index 688290ea2b..ddd0f67924 100644 --- a/plugins/ruflo-console/hooks/views/swarm.ts +++ b/plugins/ruflo-console/hooks/views/swarm.ts @@ -1,5 +1,6 @@ import type { RenderElement } from 'claude-code' +import { agentLabels, shortId } from '../data/parse' import { button, clip, col, kv, picture, row, rule, text, THEME, type Ctx } from './common' import { selection } from './select' @@ -28,8 +29,11 @@ export function swarmView(ctx: Ctx): RenderElement { rows.push(kv(ctx, 'topology', swarm === null ? `${hive?.topology ?? 'n/a'} (hive-mind)` : `${swarm.topology}${swarm.strategy !== undefined ? ` · ${swarm.strategy}` : ''} · ${swarm.status}${swarm.maxAgents !== undefined ? ` · max ${swarm.maxAgents}` : ''}`)) rows.push(picture(ctx, 'topology', `graph needs a terminal: ${agents.length} agents`)) - rows.push(text(ctx, '★ leader (its heartbeat is decoration) · ● idle / busy / stopped as ruflo wrote them · a white pulse = an event about that agent', { dimColor: true })) + rows.push(text(ctx, '★ leader · ◉ busy (a dot runs to it while it works) · ● idle · grey stopped · a white flash = an event about that agent', { dimColor: true })) rows.push(rule(ctx, 'Agents', `${agents.length} · j/k pick · d open · x actions`)) + const labels = agentLabels(agents) + // The type column only earns its room when some agent has a name that is not its type. + const hasTypes = agents.some(agent => agent.name !== undefined && agent.name !== agent.type) for (const agent of agents.slice(0, 10)) { const isPicked = picked?.id === agent.id @@ -41,7 +45,8 @@ export function swarmView(ctx: Ctx): RenderElement { ctx.kit.Text({ wrap: 'truncate-end', ...(isPicked && { bold: true }), - children: clip(`${(agent.name ?? agent.type).padEnd(14)} ${agent.type.padEnd(12)} ${agent.status.padEnd(9)} tasks ${agent.taskCount ?? 'n/a'} · health ${agent.health === undefined ? 'n/a' : `${Math.round(agent.health * 100)}%`} · ${agent.id}`, ctx.columns - 3), + // One label (name, else type, with a short id only where two read the same); the type only when it differs. + children: clip(`${(labels.get(agent.id) ?? agent.type).padEnd(16)} ${agent.status.padEnd(8)} ${hasTypes ? `${(agent.name !== undefined && agent.name !== agent.type ? agent.type : '').padEnd(12)} ` : ''}tasks ${agent.taskCount ?? 'n/a'} · health ${agent.health === undefined ? 'n/a' : `${Math.round(agent.health * 100)}%`} · #${shortId(agent.id)}`, ctx.columns - 3), }), ]), ) diff --git a/plugins/ruflo-console/tests/band.spec.ts b/plugins/ruflo-console/tests/band.spec.ts new file mode 100644 index 0000000000..c7b03a5538 --- /dev/null +++ b/plugins/ruflo-console/tests/band.spec.ts @@ -0,0 +1,73 @@ +/** + * The band's words under vitest: most important first, never a zero that says nothing. + * npx vitest run plugins/ruflo-console/tests/band.spec.ts + */ +import { describe, expect, it } from 'vitest' + +import type { ReadCache } from '../hooks/data/files' +import { readSnapshot } from '../hooks/data/snapshot' +import { newState } from '../hooks/state' +import { barParts, barText, money } from '../hooks/views/bar' +import { RUFLO_FILES } from './fixtures/ruflo-run' + +const memoryFs = (files: Record) => ({ + read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')), + stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: (files[path] as string).length } : Promise.reject(new Error('ENOENT'))), + list: async () => Promise.reject(new Error('ENOENT')), +}) + +async function capturedState(marketplace: string[]) { + const files = { + ...Object.fromEntries(Object.entries(RUFLO_FILES).map(([path, text]) => [`/work/${path}`, text])), + '/home/dev/.claude/plugins/known_marketplaces.json': JSON.stringify({ ruflo: { installLocation: '/home/dev/m/ruflo' } }), + '/home/dev/m/ruflo/.claude-plugin/marketplace.json': JSON.stringify({ plugins: marketplace.map(name => ({ name })) }), + } + const state = newState({}) + + state.snapshot = await readSnapshot(memoryFs(files), new Map() as ReadCache, '/work', '/home/dev', {}, 0) + + return state +} + +describe('band', () => { + it('leads with what needs a person, then the swarm in words, then the rest', async () => { + const state = await capturedState(['ruflo-core', 'ruflo-swarm', 'ruflo-mods', 'ruflo-console']) + + state.usage = { costUsd: 1010.66 } + state.ruflo.route = { agent: 'coder', confidence: 0.8, matched: true, reason: 'keyword' } + state.history.patterns = [{ atMs: 0, value: 7466 }, { atMs: 1, value: 7478 }] + + const parts = barParts(state, 0) + + expect(parts.filter(part => part.tone === 'attention').map(part => part.text)).toEqual(['2 to approve (q)']) + expect(barText(state, 0)).toBe('ruflo · 2 to approve (q) · 2 agents idle · $1,011 this session · 2 claims (1 stealable) · routed → coder · +12 learned') + }) + + 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(barText(state, 0)).not.toContain('STALE') + }) + + it('never says 0/0: an empty swarm is named as such, and no growth means no learned part', () => { + const state = newState({}) + + state.snapshot = { swarm: { topology: 'hierarchical', agentIds: [] }, agents: [], claims: [], plugins: { missingFromClone: [] }, daemon: null, isRufloProject: true } as never + state.history.patterns = [{ atMs: 0, value: 7466 }, { atMs: 1, value: 7466 }] + expect(barText(state, 0)).toBe('ruflo · swarm, no agents') + }) + + it('money: cents under $100, whole dollars with separators above', () => { + expect(money(0.4213)).toBe('$0.42') + expect(money(99.994)).toBe('$99.99') + expect(money(1010.66)).toBe('$1,011') + }) + + it('no spend part until there is a cent to show', () => { + const state = newState({}) + + state.usage = { costUsd: 0.004 } + expect(barText(state, 0)).toBe('ruflo') + }) +}) diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.ts index 6ba556f7b6..960df24e15 100644 --- a/plugins/ruflo-console/tests/behaviour.test.ts +++ b/plugins/ruflo-console/tests/behaviour.test.ts @@ -14,9 +14,9 @@ describe('behaviour', () => { const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN }) - expect(textOf(await pane.drawn())).toContain('Ovr◂') + expect(textOf(await pane.drawn())).toContain('⌂ Overview') await pane.press({ key: 'tab-claims' }) - expect(textOf(await pane.drawn())).toContain('Clm◂') + expect(textOf(await pane.drawn())).toContain('⚑ Claims') expect(world.stored.get('ruflo-console/ui:/work')).toEqual({ view: 'claims', isClosedByPerson: false }) expect(world.opened.length).toBeGreaterThanOrEqual(2) await pane.unmount() @@ -96,7 +96,7 @@ describe('behaviour', () => { const pane = await $.ui.mount({ ...paneAt(100), plugin: PLUGIN }) const text = textOf(await pane.drawn()) - expect(text).toContain('◂') + expect(text).toMatch(/\n\S [A-Z][A-Za-z]+\n — \w/) // the line under the tabs: icon, view name, what it is for await pane.unmount() } @@ -197,7 +197,8 @@ describe('behaviour', () => { const swarm = textOf(await $.ui.render(paneAt(110))) - expect(swarm).toContain('c1 [31m EVIL') + expect(swarm).toContain('c1 EVIL') // the whole colour sequence is gone, not just its ESC byte + expect(swarm).not.toContain('[31m') expect(swarm).not.toMatch(/[\u0000-\u001f‪-‮](? { await $.session.start(SESSION) await $.command.run(command('status')) - expect(textOf(await $.ui.render(BAND))).toContain('ruflo · hierarchical 0/2 busy · 2 claims (1 stealable) · 30.8k patterns · → tester · $0.42') + // One Text per part (attention parts are coloured); the row lays them side by side, the harness joins with \n. + const band = textOf(await $.ui.render(BAND)).replace(/\n/g, '') + + expect(band).toContain('ruflo · 3 to approve (q) · ⚠ 1 alert · 2 agents idle · $0.42 this session · 2 claims (1 stealable)') + expect(band).not.toMatch(/0\/\d+ busy|\d patterns/) + expect(band).toContain('open console') expect(textOf(await $.ui.render({ ...BAND, props: { ...BAND.props, hasSurvey: true } }))).toBe('engine') await $.ui.render({ ...BAND, props: { ...BAND.props, isWorking: true } }) diff --git a/plugins/ruflo-console/tests/diagrams.spec.ts b/plugins/ruflo-console/tests/diagrams.spec.ts index 0d776c0b0b..4a119ef302 100644 --- a/plugins/ruflo-console/tests/diagrams.spec.ts +++ b/plugins/ruflo-console/tests/diagrams.spec.ts @@ -64,14 +64,25 @@ describe('diagrams', () => { }) it('an event pulse is data: it runs only in the 1.4 s after its event, and the frames differ while it does', () => { - const model = swarmOf(3, 'hierarchical', 99) + const idle = (model: TopoModel): TopoModel => ({ ...model, nodes: model.nodes.map(node => (node.isLeader ? node : { ...node, status: 'idle' })) }) + const model = idle(swarmOf(3, 'hierarchical', 99)) const frame = (t: number) => topologyPicture(model, 60, 12, t).encode() expect(frame(1_300)).not.toBe(frame(1_900)) - // Before the event, at two instants where the heartbeat (decoration) rests: nothing else moves. + // Before the event, with every agent idle, at two instants where the heartbeat (decoration) rests: nothing else moves. expect(frame(0)).toBe(frame(Math.PI * 260)) }) + it('work in flight is data too: a busy agent keeps a dot moving with no event, and it stops when the agent goes idle', () => { + const busy: TopoModel = { topology: 'hierarchical', nodes: [{ id: 'q', label: 'queen', status: 'leader', isLeader: true }, { id: 'a', label: 'coder', status: 'busy', isLeader: false }] } + const idle: TopoModel = { ...busy, nodes: busy.nodes.map(node => (node.isLeader ? node : { ...node, status: 'idle' })) } + // Two instants where the leader's heartbeat rests, so only data can differ between them. + const [t0, t1] = [0, Math.PI * 260] + + expect(topologyPicture(busy, 60, 12, t0).encode()).not.toBe(topologyPicture(busy, 60, 12, t1).encode()) + expect(topologyPicture(idle, 60, 12, t0).encode()).toBe(topologyPicture(idle, 60, 12, t1).encode()) + }) + it('claims fall in their lanes and a ring counts down a TTL on the real clock, else fills with age', () => { expect(flowModelOf(claims, []).map(card => [card.id, card.lane])).toEqual([ ['console-demo-1', 'claimed'], diff --git a/plugins/ruflo-console/tests/pure.spec.ts b/plugins/ruflo-console/tests/pure.spec.ts index 7e3ad6e560..3963738993 100644 --- a/plugins/ruflo-console/tests/pure.spec.ts +++ b/plugins/ruflo-console/tests/pure.spec.ts @@ -25,6 +25,11 @@ const memoryFs = (files: Record) => ({ }) describe('readers', () => { + it('plain() drops whole ANSI colour sequences, not just the ESC byte', () => { + expect(plain('\u001b[1mLogs for agent-1\u001b[0m')).toBe('Logs for agent-1') + expect(plain('\u001b[2m11:24:13 AM\u001b[0m [INFO] created')).toBe('11:24:13 AM [INFO] created') + }) + it('read the captured run: one swarm, two agents, two claims (one stealable), a queen and a proposal, no token', () => { expect(parseSwarmStore(at('.claude-flow/swarm/swarm-state.json'))).toMatchObject({ id: 'swarm-1790903031804-y9rnjr', topology: 'hierarchical', status: 'running', strategy: 'specialized', maxAgents: 6 }) expect(parseAgents(at('.claude-flow/agents/store.json')).map(agent => `${agent.type}:${agent.status}`)).toEqual(['coder:idle', 'tester:idle']) @@ -53,7 +58,7 @@ describe('readers', () => { }) it('plain strips control and bidi characters; idOf admits only id-shaped strings', () => { - expect(plain('a\u001b[31m‮b\u0000c')).toBe('a [31m b c') + expect(plain('a\u001b[31m‮b\u0000c')).toBe('a b c') expect(plain('x'.repeat(50), 10)).toHaveLength(10) expect(idOf('agent-1790903032181-97m25s')).toBe('agent-1790903032181-97m25s') for (const bad of ['bad id!', '-rf', '', 'a'.repeat(200), '../etc', 42]) expect(idOf(bad)).toBeNull() diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts index 609ca17ef0..2d0156a7b2 100644 --- a/plugins/ruflo-console/tests/views.test.ts +++ b/plugins/ruflo-console/tests/views.test.ts @@ -61,7 +61,9 @@ describe('views', () => { expect(rasters).toEqual(['header', 'topology']) expect(text).toContain('hierarchical · specialized · running · max 6') - expect(text).toMatch(/▸● \ncoder\s+coder\s+idle/) + // One label per agent (no repeated type), then status; a short id instead of the full one. + expect(text).toMatch(/▸● \ncoder\s+idle\s+tasks/) + expect(text).toMatch(/· #[a-z0-9]{4,6}/) expect(text).toContain('design (raft) pending · for 0 · against 0') expect(text).not.toContain(HIVE_TOKEN) expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['agent-next', 'agent-prev', 'drill', 'palette', 'actions']))