🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(console): Workflows layout at every dock width, replay play loop, quiet stale presses (ADR-469)
ruv6206c1161709
diff --git a/plugins/ruflo-console/hooks/data/wf-replay.ts b/plugins/ruflo-console/hooks/data/wf-replay.tsindex e70e7e7738..7234273c50 100644--- a/plugins/ruflo-console/hooks/data/wf-replay.ts+++ b/plugins/ruflo-console/hooks/data/wf-replay.ts@@ -141,6 +141,28 @@ export function stepNow(ui: ReplayUi, tl: Timeline, nowMs: number): number {return step}+/** The most events one clock tick may carry a playing replay over: a tick is bounded work however fast the speed or long the gap since the last. */+export const TICK_MAX_STEPS = 400++/**+ * A playing replay brought up to `nowMs` and re-based there, so the next tick scans only the events that fall after it (never again from+ * where play began). The clock keeps its fractional progress between two events (a step minutes apart at 16x is reached by ticks, not+ * lost to each of them). It stops at the end, and carries at most TICK_MAX_STEPS events in one call. A paused replay is returned as it is.+ */+export function settle(ui: ReplayUi, tl: Timeline, nowMs: number): ReplayUi {+ if (ui.playFromMs === null) return ui++ const n = tl.events.length+ const from = Math.max(0, Math.min(n, ui.step))+ const clock = ui.baseMs + Math.max(0, nowMs - ui.playFromMs) * ui.speed+ const reached = stepNow(ui, tl, nowMs)+ const step = Math.min(reached, from + TICK_MAX_STEPS)++ if (step >= n) return { ...ui, step: n, baseMs: offsetOf(tl, n), playFromMs: null }++ return { ...ui, step, baseMs: step < reached ? offsetOf(tl, step) : clock, playFromMs: nowMs }+}+export const isPlaying = (ui: ReplayUi, tl: Timeline, nowMs: number): boolean => ui.playFromMs !== null && stepNow(ui, tl, nowMs) < tl.events.lengthexport type ReplayCommand = 'next' | 'prev' | 'first' | 'last' | 'next-phase' | 'prev-phase' | 'play' | 'faster' | 'slower'diff --git a/plugins/ruflo-console/hooks/press-guard.ts b/plugins/ruflo-console/hooks/press-guard.tsnew file mode 100644index 0000000000..0d878bb935--- /dev/null+++ b/plugins/ruflo-console/hooks/press-guard.ts@@ -0,0 +1,22 @@+/**+ * A press that outlived its drawing (ADR-469). The engine holds a Button's `onPress` only for the life of the drawing that made it+ * (types: "The host holds only a handle, for the drawing's life"). A click that was sent while the pane was redrawn (a resize, a refresh+ * tick, a view switch) can reach the engine after the drawing it was aimed at is gone: the chain then ends at a handle nobody holds,+ * and the engine logs "ui.press hook skipped… no handler is held under handle". Nothing was lost but that click, and it is not an+ * error of ours, so the `ui.press` hook answers it quietly with the element it was aimed at instead of letting it throw into the log.+ * Every other failure still propagates.+ */+export const STALE_HANDLE = /no handler is held/i++const messageOf = (error: unknown): string => (error instanceof Error ? error.message : typeof error === 'string' ? error : '')++/** `next()`'s answer, or `fallback` when it fails only because the press's handler is no longer held. */+export async function tolerantPress<R>(next: () => R | Promise<R>, fallback: R): Promise<R> {+ try {+ return await next()+ } catch (error) {+ if (STALE_HANDLE.test(messageOf(error))) return fallback++ throw error+ }+}diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsindex 4507b8fede..f8f6fe665e 100644--- a/plugins/ruflo-console/hooks/register.ts+++ b/plugins/ruflo-console/hooks/register.ts@@ -1,4 +1,5 @@import type { EngineInterface, PluginOptions, Register } from 'claude-code'+import { tolerantPress } from './press-guard'import { ANSWER_KEYS } from './views/attention'import { createController, type Controller } from './controller'@@ -261,7 +262,8 @@ export const register: Register = (on, raw: PluginOptions) => {on('ui.press', { component: 'Pane' }, ($, e, next) => {if (!ANSWER_KEYS.has(e.element)) state.lastPressed = e.element- return next(e)+ // A click that reaches the engine after its drawing was replaced (a resize) finds no handler: answered quietly (press-guard.ts).+ return tolerantPress(() => next(e), { element: e.element })})on('ui.input', { component: 'Pane' }, ($, e, next) => {diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.tsindex 00aa334da0..ace04b1486 100644--- a/plugins/ruflo-console/hooks/views/common.ts+++ b/plugins/ruflo-console/hooks/views/common.ts@@ -264,18 +264,22 @@ export function section(ctx: Ctx, id: string, title: string, right: string, chilexport function rule(ctx: Ctx, title: string, right = ''): RenderElement {if (look === 'bbs') {// BBS section header: ▓▒░ SWARM ░▒▓══════════ right- const head = `▓▒░ ${title.toUpperCase()} ░▒▓`- const fill = Math.max(1, ctx.columns - head.length - right.length - 2)+ const head = `▓▒░ ${clip(title, Math.max(4, ctx.columns - 12)).toUpperCase()} ░▒▓`+ const room = Math.max(0, ctx.columns - head.length - 3)+ const tail = clip(right, room)+ const fill = Math.max(1, ctx.columns - head.length - tail.length - 2)- const line = row(ctx, [ctx.kit.Text({ bold: true, color: accentOf(ctx), children: head }), ctx.kit.Text({ color: accentOf(ctx), dimColor: true, children: `${'═'.repeat(fill)} ` }), ctx.kit.Text({ color: accentOf(ctx), children: right })])+ const line = row(ctx, [ctx.kit.Text({ bold: true, color: accentOf(ctx), wrap: 'truncate-end', children: head }), ctx.kit.Text({ color: accentOf(ctx), dimColor: true, children: `${'═'.repeat(fill)} ` }), ctx.kit.Text({ color: accentOf(ctx), wrap: 'truncate-end', children: tail })])// In a card the header is the card's first row; otherwise a blank line above each section, so the board breathes instead of packing every block together.return ctx.cards === true ? marked(HEADS, line) : marked(HEADS, col(ctx, [ctx.kit.Text({ children: ' ' }), line]))}- const fill = Math.max(1, ctx.columns - title.length - right.length - 3)+ const name = clip(title, Math.max(4, ctx.columns - 4))+ const tail = clip(right, Math.max(0, ctx.columns - name.length - 4))+ const fill = Math.max(1, ctx.columns - name.length - tail.length - 3)- return marked(HEADS, row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, children: title }), ctx.kit.Text({ dimColor: true, children: ` ${'─'.repeat(fill)} ` }), ctx.kit.Text({ dimColor: true, children: right })]))+ return marked(HEADS, row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, wrap: 'truncate-end', children: name }), ctx.kit.Text({ dimColor: true, children: ` ${'─'.repeat(fill)} ` }), ctx.kit.Text({ dimColor: true, wrap: 'truncate-end', children: tail })]))}/** A label and its value; the value dims when it is n/a. */diff --git a/plugins/ruflo-console/hooks/views/wf-compare.ts b/plugins/ruflo-console/hooks/views/wf-compare.tsindex 9195acc7bb..7f384f998e 100644--- a/plugins/ruflo-console/hooks/views/wf-compare.ts+++ b/plugins/ruflo-console/hooks/views/wf-compare.ts@@ -5,9 +5,10 @@import type { RenderElement } from 'claude-code'import { compareRuns, fmtRatio, otherRunsOf, TIME_DELTA, TOKEN_DELTA, type AgentDiff, type Comparison, type Mark } from '../data/wf-compare'-import { fmtElapsed, fmtTokens, shortId, type WfAgent, type WfRun } from '../data/workflows'-import { button, clip, row, text, THEME, type Ctx } from './common'+import { fmtElapsed, fmtTokens, type WfAgent, type WfRun } from '../data/workflows'+import { clip, row, text, THEME, type Ctx } from './common'import { fold, redraw } from './wf-fold'+import { flow, runTag } from './wf-layout'import { registerSlot, type SlotEnv } from './wf-slots'const against = new Map<string, string>()@@ -78,8 +79,8 @@ export function compareBody(env: SlotEnv, run: WfRun): RenderElement[] {}return [- row(ctx, [text(ctx, ` A ${shortId(run.id)}`, { bold: true }), text(ctx, ' vs '), text(ctx, `B ${shortId(other.id)}`, { bold: true }), text(ctx, total > 1 ? ` (${total} other runs of this workflow)` : '', { dimColor: true })], 'wf-cmp-ids'),- row(ctx, [...(total > 1 ? [button(ctx, 'wf-cmp-prev', '◂ other run', () => (stepPartner(run, runs, -1), redraw(ctx))), button(ctx, 'wf-cmp-next', 'other run ▸', () => (stepPartner(run, runs, 1), redraw(ctx)))] : []), button(ctx, 'wf-cmp-only', isOnly ? 'show all agents' : 'changed only', flip)], 'wf-cmp-controls'),+ row(ctx, [text(ctx, ` A ${runTag(run.id)}`, { bold: true }), text(ctx, ' vs '), text(ctx, `B ${runTag(other.id)}`, { bold: true }), text(ctx, total > 1 ? ` (${total} other runs of this workflow)` : '', { dimColor: true })], 'wf-cmp-ids'),+ ...flow(ctx, [...(total > 1 ? [{ key: 'wf-cmp-prev', label: '◂ other run', onPress: () => (stepPartner(run, runs, -1), redraw(ctx)) }, { key: 'wf-cmp-next', label: 'other run ▸', onPress: () => (stepPartner(run, runs, 1), redraw(ctx)) }] : []), { key: 'wf-cmp-only', label: isOnly ? 'show all agents' : 'changed only', onPress: flip }], 'wf-cmp-controls'),...totalsRows(ctx, result),text(ctx, ` ${result.counts.same} same · ${result.counts.changed} changed · ${result.counts.added} only in B (+) · ${result.counts.removed} only in A (-) ~ = tokens off by ${TOKEN_DELTA * 100}% or time by ${TIME_DELTA * 100}% or a state/model change`, { dimColor: true }),...shown.slice(0, ROWS_MAX).map(entry => diffRow(ctx, entry)),diff --git a/plugins/ruflo-console/hooks/views/wf-detail.ts b/plugins/ruflo-console/hooks/views/wf-detail.tsindex e4318f3f21..f1839ebab7 100644--- a/plugins/ruflo-console/hooks/views/wf-detail.ts+++ b/plugins/ruflo-console/hooks/views/wf-detail.ts@@ -17,7 +17,8 @@ import { isBound, loadDiff, loadResult, loadTranscript, noteOf, parsedOf, reloadimport { filterLines, logLines, mergeLines, nextFilter, type LogLine } from '../data/wf-log'import { crumbs, deeper, jump, LEVEL_NAME, move, nextSub, newDrill, shallower, sync, toLevel, type Drill, type DrillLevel, type Here, type PageKey, type Step, type Sub, type Target } from '../data/wf-trail'import { fmtElapsed, fmtTokens } from '../data/workflows'-import { button, clip, col, row, text, THEME } from './common'+import { clip, col, text, THEME } from './common'+import { crumbRow, flow } from './wf-layout'import { agentBody, itemBody, type Model, type Ops } from './wf-drill-body'import { registerSlot, type SlotEnv } from './wf-slots'import type { State } from '../state'@@ -158,26 +159,21 @@ const opsOf = (env: SlotEnv, m: Model): Ops => ({scroll: by => commit(env, { drill: { ...m.drill, scroll: Math.max(0, m.drill.scroll + by) } }),})-/** The breadcrumb: each level so far as a button that goes back to it, the level you are on in bold. */+/**+ * The breadcrumb: each level so far as a button that goes back to it, the level you are on in bold. It folds its middle crumbs before it+ * wraps (`Runs › … › Agent: x`), keeps the last crumb whole, and leaves the sub-tab (Activity, Log, Files, Result) to the tab row below it.+ */function breadcrumb(env: SlotEnv, m: Model): RenderElement {const { ctx } = envconst names: Record<DrillLevel, string> = {- runs: env.run?.name ?? '—',- phases: env.phase?.title ?? '—',- agents: env.agent?.label ?? '—',- agent: '',- item: m.drill.sub === 'log' ? `line ${m.drill.follow ? m.lines.length : m.drill.logSel + 1}` : `call ${m.drill.callSel + 1}`,- }- const parts: RenderElement[] = []-- for (const crumb of crumbs(m.drill)) {- const label = crumb.level === 'agent' ? crumb.label : `${LEVEL_NAME[crumb.level]}: ${clip(names[crumb.level], 16)}`-- if (parts.length > 0) parts.push(text(ctx, ' › ', { dimColor: true }))- parts.push(crumb.isHere ? ctx.kit.Text({ bold: true, color: THEME.head, children: label }) : button(ctx, `wf-crumb-${crumb.level}`, label, () => commit(env, toLevel(m.drill, crumb.level))))+ runs: `: ${clip(env.run?.name ?? '—', 16)}`,+ phases: `: ${clip(env.phase?.title ?? '—', 16)}`,+ agents: '',+ agent: `: ${clip(env.agent?.label ?? '—', 20)}`,+ item: m.drill.sub === 'log' ? `: line ${m.drill.follow ? m.lines.length : m.drill.logSel + 1}` : `: call ${m.drill.callSel + 1}`,}- return row(ctx, parts, 'wf-crumbs')+ return crumbRow(ctx, crumbs(m.drill).map(crumb => ({ key: `wf-crumb-${crumb.level}`, label: `${LEVEL_NAME[crumb.level]}${names[crumb.level]}`, isHere: crumb.isHere, onPress: () => commit(env, toLevel(m.drill, crumb.level)) })), 'wf-crumbs', { here: label => ctx.kit.Text({ bold: true, color: THEME.head, wrap: 'truncate-end', children: label }) })}function list(env: SlotEnv, m: Model): RenderElement[] {@@ -220,7 +216,8 @@ function panel(env: SlotEnv): RenderElement[] {if (!m.drill.open) {return [- row(ctx, [button(ctx, 'wf-drill-open', 'Drill into this run', () => drillKey(env, 'in')), text(ctx, ` ${hint('in', 'deeper')} · ${hint('search', 'search')} — runs › phases › agents › one agent (activity, log, files, result) › one call`, { dimColor: true })]),+ ...flow(ctx, [{ key: 'wf-drill-open', label: 'Drill into this run', onPress: () => drillKey(env, 'in') }], 'wf-drill-open-row'),+ text(ctx, ` ${hint('in', 'deeper')} · ${hint('search', 'search')} — runs › phases › agents › one agent (activity, log, files, result) › one call`, { dimColor: true }),...(msg === undefined ? [] : [text(ctx, msg, { color: THEME.warn })]),]}@@ -235,7 +232,12 @@ function panel(env: SlotEnv): RenderElement[] {return [breadcrumb(env, m),- row(ctx, [button(ctx, 'wf-drill-in', '▸ deeper', () => drillKey(env, 'in')), button(ctx, 'wf-drill-out', m.drill.level === 'runs' ? '✕ close' : '◂ back', () => drillKey(env, 'out')), button(ctx, 'wf-drill-prev', '▴ prev', () => drillKey(env, 'prev')), button(ctx, 'wf-drill-next', '▾ next', () => drillKey(env, 'next'))], 'wf-drill-moves'),+ ...flow(ctx, [+ { key: 'wf-drill-in', label: '▸ deeper', onPress: () => drillKey(env, 'in') },+ { key: 'wf-drill-out', label: m.drill.level === 'runs' ? '✕ close' : '◂ back', onPress: () => drillKey(env, 'out') },+ { key: 'wf-drill-prev', label: '▴ prev', onPress: () => drillKey(env, 'prev') },+ { key: 'wf-drill-next', label: '▾ next', onPress: () => drillKey(env, 'next') },+ ], 'wf-drill-moves'),...(msg === undefined ? [] : [text(ctx, msg, { color: THEME.warn })]),col(ctx, body, 'wf-drill-body'),text(ctx, `keys: ${hint('in', 'deeper')} · ${hint('out', 'back')} · ${hint('next', 'next')} · ${hint('prev', 'prev')} · ${hint('sub', 'next tab')} · ${hint('follow', 'follow')} · ${hint('filter', 'level')} · ${hint('search', 'search')}`, { dimColor: true }),diff --git a/plugins/ruflo-console/hooks/views/wf-drill-body.ts b/plugins/ruflo-console/hooks/views/wf-drill-body.tsindex 973b2391e1..b2a91e203b 100644--- a/plugins/ruflo-console/hooks/views/wf-drill-body.ts+++ b/plugins/ruflo-console/hooks/views/wf-drill-body.ts@@ -13,6 +13,7 @@ import { SUBS, SUB_NAME, type Drill, type Sub } from '../data/wf-trail'import { TAIL_BYTES, TRANSCRIPT_CAP } from '../data/workflows-read'import { fmtTokens, type WfAgent, type WfRun } from '../data/workflows'import { button, clip, row, text, THEME, type Ctx } from './common'+import { buttonWidth, flow } from './wf-layout'import type { LevelFilter } from '../data/wf-log'export type Model = { drill: Drill; parsed: Parsed | null; lines: LogLine[]; /** Phase scope: agents of the phase whose transcript is not in memory. */ unread: number }@@ -35,14 +36,15 @@ function unread(ctx: Ctx, what: string, path: string | undefined, load: () => voreturn [text(ctx, `${what} is not in memory${why}.`, { color: THEME.warn }),- isBound()- ? row(ctx, [button(ctx, 'wf-drill-load', note?.phase === 'loading' ? 'reading…' : `Read it (up to ${cap(TRANSCRIPT_CAP)}; the last ${Math.round(TAIL_BYTES / 1000)} KB of a larger file)`, load)])- : text(ctx, 'The page reads a live run\'s transcripts as it refreshes; a finished run\'s figures come from its record, so they are not read. Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true }),+ ...(isBound()+ ? flow(ctx, [{ key: 'wf-drill-load', label: note?.phase === 'loading' ? 'reading…' : `Read it (up to ${cap(TRANSCRIPT_CAP)}; the last ${Math.round(TAIL_BYTES / 1000)} KB of a larger file)`, onPress: load }], 'wf-drill-load-row')+ : [text(ctx, 'The page reads a live run\'s transcripts as it refreshes; a finished run\'s figures come from its record, so they are not read. Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true })]),]}-function subTabs(ctx: Ctx, drill: Drill, ops: Ops): RenderElement {- return row(ctx, [text(ctx, 'view'), ...SUBS.map(sub => button(ctx, `wf-sub-${sub}`, `${drill.sub === sub ? '●' : '○'} ${SUB_NAME[sub]}`, () => ops.sub(sub)))], 'wf-subs')+/** The tab row of one agent: Activity, Log, Files, Result on a row of their own, wrapping rather than overrunning a narrow pane. */+function subTabs(ctx: Ctx, drill: Drill, ops: Ops): RenderElement[] {+ return flow(ctx, SUBS.map(sub => ({ key: `wf-sub-${sub}`, label: `${drill.sub === sub ? '●' : '○'} ${SUB_NAME[sub]}`, onPress: () => ops.sub(sub) })), 'wf-subs', 'view ')}const sourceLine = (ctx: Ctx, agent: WfAgent, parsed: Parsed, cache: Ctx['state']['cache']): RenderElement => {@@ -80,13 +82,13 @@ function activity(ctx: Ctx, m: Model, agent: WfAgent): RenderElement[] {function log(ctx: Ctx, m: Model, ops: Ops, isPhase: boolean): RenderElement[] {const window = tailWindow(m.lines, { sel: m.drill.logSel, follow: m.drill.follow })- const head = row(ctx, [- button(ctx, 'wf-log-follow', m.drill.follow ? '● following' : '○ follow', ops.follow),- button(ctx, 'wf-log-filter', `level: ${FILTER_WORD[m.drill.filter]}`, ops.filter),- button(ctx, 'wf-log-scope', isPhase ? 'scope: whole phase' : 'scope: this agent', ops.scope),+ const head = flow(ctx, [+ { key: 'wf-log-follow', label: m.drill.follow ? '● following' : '○ follow', onPress: ops.follow },+ { key: 'wf-log-filter', label: `level: ${FILTER_WORD[m.drill.filter]}`, onPress: ops.filter },+ { key: 'wf-log-scope', label: isPhase ? 'scope: whole phase' : 'scope: this agent', onPress: ops.scope },], 'wf-log-head')- if (window.total === 0) return [head, text(ctx, m.drill.filter === 'all' ? 'No line in the part of the transcript read.' : `No ${FILTER_WORD[m.drill.filter]} among the lines read: change the level.`, { dimColor: true })]+ if (window.total === 0) return [...head, text(ctx, m.drill.filter === 'all' ? 'No line in the part of the transcript read.' : `No ${FILTER_WORD[m.drill.filter]} among the lines read: change the level.`, { dimColor: true })]const rows = window.rows.map((line, i) => {const here = i === window.at@@ -100,7 +102,7 @@ function log(ctx: Ctx, m: Model, ops: Ops, isPhase: boolean): RenderElement[] {})return [- head,+ ...head,...rows,text(ctx, `${window.above} above · ${window.below} below · line ${window.from + window.at + 1} of ${window.total}${m.unread > 0 ? ` · ${m.unread} agents of the phase not in memory` : ''}`, { dimColor: true }),text(ctx, 'follow pins the newest line and is re-drawn on this page\'s refresh; it is not a stream', { dimColor: true }),@@ -117,7 +119,13 @@ function files(ctx: Ctx, m: Model, agent: WfAgent): RenderElement[] {if (wt === undefined) rows.push(text(ctx, agent.hasWorktree ? 'The agent ran in a worktree whose path its metadata does not name: no diff stat.' : 'This agent has no worktree, so there is no diff stat: the list below is only the files its tool inputs name.', { dimColor: true }))else if (diff !== undefined) rows.push(text(ctx, `worktree ${clip(wt, Math.max(20, ctx.columns - 40))} · ${diff.files.size + diff.extra} changed files vs HEAD (tracked files only; \`git diff --numstat\`)`, { dimColor: true }))- else rows.push(row(ctx, [text(ctx, `worktree ${clip(wt, Math.max(20, ctx.columns - 50))}`, { dimColor: true }), ...(isBound() ? [button(ctx, 'wf-diff-load', note?.phase === 'loading' ? 'reading…' : 'Read diff stat', () => void loadDiff(agent))] : [text(ctx, ' diff stat: n/a (host not bound)', { dimColor: true })])]))+ else if (!isBound()) rows.push(text(ctx, `worktree ${clip(wt, Math.max(20, ctx.columns - 10))}`, { dimColor: true }), text(ctx, 'diff stat: n/a (host not bound)', { dimColor: true }))+ else {+ // The path takes what the button leaves, then one space, then the button: the two never touch.+ const label = note?.phase === 'loading' ? 'reading…' : 'Read diff stat'++ rows.push(row(ctx, [text(ctx, `worktree ${clip(wt, Math.max(12, ctx.columns - buttonWidth(label) - 11))} `, { dimColor: true }), button(ctx, 'wf-diff-load', label, () => void loadDiff(agent))], 'wf-diff-row'))+ }if (note?.phase === 'failed' || note?.phase === 'none') rows.push(text(ctx, `diff stat not read: ${note.why ?? 'failed'}`, { color: THEME.warn }))@@ -155,7 +163,7 @@ function result(ctx: Ctx, run: WfRun, agent: WfAgent): RenderElement[] {return [...(agent.resultPreview !== undefined ? [text(ctx, `preview: ${agent.resultPreview}`, { dimColor: true })] : []),...unread(ctx, 'The agent\'s return', `${run.id}/${agent.id}`, () => void loadResult(run, agent)).slice(0, 1),- ...(isBound() ? [row(ctx, [button(ctx, 'wf-result-load', note?.phase === 'loading' ? 'reading…' : 'Read the journal (up to 1.0 MB)', () => void loadResult(run, agent))])] : [text(ctx, 'Reading the journal needs the drill bound to the host (ADR-459).', { dimColor: true })]),+ ...(isBound() ? flow(ctx, [{ key: 'wf-result-load', label: note?.phase === 'loading' ? 'reading…' : 'Read the journal (up to 1.0 MB)', onPress: () => void loadResult(run, agent) }], 'wf-result-load-row') : [text(ctx, 'Reading the journal needs the drill bound to the host (ADR-459).', { dimColor: true })]),]}@@ -178,7 +186,7 @@ export function blockRows(ctx: Ctx, title: string, block: Capped, from: number,/** The sub-tab rows of one agent. */export function agentBody(ctx: Ctx, run: WfRun, agent: WfAgent, m: Model, ops: Ops): RenderElement[] {- const rows: RenderElement[] = [subTabs(ctx, m.drill, ops)]+ const rows: RenderElement[] = [...subTabs(ctx, m.drill, ops)]const tokens = agent.tokens === undefined ? '' : ` · ${fmtTokens(agent.tokens, agent.isTokensPartial)} tok`rows.push(text(ctx, `${agent.label} · ${agent.state}${tokens}${agent.model === undefined ? '' : ` · ${agent.model}`}`, { dimColor: true }))diff --git a/plugins/ruflo-console/hooks/views/wf-layout.ts b/plugins/ruflo-console/hooks/views/wf-layout.tsnew file mode 100644index 0000000000..c85376e67c--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-layout.ts@@ -0,0 +1,121 @@+/**+ * Layout helpers of the Workflows page (ADR-469). The engine lays a row out left to right and gives a Button the width of its label+ * plus the `[ ` and ` ]` it draws; a row that asks for more than the pane runs off the right edge (the `[ Close` cut, the stray+ * letters past the border), and a plain Text squeezed between buttons wraps one letter per row. So every row of buttons on this+ * page is packed here: it wraps to a new row instead of overflowing, a label too long for a row is clipped, never overrun, and+ * a breadcrumb folds its middle crumbs before it would wrap. A press handler never throws into the engine.+ */+import type { RenderElement } from 'claude-code'++import { button, clip, row, text, type Ctx } from './common'++/** Terminal cells of a string: emoji-presentation glyphs count two, so a row is never packed tighter than it draws. */+export function cells(value: string): number {+ let n = 0++ for (const ch of value) {+ const cp = ch.codePointAt(0) as number++ n += cp >= 0x1f000 || (cp >= 0x23e9 && cp <= 0x23fa) || cp === 0x2b50 || cp === 0x2705 || cp === 0x274c ? 2 : 1+ }++ return n+}++/** What a Button asks of a row: its label and the two brackets with their spaces. */+export const buttonWidth = (label: string): number => cells(label) + 4++/** A handler that cannot throw into the engine: a press whose closure fails (or whose page was redrawn away) changes nothing and says nothing. */+export const safe = (run: () => void): (() => void) => () => {+ try {+ run()+ } catch {+ // A press that fails costs that press only; the page stays as it was.+ }+}++export type Btn = { key: string; label: string; onPress: () => void; hotkey?: string; primary?: boolean }++/** `label` cut to what fits `room` cells as a button label, with an ellipsis. */+const fit = (label: string, room: number): string => (buttonWidth(label) <= room ? label : clip(label, Math.max(1, room - 4)))++/**+ * Buttons packed into rows no wider than the pane. `lead` (a word such as `tabs` or `view`) opens the first row. Every button is+ * kept, in order, and stays clickable: a row that is full wraps to the next one. Row keys are `key`, `key-2`, `key-3`…+ */+export function flow(ctx: Ctx, items: readonly Btn[], key: string, lead = ''): RenderElement[] {+ const avail = Math.max(8, ctx.columns)+ const rows: RenderElement[][] = [[]]+ let used = cells(lead)+ let inRow = 0++ if (lead !== '') rows[0]?.push(text(ctx, lead, { dimColor: true }))++ for (const item of items) {+ const label = fit(item.label, avail)+ const width = buttonWidth(label)+ let current = rows[rows.length - 1] as RenderElement[]++ if (used + width > avail && inRow > 0) {+ current = []+ rows.push(current)+ used = 0+ inRow = 0+ }++ current.push(button(ctx, item.key, label, safe(item.onPress), { ...(item.hotkey !== undefined && { hotkey: item.hotkey }), ...(item.primary === true && { primary: true }) }))+ used += width+ inRow += 1+ }++ return rows.map((parts, i) => row(ctx, parts, i === 0 ? key : `${key}-${i + 1}`))+}++export type Crumb = { key: string; label: string; isHere: boolean; onPress: () => void }++/**+ * The drill-down breadcrumb: every crumb a button that goes back to it, the last (where you are) bold text. When the whole trail is+ * wider than the pane the middle crumbs fold to one `…` (`Runs › … › Agent: x`), then the first goes too; only in the last resort is+ * the last crumb clipped. The Text never wraps, so it cannot fall to one letter per row.+ */+export function crumbRow(ctx: Ctx, crumbs: readonly Crumb[], key: string, style: { here: (label: string) => RenderElement }): RenderElement {+ const sep = ' › '+ const last = crumbs.length - 1+ const size = (crumb: Crumb): number => (crumb.isHere ? cells(crumb.label) : buttonWidth(crumb.label))+ const plans: (number | '…')[][] = [crumbs.map((_, i) => i)]++ if (crumbs.length > 2) plans.push([0, '…', last])+ if (crumbs.length > 1) plans.push(['…', last])++ const width = (plan: (number | '…')[]): number => plan.reduce<number>((sum, item, i) => sum + (item === '…' ? 1 : size(crumbs[item] as Crumb)) + (i > 0 ? cells(sep) : 0), 0)+ const plan = plans.find(candidate => width(candidate) <= ctx.columns) ?? (plans[plans.length - 1] as (number | '…')[])+ const parts: RenderElement[] = []++ for (const [i, item] of plan.entries()) {+ if (i > 0) parts.push(text(ctx, sep, { dimColor: true }))++ if (item === '…') parts.push(text(ctx, '…', { dimColor: true }))+ else {+ const crumb = crumbs[item] as Crumb++ // The last crumb is clipped only when even alone it is wider than the pane, and then to what is left after the folded trail.+ parts.push(crumb.isHere ? style.here(clip(crumb.label, Math.max(4, ctx.columns - (width(plan) - cells(crumb.label))))) : button(ctx, crumb.key, crumb.label, safe(crumb.onPress)))+ }+ }++ return row(ctx, parts, key)+}++/** A run's tag for a line of the page: its last word, or, when that is too short to tell runs apart, the last words whole (never a cut through the middle of a word: `le-btr`). */+export function runTag(id: string): string {+ const words = id.split(/[-_:]/).filter(word => word !== '')+ const tail = words[words.length - 1] ?? id++ if (tail.length >= 4) return tail.slice(-6)++ let out = tail++ for (let i = words.length - 2; i >= 0 && (words[i] as string).length + 1 + out.length <= 14; i -= 1) out = `${words[i]}-${out}`++ return out+}diff --git a/plugins/ruflo-console/hooks/views/wf-page.ts b/plugins/ruflo-console/hooks/views/wf-page.tsindex 2cf14ec7f8..ca10bee382 100644--- a/plugins/ruflo-console/hooks/views/wf-page.ts+++ b/plugins/ruflo-console/hooks/views/wf-page.ts@@ -5,7 +5,8 @@ import { cleanText } from '../data/wf-clean'import { CONTROL_TAB, controlLine } from '../data/wf-control'import { pick } from '../data/workflows-nav'import { workflowsModelOf } from '../wf-live'-import { ago, button, clip, col, row, rule, text, THEME, type Ctx } from './common'+import { ago, clip, col, rule, text, THEME, type Ctx } from './common'+import { flow, safe } from './wf-layout'import './wf-register'import { DETAIL_TAB, slotsFor, type SlotEnv } from './wf-slots'import { workflowsView } from './workflows'@@ -19,26 +20,18 @@ function guarded<T>(id: string, ctx: Ctx, draw: () => T, fallback: (line: Render}}-const press = (run: () => void): (() => void) => () => {- try {- run()- } catch {- // A slot's handler that throws changes nothing; the page stays as it was.- }-}-/** The movement and run-switch buttons: j k move, b and l pick the column (h is Help's), u and i switch run (a hotkey is one letter or digit, so not [ and ]), d inspects. */-function moves(ctx: Ctx, isInspecting: boolean): RenderElement {+function moves(ctx: Ctx, isInspecting: boolean): RenderElement[] {const act = ctx.act.workflows- return row(ctx, [- button(ctx, 'wf-prev', 'prev', () => act.key('k'), { hotkey: 'k' }),- button(ctx, 'wf-next', 'next', () => act.key('j'), { hotkey: 'j' }),- button(ctx, 'wf-col-phases', '◂ phases', () => act.key('h'), { hotkey: 'b' }),- button(ctx, 'wf-col-agents', 'agents ▸', () => act.key('l'), { hotkey: 'l' }),- button(ctx, 'wf-run-prev', '◂ run', () => act.key('['), { hotkey: 'u' }),- button(ctx, 'wf-run-next', 'run ▸', () => act.key(']'), { hotkey: 'i' }),- button(ctx, 'wf-inspect', isInspecting ? 'Close inspector' : 'Inspect', () => act.key('enter'), { hotkey: 'd' }),+ return flow(ctx, [+ { key: 'wf-prev', label: 'prev', onPress: () => act.key('k'), hotkey: 'k' },+ { key: 'wf-next', label: 'next', onPress: () => act.key('j'), hotkey: 'j' },+ { key: 'wf-col-phases', label: '◂ phases', onPress: () => act.key('h'), hotkey: 'b' },+ { key: 'wf-col-agents', label: 'agents ▸', onPress: () => act.key('l'), hotkey: 'l' },+ { key: 'wf-run-prev', label: '◂ run', onPress: () => act.key('['), hotkey: 'u' },+ { key: 'wf-run-next', label: 'run ▸', onPress: () => act.key(']'), hotkey: 'i' },+ { key: 'wf-inspect', label: isInspecting ? 'Close inspector' : 'Inspect', onPress: () => act.key('enter'), hotkey: 'd' },], 'wf-moves')}@@ -60,21 +53,21 @@ export function workflowsPage(ctx: Ctx): RenderElement {const rows: RenderElement[] = [workflowsView(ctx, model, ui, { ask: spec => act.ask(spec), show: act.show })]if (env !== null && env.run !== null && ctx.columns >= 44) {- rows.push(moves(ctx, env.ui.isInspecting))+ rows.push(...moves(ctx, env.ui.isInspecting))const extras = [- ...slotsFor('key').map(slot => button(ctx, `wf-key-${slot.id}`, slot.label, press(() => slot.run(env)), { hotkey: slot.key })),- ...slotsFor('action').map(slot => button(ctx, `wf-act-${slot.id}`, slot.label, press(() => act.ask(slot.spec(env), slot.why)), slot.hotkey === undefined ? {} : { hotkey: slot.hotkey })),+ ...slotsFor('key').map(slot => ({ key: `wf-key-${slot.id}`, label: slot.label, onPress: safe(() => slot.run(env)), hotkey: slot.key })),+ ...slotsFor('action').map(slot => ({ key: `wf-act-${slot.id}`, label: slot.label, onPress: safe(() => act.ask(slot.spec(env), slot.why)), ...(slot.hotkey === undefined ? {} : { hotkey: slot.hotkey }) })),]- if (extras.length > 0) rows.push(row(ctx, extras, 'wf-extras'))+ if (extras.length > 0) rows.push(...flow(ctx, extras, 'wf-extras'))// Stop and message are the control tab's (ADR-465) where it is registered; where it is not, this says where that is done instead of a dead button.if (env.run.kind === 'workflow') rows.push(text(ctx, controlLine(slotsFor('tab').some(slot => slot.id === CONTROL_TAB)), { dimColor: true }))}if (env !== null && tabs.length > 0) {- rows.push(row(ctx, [text(ctx, 'tabs'), button(ctx, 'wf-tab-detail', `${slotTab === undefined ? '●' : '○'} detail`, () => act.tab(DETAIL_TAB)), ...tabs.map(slot => button(ctx, `wf-tab-${slot.id}`, `${slot.id === slotTab?.id ? '●' : '○'} ${slot.label}`, () => act.tab(slot.id)))], 'wf-tabs'))+ rows.push(...flow(ctx, [{ key: 'wf-tab-detail', label: `${slotTab === undefined ? '●' : '○'} detail`, onPress: () => act.tab(DETAIL_TAB) }, ...tabs.map(slot => ({ key: `wf-tab-${slot.id}`, label: `${slot.id === slotTab?.id ? '●' : '○'} ${slot.label}`, onPress: () => act.tab(slot.id) }))], 'wf-tabs', 'tabs '))if (slotTab !== undefined) rows.push(...guarded(slotTab.id, ctx, () => slotTab.render(env), line => [line]))}diff --git a/plugins/ruflo-console/hooks/views/wf-replay.ts b/plugins/ruflo-console/hooks/views/wf-replay.tsindex a159ad661c..5a9567ae81 100644--- a/plugins/ruflo-console/hooks/views/wf-replay.ts+++ b/plugins/ruflo-console/hooks/views/wf-replay.ts@@ -9,10 +9,11 @@*/import type { RenderElement } from 'claude-code'-import { boardAt, buildTimeline, describeStep, isPlaying, newReplay, offsetOf, SPEEDS, stepNow, stepReplay, type ReplayCommand, type ReplayUi, type Timeline } from '../data/wf-replay'+import { boardAt, buildTimeline, describeStep, isPlaying, newReplay, offsetOf, settle, SPEEDS, stepNow, stepReplay, type ReplayCommand, type ReplayUi, type Timeline } from '../data/wf-replay'import { fmtElapsed, fmtTokens, type WfAgent, type WfRun } from '../data/workflows'import { button, clip, row, text, THEME, type Ctx } from './common'import { fold, redraw } from './wf-fold'+import { flow, safe } from './wf-layout'import { registerSlot, type SlotEnv } from './wf-slots'import './wf-compare'import './wf-export'@@ -51,6 +52,28 @@ export function applyReplay(run: WfRun, command: ReplayCommand, nowMs: number):return next}+/** How often a playing replay advances and redraws, on the console's clock. */+export const TICK_MS = 400++/**+ * One tick of a playing replay: brings it up to `nowMs` (bounded: data/wf-replay.ts `settle`) and says whether it is still playing. False for a+ * paused, finished or unknown replay, which ends its timer.+ */+export function replayTick(run: WfRun, nowMs: number): boolean {+ const ui = replays.get(run.id)++ if (ui === undefined || ui.playFromMs === null) return false++ const next = settle(ui, timelineOf(run), nowMs)++ replays.set(run.id, next)++ return next.playFromMs !== null+}++/** Starts the replay's clock for a run while it plays (one timer per run; asking again is harmless). Needs the page's `tick` action, which a surface without a clock lacks: then it advances on each redraw as it always did. */+const startTick = (ctx: Ctx, run: WfRun): void => ctx.act.workflows.tick?.(`replay-${run.id}`, TICK_MS, () => replayTick(run, Date.now()))+/** For tests. */export const resetReplays = (): void => (replays.clear(), timelines.clear())@@ -108,17 +131,30 @@ export function replayBody(env: SlotEnv, run: WfRun): RenderElement[] {const playing = isPlaying(ui, tl, nowMs)const board = boardAt(run, tl, step)const go = (command: ReplayCommand) => () => {- applyReplay(run, command, Date.now())+ const next = applyReplay(run, command, Date.now())++ if (next.playFromMs !== null) startTick(ctx, run)redraw(ctx)}++ // A replay that is playing when the page is drawn (the person left it and came back) gets its clock again.+ if (playing) startTick(ctx, run)const span = tl.t1 - tl.t0return [text(ctx, ` step ${step}/${n} · ${clock(offsetOf(tl, step))} of ${clock(span)} · ${ui.speed}x · ${playing ? '▶ playing' : step >= n ? '■ at the end' : '⏸ paused'}`),text(ctx, ` ${bar(span === 0 ? (step >= n ? 1 : 0) : offsetOf(tl, step) / span, Math.max(10, Math.min(48, ctx.columns - 6)))}`, { dimColor: true }),text(ctx, ` ▸ ${clip(describeStep(tl, step), Math.max(10, ctx.columns - 6))}`, { color: THEME.info }),- row(ctx, [button(ctx, 'wf-rp-first', '⏮', go('first')), button(ctx, 'wf-rp-pphase', '◂◂ phase', go('prev-phase')), button(ctx, 'wf-rp-prev', '◂ step', go('prev')), button(ctx, 'wf-rp-play', playing ? '⏸ pause' : '▶ play', go('play'), { primary: true }), button(ctx, 'wf-rp-next', 'step ▸', go('next')), button(ctx, 'wf-rp-nphase', 'phase ▸▸', go('next-phase')), button(ctx, 'wf-rp-last', '⏭', go('last'))], 'wf-rp-controls'),- row(ctx, [text(ctx, ' speed '), button(ctx, 'wf-rp-slower', '−', go('slower')), text(ctx, ` ${ui.speed}x `), button(ctx, 'wf-rp-faster', '+', go('faster')), text(ctx, ` of ${SPEEDS.join(' · ')}`, { dimColor: true })], 'wf-rp-speed'),+ ...flow(ctx, [+ { key: 'wf-rp-first', label: '⏮', onPress: go('first') },+ { key: 'wf-rp-pphase', label: '◂◂ phase', onPress: go('prev-phase') },+ { key: 'wf-rp-prev', label: '◂ step', onPress: go('prev') },+ { key: 'wf-rp-play', label: playing ? '⏸ pause' : '▶ play', onPress: go('play'), primary: true },+ { key: 'wf-rp-next', label: 'step ▸', onPress: go('next') },+ { key: 'wf-rp-nphase', label: 'phase ▸▸', onPress: go('next-phase') },+ { key: 'wf-rp-last', label: '⏭', onPress: go('last') },+ ], 'wf-rp-controls'),+ row(ctx, [text(ctx, ' speed '), button(ctx, 'wf-rp-slower', '−', safe(go('slower'))), text(ctx, ` ${ui.speed}x `), button(ctx, 'wf-rp-faster', '+', safe(go('faster'))), ...(ctx.columns >= 64 ? [text(ctx, ` of ${SPEEDS.join(' · ')}`, { dimColor: true })] : [])], 'wf-rp-speed'),...boardRows(ctx, board),...(tl.untimed.length > 0 ? [text(ctx, ` ${tl.untimed.length} agent${tl.untimed.length === 1 ? '' : 's'} left off: no start time (or no span) in the run's files, so there is no moment to place ${tl.untimed.length === 1 ? 'it' : 'them'} at`, { color: THEME.warn })] : []),text(ctx, step >= n ? ' This is the run\'s real final board.' : ' Tokens show n/a until an agent ends: only its final figure is recorded. A running agent\'s time is measured to this step.', { dimColor: true }),diff --git a/plugins/ruflo-console/hooks/views/wf-search.ts b/plugins/ruflo-console/hooks/views/wf-search.tsindex 7db45b8cae..bb1fced606 100644--- a/plugins/ruflo-console/hooks/views/wf-search.ts+++ b/plugins/ruflo-console/hooks/views/wf-search.ts@@ -9,8 +9,9 @@ import type { RenderElement } from 'claude-code'import { MAX_QUERY, flatHits, HIT_NAME, HIT_ORDER, MAX_SHOWN, MIN_QUERY, SCAN_CHARS, search, type Hit, type MissionTaskRef, type SearchResult } from '../data/wf-search'import { isBound, LOAD_BUDGET, loadRun, parsedOf, textOf } from '../data/wf-drill-io'-import { button, clip, col, row, text, THEME } from './common'+import { button, clip, col, text, THEME } from './common'import { drillOf, jumpTo, setQuery } from './wf-detail'+import { flow } from './wf-layout'import { registerSlot, type SlotEnv } from './wf-slots'const memo = new WeakMap<object, { query: string; runs: number; tasks: number; texts: (string | null)[]; tails: boolean[]; result: SearchResult }>()@@ -95,7 +96,7 @@ export function searchPanel(env: SlotEnv): RenderElement[] {if (result.unread > 0 && env.run !== null) {const run = env.run- rows.push(isBound() ? row(ctx, [button(ctx, 'wf-search-load', `Read this run's transcripts (up to ${(LOAD_BUDGET / 1_000_000).toFixed(0)} MB in all)`, () => void loadRun(run).then(() => ctx.act.workflows.setUi({})))]) : text(ctx, 'Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true }))+ rows.push(...(isBound() ? flow(ctx, [{ key: 'wf-search-load', label: `Read this run's transcripts (up to ${(LOAD_BUDGET / 1_000_000).toFixed(0)} MB in all)`, onPress: () => void loadRun(run).then(() => ctx.act.workflows.setUi({})) }], 'wf-search-load-row') : [text(ctx, 'Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true })]))}return [col(ctx, rows, 'wf-search-panel')]diff --git a/plugins/ruflo-console/hooks/views/wf-templates.ts b/plugins/ruflo-console/hooks/views/wf-templates.tsindex 74f5ef83ac..8f5dfc742b 100644--- a/plugins/ruflo-console/hooks/views/wf-templates.ts+++ b/plugins/ruflo-console/hooks/views/wf-templates.ts@@ -14,6 +14,7 @@ import { estimate, hasMasked, missingOf, promptOf, templateById, TEMPLATES, valuimport type { Host } from '../host'import type { State } from '../state'import { button, clip, row, text, THEME, type Ctx } from './common'+import { flow } from './wf-layout'import { registerSlot, type SlotEnv } from './wf-slots'type Draft = { selected: string; raw: Record<string, Record<string, string | number>> }@@ -45,7 +46,7 @@ export function cycleTemplate(state: State): void {hosts.get(state)?.invalidate()}-function paramRow(ctx: Ctx, template: Template, param: Param, current: string | number): RenderElement {+function paramRow(ctx: Ctx, template: Template, param: Param, current: string | number): RenderElement[] {const { state } = ctxconst host = hosts.get(state)const key = `wft-${template.id}-${param.id}`@@ -53,14 +54,14 @@ function paramRow(ctx: Ctx, template: Template, param: Param, current: string |if (param.kind === 'int') {const n = Number(current)- return row(ctx, [text(ctx, ` ${param.label.padEnd(14)}`, { dimColor: true }), button(ctx, `${key}-less`, ' − ', () => setValue(state, host, template, param.id, Math.max(param.min, n - 1))), text(ctx, ` ${n} `, { bold: true }), button(ctx, `${key}-more`, ' + ', () => setValue(state, host, template, param.id, Math.min(param.max, n + 1))), text(ctx, ` (${param.min} to ${param.max})`, { dimColor: true })], key)+ return [row(ctx, [text(ctx, ` ${param.label.padEnd(14)}`, { dimColor: true }), button(ctx, `${key}-less`, ' − ', () => setValue(state, host, template, param.id, Math.max(param.min, n - 1))), text(ctx, ` ${n} `, { bold: true }), button(ctx, `${key}-more`, ' + ', () => setValue(state, host, template, param.id, Math.min(param.max, n + 1))), text(ctx, ` (${param.min} to ${param.max})`, { dimColor: true })], key)]}- if (param.kind === 'choice') return row(ctx, [text(ctx, ` ${param.label.padEnd(14)}`, { dimColor: true }), ...param.choices.map(choice => button(ctx, `${key}-${choice}`, `${choice === current ? '●' : '○'} ${choice}`, () => setValue(state, host, template, param.id, choice)))], key)+ if (param.kind === 'choice') return flow(ctx, param.choices.map(choice => ({ key: `${key}-${choice}`, label: `${choice === current ? '●' : '○'} ${choice}`, onPress: () => setValue(state, host, template, param.id, choice) })), key, ` ${param.label.padEnd(14)}`)- return ctx.kit.Input === undefined+ return [ctx.kit.Input === undefined? text(ctx, ` ${param.label}: this surface has no text field, so the default is used: ${param.fallback === '' ? 'none (required)' : param.fallback}`, { dimColor: true })- : ctx.kit.Input({ key, label: param.label, value: String(current), placeholder: `${param.hint}${param.fallback === '' ? ' (required)' : ''}`, onInput: value => setValue(state, host, template, param.id, value.slice(0, TEXT_MAX)), submitLabel: 'set', onSubmit: value => setValue(state, host, template, param.id, value.slice(0, TEXT_MAX)) })+ : ctx.kit.Input({ key, label: param.label, value: String(current), placeholder: `${param.hint}${param.fallback === '' ? ' (required)' : ''}`, onInput: value => setValue(state, host, template, param.id, value.slice(0, TEXT_MAX)), submitLabel: 'set', onSubmit: value => setValue(state, host, template, param.id, value.slice(0, TEXT_MAX)) })]}export function boardRows(env: SlotEnv): RenderElement[] {@@ -72,9 +73,9 @@ export function boardRows(env: SlotEnv): RenderElement[] {const missing = missingOf(template, values)return [- row(ctx, [text(ctx, ' template '), ...TEMPLATES.map(entry => button(ctx, `wft-pick-${entry.id}`, `${entry.id === template.id ? '●' : '○'} ${entry.title}`, () => (draftOf(ctx.state).selected = entry.id, hosts.get(ctx.state)?.invalidate())))], 'wft-pick'),+ ...flow(ctx, TEMPLATES.map(entry => ({ key: `wft-pick-${entry.id}`, label: `${entry.id === template.id ? '●' : '○'} ${entry.title}`, onPress: () => (draftOf(ctx.state).selected = entry.id, hosts.get(ctx.state)?.invalidate()) })), 'wft-pick', ' template '),ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: ` ${template.summary}` }),- ...template.params.map(param => paramRow(ctx, template, param, raw[param.id] ?? param.fallback)),+ ...template.params.flatMap(param => paramRow(ctx, template, param, raw[param.id] ?? param.fallback)),text(ctx, ` dry run: ${plan.agents} agents in ${plan.phases} phases (${plan.rows.map(entry => `${clip(entry.title, 14)} ${entry.agents}`).join(' · ')}), at most ${plan.widest} at once`, { bold: true, ...(plan.isOverCap ? { color: THEME.bad } : {}) }),text(ctx, ' counts only: tokens, time and cost are not estimated, nothing has measured them for this template', { dimColor: true }),...(plan.isOverCap ? [text(ctx, ` over the ${AGENTS_MAX}-agent ceiling: lower a count before launching`, { color: THEME.bad })] : []),diff --git a/plugins/ruflo-console/hooks/views/wf-worktrees.ts b/plugins/ruflo-console/hooks/views/wf-worktrees.tsindex bf02454fa4..bff362258c 100644--- a/plugins/ruflo-console/hooks/views/wf-worktrees.ts+++ b/plugins/ruflo-console/hooks/views/wf-worktrees.ts@@ -18,7 +18,8 @@ import { checkProcs, failureOf, inUseOf, planRemoval, readSummary, readWorktreesimport type { Host } from '../host'import type { State } from '../state'import { workflowsModelOf } from '../wf-live'-import { ago, button, clip, row, text, THEME, type Ctx } from './common'+import { ago, clip, row, text, THEME, type Ctx } from './common'+import { flow } from './wf-layout'import { registerSlot, type SlotEnv } from './wf-slots'type Store = { read: WtRead | null; check: ProcCheck | null; isReading: boolean; error: string | null; lastMs: number }@@ -126,7 +127,7 @@ export function boardRows(env: SlotEnv): RenderElement[] {rows.push(text(ctx, check === null ? ' live processes: not checked (the read button, w, checks them; the timer never does)' : check.ok ? ` live processes: ${check.seen} working directories seen, ${ago(check.atMs, nowMs)}, your own processes only` : ` live processes: ${check.why ?? 'unknown'}`, { dimColor: check?.ok === true, ...(check?.ok === true ? {} : { color: THEME.warn }) }))rows.push(text(ctx, plan.targets.length > 0 ? ` cleanup: ${plan.targets.length} worktree${plan.targets.length === 1 ? '' : 's'} ready to remove${plan.more > 0 ? ` (${plan.more} more after these ${REMOVE_MAX})` : ''}; the button lists them first` : ` cleanup: ${plan.blocked ?? 'nothing to remove'}`, { color: plan.targets.length > 0 ? THEME.ok : undefined, dimColor: plan.targets.length === 0 }))rows.push(text(ctx, ' removed: the directory only, never the branch, never with --force; each is re-checked just before it goes', { dimColor: true }))- rows.push(row(ctx, [button(ctx, 'wt-read', store.isReading ? 'reading…' : 'read worktrees + live processes', () => void readFull(env.ctx.state))], 'wt-actions'))+ rows.push(...flow(ctx, [{ key: 'wt-read', label: store.isReading ? 'reading…' : 'read worktrees + live processes', onPress: () => void readFull(env.ctx.state) }], 'wt-actions'))return rows}diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.tsindex 075043eedd..c88f5938ba 100644--- a/plugins/ruflo-console/hooks/views/workflows.ts+++ b/plugins/ruflo-console/hooks/views/workflows.ts@@ -1,11 +1,12 @@import type { RenderElement } from 'claude-code'import type { ActionSpec } from '../actions'-import { fmtElapsed, fmtTokens, modelName, currentPhase, shortId, type AgentState, type WfAgent, type WfPhase, type WfRun } from '../data/workflows'+import { fmtElapsed, fmtTokens, modelName, currentPhase, type AgentState, type WfAgent, type WfPhase, type WfRun } from '../data/workflows'import { pick, type WfUi } from '../data/workflows-nav'import { CONTROL_TAB, controlLine } from '../data/wf-control'import { spawnAgent, stopAgent } from '../ops'-import { button, clip, col, kv, row, rule, text, THEME, type Ctx } from './common'+import { clip, col, kv, row, rule, text, THEME, type Ctx } from './common'+import { flow, runTag } from './wf-layout'import { slotsFor } from './wf-slots'/** What the workflows view asks of the controller: a confirm-gated ruflo verb, or to name a transcript's path. */@@ -41,7 +42,7 @@ function header(ctx: Ctx, run: WfRun, runs: readonly WfRun[], at: number): Rendeconst tabs = runs.length > 1 ? runs.map((entry, i) => `${i === at ? '▸' : ' '}${i + 1} ${clip(entry.name, 18)}`).join(' ') : ''return [- row(ctx, [ctx.kit.Text({ bold: true, children: `${clip(run.name, Math.max(8, ctx.columns - 24))} ` }), ctx.kit.Text({ ...(tone !== undefined && { color: tone }), children: run.state })]),+ row(ctx, [ctx.kit.Text({ bold: true, wrap: 'truncate-end', children: `${clip(run.name, Math.max(8, ctx.columns - 24))} ` }), ctx.kit.Text({ wrap: 'truncate-end', ...(tone !== undefined && { color: tone }), children: run.state })]),text(ctx, `${run.total} agents · ${counts} · ${tokens}${span}`, { dimColor: true }),...(tabs === '' ? [] : [text(ctx, `${tabs} [ ] switch run`, { dimColor: true })]),]@@ -91,10 +92,10 @@ function inspect(ctx: Ctx, run: WfRun, agent: WfAgent, hooks: WorkflowsHooks): Rrows.push(kv(ctx, 'health / tasks', `${a.health === undefined ? 'n/a' : `${Math.round(a.health * 100)}%`} · ${a.taskCount ?? 'n/a'} tasks`))rows.push(kv(ctx, 'model / tokens', 'n/a (ruflo records neither per agent)'))rows.push(- row(ctx, [- button(ctx, 'wf-stop', 'Stop agent', () => { const spec = stopAgent(a); if (spec !== null) hooks.ask(spec) }),- button(ctx, 'wf-spawn', `Spawn another ${a.type}`, () => { const spec = spawnAgent(a.type, ctx.nowMs); if (spec !== null) hooks.ask(spec) }),- ]),+ ...flow(ctx, [+ { key: 'wf-stop', label: 'Stop agent', onPress: () => { const spec = stopAgent(a); if (spec !== null) hooks.ask(spec) } },+ { key: 'wf-spawn', label: `Spawn another ${a.type}`, onPress: () => { const spec = spawnAgent(a.type, ctx.nowMs); if (spec !== null) hooks.ask(spec) } },+ ], 'wf-agent-actions'),)return rows@@ -111,7 +112,7 @@ function inspect(ctx: Ctx, run: WfRun, agent: WfAgent, hooks: WorkflowsHooks): Rif (agent.transcriptPath !== undefined) {const path = agent.transcriptPath- rows.push(row(ctx, [button(ctx, 'wf-open', 'Open transcript', () => hooks.show(path), { hotkey: 'o' })]))+ rows.push(...flow(ctx, [{ key: 'wf-open', label: 'Open transcript', onPress: () => hooks.show(path), hotkey: 'o' }], 'wf-open-row'))}rows.push(text(ctx, run.kind === 'workflow' ? controlLine(slotsFor('tab').some(slot => slot.id === CONTROL_TAB)) : '', { dimColor: true }))@@ -179,7 +180,7 @@ export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi,}if (model.more > 0) rows.push(text(ctx, `+${model.more} older runs not shown`, { dimColor: true }))- if (wide && !here.ui.isInspecting) rows.push(text(ctx, `${shortId(run.id)} · d inspects the agent · u/i switches run`, { dimColor: true }))+ if (wide && !here.ui.isInspecting) rows.push(text(ctx, `${runTag(run.id)} · d inspects the agent · u/i switches run`, { dimColor: true }))return col(ctx, rows, 'workflows')}diff --git a/plugins/ruflo-console/hooks/wf-actions.ts b/plugins/ruflo-console/hooks/wf-actions.tsindex 92f35bc0c6..c40e387a71 100644--- a/plugins/ruflo-console/hooks/wf-actions.ts+++ b/plugins/ruflo-console/hooks/wf-actions.ts@@ -22,6 +22,12 @@ export type WorkflowsActions = {ask: (spec: ActionSpec | null, why?: string) => void/** Names a transcript's path on the footer outcome row, after checking it is inside the config directory's projects folder. */show: (path: string) => void+ /**+ * Runs `fn` every `ms` on the console's own clock (host.every) while this page is the one in front and the pane is shown, redrawing after each+ * call, until `fn` answers false (or the page is closed or switched away: the console's stop cancels every timer). One timer per `name`; a+ * second call with a name already running does nothing. A call that throws stops it.+ */+ tick?: (name: string, ms: number, fn: () => boolean) => void}/** True for a path under `<configDir>/projects/` with no `..` part: the only place a run's files live. */@@ -49,6 +55,30 @@ export function workflowsActions(state: State, host: Host, runner: Runner): Workstate.wf.ui = { ...state.wf.ui, ...patch }host.invalidate()},+ tick: (name, ms, fn) => {+ const key = `wf-tick-${name}`++ if (state.timers.has(key)) return++ const stop = (): void => {+ state.timers.get(key)?.cancel()+ state.timers.delete(key)+ }+ const timer = host.every(ms, () => {+ let keep = false++ try {+ keep = state.view === 'workflows' && !(state.isInteractive && !(state.pane.isOpen && state.pane.isShown)) && fn()+ } catch {+ keep = false+ }++ host.invalidate()+ if (!keep) stop()+ })++ state.timers.set(key, timer)+ },ask: (spec, why = 'that cannot run here') => runner.ask(spec, why),show: path => {const ok = isRunPath(path, state.configDir)diff --git a/plugins/ruflo-console/tests/fixtures/wf-layout-rig.ts b/plugins/ruflo-console/tests/fixtures/wf-layout-rig.tsnew file mode 100644index 0000000000..c6bbe005f4--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/wf-layout-rig.ts@@ -0,0 +1,90 @@+/**+ * A layout meter for a recorded element tree (ADR-469). The engine lays a row out left to right and gives a Button or a plain Text+ * the width it asks for; only a Text with `wrap: 'truncate-*'` gives way, and a Text squeezed below its length wraps by letter.+ * This meter does the same sum: a row whose fixed parts (buttons at label + 4 for `[ ` and ` ]`, plain texts at their length)+ * come to more than the pane is overflowing, and a plain Text left almost nothing is a letter-per-row wrap.+ */+export type El = { kind: string; props: Record<string, unknown> }+export type Finding = { kind: 'overflow' | 'letters'; at: string; width: number; avail: number }++/** Terminal cells of a string: the emoji-presentation glyphs the console draws count two, so a row is never judged narrower than it is. */+export function cells(text: string): number {+ let n = 0++ for (const ch of text) {+ const cp = ch.codePointAt(0) as number++ n += cp >= 0x1f000 || (cp >= 0x23e9 && cp <= 0x23fa) || cp === 0x2b50 || cp === 0x2705 || cp === 0x274c ? 2 : 1+ }++ return n+}++const textOf = (el: El): string => {+ const c = el.props.children++ return typeof c === 'string' || typeof c === 'number' ? String(c) : Array.isArray(c) ? c.filter(x => typeof x === 'string' || typeof x === 'number').join('') : ''+}++const shrinks = (el: El): boolean => typeof el.props.wrap === 'string' && el.props.wrap.startsWith('truncate')+const childrenOf = (el: El): El[] => {+ const c = el.props.children+ const list = Array.isArray(c) ? c.flat(3) : [c]++ return list.filter((x): x is El => typeof x === 'object' && x !== null && 'kind' in x)+}+const chrome = (el: El): number => (el.props.borderStyle !== undefined ? 2 : 0) + (typeof el.props.paddingX === 'number' ? el.props.paddingX * 2 : 0)++/** The width a node asks for, with `floor` for what it can give up (a truncating Text asks for one cell). */+export function ask(el: El, mode: 'fixed' | 'full'): number {+ if (el.kind === 'Button') return cells(String(el.props.label ?? '')) + 4+ if (el.kind === 'Text') return mode === 'fixed' && shrinks(el) ? 1 : cells(textOf(el))+ if (el.kind === 'Box') {+ const parts = childrenOf(el).map(child => ask(child, mode))++ return chrome(el) + (el.props.flexDirection === 'row' ? parts.reduce((a, b) => a + b, 0) : Math.max(0, ...parts))+ }++ return 0+}++/** Every row of the tree that does not fit `avail` columns, and every plain Text a row squeezes to two cells or fewer. */+export function measure(node: unknown, avail: number, path = 'page', out: Finding[] = []): Finding[] {+ if (typeof node !== 'object' || node === null || !('kind' in node)) return out++ const el = node as El++ if (el.kind !== 'Box') return out++ const inner = avail - chrome(el)+ const kids = childrenOf(el)+ const name = `${path}/${String(el.props.key ?? 'box')}`++ if (el.props.flexDirection === 'row') {+ const fixed = kids.reduce((sum, kid) => sum + ask(kid, 'fixed'), 0)++ if (fixed > inner) out.push({ kind: 'overflow', at: `${name} [${kids.map(k => (k.kind === 'Button' ? `[${String(k.props.label)}]` : textOf(k) || k.kind)).join('|').slice(0, 90)}]`, width: fixed, avail: inner })++ for (const kid of kids) {+ if (kid.kind !== 'Text' || shrinks(kid) || cells(textOf(kid)) <= 3) continue++ const left = inner - (fixed - ask(kid, 'fixed'))++ if (left <= 2) out.push({ kind: 'letters', at: `${name} "${textOf(kid).slice(0, 40)}"`, width: cells(textOf(kid)), avail: left })+ }++ for (const kid of kids) measure(kid, Math.max(1, inner - (fixed - ask(kid, 'fixed'))), name, out)+ } else for (const kid of kids) measure(kid, inner, name, out)++ return out+}++export const flatten = (node: unknown, out: El[] = []): El[] => {+ if (Array.isArray(node)) node.forEach(child => flatten(child, out))+ else if (typeof node === 'object' && node !== null) {+ out.push(node as El)+ flatten((node as El).props?.children, out)+ }++ return out+}diff --git a/plugins/ruflo-console/tests/press-guard.spec.ts b/plugins/ruflo-console/tests/press-guard.spec.tsnew file mode 100644index 0000000000..d5d1ae2be1--- /dev/null+++ b/plugins/ruflo-console/tests/press-guard.spec.ts@@ -0,0 +1,48 @@+/**+ * A press that outlives its drawing (ADR-469): the engine finds no handler under the handle and the `ui.press` hook answers it quietly;+ * every other failure still propagates, and the page's own handlers never throw into the engine. Run with+ * npx vitest run plugins/ruflo-console/tests/press-guard.spec.ts --testTimeout=30000+ */+import { describe, expect, it } from 'vitest'++import { tolerantPress } from '../hooks/press-guard'+import { buttonWidth, flow, safe } from '../hooks/views/wf-layout'+import { kit } from './fixtures/wf-drill-world'+import type { Ctx } from '../hooks/views/common'+import { newState } from '../hooks/state'++describe('tolerantPress', () => {+ it('passes the answer through', async () => {+ await expect(tolerantPress(() => ({ element: 'a' }), { element: 'fallback' })).resolves.toEqual({ element: 'a' })+ await expect(tolerantPress(async () => ({ element: 'b' }), { element: 'fallback' })).resolves.toEqual({ element: 'b' })+ })++ it('answers a stale handle with the fallback, sync or async, and no throw', async () => {+ const stale = (): never => {+ throw new Error('ui.press: no handler is held under handle 41')+ }++ await expect(tolerantPress(stale, { element: 'wf-next' })).resolves.toEqual({ element: 'wf-next' })+ await expect(tolerantPress(async () => stale(), { element: 'wf-next' })).resolves.toEqual({ element: 'wf-next' })+ await expect(tolerantPress(() => Promise.reject('no handler is held under handle 3'), { element: 'x' })).resolves.toEqual({ element: 'x' })+ })++ it('lets any other failure through', async () => {+ await expect(tolerantPress(() => { throw new Error('disk full') }, { element: 'x' })).rejects.toThrow('disk full')+ await expect(tolerantPress(() => Promise.reject(new Error('boom')), { element: 'x' })).rejects.toThrow('boom')+ })+})++describe('a page handler never throws into the engine', () => {+ const ctx = { kit, state: newState({}), nowMs: 0, columns: 40, pictures: new Map(), act: {} } as unknown as Ctx++ it('safe swallows a throwing closure, and a flowed button is safe', () => {+ expect(() => safe(() => { throw new Error('stale') })()).not.toThrow()++ const rows = flow(ctx, [{ key: 'k', label: 'go', onPress: () => { throw new Error('orphaned') } }], 'r')+ const button = (rows[0] as unknown as { props: { children: { props: { onPress: () => void } }[] } }).props.children[0]++ expect(() => button?.props.onPress()).not.toThrow()+ expect(buttonWidth('go')).toBe(6)+ })+})diff --git a/plugins/ruflo-console/tests/wf-drill.spec.ts b/plugins/ruflo-console/tests/wf-drill.spec.tsindex 4f0ce690f4..7f7aaf6d7b 100644--- a/plugins/ruflo-console/tests/wf-drill.spec.ts+++ b/plugins/ruflo-console/tests/wf-drill.spec.ts@@ -59,7 +59,9 @@ describe('the panel', () => {const agent = screen(world)expect(drillOf(world.state)).toMatchObject({ level: 'agent', sub: 'activity' })- expect(agent).toMatch(/Agent · Activity/)+ expect(agent).toMatch(/Agent: build:x/)+ expect(agent).not.toMatch(/Agent · /)+ expect(agent).toMatch(/● Activity/)expect(agent).toMatch(/Bash\s+ls -la/)expect(agent).toMatch(/Edit\s+\/work\/proj\/.*a\.ts/)expect(agent).toMatch(/transcript: whole file/)diff --git a/plugins/ruflo-console/tests/wf-layout.spec.ts b/plugins/ruflo-console/tests/wf-layout.spec.tsnew file mode 100644index 0000000000..282cb1ee33--- /dev/null+++ b/plugins/ruflo-console/tests/wf-layout.spec.ts@@ -0,0 +1,211 @@+/**+ * The Workflows page at every dock width the engine gives (ADR-469): 56 to 125 columns. Every section is drawn with a recording kit and+ * metered the way the engine lays a row out (tests/fixtures/wf-layout-rig.ts): no row is wider than the pane, no text is squeezed to a+ * letter per row, every button of an action row is reachable (a long row wraps to a new row instead of running off the edge), and the+ * breadcrumb folds its middle crumbs before it wraps. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-layout.spec.ts --testTimeout=30000+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { resetDrillIo } from '../hooks/data/wf-drill-io'+import { newState } from '../hooks/state'+import { workflowsActions } from '../hooks/wf-actions'+import { resetSavedLive } from '../hooks/wf-saved-live'+import type { Host } from '../hooks/host'+import { rule, setLook, type Actions, type Ctx } from '../hooks/views/common'+import { flow, runTag } from '../hooks/views/wf-layout'+import { drillOf, setQuery } from '../hooks/views/wf-detail'+import { resetCompare } from '../hooks/views/wf-compare'+import { resetExport } from '../hooks/views/wf-export'+import { resetFolds } from '../hooks/views/wf-fold'+import { resetReplays } from '../hooks/views/wf-replay'+import { workflowsPage } from '../hooks/views/wf-page'+import '../hooks/views/wf-register'+import { bindWorkflowDrill } from '../hooks/wf-drill'+import { BASE, runOf } from './fixtures/wf-runs'+import { T0 } from './fixtures/workflows'+import { buttonOf, click, flush, frame, kit, liveFiles, worldOf, type World } from './fixtures/wf-drill-world'+import { cells, flatten, measure, type El, type Finding } from './fixtures/wf-layout-rig'++const WIDTHS = [56, 60, 72, 80, 100, 125] as const++const a = runOf('wf_a', BASE, {}, 'sample-build-tune-review')+const b = runOf('wf_b', BASE.map(x => (x.id === 'ra1' ? { ...x, tokens: 250_000 } : x)), {}, 'sample-build-tune-review')++/** The full page with every registered slot, over two finished runs of one workflow. */+function fullPage(columns: number) {+ const state = newState({})++ state.view = 'workflows'+ state.cwd = '/work/proj'+ state.wf.read = { runs: [a, b], root: '/x', capBytes: 1, skipped: 0, more: 0 }++ const host = { invalidate: () => undefined } as unknown as Host+ const act = { workflows: workflowsActions(state, host, { ask: () => undefined } as never), focus: () => undefined, view: () => undefined } as unknown as Actions+ const ctx: Ctx = { kit, state, nowMs: T0 + 600_000, columns, pictures: new Map(), act }++ return { state, ctx, page: () => workflowsPage(ctx) }+}++const report = (found: Finding[]): string => found.map(f => `${f.kind} ${f.width}>${f.avail} ${f.at}`).join('\n')++beforeEach(() => {+ resetFolds()+ resetReplays()+ resetCompare()+ resetExport()+ resetSavedLive()+ resetDrillIo()+})+afterEach(() => {+ resetDrillIo()+ setLook('plain')+})++describe('the page at every width', () => {+ for (const [look, columns] of WIDTHS.flatMap(width => (['plain', 'bbs'] as const).map(name => [name, width] as const))) {+ it(`draws the board, the inspector and every folded section within ${columns} columns (${look} look)`, () => {+ setLook(look)++ const w = fullPage(columns)++ for (const key of ['wf-replay-fold', 'wf-compare-fold', 'wf-export-fold', 'wf-saved-fold']) buttonOf(w.page(), key) !== undefined && click(w.page(), key)++ expect(report(measure(w.page(), columns))).toBe('')++ click(w.page(), 'wf-inspect')+ expect(report(measure(w.page(), columns))).toBe('')+ })+ }+})++async function drillWorld(columns: number): Promise<{ world: World; at: () => ReturnType<typeof frame> }> {+ const world = await worldOf(liveFiles())++ bindWorkflowDrill(world.state, world.host as never)++ return { world, at: () => frame(world, columns) }+}++describe('the drill-down at every width', () => {+ for (const columns of WIDTHS) {+ it(`keeps each level, tab and the search within ${columns} columns, with a whole last crumb and the tab on its own row`, async () => {+ const { world, at } = await drillWorld(columns)++ click(at().tree, 'wf-inspect')+ expect(report(measure(at().tree, columns))).toBe('')+ click(at().tree, 'wf-inspect')+ click(at().tree, 'wf-drill-open')++ const crumbsOf = (): El | undefined => flatten(at().tree).find(el => el.kind === 'Box' && el.props.key === 'wf-crumbs')++ for (let level = 0; level < 4; level += 1) {+ expect(report(measure(at().tree, columns))).toBe('')++ const crumbs = crumbsOf()++ if (crumbs !== undefined) {+ const row = flatten(crumbs.props.children).filter(el => el.kind === 'Text' || el.kind === 'Button')+ const words = row.map(el => String(el.kind === 'Button' ? el.props.label : el.props.children))++ expect(words.join('')).not.toMatch(/Activity|Log|Files|Result/)+ if (drillOf(world.state).level === 'agent') expect(words.some(word => /^Agent: /.test(word))).toBe(true)+ }++ click(at().tree, 'wf-drill-in')+ }++ expect(drillOf(world.state).level).toBe('item')+ click(at().tree, 'wf-drill-out')+ expect(drillOf(world.state).level).toBe('agent')++ for (const sub of ['log', 'files', 'result', 'activity']) {+ click(at().tree, `wf-sub-${sub}`)+ expect(report(measure(at().tree, columns))).toBe('')+ }++ setQuery(at().env, 'build')+ await flush()+ expect(report(measure(at().tree, columns))).toBe('')+ })+ }++ it('collapses the middle crumbs before it wraps, and keeps the last whole', async () => {+ const { world, at } = await drillWorld(60)++ click(at().tree, 'wf-drill-open')+ for (let n = 0; n < 2; n += 1) click(at().tree, 'wf-drill-in')+ expect(drillOf(world.state).level).toBe('agent')++ const crumbs = flatten(at().tree).find(el => el.kind === 'Box' && el.props.key === 'wf-crumbs') as El+ const parts = flatten(crumbs.props.children).filter(el => el.kind === 'Text' || el.kind === 'Button')+ const shown = parts.map(el => String(el.kind === 'Button' ? el.props.label : el.props.children)).join('')++ expect(shown).toMatch(/…/)+ expect(shown).toMatch(/Agent: /)+ expect(cells(shown) + parts.filter(el => el.kind === 'Button').length * 4).toBeLessThanOrEqual(60)+ expect(parts[parts.length - 1]?.kind).toBe('Text')+ })++ it('puts a space between the diff-stat button and the worktree path on the wide Files tab', async () => {+ const { at } = await drillWorld(125)++ click(at().tree, 'wf-drill-open')+ for (let n = 0; n < 2; n += 1) click(at().tree, 'wf-drill-in')+ click(at().tree, 'wf-sub-files')++ const row = flatten(at().tree).find(el => el.kind === 'Box' && el.props.key === 'wf-diff-row') as El+ const kids = flatten(row.props.children).filter(el => el.kind === 'Text' || el.kind === 'Button')+ const path = kids.findIndex(el => el.kind === 'Text' && String(el.props.children).startsWith('worktree'))+ const button = kids.findIndex(el => el.kind === 'Button')++ expect(path).toBeGreaterThanOrEqual(0)+ expect(button).toBeGreaterThan(path)+ expect(String(kids[path]?.props.children)).toMatch(/ $/)+ expect(button).toBe(path + 1)+ })+})++describe('the helpers', () => {+ const at = (columns: number): Ctx => ({ kit, state: newState({}), nowMs: 0, columns, pictures: new Map(), act: {} as Actions })++ it('clips a rule whose title or right-hand text is longer than the pane, in both looks', () => {+ for (const look of ['plain', 'bbs'] as const) {+ setLook(look)++ for (const columns of [30, 56, 60]) {+ expect(report(measure({ kind: 'Box', props: { flexDirection: 'column', children: [rule(at(columns), 'T'.repeat(90), 'right '.repeat(30)), rule(at(columns), 'Phases', 'x'.repeat(200))] } }, columns))).toBe('')+ }+ }+ })++ it('wraps a long run of buttons onto more rows, keeps every one in order, and clips a label longer than a row', () => {+ const items = Array.from({ length: 9 }, (_, i) => ({ key: `k${i}`, label: `button ${i}`, onPress: () => undefined }))+ const rows = flow(at(40), [...items, { key: 'long', label: 'L'.repeat(120), onPress: () => undefined }], 'r', 'lead ')++ expect(rows.length).toBeGreaterThan(2)+ expect(report(measure({ kind: 'Box', props: { flexDirection: 'column', children: rows } }, 40))).toBe('')+ expect(flatten(rows).filter(el => el.kind === 'Button').map(el => el.props.key)).toEqual([...items.map(item => item.key), 'long'])+ expect(String(flatten(rows).find(el => el.props.key === 'long')?.props.label)).toMatch(/…$/)+ })++ it('names a run by whole words, never a cut through the middle of one', () => {+ expect(runTag('sample-btr')).toBe('sample-btr')+ expect(runTag('wf_live')).toBe('live')+ expect(runTag('wf_ab')).toBe('wf-ab')+ expect(runTag('wf_a1b2c3d4e5')).toBe('c3d4e5')+ expect(runTag('x')).toBe('x')+ expect(runTag('sample-btr')).not.toMatch(/^le-/)+ })+})++describe('the meter itself', () => {+ const row = (children: unknown[]): El => ({ kind: 'Box', props: { flexDirection: 'row', children } })+ const btn = (label: string): El => ({ kind: 'Button', props: { label } })++ it('flags a row whose buttons are wider than the pane, and a plain text squeezed to a letter', () => {+ expect(measure(row([btn('abcdefgh'), btn('abcdefgh')]), 20).map(f => f.kind)).toEqual(['overflow'])+ expect(measure(row([btn('abcdefghijkl'), { kind: 'Text', props: { children: 'Agent · Log' } }]), 18).map(f => f.kind)).toEqual(['overflow', 'letters'])+ expect(measure(row([btn('abcdefghijkl'), { kind: 'Text', props: { wrap: 'truncate-end', children: 'Agent · Log' } }]), 18)).toEqual([])+ })+})diff --git a/plugins/ruflo-console/tests/wf-replay-tick.spec.ts b/plugins/ruflo-console/tests/wf-replay-tick.spec.tsnew file mode 100644index 0000000000..7ba8cc4ef0--- /dev/null+++ b/plugins/ruflo-console/tests/wf-replay-tick.spec.ts@@ -0,0 +1,181 @@+/**+ * The replay's clock (ADR-469): a playing replay advances on the console's own timer (host.every), not only when something else redraws the+ * page; it stops when it ends, is paused, or the page is left; each tick is bounded work. A fake host and a fake clock; no engine. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-replay-tick.spec.ts --testTimeout=30000+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { buildTimeline, newReplay, offsetOf, settle, stepNow, TICK_MAX_STEPS, type ReplayUi, type Timeline } from '../hooks/data/wf-replay'+import type { Host } from '../hooks/host'+import { newState } from '../hooks/state'+import { workflowsActions } from '../hooks/wf-actions'+import { resetSavedLive } from '../hooks/wf-saved-live'+import type { Actions, Ctx } from '../hooks/views/common'+import { resetCompare } from '../hooks/views/wf-compare'+import { resetExport } from '../hooks/views/wf-export'+import { resetFolds } from '../hooks/views/wf-fold'+import { replayOf, resetReplays, TICK_MS } from '../hooks/views/wf-replay'+import { workflowsPage } from '../hooks/views/wf-page'+import { BASE, runOf } from './fixtures/wf-runs'+import { T0 } from './fixtures/workflows'+import { click, kit } from './fixtures/wf-drill-world'++type Timer = { ms: number; fn: () => void; cancelled: boolean }++const run = runOf('wf_tick', BASE)+const START = 1_800_000_000_000++function world() {+ const timers: Timer[] = []+ const state = newState({})+ let drawn = 0++ state.view = 'workflows'+ state.cwd = '/work/proj'+ state.isInteractive = false+ state.wf.read = { runs: [run], root: '/x', capBytes: 1, skipped: 0, more: 0 }++ const host = { invalidate: () => void (drawn += 1), every: (ms: number, fn: () => void) => { const timer = { ms, fn, cancelled: false }; timers.push(timer); return { cancel: () => void (timer.cancelled = true) } } } as unknown as Host+ const act = { workflows: workflowsActions(state, host, { ask: () => undefined } as never), focus: () => undefined, view: () => undefined } as unknown as Actions+ const ctx: Ctx = { kit, state, nowMs: T0 + 600_000, columns: 100, pictures: new Map(), act }++ return { state, timers, page: () => workflowsPage(ctx), drawn: () => drawn, live: () => timers.filter(t => !t.cancelled) }+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(START)+ resetFolds()+ resetReplays()+ resetCompare()+ resetExport()+ resetSavedLive()+})+afterEach(() => vi.useRealTimers())++describe('the play loop', () => {+ it('starts one timer on play and advances the replay on each tick with no other redraw', () => {+ const w = world()++ click(w.page(), 'wf-replay-fold')+ expect(w.timers).toHaveLength(0)+ click(w.page(), 'wf-rp-play')+ expect(w.live()).toHaveLength(1)+ expect(w.live()[0]?.ms).toBe(TICK_MS)+ expect(replayOf(run.id).step).toBe(0)++ vi.setSystemTime(START + 1000)+ w.live()[0]?.fn()+ // 16x: one second of wall clock is 16 s of the run: both starts and build:b's end at 5 s are behind it.+ expect(replayOf(run.id).step).toBe(3)+ expect(replayOf(run.id).playFromMs).not.toBeNull()+ expect(w.drawn()).toBeGreaterThan(1)++ // The page drawn again while playing does not start a second timer.+ w.page()+ w.page()+ expect(w.timers).toHaveLength(1)+ })++ it('plays to the end and then stops its timer, leaving the final board', () => {+ const w = world()++ click(w.page(), 'wf-replay-fold')+ click(w.page(), 'wf-rp-play')+ vi.setSystemTime(START + 30_000)+ w.live()[0]?.fn()+ expect(replayOf(run.id).step).toBe(6)+ expect(replayOf(run.id).playFromMs).toBeNull()+ expect(w.live()).toHaveLength(0)+ expect(w.state.timers.size).toBe(0)+ })++ it('stops on pause, and a replay started again gets a fresh timer', () => {+ const w = world()++ click(w.page(), 'wf-replay-fold')+ click(w.page(), 'wf-rp-play')+ vi.setSystemTime(START + 500)+ click(w.page(), 'wf-rp-play')+ expect(replayOf(run.id).playFromMs).toBeNull()+ w.live()[0]?.fn()+ expect(w.live()).toHaveLength(0)++ const held = replayOf(run.id).step++ vi.setSystemTime(START + 60_000)+ expect(replayOf(run.id).step).toBe(held)+ click(w.page(), 'wf-rp-play')+ expect(w.live()).toHaveLength(1)+ })++ it('stops when the page is left, and when the pane is hidden, without redrawing a closed page forward', () => {+ const w = world()++ click(w.page(), 'wf-replay-fold')+ click(w.page(), 'wf-rp-play')+ w.state.view = 'overview'+ vi.setSystemTime(START + 1000)+ w.live()[0]?.fn()+ expect(w.live()).toHaveLength(0)+ // The replay itself still says where its own clock puts it when the page comes back, and the draw then restarts the timer.+ w.state.view = 'workflows'+ w.page()+ expect(w.live()).toHaveLength(1)++ w.state.isInteractive = true+ w.state.pane.isOpen = true+ w.state.pane.isShown = false+ w.live()[0]?.fn()+ expect(w.live()).toHaveLength(0)+ })++ it('swallows a failing tick and ends it', () => {+ const w = world()+ const act = workflowsActions(w.state, { invalidate: () => undefined, every: (_ms: number, fn: () => void) => (fn(), { cancel: () => undefined }) } as unknown as Host, { ask: () => undefined } as never)++ w.state.view = 'workflows'+ expect(() => act.tick?.('boom', 10, () => { throw new Error('x') })).not.toThrow()+ })+})++describe('settle: bounded work per tick', () => {+ const longRun = (events: number, gapMs: number): Timeline => ({ events: Array.from({ length: events }, (_, i) => ({ atMs: 1000 + i * gapMs, agentId: `a${i}`, kind: 'start' as const, phase: 'p', label: `a${i}` })), t0: 1000, t1: 1000 + (events - 1) * gapMs, untimed: [], why: null })+ const playing = (speed: number): ReplayUi => ({ ...newReplay(), speed, playFromMs: 0, baseMs: 0 })++ it('carries at most TICK_MAX_STEPS events in one call, however far the clock ran', () => {+ const tl = longRun(5000, 10)+ const next = settle(playing(256), tl, 600_000)++ expect(next.step).toBe(TICK_MAX_STEPS)+ expect(next.playFromMs).toBe(600_000)+ expect(next.baseMs).toBe(offsetOf(tl, TICK_MAX_STEPS))+ expect(settle(next, tl, 600_001).step).toBeGreaterThan(TICK_MAX_STEPS)+ })++ it('re-bases at the tick, so ticks scan only the new events, and it never loses the time between two events', () => {+ const tl = longRun(10, 100_000)+ let ui = playing(16)++ // 100 s between events at 16x is 6.25 s of wall clock: ticks of 400 ms get there only if each keeps its partial progress.+ for (let now = 400; now <= 6600; now += 400) ui = settle(ui, tl, now)+ expect(ui.step).toBe(1 + 1)+ expect(stepNow(ui, tl, 6600)).toBe(2)+ })++ it('ends at the last event and leaves a paused replay alone', () => {+ const tl = longRun(3, 1000)++ expect(settle(playing(256), tl, 10_000)).toMatchObject({ step: 3, playFromMs: null })++ const paused = { ...newReplay(), step: 1 }++ expect(settle(paused, tl, 10_000)).toBe(paused)+ })++ it('stays consistent with the timeline the page builds from a run', () => {+ const tl = buildTimeline(run)++ expect(settle({ ...newReplay(), speed: 16, playFromMs: 0, baseMs: 0 }, tl, 1000).step).toBe(3)+ })+})diff --git a/v3/docs/adr/ADR-469-workflows-layout-and-replay-tick.md b/v3/docs/adr/ADR-469-workflows-layout-and-replay-tick.mdnew file mode 100644index 0000000000..e7b6ffc235--- /dev/null+++ b/v3/docs/adr/ADR-469-workflows-layout-and-replay-tick.md@@ -0,0 +1,80 @@+# ADR 469: Workflows page layout at every dock width, and a clock for replay++Status: Accepted++Date: 2026-10-06++Builds on: ADR-458 (the page), ADR-459 (drill-down), ADR-461 (replay, compare), ADR-463 (worktrees, templates), ADR-464 (slots)++## 1. Context++Recordings of the Workflows page at the widths the engine really gives the dock (about 60 to 125 columns, `RUFLO_CONSOLE_COLUMNS`+overrides) showed six defects:++1. The drill breadcrumb's last crumb (`Agent · Activity`, `Agent · Log`...) wrapped one letter per row at narrow widths.+2. A run's id in the Phases footer and in Compare (`B le-btr`) was cut from the left.+3. Button rows ran past the right edge at 60 and 72 columns (`[ Close` cut, stray letters past the border); the inspector's tab row+ clipped at 60 so the `control` tab could not be clicked. The extras row (every key and action slot, nine buttons) was 193 cells wide+ at every width, even 125.+4. On the wide Files tab, `Read diff stat` touched the worktree path with no space.+5. Compare labelled a run `B le-btr`: the same left-cut family as 2.+6. One unreproduced `ui.press hook skipped... no handler is held under handle` after a resize.++Replay also only advanced when something else redrew the page: pressing play moved nothing until the next refresh tick.++Root causes. (1)(3)(4): the engine gives a Button its label plus `[ ` and ` ]`, gives a plain Text its length, and only a Text with+`wrap: 'truncate-*'` gives way; a row that asks for more than the pane overflows, and a plain Text left almost nothing wraps by letter.+Every row was built as one fixed `row(...)` of however many buttons there were. (2)(5): `shortId` (data/parse.ts) takes the last six+characters of the id when its last word is shorter than four (`sample-btr` becomes `le-btr`), a cut through the middle of a word.+(6): the host holds a Button's `onPress` only for the life of the drawing that made it (the engine's own type comment), so a click+sent while the pane was redrawn (a resize) can reach a drawing that is gone.++## 3. Decision++**One layout module, `views/wf-layout.ts`.**+`flow(ctx, buttons, key, lead?)` packs buttons into rows no wider than the pane (each at label + 4 cells, emoji at two), wrapping to+`key-2`, `key-3` where a row is full; a label longer than a row is clipped with an ellipsis, never overrun; every button stays, in order,+and clickable. `crumbRow` draws the breadcrumb: the whole trail while it fits, then `Runs › … › Agent: x` (middle crumbs folded), then+`… › last`, and only then a clipped last crumb; the last crumb is a `truncate-end` Text, so it cannot fall to a letter per row, and the+sub-tab (Activity, Log, Files, Result) is no longer in the crumb: it is the `view` tab row of its own below it. `runTag` names a run by its+last word, or by whole words where that is too short (`sample-btr`), never a cut through a word. `safe` wraps a handler so a throwing closure+changes nothing and says nothing.++Used for: the page's move row, extras row and tab row; the drill's moves, breadcrumb, tab row, log head, loaders; replay controls;+compare controls; the inspector's agent actions and transcript button; template pick and choice rows; the worktree read button; the+search's loader. The Files tab draws the path then one space then the button, and the unbound case is two lines, not one row.+`rule` and `section` headers in `common.ts` clip their title and right-hand text to the pane (a `truncate-end` Text), so a long phase title+or slot title cannot push the row past the border.++**Replay has a clock.** `data/wf-replay.ts: settle(ui, timeline, now)` brings a playing replay up to now and re-bases it there (the clock+keeps its fractional progress, so two events minutes apart are reached by ticks), stops at the end, and carries at most `TICK_MAX_STEPS`+(400) events per call. The page's `workflows.tick(name, ms, fn)` action (wf-actions.ts) runs `fn` on the console's own clock+(`host.every`, one timer per name in `state.timers`, so the console's stop cancels it), redraws after each call, and ends the timer when `fn`+answers false, throws, the page is not the one in front, or the pane is hidden. Replay starts it on play (every 400 ms) and on any draw that+finds the replay playing (so coming back to the page resumes it), and `replayTick` ends it at the end or on pause. A surface without+the action keeps the old behaviour (it advances on the next redraw).++**Orphaned presses.** The only place a press can be orphaned is the engine's drawing handle. `hooks/press-guard.ts: tolerantPress` wraps the+`ui.press` hook's `next(e)`: a rejection saying `no handler is held` answers `{ element }` quietly; any other failure still propagates. The page's+own handlers are all `safe`.++## 4. Consequences++- Rows that were one line become two at the narrowest widths (the move row at 56 columns is two rows); reading order is unchanged.+- The drill's crumb at the agent level reads `Agent: label`; the tab is shown on the tab row. Specs that matched `Agent · Activity` were updated.+- `shortId` itself is unchanged (not this page's file); the Workflows views stopped using it for run names. Other pages that use it keep its cut.+- A playing replay costs one timer, a bounded scan and one redraw per 400 ms while the page is open; none while it is closed or paused.+- A stale click is dropped silently; it cannot be told from the engine's own message by anything but its text, so the pattern is narrow.+- The press hook change is in register.ts (a one-line wrap), the only edit outside the Workflows views, data and actions.++## 5. Tests++- `tests/wf-layout.spec.ts` (24): draws the full page (every slot, replay/compare/export/saved opened, inspector open) at 56, 60, 72, 80, 100 and 125 columns in both looks, and the drill at every level and tab plus search at the same widths, with a meter (`tests/fixtures/wf-layout-rig.ts`) that sums a row the way the engine lays it out: no row wider than the pane, no plain Text squeezed to a letter, every button reachable, the crumb folded before it wraps with its last crumb whole and no tab name in it, a space before `Read diff stat`; helper tests for `flow`, `rule`, `runTag`, and the meter itself.+- `tests/wf-replay-tick.spec.ts` (9): a fake host and clock; play starts one timer and ticks advance it with no other redraw; it stops at the end, on pause, when the page is left and when the pane is hidden; a throwing tick ends; `settle` is bounded (5000 events, one call, at most 400 steps), keeps partial progress across ticks, ends at the last event.+- `tests/press-guard.spec.ts` (4): the stale-handle answer, other failures propagate, handlers never throw.+- Mutation-checked: no wrapping in `flow` (18 fail), no crumb fold (3), an unclipped rule title (2), no space before the diff button (1), no label clip (2).++## 6. Rollback++Revert the commit. `flow` and `crumbRow` are additive helpers; the views return to their fixed rows. The `tick` action is optional in+`WorkflowsActions`, so removing it leaves replay advancing on redraw as before. The press guard is one wrapped line in register.ts.