/** * Bounded live-region cockpit for optional Harness work. * * It never commits rows: finished transcript output remains in the terminal's * native scrollback while this temporary inspection view is open. Every stage — * the grouped overview, a workflow and its members, one subagent, one job — is * an internal submode of the same frame, so inspecting a row never creates a * detached modal. * * All four stages are built from the same primitive: a flat list of rows, some * of which carry a focus identity. That is what makes a detail view a real * inspectable list rather than a text page with an incidental highlight, and it * is why the arrow keys move a visible cursor everywhere instead of scrolling * underneath a stuck one. * @module dshline/work/overlay */ import type { Key, Role } from '@dshline/renderer' import { BOX_CHROME_COLUMNS, displayWidth, escapeControls, formatElapsed, formatTokens, paint, SPINNER_INTERVAL_MS, spinnerFrameOrbit, spinnerMark, SPINNER_MARK_COLUMNS, tailToWidth, truncateToWidth, wrapToWidth, } from '@dshline/renderer' import { chromeWidth, fitFooterHelp, footerBudget, rootFrame } from '../chrome.ts' import { FocusRing } from '../focus.ts' import { RowViewport } from '../scroll.ts' import type { TuiOverlay } from '../slots.ts' import { compactRows, noticeRow, noticeText } from '../surface.ts' import type { JobWorkItem, SubagentWorkItem, WorkConversationTarget, WorkItem, WorkMark, WorkflowMemberItem, WorkflowWorkItem, WorkSnapshot, WorkInterruptResult, } from './model.ts' import { directConversationTarget, looseSubagents, memberMark, routeLabel, subagentDuration, workflowMemberKey, workItemKey, workMark, } from './model.ts' import type { JobOutputLine, JobOutputObservation } from './jobs.ts' /** Rows outside the listing: leading blank, borders, counter, and spacer. */ const WORK_FIXED_ROWS = 5 /** Minimum terminal width that can show the framed work list without wrapping. */ const WORK_MIN_COLUMNS = BOX_CHROME_COLUMNS + 10 /** How long an interrupt result remains visible before the normal view returns. */ const NOTICE_MS = 3_000 /** * How long an armed Job stop waits for its confirming press. * * Upstream's human kill affordance uses three seconds, and matching it is worth * more than picking a number: it is long enough to notice what was armed and * short enough that a stray second press is unlikely. The window is checked * against the overlay's OWN clock, the same lazily-expired shape as * {@link NOTICE_MS}, rather than owning a second timer — the overlay already * runs one heartbeat for elapsed readings and the spinner, and a destructive * action does not need a timer of its own in order to expire. */ const STOP_ARM_MS = 3_000 /** Columns a row spends on its gutter mark and the space after it. */ const GUTTER_COLUMNS = 2 /** * The detail row key for the live assistant-text tail. * * Named once so the row's construction and its identity cannot drift; the key * is also the row's stable selection identity, exactly like every other fact. */ const OUTPUT_KEY = 'output' /** * Focus-identity prefix for the Job output section's rows. * * Distinct from {@link OUTPUT_KEY} because the two never share a stage: that key * belongs to a subagent's assistant-text tail, this one to a Job's retained * ring, and two row families sharing a key namespace would make the cursor able * to aim at a row that is no longer the one it named. */ const JOB_OUTPUT_KEY_PREFIX = 'job-output:' /** * The one line that stands in for missing earlier output. * * Three different layers can drop bytes — the Harness ring's retention, a * producer-side gap, and dshline's own presentation cap — and a reader cannot * act differently on any of them from inside a 100-column frame. So the marker * says exactly what is true and nothing more, and it appears once per missing * region rather than once per adjacent chunk: a stream that suffered a loss and * then continued has to stay readable afterwards. */ const GAP_MARKER = '… earlier output not retained …' /** * The settled glyph for each non-animating mark. * * The vocabulary is deliberately not interchangeable. The two-cell orbit means * execution that is actually observed, `●` an active lifecycle whose internals * are not observable, `•` a background record that exists, and `◐` a record * that is transitioning. Terminal glyphs report a published outcome. * * Every one of these is padded to the orbit's box, so a row's text starts in the * same column whether its mark is turning or settled. */ const MARK_GLYPH: Readonly, string>> = { active: '●', record: '•', stopping: '◐', completed: '✓', failed: '✗', cancelled: '⊘', } /** The role each mark's glyph is painted with when its row is not focused. */ const MARK_ROLE: Readonly> = { executing: 'busy', active: 'subdued', record: 'subdued', stopping: 'busy', completed: 'success', failed: 'error', cancelled: 'warning', } /** Which stage of the temporary live region is on screen. */ type Stage = | { readonly kind: 'list' } | { readonly kind: 'workflow'; readonly subject: string } | { readonly kind: 'subagent'; readonly subject: string } | { readonly kind: 'job'; readonly subject: string } /** One entry on the stage stack: what is shown, and where its cursor is. */ interface StageFrame { readonly stage: Stage readonly focus: FocusRing } /** Inputs the Work overlay needs from its owner. */ export interface WorkOverlaySpec { /** Current read-only capability projection. */ readonly snapshot: () => WorkSnapshot /** Ask Harness to interrupt one subagent, which is the only interruptible kind. */ readonly interruptSubagent: (item: SubagentWorkItem | WorkflowWorkItem) => WorkInterruptResult /** * Ask Harness to stop one running Job, on a human's behalf. * * Separate from {@link interruptSubagent} rather than folded into one * `control(item)`: a subagent interrupt cancels a turn and a Job stop cancels * a producer, and a union whose meaning has to be rediscovered from `source` * is how a control ends up applied to the wrong authority. */ readonly stopJob: (item: JobWorkItem) => WorkInterruptResult /** * Begin observing one Job's retained output, non-consumingly. Called only * when a Job detail stage actually opens, and the returned handle is disposed * the moment that stage closes. */ readonly observeJob?: (id: string) => JobOutputObservation | undefined /** * Open the durable subagent-conversation catalog, when `ctx.subagents` is * mounted. The catalog belongs to a separate presenter: Work hands off and * keeps no durable conversation state of its own, and this is absent exactly * when that authority is. */ readonly conversations?: () => void /** * Open the subagent detail stage's selected child conversation directly, when * Work holds the complete durable descriptor for it. Offered only on that * stage: the overview keeps `c` as the catalog, because a focused list row is * not yet an inspected subject. Mounted with the same seam as * {@link conversations}, and the catalog remains the fallback whenever the * selection is not addressable. */ readonly conversation?: (target: WorkConversationTarget) => void /** Remove this overlay from the live region. */ readonly close: () => void /** Redraw after selection, a result, or a timer tick. */ readonly invalidate: () => void } /** A short result shown over the view without committing transcript output. */ interface Notice { readonly text: string readonly failed: boolean readonly expiresAt: number } /** * A Job stop waiting for its confirming press. * * Armed against the EXACT Job identity, never a screen position or a row * index, so navigating away and coming back to a different Job can never turn * one arming into a kill of whatever now occupies the same place. The overlay * also re-resolves the id against a FRESH projection before the second press, * which is what makes a Job that settled or began stopping in the meantime * refuse the action rather than transfer it. */ interface ArmedStop { /** The exact Job id that was armed. */ readonly id: string /** Epoch ms after which the arming is spent. */ readonly expiresAt: number } /** One rendered line of a stage, and whether a human can aim at it. */ interface StageRow { /** `row` takes a gutter and may be focused; the others are structure. */ readonly kind: 'line' | 'blank' | 'row' /** Focus identity. Present exactly when this row can be aimed at. */ readonly key?: string /** The leading mark, already chosen from an authoritative fact. */ readonly mark?: string /** Role for the mark alone, so an outcome reads without shouting. */ readonly markRole?: Role /** The row's text after the mark: escaped and already fitted. */ readonly text: string /** Role for the text when the row is not focused. */ readonly role: Role /** Stage this row opens on Enter; absent rows ignore Enter safely. */ readonly open?: Stage } /** One whole fact a row yields as a unit, never by being cut in half. */ interface RowSegment { /** The already-escaped text. */ readonly text: string /** Separator drawn before this segment when it survives fitting. */ readonly separator: ' ' | ' · ' /** Drop priority: the highest surviving rank yields first. */ readonly rank: number } /** * Create the bounded Work overlay. * @param spec - current projection and overlay controls. * @returns a temporary live-region overlay. */ export function createWorkOverlay(spec: WorkOverlaySpec): TuiOverlay { const viewport = new RowViewport() // A STACK, not a flag: a workflow member opens the shared subagent stage, and // `esc` has to return to the workflow it was reached from rather than to the // overview, which is the difference between a hierarchy and two flat modes. const stack: StageFrame[] = [{ stage: { kind: 'list' }, focus: new FocusRing() }] let closed = false let ticker: NodeJS.Timeout | undefined let tick = 0 let notice: Notice | undefined /** A Job stop armed by the first `k`, awaiting its confirming press. */ let armedStop: ArmedStop | undefined /** * The open Job output observation, alive only while a Job detail is shown. * * Exactly one can exist, because exactly one Job detail stage can be on the * stack. The overview holds none, so a closed or never-opened detail costs * zero `readAt` calls. */ let jobObservation: JobOutputObservation | undefined /** Rows of the last render, used by key handling before the next paint. */ let rows: readonly StageRow[] = [] // Whether the last paint was the compact fallback. That frame shows no rows // and no cursor, so a keystroke that would open or interrupt an aimed row // would be acting on something the human cannot see. It advertises exactly // `esc close`, and while it is on screen that is all it does. let fellBack = false const frame = (): StageFrame => stack[stack.length - 1] ?? { stage: { kind: 'list' }, focus: new FocusRing() } const close = (): void => { if (closed) return closed = true // Closing `/work` ends every observation it started. Nothing about a Job's // output outlives the view that was asked to look at it. releaseJobObservation() armedStop = undefined spec.close() } const currentNotice = (): Notice | undefined => { if (notice !== undefined && Date.now() >= notice.expiresAt) notice = undefined return notice } /** The arming still inside its window, expiring it lazily like the notice. */ const currentArmedStop = (): ArmedStop | undefined => { if (armedStop !== undefined && Date.now() >= armedStop.expiresAt) armedStop = undefined return armedStop } /** * Drop the open Job output observation, if any. * * Synchronous and idempotent by contract, so every path out of a Job detail * calls it without needing to know whether another already did. */ const releaseJobObservation = (): void => { const open = jobObservation jobObservation = undefined open?.dispose() } /** * Keep exactly one Job observation alive, and only for the Job being inspected. * * This is what makes observation demand-driven rather than ambient: the * overview, arrow movement, and a closed `/work` all hold none, so they cost * zero output reads. A Job settling pops its stage, and the next `build` sees * a different subject and disposes what it was reading. */ const syncJobObservation = (): void => { const stage = frame().stage const wanted = stage.kind === 'job' ? stage.subject : undefined if (jobObservation !== undefined && observationId === wanted) return releaseJobObservation() if (wanted === undefined || spec.observeJob === undefined) return // The stage subject is a Work SELECTION key (`job:bash-1`), not the registry // id. Resolving the row first is what keeps the two namespaces from drifting // apart, and it is also the cheapest proof that the Job is still in the // projection rather than only in a stale stage. const item = index.get(wanted) if (item === undefined || item.source !== 'job') return observationId = wanted jobObservation = spec.observeJob(item.id) } /** * Build every row of the current stage and re-align the cursor with them. * * `retarget` governs what happens when the aimed identity vanished: a render * adopts the predictable neighbour, while a human ACTION keeps the dead aim so * it can refuse rather than hit whatever inherited that screen position. */ /** Identity index of the last build, so one paint indexes the projection once. */ let index: ReadonlyMap = new Map() /** The Job id `jobObservation` is reading, so a re-render never re-reads. */ let observationId: string | undefined const build = (snapshot: WorkSnapshot, width: number, retarget: boolean): readonly StageRow[] => { index = workIndex(snapshot) // A subject that settled while it was inspected must not keep painting // stale authority: the stage leaves, one level at a time, until a live one // is reached. The overview is always live. while (stack.length > 1) { const stage = frame().stage if (stage.kind === 'list' || index.has(stage.subject)) break // Popping a Job detail abandons the Job it was inspecting, so the arming // for it cannot survive into whatever stage took its place. if (stage.kind === 'job') armedStop = undefined stack.pop() } syncJobObservation() const built = stageRows(frame().stage, snapshot, index, width, tick, jobObservation) frame().focus.update(built.flatMap(row => row.key === undefined ? [] : [row.key]), retarget) return built } const readStage = (retarget: boolean, width: number): { snapshot: WorkSnapshot; built: readonly StageRow[] } => { const snapshot = spec.snapshot() const built = build(snapshot, width, retarget) rows = built return { snapshot, built } } /** The row the cursor is on, resolved by identity against the newest rows. */ const focusedRow = (): StageRow | undefined => { const aim = frame().focus.current if (aim === undefined) return undefined return rows.find(row => row.key === aim) } /** * The item a human action applies to. * * On the overview that is the focused row's item; inside a detail stage it is * the stage's own subject, so `k` keeps working while the cursor sits on a * fact row that has no action of its own. */ const subject = (): WorkItem | undefined => { const stage = frame().stage if (stage.kind !== 'list') return index.get(stage.subject) const aim = frame().focus.current return aim === undefined ? undefined : index.get(aim) } const push = (stage: Stage): void => { // Pushing a new stage abandons the previous stage's arming. An arming is // consent to act on one named Job, and consent does not travel — so opening // a different Job's detail cannot leave A armed behind B. if (frame().stage.kind !== 'job') armedStop = undefined stack.push({ stage, focus: new FocusRing() }) viewport.first() spec.invalidate() } const pop = (): void => { if (stack.length <= 1) { close() return } stack.pop() // Leaving a Job detail abandons both the output observation and the arming, // so nothing about that Job stays actionable from another stage. if (frame().stage.kind !== 'job') { releaseJobObservation() armedStop = undefined } viewport.first() spec.invalidate() } /** * One `k` press against a Job row: arm, or confirm an existing arming. * * Requires a freshly built `index` — the caller re-reads the projection before * resolving the subject, which is what lets the confirming press re-validate * against current authority rather than against a remembered row. * @param item - the Job the press resolved to. */ const handleJobStop = (item: JobWorkItem): void => { // Stop belongs to the DETAIL stage only. A destructive operation gets an // inspect step before its confirmation, and the overview is a browsing // surface where a letter key should not be able to cancel anything. if (frame().stage.kind !== 'job') { armedStop = undefined return } const armed = currentArmedStop() if (armed === undefined || armed.id !== item.id) { // FIRST press. Arm this exact id — not the row, not the position, not the // kind — so a later press on a different Job re-arms rather than fires. // A Job that is not stoppable is never armed at all, so the confirming // press has nothing to confirm and there is no arming to expire. if (item.state !== 'running') { armedStop = undefined return } armedStop = { id: item.id, expiresAt: Date.now() + STOP_ARM_MS } notice = { text: 'press k again to stop', failed: false, expiresAt: Date.now() + STOP_ARM_MS } return } // SECOND press. The arming is spent either way, so it cannot be reused even // if the request below fails. armedStop = undefined // The ONE gate: re-resolve the exact armed Job against the projection this // press just re-read, and require it to still be a live Job in this view. If // it settled, was removed, or began stopping in the meantime, the action is // refused outright — whatever now occupies that screen position is a // different Job, and stopping it would transfer consent never given. This is // deliberately the only place the decision is made, so there is no earlier // guard that could quietly make the re-validation redundant. const stage = frame().stage const fresh = stage.kind === 'job' ? index.get(stage.subject) : undefined if (fresh === undefined || fresh.source !== 'job' || fresh.state !== 'running') { notice = { text: 'That job is no longer running.', failed: false, expiresAt: Date.now() + NOTICE_MS } return } const result = spec.stopJob(fresh) notice = { text: result.message, failed: result.kind === 'failed', expiresAt: Date.now() + NOTICE_MS } } const stopTicker = (): void => { if (ticker === undefined) return clearInterval(ticker) ticker = undefined } return { mounted() { // One heartbeat drives the elapsed readings AND the shared spinner phase, // so every animated row turns together instead of flickering independently. // The parent may be idle while independent work runs; the timer exists only // for this mounted overlay, and unref keeps it from owning process life. ticker ??= setInterval(() => { tick += 1 spec.invalidate() }, SPINNER_INTERVAL_MS).unref() }, dispose: () => { // Overlay disposal is the last word on everything it opened, and it is // the path a torn-down attachment takes. Disposing the observation here // as well as in `HarnessWork.dispose()` is deliberate: the two contain // each other, so a teardown ordering mistake cannot leave a registry // subscription calling `invalidate()` into the next session. stopTicker() releaseJobObservation() armedStop = undefined }, render(columns, terminalRows = 24) { const activeNotice = currentNotice() const width = chromeWidth(columns) const inner = width - BOX_CHROME_COLUMNS const { snapshot, built } = readStage(true, inner) const fallback = (): string[] => { fellBack = true return compactFallback(snapshot, columns, terminalRows, activeNotice) } if (terminalRows <= WORK_FIXED_ROWS || columns < WORK_MIN_COLUMNS) return fallback() const visible = terminalRows - WORK_FIXED_ROWS - (activeNotice === undefined ? 0 : 1) if (visible <= 0) return fallback() viewport.update(built.length, visible) const focusedAt = built.findIndex(row => row.key !== undefined && row.key === frame().focus.current) if (focusedAt >= 0) { if (focusedAt < viewport.start) viewport.move(focusedAt - viewport.start) if (focusedAt >= viewport.end) viewport.move(focusedAt - viewport.end + 1) } const counter = built.length === 0 ? 'no active work' : `rows ${String(viewport.start + 1)}–${String(viewport.end)} of ${String(built.length)}` const aimed = focusedRow() const selected = subject() // The footer and `c` share this ONE decision, so the wording cannot // diverge from the key: `c conversation` labels the direct open exactly // when the key would take it, and `c conversations` the fallback. const conversation = conversationAction(frame().stage, selected, spec.conversation, spec.conversations) const candidate = [ '', ...rootFrame({ columns, context: paint('Work', 'overlay-title'), body: [ paint(truncateToWidth(counter, inner), 'muted'), ...activeNotice === undefined ? [] : [paint( truncateToWidth(noticeText(activeNotice.text), inner), activeNotice.failed ? 'error' : 'busy', )], '', ...built.slice(viewport.start, viewport.end).map(row => paintRow(row, frame().focus.current)), ], footer: fitFooterHelp( stageHelp(frame().stage, aimed, selected, conversation, currentArmedStop()?.id), footerBudget(columns), ), }), ] // The root frame wraps its content, including short-state text a caller may not // have pre-truncated. Count the same physical rows Screen will draw; a // too-tall candidate falls back rather than leaking a row into scrollback. if (physicalRows(candidate, columns).length > terminalRows) return fallback() fellBack = false return candidate }, handleKey(key: Key) { if (closed) return // While the compact fallback is on screen there is no visible cursor, so // no key may act on the aimed row. `esc` still does what that frame says // it does — and closing outright, rather than popping one hidden stage at // a time, is what makes the advertised `esc close` true. if (fellBack) { if (key.kind === 'key' && (key.name === 'escape' || key.name === 'ctrl-c')) close() return } // Printable letters remain text input in the renderer. The overlay owns // text entry, so recognize its one letter command here rather than adding // a presentation-specific key name to the renderer's generic decoder. if (key.kind === 'text' && key.text === 'k') { // The ACTION reads the projection WITHOUT retargeting the cursor: if the // aimed identity vanished, nothing may be interrupted — the next paint // re-anchors the cursor instead of acting on the successor. build(spec.snapshot(), LOGICAL_KEY_WIDTH, false) const item = subject() if (item !== undefined && item.source === 'subagent' && item.interruptible) { // A subagent interrupt stays ONE press. It is a signal to a live // continuable child whose turn it ends without touching its // conversation, not a destructive act, and the arming below exists for // the one that is. const result = spec.interruptSubagent(item) notice = { text: result.message, failed: result.kind === 'failed', expiresAt: Date.now() + NOTICE_MS } armedStop = undefined spec.invalidate() return } if (item !== undefined && item.source === 'job') handleJobStop(item) spec.invalidate() return } // The durable conversation drawer lives in its own presenter. Work only // hands the keyboard over: it keeps no child list, no transcript, and no // message buffer of its own. if (key.kind === 'text' && key.text === 'c') { // Read the projection WITHOUT retargeting the cursor, exactly as `k` // does: a keystroke is a human ACTION, so if the aimed identity vanished // the press must not transfer to whichever row inherited the cursor. // Reusing `k`'s freshness discipline keeps the two actions honest // together instead of inventing a second rule for this key. build(spec.snapshot(), LOGICAL_KEY_WIDTH, false) const action = conversationAction(frame().stage, subject(), spec.conversation, spec.conversations) if (action === undefined) return if (action.kind === 'direct') { spec.conversation?.(action.target) return } spec.conversations?.() return } if (key.kind !== 'key') return const retarget = key.name !== 'enter' readStage(retarget, LOGICAL_KEY_WIDTH) switch (key.name) { case 'up': frame().focus.move(-1) spec.invalidate() return case 'down': frame().focus.move(1) spec.invalidate() return case 'enter': { // A focused row does not have to be actionable. Enter on a plain fact // is a no-op rather than an invented action. const next = focusedRow()?.open if (next !== undefined) push(next) else spec.invalidate() return } case 'home': case 'ctrl-a': frame().focus.first() viewport.first() spec.invalidate() return case 'end': case 'ctrl-e': frame().focus.last() viewport.last() spec.invalidate() return case 'escape': case 'ctrl-c': pop() return default: return } }, } } /** * Text width used when a keystroke must resolve rows before the next paint. * * Key handling needs the row IDENTITIES, never their pixels, and the terminal's * real width belongs to `render`. A generous logical width keeps fitting from * dropping a fact that a narrower guess would have removed, which could * otherwise change what a key resolves to. */ const LOGICAL_KEY_WIDTH = 200 /** Index every item of the projection by its selection identity. */ function workIndex(snapshot: WorkSnapshot): Map { const index = new Map() for (const item of snapshot.workflows) index.set(workItemKey(item), item) for (const item of snapshot.subagents) index.set(workItemKey(item), item) for (const item of snapshot.jobs) index.set(workItemKey(item), item) return index } /** * Build the rows of one stage. * @param stage - the stage currently on screen. * @param snapshot - the projection this build was taken from. * @param index - that projection, indexed by selection identity. * @param width - the inner frame width. * @param tick - the shared spinner phase. * @param observation - the open Job output observation, for a Job detail only. * @returns the stage's rows. */ function stageRows( stage: Stage, snapshot: WorkSnapshot, index: ReadonlyMap, width: number, tick: number, observation?: JobOutputObservation, ): readonly StageRow[] { if (stage.kind === 'list') return overviewRows(snapshot, width, tick) const item = index.get(stage.subject) if (item === undefined) return [muted('No active work to inspect.', width)] if (item.source === 'workflow' && stage.kind === 'workflow') return workflowRows(item, width, tick) if (item.source === 'subagent' && stage.kind === 'subagent') { return subagentRows(item, snapshot.workflows, width, tick) } if (item.source === 'job' && stage.kind === 'job') return jobRows(item, observation, width) return [muted('No active work to inspect.', width)] } /** Render the grouped overview: one section per Harness authority. */ function overviewRows(snapshot: WorkSnapshot, width: number, tick: number): StageRow[] { // `available` reports the two capability SEAMS. A workflow run is proved by // this session's own durable records rather than by a mounted service, so an // owned run is still shown if it somehow outlives them. if (!snapshot.available && snapshot.workflows.length === 0) { return [muted('Jobs and subagents are not installed in this profile.', width)] } // A workflow presents its own members, so a child one of them already shows is // not repeated in the flat Subagents section. "Presents" follows the member and // its open child, not the run's reported state: a run that has reported a result // can still owe a member's ending. The join is Harness's own `childId`, never a // name or a timing coincidence, and the same rule decides the status line's // subagent count so the two can never disagree. const loose = looseSubagents(snapshot) if (snapshot.workflows.length === 0 && loose.length === 0 && snapshot.jobs.length === 0) { return [muted('No active workflows, jobs, or subagents.', width)] } const rows: StageRow[] = [] if (snapshot.workflows.length > 0) { rows.push(heading('Workflows')) for (const item of snapshot.workflows) rows.push(workflowOverviewRow(item, width, tick)) } if (loose.length > 0) { if (rows.length > 0) rows.push(blank()) rows.push(heading('Subagents')) for (const item of loose) rows.push(subagentOverviewRow(item, width, tick)) } if (snapshot.jobs.length > 0) { if (rows.length > 0) rows.push(blank()) rows.push(heading('Jobs')) for (const item of snapshot.jobs) rows.push(jobOverviewRow(item, width)) } return rows } /** How a settled workflow run or member reads as one word. */ function outcomeWord(mark: WorkMark): string | undefined { if (mark === 'completed') return 'completed' if (mark === 'failed') return 'failed' if (mark === 'cancelled') return 'cancelled' return undefined } /** The counts a workflow row may truthfully claim. */ function workflowCounts(item: WorkflowWorkItem): string { const started = item.agentsStarted ?? item.members.length if (item.state !== 'running') { return `${String(started)} ${started === 1 ? 'agent' : 'agents'}` } const active = item.members.filter(member => member.outcome === undefined).length // No denominator: `meta.phases` declares progress vocabulary, not how many // `agent()` calls a script will make, so there is no truthful total to divide by. return `${String(active)} active · ${String(started)} started` } /** One workflow row on the overview. */ function workflowOverviewRow(item: WorkflowWorkItem, width: number, tick: number): StageRow { const mark = workMark(item) const settled = outcomeWord(mark) const segments: RowSegment[] = [ { text: workflowCounts(item), separator: ' · ', rank: 2 }, { text: formatElapsed(Math.max(0, Date.now() - item.startedAt)), separator: ' ', rank: 3 }, ] const narration = settled ?? item.phase if (narration !== undefined && narration !== '') { segments.unshift({ text: escapeControls(narration), separator: ' · ', rank: 4 }) } return itemRow(item, mark, escapeControls(item.label), segments, width, tick, { kind: 'workflow', subject: workItemKey(item) }) } /** * Drop ranks for a child's yieldable facts, in the order they give way. * * The rule Work 3.0 turns around: a row exists to say what a worker is DOING, * so the semantic word survives longest and the backend — which used to lead * the row purely because it was once the only identity Harness exposed — is * the first thing a narrowing terminal loses. The route and the backend never * appear together, so their neighbouring ranks never race: a route exists only * while a live child Agent is observable, and the backend is offered only when * one is not. */ const CHILD_RANK = { /** The semantic activity word: the answer to the row's own question. */ word: 1, /** What the current operation is being done to. */ title: 2, /** Which LLM is actually powering the child. */ route: 3, /** Which subagent backend owns the lifecycle, when nothing better is known. */ backend: 4, /** How long it has worked. */ duration: 5, } as const /** * The facts a live child contributes to any row that presents it. * * Shared by the flat Subagents section and by a workflow member, because a * member joined to a live child is the same child: giving the two rows separate * builders is how one of them would quietly fall behind the other. * @param item - the joined subagent row. * @param name - the row's leading name, so the backend is not repeated as a fact. * @returns activity, route, and backend segments, in display order. */ function childSegments(item: SubagentWorkItem, name: string): RowSegment[] { const segments: RowSegment[] = [] if (item.activityWord !== undefined) { segments.push({ text: escapeControls(item.activityWord), separator: ' · ', rank: CHILD_RANK.word }) if (item.activityTitle !== undefined && item.activityTitle !== '') { segments.push({ text: escapeControls(item.activityTitle), separator: ' ', rank: CHILD_RANK.title }) } } if (item.route !== undefined) { segments.push({ text: escapeControls(routeLabel(item.route)), separator: ' · ', rank: CHILD_RANK.route }) } // The backend earns overview space only when the row has no observable // activity to show instead: for a provider-managed run it is the fact that // EXPLAINS the silence, and for a local child it is detail-stage material. if (item.activityWord === undefined && escapeControls(item.provider) !== name) { segments.push({ text: escapeControls(item.provider), separator: ' · ', rank: CHILD_RANK.backend }) } return segments } /** One subagent row on the overview. */ function subagentOverviewRow(item: SubagentWorkItem, width: number, tick: number): StageRow { const mark = workMark(item) // The durable label is the task this worker is responsible for, so it leads // and never yields. Only a child Harness gave no label at all falls back to // the backend name for its identity. const name = escapeControls(item.label === undefined || item.label === '' ? item.provider : item.label) const segments = childSegments(item, name) segments.push({ text: formatElapsed(subagentDuration(item, Date.now()).ms), separator: ' ', rank: CHILD_RANK.duration, }) return itemRow(item, mark, name, segments, width, tick, { kind: 'subagent', subject: workItemKey(item) }) } /** * Drop ranks for a Job row's yieldable facts, in the order they give way. * * A Job row exists to answer "what is this doing", and the producer's own * progress line is the only fact that answers it — so it outlives the clock and * the `stopping` word. The label is not ranked at all: it is the row's NAME, and * `fitSegments` never yields a name, so an over-narrow terminal degrades to * `bash` plus whatever still fits rather than to an unidentifiable fragment. * * Crucially, a progress fact is dropped WHOLE or kept whole. A truncated * `127/2` reads as a different, smaller claim than `127/203`, which is worse than * showing the clock alone. */ const JOB_RANK = { /** The producer's live progress line, verbatim. */ progress: 1, /** How long the Job has been open. */ elapsed: 2, /** That the Job is transitioning, which the mark alone would not say. */ stopping: 3, } as const /** One job row on the overview. */ function jobOverviewRow(item: JobWorkItem, width: number): StageRow { const mark = workMark(item) const segments: RowSegment[] = [] if (item.label !== '') segments.push({ text: escapeControls(item.label), separator: ' ', rank: 4 }) // Opaque producer text, escaped whole. Never split into a numerator and a // denominator: `127/203` means nothing to dshline, and a partial cut of it // would be a smaller truth wearing the same clothes. if (item.progress !== undefined && item.progress !== '') { segments.push({ text: escapeControls(item.progress), separator: ' · ', rank: JOB_RANK.progress }) } segments.push({ text: formatElapsed(Math.max(0, Date.now() - item.startedAt)), separator: ' ', rank: JOB_RANK.elapsed, }) if (item.state === 'stopping') segments.push({ text: 'stopping', separator: ' ', rank: JOB_RANK.stopping }) return itemRow(item, mark, escapeControls(item.kind), segments, width, 0, { kind: 'job', subject: workItemKey(item) }) } /** Assemble one overview row from its mark, name, and yieldable segments. */ function itemRow( item: WorkItem, mark: WorkMark, name: string, segments: readonly RowSegment[], width: number, tick: number, open: Stage, ): StageRow { return { kind: 'row', key: workItemKey(item), mark: glyph(mark, tick), markRole: MARK_ROLE[mark], text: fitSegments(name, segments, textBudget(width, true)), role: 'subdued', open, } } /** Render one workflow run: its facts, then its published members by phase. */ function workflowRows(item: WorkflowWorkItem, width: number, tick: number): StageRow[] { const mark = workMark(item) const rows: StageRow[] = [ heading(`Workflow · ${escapeControls(item.label)}`), blank(), ] if (item.description !== undefined && item.description !== '') { rows.push(fact('description', item.description, width)) } rows.push(fact('state', outcomeWord(mark) ?? 'running', width)) if (item.phase !== undefined) rows.push(fact('phase', item.phase, width)) if (item.log !== undefined) rows.push(fact('log', item.log, width)) rows.push(fact('elapsed', formatElapsed(Math.max(0, Date.now() - item.startedAt)), width)) rows.push(fact('agents', workflowCounts(item), width)) rows.push(fact('run id', item.id, width)) if (item.members.length === 0) { rows.push(blank()) rows.push(muted('No members published yet.', width)) return rows } for (const group of groupMembers(item.members)) { rows.push(blank()) // An unphased call has no heading at all, while a phase the script actually // titled gets one — including a title that is the empty string. Collapsing // the two would erase a distinction the record keeps. if (group.phase !== undefined) rows.push(heading(escapeControls(group.phase))) for (const member of group.members) rows.push(memberRow(item, member, width, tick)) } return rows } /** Members grouped by their exact recorded phase, in first-appearance order. */ function groupMembers( members: readonly WorkflowMemberItem[], ): { readonly phase?: string; readonly members: WorkflowMemberItem[] }[] { const groups: { phase?: string; members: WorkflowMemberItem[] }[] = [] for (const member of members) { const existing = groups.find(group => group.phase === member.phase) if (existing !== undefined) { existing.members.push(member) continue } groups.push(member.phase === undefined ? { members: [member] } : { phase: member.phase, members: [member] }) } return groups } /** One workflow member row; it opens the shared subagent stage when its child is live. */ function memberRow( workflow: WorkflowWorkItem, member: WorkflowMemberItem, width: number, tick: number, ): StageRow { const mark = memberMark(member) const child = member.subagent const name = escapeControls(member.label) // The ONE join Work makes carries the whole child presentation with it: a // member whose `childId` resolves to a live child says what that child is // doing and which LLM powers it, from the child's own state. A settled member // holds no child at all, so it cannot keep a stale activity claim. const segments = child === undefined ? [] : childSegments(child, name) return { kind: 'row', key: workflowMemberKey(workflow, member), mark: glyph(mark, tick), markRole: MARK_ROLE[mark], text: fitSegments(name, segments, textBudget(width, true)), role: 'subdued', // Only a member whose `childId` resolves to a live epoch can be opened. // A settled member is a record, not a place to navigate to. ...child === undefined ? {} : { open: { kind: 'subagent' as const, subject: workItemKey(child) } }, } } /** * Render one subagent, ordered by what a person asks first. * * What it is doing, what it is doing it to, which LLM is powering it, which * backend owns it, how much work it has done, where it came from, what can be * done to it — and only then the lower level identities, which stay because * they are the facts that make a report actionable, not because they lead. * * `backend` and `model` are two columns rather than one word, because they are * two authorities: a `spawn` child can run on any registered route at all, so * calling both of them "provider" was a presentation bug that made the more * interesting fact invisible. */ function subagentRows( item: SubagentWorkItem, workflows: readonly WorkflowWorkItem[], width: number, tick: number, ): StageRow[] { const mark = workMark(item) const identity = item.label === undefined || item.label === '' ? item.provider : item.label const rows: StageRow[] = [ heading(`Subagent · ${escapeControls(identity)}`), blank(), ] const headline = item.activityWord === undefined ? 'active' : item.activityTitle === undefined || item.activityTitle === '' ? item.activityWord : `${item.activityWord} · ${item.activityTitle}` rows.push({ kind: 'row', key: 'state', mark: glyph(mark, tick), markRole: MARK_ROLE[mark], text: truncateToWidth(escapeControls(headline), textBudget(width, true)), role: 'subdued', }) const live = item.outputTail === undefined ? undefined : outputTailRow(item.outputTail, width) if (live !== undefined) rows.push(live) rows.push(blank()) if (item.route !== undefined) { rows.push(fact('model', routeLabel(item.route), width)) // Only when the effective route genuinely carries one. An adapter that // resolves no reasoning effort has none, and a blank row claiming otherwise // would be an invention. if (item.route.reasoningEffort !== undefined) { rows.push(fact('reasoning', item.route.reasoningEffort, width)) } } rows.push(fact('backend', item.provider, width)) // No paragraph about what the seam does or does not carry: an opaque backend // simply says who manages the detail, in the same two columns as every other fact. if (item.activityWord === undefined) rows.push(fact('activity', 'provider-managed', width)) const duration = subagentDuration(item, Date.now()) // The label names which clock this is. Harness's projection measures the // child's own active turns; the fallback measures how long this lifecycle // epoch has been open, which is a different and weaker statement. rows.push(fact(duration.kind === 'active' ? 'active time' : 'elapsed', formatElapsed(duration.ms), width)) if (item.tokens !== undefined) rows.push(fact('tokens', formatTokens(item.tokens), width)) if (item.mode !== undefined) rows.push(fact('mode', item.mode, width)) const membership = findMembership(item.id, workflows) if (membership !== undefined) { rows.push(blank()) rows.push(fact('workflow', membership.workflow.label, width)) if (membership.member.phase !== undefined) rows.push(fact('phase', membership.member.phase, width)) rows.push(fact('member', membership.member.label, width)) } rows.push(blank()) if (item.interruptible) rows.push(fact('interrupt', 'available', width)) rows.push(fact('session', item.id, width)) if (item.agentStatus !== undefined) rows.push(fact('agent status', item.agentStatus, width)) if (item.residency !== undefined) { rows.push(fact('residency', item.residency === 'resident' ? 'live session' : 'stored session', width)) } if (item.hasChildren !== undefined) { // Harness's `hasChildren` is a durable lineage fact, not a claim that // sub-workers are active right now. rows.push(fact('child sessions', item.hasChildren ? 'yes' : 'no', width)) } // The lifecycle edge is scoped to this delegating session and discovery is // the direct-parent query, so the direct-child relationship is provable. rows.push(fact('lineage', 'direct child of this session', width)) rows.push(fact('run id', item.runId, width)) rows.push(fact('local agent', item.local ? 'yes' : 'no', width)) return rows } /** The owned workflow membership of one child session, when one is authoritative. */ function findMembership( childId: string, workflows: readonly WorkflowWorkItem[], ): { readonly workflow: WorkflowWorkItem; readonly member: WorkflowMemberItem } | undefined { for (const workflow of workflows) { for (const member of workflow.members) { if (member.childId === childId) return { workflow, member } } } return undefined } /** * Render one Job: what it is doing, what it has said, then the identity a * report needs. * * Information first. The retained output is the reason to open this stage at * all, so it gets its own section between the status facts and the low-level * identities, and the `owner`/`job id` pair stays at the bottom where a report * fact belongs. A Job with no `progress` gets no progress row, and a Job with * no output gets one restrained line saying so — an empty section would read as * a rendering fault rather than as a producer that has not spoken. * @param item - the inspected Job row. * @param observation - the open output observation, when one exists. * @param width - the inner frame width. * @returns the stage's rows. */ function jobRows(item: JobWorkItem, observation: JobOutputObservation | undefined, width: number): StageRow[] { const rows: StageRow[] = [ heading(`Job · ${escapeControls(item.label === '' ? item.kind : item.label)}`), blank(), fact('status', item.state, width), fact('kind', item.kind, width), ] // The producer's progress line as published. Distinct from `detail`, and never // a substitute for it: one is a moving statement about work in flight, the // other is the standing reason the Job exists. No progress means no row. if (item.progress !== undefined) rows.push(fact('progress', item.progress, width)) if (item.detail !== undefined) rows.push(fact('detail', item.detail, width)) rows.push(fact('elapsed', formatElapsed(Math.max(0, Date.now() - item.startedAt)), width)) rows.push(fact('owner', item.ownership === 'this-session' ? 'this session' : 'unowned', width)) rows.push(...jobOutputRows(observation, width)) rows.push(blank()) // No `stop unavailable` row for a stopping Job: announcing the absence of an // action is noise, and a control appears in this view only when it exists. rows.push(fact('job id', item.id, width)) return rows } /** * The Output section of a Job detail, or nothing when there is no observation. * * A Job's ring is an OBSERVATION STREAM, not an interactive terminal contract, * so this is bounded Work rows inside the temporary live region: no alternate * screen, no cursor emulation, no ANSI interpretation, and nothing that could * reach native scrollback. Every producer byte is made safe before any styling * is applied, in that order. * @param observation - the open output observation, when one exists. * @param width - the inner frame width. * @returns the section's rows, which is empty when nothing was ever observed. */ function jobOutputRows(observation: JobOutputObservation | undefined, width: number): StageRow[] { if (observation === undefined) return [] const lines = observation.reading().lines const rows: StageRow[] = [blank(), heading('Output')] if (lines.length === 0) { rows.push(muted('No output yet.', width)) return rows } lines.forEach((line, position) => { rows.push(jobOutputLineRow(line, position, width)) }) return rows } /** * One line of a Job's output, as one bounded Work row. * * The order is load-bearing and is the same order the assistant tail uses: * escape the producer's text FIRST, then cut to the display budget, then let the * painter choose a role. Styling first and escaping after would strip the colour * back out, and cutting before escaping would measure a control sequence as if * it were visible. * * A line is focusable but not actionable, which is the one deliberate exception * to keeping presentation rows out of the cursor. A bounded live region shows * only `visible` rows, so without a focus identity there is no way to scroll a * multi-kilobyte tail at all, and `end` would land on the OLDEST output line * rather than the newest. It carries no `open` stage, so `↵` on it does nothing * rather than inventing a destination. * @param line - one retained output line. * @param position - its index in the retained tail, which is its focus identity. * @param width - the inner frame width. * @returns the rendered row. */ function jobOutputLineRow(line: JobOutputLine, position: number, width: number): StageRow { // A loss marker is this frontend's own report, not a producer stream, so it // takes no channel role. It says that earlier output is missing WITHOUT // claiming to know which layer dropped it: the ring's retention, a producer // gap, and dshline's own presentation cap are three different failures that a // reader cannot act on differently. if (line.gapBefore === true) { return { kind: 'line', text: truncateToWidth(GAP_MARKER, textBudget(width, false)), role: 'muted' } } const escaped = escapeControls(line.text) return { kind: 'row', key: `${JOB_OUTPUT_KEY_PREFIX}${String(position)}`, text: truncateToWidth(escaped, textBudget(width, false)), role: jobOutputRole(line.channel), } } /** * The role one output channel is painted with. * * Restrained by design: a colour difference is enough to tell a failure line from * ordinary output, and prefixing every line with `stderr:` would spend the * reader's width restating what the colour already says. An unrecognized * channel is neutral, exactly as the seam's contract requires. * @param channel - the chunk's producer stream label, when it had one. * @returns the palette role for that line. */ function jobOutputRole(channel: JobOutputLine['channel']): Role { if (channel === 'stderr') return 'error' if (channel === 'log') return 'muted' // `stdout` and an absent or unrecognized label both read as ordinary output. return 'subdued' } /** * Columns a row's text may use, after its gutter and, for a row that has one, * its mark box. * * The mark box is subtracted rather than assumed, because a row is painted as * two gutter columns, a mark of {@link SPINNER_MARK_COLUMNS} and a space — and * a budget that ignored it let a mark row be fitted two columns wider than the * frame it is drawn in. Deriving the number from the mark the row actually * carries is what keeps the frame honest; it is not a compensating constant. * @param width - the inner frame width. * @param marked - whether the row spends a mark box before its text. * @returns the columns the row's text may occupy. */ function textBudget(width: number, marked: boolean): number { return Math.max(1, width - GUTTER_COLUMNS - (marked ? SPINNER_MARK_COLUMNS + 1 : 0)) } /** * The mark one row draws, always the width of the orbit's box. * * Observed execution turns the original six-shape arc through a two-column slot; * everything else settles to its own glyph padded to the same width, so the row * body never moves a column because a worker started or finished. * @param mark - the row's authoritative mark. * @param tick - the overlay's heartbeat. * @returns exactly {@link SPINNER_MARK_COLUMNS} columns. */ function glyph(mark: WorkMark, tick: number): string { return mark === 'executing' ? spinnerFrameOrbit(tick) : spinnerMark(MARK_GLYPH[mark]) } /** A focusable two-column fact row. */ function fact(key: string, value: string, width: number): StageRow { return { kind: 'row', key: `fact:${key}`, text: truncateToWidth(`${key} ${escapeControls(value)}`, textBudget(width, false)), role: 'subdued', } } /** * Render the live assistant-text tail as ONE bounded Work row. * * The stream is model text, so it may carry CR/LF, controls, and wide glyphs, * and a Work fact is exactly one physical row. The order below is load-bearing: * collapse line structure first (a preserved newline would wrap the frame into * rows the live region never budgeted), then neutralize controls, then cut from * the FRONT to the display budget so the newest text survives, and style last. * Cutting by code unit would slice a wide glyph in half. * @param text - the newest streamed assistant text. * @param width - the inner frame width available to the row. * @returns the row, or undefined when nothing displayable survives. */ function outputTailRow(text: string, width: number): StageRow | undefined { const prefix = `${OUTPUT_KEY} ` const budget = textBudget(width, false) - displayWidth(prefix) if (budget < 1) return undefined const normalized = text.replace(/[\r\n]+/gu, ' ') const escaped = escapeControls(normalized) // Whole-control text is deliberately NOT suppressed: `escapeControls` turns // an ESC into the visible `^[`, so it stays and is shown. What has no visible // content is LAYOUT alone — spaces, CR/LF collapsed to spaces, and tabs // expanded to spaces — and an `output` row of blanks would advertise an // answer that is not there. if (escaped.trim() === '') return undefined const content = tailToWidth(escaped, budget) if (content === '') return undefined return { kind: 'row', key: `fact:${OUTPUT_KEY}`, text: `${prefix}${content}`, role: 'assistant' } } /** A non-focusable section heading. */ function heading(text: string): StageRow { return { kind: 'line', text, role: 'section-heading' } } /** A non-focusable spacer. */ function blank(): StageRow { return { kind: 'blank', text: '', role: 'muted' } } /** A non-focusable explanatory line, for a stage with nothing to inspect. */ function muted(text: string, width: number): StageRow { return { kind: 'line', text: truncateToWidth(text, Math.max(1, width)), role: 'muted' } } /** * Paint one row. * * The mark keeps its own role so an outcome reads at a glance without turning * the whole line into a colour. One `paint` per span on one row: colouring a * multi-row string in one call is what leaks style into the next row. * * Focus owns the focused row whole, mark and text alike, in a single inverted * span. That costs a turning mark its own colour on the row the cursor is on, * which is the same trade the mark's role has always made and the reason * `selection` and the mark roles are separate. * @param row - the row to paint. * @param focus - the identity the cursor is on, if any. * @returns one physical row, or the empty string for a blank. */ function paintRow(row: StageRow, focus: string | undefined): string { if (row.kind === 'blank') return '' if (row.kind === 'line') return paint(row.text, row.role) const focused = row.key !== undefined && row.key === focus const body = row.mark === undefined ? row.text : `${row.mark} ${row.text}` if (focused) return paint(`❯ ${body}`, 'selection') const painted = row.mark === undefined ? paint(row.text, row.role) : `${paint(row.mark, row.markRole ?? row.role)} ${paint(row.text, row.role)}` return ` ${painted}` } /** * Fit a row by dropping whole facts, never by cutting one in half. * * `reading overla…` states less than the word alone, so the highest-ranked * segment yields first and the name never yields at all. * * @param name - the row's leading name, already escaped. * @param segments - the yieldable facts, in display order. * @param width - display columns available for name and segments. * @returns the fitted row text. */ function fitSegments(name: string, segments: readonly RowSegment[], width: number): string { const surviving = [...segments] const render = (): string => name + surviving.map(part => `${part.separator}${part.text}`).join('') while (surviving.length > 0 && displayWidth(render()) > width) { let worst = 0 for (let index = 1; index < surviving.length; index += 1) { const candidate = surviving[index] const incumbent = surviving[worst] if (candidate !== undefined && incumbent !== undefined && candidate.rank > incumbent.rank) worst = index } surviving.splice(worst, 1) } return truncateToWidth(render(), width) } /** * What `c` will do for the current selection, or undefined when no capability is mounted. * * The footer and the key both read this one result, so the wording cannot * promise an action the key would refuse or hide one it would take. Preferring * the direct open when Work holds the descriptor keeps the catalog as the * fallback rather than making two capabilities compete for the same key. */ type ConversationAction = | { readonly kind: 'direct'; readonly target: WorkConversationTarget } | { readonly kind: 'catalog' } /** * Decide what `c` does for one stage and selection, from the mounted capabilities alone. * * The direct open belongs to the SUBAGENT DETAIL STAGE only. There, the selected * child is the subject of the whole view, so Work is addressing exactly the child * the reader is looking at. On the overview the same item is a list ENTRY — the * reader has not asked to inspect it yet — and `c` keeps its established meaning * of opening the catalog, so the singular action is never offered there. The * stage gate also makes a vanished detail subject fall back truthfully: the * rebuild pops the dead stage, and the action becomes the catalog rather than a * direct open aimed at whichever row inherited the cursor. * @param stage - the stage currently on screen. * @param item - the selected Work item, or undefined when nothing is selected. * @param direct - the direct-open callback, present exactly with the subagent seam. * @param catalog - the catalog callback, present exactly with the subagent seam. * @returns the action, or undefined when neither capability is available. */ function conversationAction( stage: Stage, item: WorkItem | undefined, direct: ((target: WorkConversationTarget) => void) | undefined, catalog: (() => void) | undefined, ): ConversationAction | undefined { if (stage.kind === 'subagent' && direct !== undefined) { const target = directConversationTarget(item) if (target !== undefined) return { kind: 'direct', target } } return catalog === undefined ? undefined : { kind: 'catalog' } } /** * The help truthful for this stage, the focused row, and the current authority. * * The Job stop segment is the one place the footer reports a PENDING action, so * it says which state the key is actually in: `k stop` before the first press, * `k confirm stop` while that exact Job is armed. A `stopping` Job gets no * segment at all, because the press would do nothing and advertising it would be * a promise the code does not keep. * @param stage - the stage currently on screen. * @param focused - the row the cursor is on. * @param item - the stage's subject, or the overview's focused row. * @param conversation - what `c` would do, decided once and shared with the key. * @param armedId - the Job id an unexpired stop arming names, when one exists. * @returns the footer help line. */ function stageHelp( stage: Stage, focused: StageRow | undefined, item: WorkItem | undefined, conversation: ConversationAction | undefined, armedId: string | undefined, ): string { const interrupt = item?.source === 'subagent' && item.interruptible ? ' · k interrupt' : '' const stop = stopHelp(stage, item, armedId) const enter = focused?.open === undefined ? '' : ' · ↵ inspect' const conversationSegment = conversation === undefined ? '' : conversation.kind === 'direct' ? ' · c conversation' : ' · c conversations' const exit = stage.kind === 'list' ? ' · esc close' : ' · esc back' return `↑↓ select${enter}${interrupt}${stop}${conversationSegment}${exit}` } /** * The `k stop` / `k confirm stop` segment, or nothing at all. * * Stop is offered from a Job's DETAIL stage only, so a destructive operation * always sits behind an inspect step. A `stopping` Job is excluded because * there is no second stop to request. * @param stage - the stage currently on screen. * @param item - the stage's subject, or the overview's focused row. * @param armedId - the Job id an unexpired arming names, when one exists. * @returns the footer segment, or an empty string. */ function stopHelp(stage: Stage, item: WorkItem | undefined, armedId: string | undefined): string { // The stage check is what keeps a destructive operation behind an inspect // step: on the overview `item` is merely the focused row, and browsing a list // should never be one keystroke away from cancelling work. if (stage.kind !== 'job') return '' if (item?.source !== 'job' || item.state !== 'running') return '' return armedId === item.id ? ' · k confirm stop' : ' · k stop' } /** Count the physical terminal rows the Screen will use for candidate lines. */ function physicalRows(lines: readonly string[], columns: number): string[] { return lines.flatMap(line => wrapToWidth(line, Math.max(1, columns))) } /** A closable answer for terminals that cannot safely hold a frame. */ function compactFallback( snapshot: WorkSnapshot, columns: number, rows: number, notice?: Notice, ): string[] { if (rows <= 0) return [] // A failed human action must survive the same geometry fallback that protects // scrollback. It takes precedence over the ordinary compact summary; clipping // its detail is preferable to making authorization or cancellation invisible. // `noticeRow` owns the zero-column boundary, so a terminal with no columns // gets no row rather than one invented for it. if (notice !== undefined && notice.failed) { const failed = noticeRow(notice, columns) if (failed !== undefined) return [failed] } const workflows = snapshot.workflows.length // The same presentation corpus the framed overview draws, not the raw // authority array: a member a workflow presents is already counted as that // workflow, and counting the full `snapshot.subagents` here would report one // Harness child as two pieces of work in a frame too small to show either row. const subagents = looseSubagents(snapshot).length const jobs = snapshot.jobs.length const counts = [ ...workflows === 0 ? [] : [`${String(workflows)} ${workflows === 1 ? 'workflow' : 'workflows'}`], `${String(subagents)} ${subagents === 1 ? 'subagent' : 'subagents'}`, `${String(jobs)} ${jobs === 1 ? 'job' : 'jobs'}`, ].join(' · ') // `available` reports the two capability SEAMS; a workflow run is proved by // this session's own durable records instead. Seam absence may not deny an // owned workflow this compact frame is too small to list, so this mirrors the // framed guard and names the missing seams only when no workflow exists. const phrase = !snapshot.available && workflows === 0 ? 'Jobs/subagents unavailable' : jobs === 0 && subagents === 0 && workflows === 0 ? 'No active work' : counts // `compactRows` is the shared whole-phrase ladder: it appends ` · esc close`, // falls back to the bare way out, and returns nothing when not even `esc` // fits. The copy this replaced truncated the summary to the terminal's width, // so an eight-column terminal read `esc clos` and a five-column one `esc c` — // a rendering fault, not a shorter help line. return compactRows(phrase, columns) }