SLOPSHOPPER

claudish

MCP runtime for external AI models. Proxies OpenRouter, Ollama and LM Studio, runs blind team voting, manages async sessions, and shows the session's runs live…

panebandguardtoaststatustimer
★ 13v2.12.0MITupdated 2026-10-23MadAppGang/magus/plugins/claudish
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · claudish
│ ┃ claudish-show ✕ › fix the failing auth test and add an audit log call │ ┃ Hide │ ┃ ───────────────────────────────────────────… ⏺ Read(src/auth.ts) │ ┃ No run to show. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · claudish-show
Hide ──────────────────────────────────────────────────────── No run to show.
README

Claudish Plugin

Provides the Claudish MCP runtime for the Magus marketplace. Claudish is an external-model proxy that exposes tools (team, create_session, list_models, etc.) for orchestrating multi-model workflows from Claude Code.

This plugin is a runtime dependency. Other plugins (code-search, dev, multimodel, designer) declare it via the dependencies field in their plugin.json and consume its tools through standard MCP.

Why this plugin exists

Before this plugin, multiple Magus plugins each declared an identical Claudish MCP server entry in their own .mcp.json. Claude Code's plugin loader deduplicates by endpoint (command + args), so only the first plugin's registration survived; others were silently suppressed. This worked by accident as long as all declarations remained byte-identical.

Extracting the runtime into a dedicated plugin makes the dependency explicit, follows Anthropic's documented dependencies-field pattern (Claude Code v2.1.110+), and removes the silent-suppression footgun.

See: Anthropic plugin dependencies docs

Requirements

  • The claudish CLI tool must be on $PATH. Install via npm: ``bash npm install -g claudish ``
  • Provider credentials, which claudish resolves itself: from the environment, its own config, the macOS Keychain, or 1Password. claudish --help lists the credential commands.

The plugin's .mcp.json declares no env entries, on purpose. The server inherits Claude Code's environment, so an exported key reaches it without one. A "OPENROUTER_API_KEY": "${OPENROUTER_API_KEY}" entry made Claude Code refuse to start the server for every user who keeps keys outside the environment.

What it provides

Tools exposed via the claudish MCP server:

  • Low-level: run_prompt, list_models, search_models
  • Agentic: team, preflight, report_error
  • Session: create_session, send_input, get_output, get_diagnostics, capture_session, cancel_session, list_sessions
  • Debug: compare_models, for claudish's own developers

Tool gating via CLAUDISH_MCP_TOOLS env var: all (default), low-level, agentic, session, debug. The plugin sets none, so every tool is exposed.

run_prompt is one completion straight to one model's API: no tools, no session, so it is never subagent work. Work goes through create_session, a panel through team.

Skills

SkillCovers
claudish:claudish-usageWhich MCP tool fits which task, model alias resolution against the live catalog, identity versus routing address, and the preferences-file trust rules

Read it before any claudish work. It is the single place the resolution procedure lives — every consumer plugin points here rather than restating it, because a second copy of claudish's routing rules guarantees two versions of the truth and no way to tell which one is stale.

Models are run through the MCP tools, never the CLI. The skill teaches team, create_session and run_prompt; the binary's only remaining role is as the runtime the MCP server launches, plus three read-only diagnostics (--help, --version, --models) for investigating that runtime. No workflow shells out.

The skill lives here rather than in multimodel because it documents the claudish runtime: a consumer that depends on claudish alone must find the resolution procedure installed beside it, without also installing multimodel.

Monitoring sessions

claudish pushes nothing into the conversation; list_sessions is the live view. Each row carries state, activity, idle_seconds, and on a failed or timed-out row reason_detail, the provider's error message in at most 160 characters. A live row also carries recent, the current turn's last 20 steps ({at, kind, tool, summary}), so a poll shows what happened since the last one. Polling about every 10 seconds is enough.

Live run status

Measured on Claude Code 2.1.286, 2.1.292 and 2.1.296 (see Older Claude Code below). While a team(mode="run") run or a create_session session that this Claude Code session started is going, a band above the prompt shows it, one line per model:

◆ claudish  review · 2 running · 1 done · 1 earlier run
  01  RUN  1m12s  gpt-6.1-sol  OpenRouter   ↑12.7k ↓780   ƒ 4  ↻ 1  $0.42  ▰▱▱▱▱     Read   [ Stop ] [ Show ]
  02  RUN    58s  glm-5.3      Z.ai          ↑9.1k ↓2.2k  ƒ 6  ↻ 2  $0.08  ▰▰▰▱▱ 1m  Bash   [ Stop ] [ Hide ]
  03  END  2m40s  haiku        Anthropic    ↑31.0k ↓4.1k  ƒ 9  ↻ 1    SUB                   [ Show ]

The band shows the run started most recently, plus any older run that is still going. Older finished runs are counted in the header (1 earlier run), not listed.

Each line starts with the status: a three-letter code on a coloured badge, then how long the slot has run, in the same colour.

  • RUN and NEW are blue, and END is green.
  • ASK (the slot needs you: input or a permission) is amber.
  • ERR, TMO, NIL and LST (it failed) are red, and STP (stopped) is grey.
  • FMT means the model answered but missed the format the run required (shape_mismatch). Its answer is still on disk, so it is gold, not red.

Then come:

  • the model, as a coloured badge with its provider (the model is the one column that never drops);
  • the tokens badge, sent (↑) and received (↓);
  • tool calls (ƒ) and loops (↻);
  • what the slot cost, or SUB when it runs on a subscription (claudish reports no charge, or it is a native Claude model); — when claudish reports nothing;
  • the stale-meter;
  • what the model is doing now.

The colours are madbench's. They follow your Claude Code theme, and an auto theme follows TERM_THEME or COLORFGBG.

The Stop and Show buttons sit at the right edge of the line. The stale-meter fills one cell at 10, 30, 60, 90 and 120 seconds without activity: green, then amber from one minute, red from two. From 30 seconds it also prints the time. On a narrow terminal the least important columns drop first; a line never wraps.

  • Stop cancels that one slot and nothing else. Press it twice: the first press turns the button into [ Stop? ], and a second press within four seconds sends the cancel. Cancelling is not a read, so Claude Code then asks its own permission question before anything stops.
  • Show opens a tab for that slot, titled by its model: the model's live screen, read-only, in the model's own colours, with its prompt on the tab's bottom edge.
  • The tabs sit in a panel beside the conversation when Claude Code runs fullscreen at 110 columns or wider, and above the prompt otherwise. If Claude Code cannot draw a tab, a toast says why.
  • Tabs belong to the runs the band shows: once a newer run replaces an older one, the older run's tabs close.
  • Hide puts the panel away and keeps its tabs. While a tab is open, its line reads [ Hide ]; the next Show on any line brings the panel back with every tab it had. Escape closes the tab you are in.
  • Wake-up. When a model in a run this session started finishes, fails or is stopped — or a create_session session starts waiting for input or a permission — an idle session wakes on its own: Claude gets a short notice naming the slot and how to fetch its result, and you see a toast. Runs another session started never wake this one.

One turn per change. A run that settles, or a create_session session that starts waiting, is named in exactly one prompt, as soon as the band sees it. A slot of a team run that ends while other slots still run gets its own notice; the next arrives as the next slot ends. While Claude is in the middle of a turn, notices wait for that turn to end and then go together in one prompt.

What it does not show. A team(mode="run-and-judge") call answers only once the run and its judging have finished, so the band first sees it settled and does not show it, and it cannot be stopped from the band. Runs started before the plugin loaded, or by anything other than this session's own claudish tool calls, are not shown either.

Read-only calls do not prompt. The plugin allows claudish's read-only calls — listing runs, a run's status, a slot's screen, listing sessions, and a session's screen — before Claude Code's permission check, so they never ask you and never wait behind another open question, such as Stop's own. It does so for claudish installed through this plugin and for a claudish server you registered yourself, and it matches each tool by its exact name. This applies to Claude's own calls of those tools too. Starting a run, cancelling one, and every other claudish call still ask as usual.

Your own permission rules still win: Claude Code applies a matching deny rule (the call is blocked) and a matching ask rule (you are asked) whatever the plugin answers. To be asked again for these calls, add an ask rule for them; the band's refresh then asks too.

What it needs. The band comes from the claudish CLI's status answers, which exist from claudish 10.4.0 (mod contract version 1). With an older claudish the band never appears and nothing else changes; run claudish update (or reinstall it) to get it.

Where it stays off. The band is a Claude Code mod, so it is inert wherever Claude Code refuses mods: --bare, safe mode, disableAllHooks, and a folder you have not trusted. claudish's tools keep working in all of these.

Older Claude Code. The band needs Claude Code 2.1.286 or later. On 2.1.250 and 2.1.284 Claude Code shows a one-line notice at startup (claudish: hooks module did not load: … is not an event) and runs without the band; on 2.1.223 nothing is shown. claudish's MCP tools, the read-only allow and the dependency check work on every one of these versions. Update Claude Code to get the band.

On Claude Desktop, the band and the tabs work in the Code tab, but a wake-up's turn stays invisible until you type something (anthropics/claude-code#96336). The toast is the visible signal there.

Used by

This is a runtime dependency of:

  • code-search — semantic code search via mnemex; uses Claudish for multi-model team review
  • dev — universal development assistant; uses Claudish for /dev:research, /team, model orchestration
  • multimodel — /team and /delegate slash commands
  • designer — UI review with multi-model validation

If you are installing Magus, this plugin is auto-installed when any of the above is enabled.

Source 14 files
hooks/status/register.tsx 208 lines
1// The composition root of the claudish status mod: every atom and every engine-interface
2// call the mod makes is spelled here, because the engine's static scan follows the
3// interface into no imported function and reads a state reference only where its plugin
4// and key are literals of the file using it. Nothing here decides anything beyond wiring:
5// poll, wake and the adapter take values and the closures bound below.
6
7import { atom, memberOf, read, update } from 'claude-code'
8import type { EngineInterface, Register } from 'claude-code'
9
10import { CLAUDISH_TOOL, makeClaudishSource } from './claudish-source'
11import { capped, claimVia, rejected, toAccepted, type Host, type PressUi, type Store } from './host'
12import { CLIENT_SURFACES, SHOW_PANE_ID } from './domain'
13import { activeTab, bandModel, childSize, paneAgentRows, paneFit, paneModel, showTabs, wrapTabs } from './layout'
14import * as poll from './poll'
15import * as wake from './wake'
16import * as controls from './controls'
17import { bandTree, type TimelineLook } from './band'
18import { DARK_PALETTE, paletteFor, type Palette } from './palette'
19import { panelTree } from './pane'
20
21// The eight atoms. plugin and key are literals HERE: the scan reads no reference from another file.
22const RUNS = atom({ plugin: 'claudish', key: 'runs' } as const, { epoch: 0, starts: {}, list: [] })
23const FEEDS = atom({ plugin: 'claudish', key: 'feeds' } as const, {})
24const STOP_REQUESTS = atom({ plugin: 'claudish', key: 'stopRequests' } as const, {})
25const PANES = atom({ plugin: 'claudish', key: 'panes' } as const, null) // a family: members by memberOf
26const LEDGER = atom({ plugin: 'claudish', key: 'wakeLedger' } as const, { epoch: 0, entries: {} })
27const TURN = atom({ plugin: 'claudish', key: 'turn' } as const, { isRunning: false, since: 0 })
28const EARLIER = atom({ plugin: 'claudish', key: 'earlier' } as const, { runs: 0, done: 0, failed: 0, stopped: 0 })
29const SHOW_TAB = atom({ plugin: 'claudish', key: 'showTab' } as const, { active: null })
30
31// One closure set per atom, spelled per atom: a generic helper taking the atom as a parameter is refused.
32function bindStore($: EngineInterface): Store {
33  return {
34    runs: {
35      read: () => read($, RUNS),
36      update: fn => update($, RUNS, capped(fn)),
37      claim: fn => claimVia(f => update($, RUNS, capped(f)), fn),
38    },
39    feeds: {
40      read: () => read($, FEEDS),
41      update: fn => update($, FEEDS, capped(fn)),
42      claim: fn => claimVia(f => update($, FEEDS, capped(f)), fn),
43    },
44    stopRequests: {
45      read: () => read($, STOP_REQUESTS),
46      update: fn => update($, STOP_REQUESTS, capped(fn)),
47      claim: fn => claimVia(f => update($, STOP_REQUESTS, capped(f)), fn),
48    },
49    ledger: {
50      read: () => read($, LEDGER),
51      update: fn => update($, LEDGER, capped(fn)),
52      claim: fn => claimVia(f => update($, LEDGER, capped(f)), fn),
53    },
54    turn: {
55      read: () => read($, TURN),
56      update: fn => update($, TURN, capped(fn)),
57      claim: fn => claimVia(f => update($, TURN, capped(f)), fn),
58    },
59    earlier: {
60      read: () => read($, EARLIER),
61      update: fn => update($, EARLIER, capped(fn)),
62      claim: fn => claimVia(f => update($, EARLIER, capped(f)), fn),
63    },
64    showTab: {
65      read: () => read($, SHOW_TAB),
66      update: fn => update($, SHOW_TAB, capped(fn)),
67      claim: fn => claimVia(f => update($, SHOW_TAB, capped(f)), fn),
68    },
69    panes: {
70      // the family member by computed id: only `id` is computed
71      read: id => read($, memberOf(PANES, { requestId: id })),
72      update: (id, fn) => update($, memberOf(PANES, { requestId: id }), capped(fn)),
73      claim: (id, fn) => claimVia(f => update($, memberOf(PANES, { requestId: id }), capped(f)), fn),
74    },
75  }
76}
77
78// The interface itself may not be kept, so each effect is one closure spelling it out.
79function bindHost($: EngineInterface): Host {
80  return {
81    store: bindStore($),
82    source: makeClaudishSource((server, tool, args) => $.mcp.call(server, tool, args)), // the mod's one MCP closure
83    now: () => $.clock.now(),
84    after: (ms, fn) => $.clock.after(ms, fn),
85    toast: (text, timeoutMs) => $.ui.toast(text, timeoutMs === undefined ? undefined : { timeoutMs }),
86    status: text => $.ui.status(text),
87    submit: text => $.prompt.submit({ text }).then(toAccepted, rejected),
88    debug: text => $.ui.log(text, { to: 'debug' }),
89    panes: () => $.ui.panes(),
90    close: id => $.ui.close({ id }),
91    messages: () => $.session.messages(),
92  }
93}
94
95// A press's pane calls, spelled on the render dispatch that drew the button: the person's press is
96// then behind the open, so Claude Code places the pane at any width (host.ts, PressUi).
97function bindPressUi($: EngineInterface): PressUi {
98  return {
99    panes: () => $.ui.panes(),
100    open: (id, title, size) => $.ui.open({ id, title, columns: size.columns, rows: size.rows, closeOnEscape: true }),
101    close: id => $.ui.close({ id }),
102  }
103}
104
105/** The badges' palette for the person's theme; null where the surface has no settings menu (keep what is drawn). */
106async function readTheme($: EngineInterface): Promise<Palette | null> {
107  try {
108    const theme = (await $.config.list()).find(row => row.key === 'theme')?.value
109    return paletteFor(theme, await $.env.get('TERM_THEME'), await $.env.get('COLORFGBG'))
110  } catch {
111    return null
112  }
113}
114
115export const register: Register = (on, options) => {
116  // The live cell's look, the plugin's `timeline` option: a change in /config reloads this module with it.
117  const look: TimelineLook = options?.timeline === 'line' ? 'line' : 'badges'
118  let host: Host | null = null // closures over the session.start dispatch, rebuilt on every load
119  // The badges' palette, by the person's theme: read at session start and at every turn end, so a
120  // theme picked mid-session shows by the next turn. (A config.set hook would be immediate, but an
121  // engine that does not know an event refuses the whole module.)
122  let palette: Palette = DARK_PALETTE
123
124  on('session.start', async ($, e, next) => {
125    host = bindHost($)
126    palette = (await readTheme($)) ?? palette
127    const bound = host
128    await wake.resetVolatile(bound) // stop requests and the turn flag: what a reload strands
129    void wake.recover(bound).then(() => wake.flushDetached(bound), () => wake.flushDetached(bound)) // inflight → delivered | pending, then deliver what is due
130    poll.ensureLoop(bound) // restarts only if state holds something to watch
131    return next(e)
132  })
133
134  on('session.end', ($, e, next) => (host ? poll.onSessionEnd(host, e, next) : next(e)))
135
136  // The main loop's turns: notices are held while one runs and delivered at its end. Never a
137  // guard: should the hook fail, the turn still runs.
138  on('turn.start', ($, e, next) => (host ? wake.onTurnStart(host, e, next) : next(e)))
139    .catch(($, e, next) => next(e))
140  on('turn.complete', async ($, e, next) => {
141    palette = (await readTheme($)) ?? palette
142    return host ? wake.onTurnComplete(host, e, next) : next(e)
143  })
144    .catch(($, e, next) => next(e))
145
146  // An observer, not a guard: should it fail, the model's call still runs (or keeps the answer it got).
147  on('tool.call', { tool: CLAUDISH_TOOL }, ($, e, next) => (host ? poll.onClaudishCall(host, e, next) : next(e)))
148    .catch(($, e, next) => next(e))
149
150  // The band. Reads use this dispatch's interface, so they subscribe it; presses act through
151  // a Store bound to this same dispatch (the reference's own onPress form).
152  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
153    const bound = host
154    if (!bound || e.props.hasSurvey) return next(e)
155    const runs = await read($, RUNS)
156    const feeds = await read($, FEEDS)
157    // The Show panel: open (a pane Claude Code lists as drawn), and the tab it shows. Both read
158    // here, so a Hide, a close or a tab press redraws the band.
159    const open = (await $.ui.panes()).some(p => p.id === SHOW_PANE_ID && p.isPlaced)
160    const active = activeTab(showTabs(runs, feeds), (await read($, SHOW_TAB)).active)
161    const model = bandModel({
162      runs,
163      feeds,
164      stops: await read($, STOP_REQUESTS),
165      ledger: await read($, LEDGER),
166      earlier: await read($, EARLIER),
167      bodyColumns: e.props.bodyColumns,
168      maxRows: e.props.maxRows,
169      now: await $.clock.now(),
170      panel: { open, active: active?.id ?? null },
171    })
172    if (model === null) return next(e) // nothing to draw
173    const press = bindStore($)
174    const ui = bindPressUi($)
175    // Where the surface draws no Client, the band is handed none, so the row falls back to the stale-meter.
176    const resolved = $.ui.resolve(e)
177    const els = CLIENT_SURFACES.includes(e.surface) ? resolved : { ...resolved, Client: undefined }
178    return bandTree(els, model, {
179      stop: target => void controls.pressStop(press, bound, target),
180      show: target => void controls.pressShow(press, ui, bound, target).then(id => poll.captureOpened(bound, id), () => poll.ensureLoop(bound)),
181      hide: () => void controls.pressHide(ui).catch(err => bound.debug(`claudish Hide failed: ${err instanceof Error ? err.message : String(err)}`)),
182    }, palette, look)
183  })
184
185  // The Show panel: a tab per slot of the runs the band shows, and the active tab's screen (its
186  // member, read, so a frame redraws the panel). A tab press makes that tab active; Hide puts it away.
187  on('ui.render', { component: 'Pane', requestId: SHOW_PANE_ID }, async ($, e, next) => {
188    const bound = host
189    if (!bound) return next(e)
190    const runs = await read($, RUNS)
191    const feeds = await read($, FEEDS)
192    const tabs = showTabs(runs, feeds)
193    const active = activeTab(tabs, (await read($, SHOW_TAB)).active)
194    const view = active ? await read($, memberOf(PANES, { requestId: active.id })) : null
195    const fit = paneFit(e.props, e.surface)
196    const strip = wrapTabs(tabs, active?.id ?? null, fit.columns) // once: the rows drawn are the rows taken off
197    const tabRows = { ...fit, rows: Math.max(1, fit.rows - strip.length - 1) } // the strip's rows and its rule (R12.6)
198    // The agent line takes a row too, the same for every tab, so the child is that row shorter and a tab switch resizes nothing.
199    const agentRows = paneAgentRows(runs, feeds)
200    poll.notePanelSize(bound, childSize({ ...tabRows, rows: tabRows.rows - agentRows }), active?.id ?? null) // each tab's child is resized to it before its capture
201    const model = view ? paneModel(view, runs, tabRows, await $.clock.now(), feeds) : null
202    const press = bindStore($)
203    return panelTree($.ui.resolve(e), tabs, strip, active?.id ?? null, model, fit.columns, palette,
204      target => void controls.pressTab(press, target).then(id => poll.captureOpened(bound, id), () => poll.ensureLoop(bound)),
205      () => void controls.pressHide(bindPressUi($)).catch(err => bound.debug(`claudish Hide failed: ${err instanceof Error ? err.message : String(err)}`)))
206  })
207}
208
hooks/status/claudish-source.ts 522 lines
1// THE ADAPTER: claudish mod contract v1 (sections A–E) → the mod's domain types.
2//
3// The only module of the mod that names a claudish tool, a mode, an argument, a capability
4// or a response field. (The plugin's PreToolUse command hook,
5// hooks/allow-read-verbs.ts, names claudish's read-only tools too; it is not part of the mod.)
6// It calls MCP only through the McpCall it was given (register.tsx builds the mod's one MCP
7// closure), holds no state, and decides nothing about display, cadence, support policy or
8// waking: it reports what the server answered.
9
10import type { McpToolResult } from 'claude-code'
11import type { ClaudishColor, ClaudishFrame, ClaudishRecentStep, ClaudishRunKind, ClaudishRunRef, ClaudishSlot, ClaudishSlotState, ClaudishStyleSpan } from '../../types'
12import { STYLE_SPANS_PER_LINE, feedKey, sanitize } from './domain'
13import type {
14  CallSeen,
15  CaptureResult,
16  ResizeResult,
17  FeedAnswer,
18  FetchSlot,
19  PollBatch,
20  PollResult,
21  RecognizedCall,
22  RunSource,
23  StopResult,
24  WatchedRun,
25} from './run-source'
26
27/** The tool.call matcher: claudish installed through the plugin, or registered directly. */
28export const CLAUDISH_TOOL = /^mcp__(plugin_claudish_claudish|claudish)__([a-z_]+)$/
29
30/** Tool-name segment → the server name the engine's mcp.call takes ("Reaching claudish"). */
31const SERVER_OF: Readonly<Record<string, string>> = {
32  plugin_claudish_claudish: 'plugin:claudish:claudish',
33  claudish: 'claudish',
34}
35
36export type McpCall = (server: string, tool: string, args: Record<string, unknown>) => Promise<McpToolResult>
37
38// ── contract v1 vocabulary ────────────────────────────────────────────────────
39
40const CONTRACT_VERSION = 1
41const SLOT_STATES: ReadonlySet<string> = new Set([
42  'STARTING', 'RUNNING', 'AWAITING_INPUT', 'AWAITING_PERMISSION',
43  'COMPLETED', 'FAILED', 'CANCELLED', 'TIMEOUT', 'EMPTY',
44])
45const FAILURE_REASONS: ReadonlySet<string> = new Set([
46  'cancelled', 'timeout', 'boot_timeout', 'boot_blocked', 'first_run_dialog', 'agent_rejected',
47  'prompt_not_accepted', 'prompt_not_read', 'child_exited', 'pane_lost', 'blocked', 'api_error',
48  'refused', 'empty_output', 'shape_mismatch',
49])
50const GONE_CODES: ReadonlySet<string> = new Set(['unknown_run', 'unknown_session', 'unknown_slot'])
51const QUESTION_ACTIVITY = 'AskUserQuestion'
52const MODEL_ID = /^[\w.@:/-]{1,80}$/
53/** An agent name as Claude Code spells one: `name`, `plugin:name`, a nested `plugin:dir:name`. */
54const AGENT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*(?::[A-Za-z0-9][A-Za-z0-9_.-]*){0,3}$/
55const AGENT_MAX = 64
56const PRECONTRACT_START = 'no run_id: pre-contract claudish'
57
58type Json = Record<string, unknown>
59
60// ── decoding helpers ──────────────────────────────────────────────────────────
61
62function isObject(v: unknown): v is Json {
63  return typeof v === 'object' && v !== null && !Array.isArray(v)
64}
65
66function parseObject(text: string | null | undefined): Json | null {
67  if (typeof text !== 'string') return null
68  try {
69    const v: unknown = JSON.parse(text)
70    return isObject(v) ? v : null
71  } catch {
72    return null
73  }
74}
75
76/** content[0].text of an MCP answer (the contract answers in one text block). */
77function firstText(result: McpToolResult): string | null {
78  const block = Array.isArray(result.content) ? result.content[0] : undefined
79  return isObject(block) && block.type === 'text' && typeof block.text === 'string' ? block.text : null
80}
81
82/** The ContractError code of an error body, or null when the body is not one. */
83function contractErrorCode(text: string | null): string | null {
84  const body = parseObject(text)
85  const err = body && isObject(body.error) ? body.error : null
86  return err && typeof err.code === 'string' && typeof err.message === 'string' ? err.code : null
87}
88
89function short(text: unknown): string {
90  const s = text instanceof Error ? text.message : typeof text === 'string' ? text : String(text)
91  return sanitize(s, 120) || 'no reason given'
92}
93
94function num(v: unknown): number | null {
95  return typeof v === 'number' && Number.isFinite(v) ? v : null
96}
97
98function str(v: unknown, max: number): string | null {
99  return typeof v === 'string' ? sanitize(v, max) : null
100}
101
102/** Server text the mod shows and quotes to the model as it stands: display-safe already, no quote or backslash. */
103function isSafeText(text: string, max: number): boolean {
104  return text.length > 0 && text.length <= max && sanitize(text, max) === text && !/["\\]/.test(text)
105}
106
107/** A run_id, session_id or slot id. */
108const isSafeId = (id: string): boolean => isSafeText(id, 128)
109
110/** run.path: absolute, and display-safe. */
111const isSafePath = (path: string): boolean => path.startsWith('/') && isSafeText(path, 4096)
112
113function lastSegment(path: string): string {
114  const parts = path.split('/').filter(p => p.length > 0)
115  return (parts[parts.length - 1] ?? path).slice(0, 16)
116}
117
118// ── recognizing a start ───────────────────────────────────────────────────────
119
120function recognizeCall(call: CallSeen): RecognizedCall {
121  const m = CLAUDISH_TOOL.exec(call.tool)
122  const server = m ? SERVER_OF[m[1] ?? ''] : undefined
123  if (!m || !server) return { kind: 'other' }
124  const verb = m[2]
125  if (call.answer.isError) return { kind: 'other' }
126
127  if (verb === 'team') {
128    const mode = call.args.mode
129    if (mode !== 'run' && mode !== 'run-and-judge') return { kind: 'other' }
130    const body = parseObject(call.answer.text)
131    if (!body) return { kind: 'unidentified', reason: 'team start answer is not a JSON object' }
132    if (typeof body.run_id !== 'string' || body.run_id.length === 0) {
133      return { kind: 'precontract', server, runKind: 'panel', reason: PRECONTRACT_START }
134    }
135    if (!isSafeId(body.run_id)) return { kind: 'unidentified', reason: 'team start answer has a run_id that is not display-safe' }
136    const run = isObject(body.run) ? body.run : null
137    if (run?.state === 'SETTLED') return { kind: 'other' }
138    const path = run?.path
139    if (typeof path !== 'string' || !path.startsWith('/')) {
140      return { kind: 'unidentified', reason: 'team start answer has no absolute run.path' }
141    }
142    if (!isSafePath(path)) return { kind: 'unidentified', reason: 'team start answer has a run.path that is not display-safe' }
143    const ref: ClaudishRunRef = { kind: 'panel', server, token: body.run_id, address: path }
144    return { kind: 'start', ref, label: lastSegment(path) }
145  }
146
147  if (verb === 'create_session') {
148    const body = parseObject(call.answer.text)
149    if (!body) return { kind: 'unidentified', reason: 'create_session answer is not a JSON object' }
150    const id = body.session_id
151    if (typeof id !== 'string' || id.length === 0) {
152      return { kind: 'unidentified', reason: 'create_session answer has no session_id' }
153    }
154    if (!isSafeId(id)) return { kind: 'unidentified', reason: 'create_session answer has a session_id that is not display-safe' }
155    const ref: ClaudishRunRef = { kind: 'delegation', server, token: id, address: id }
156    return { kind: 'start', ref, label: `#${id.slice(0, 6)}` }
157  }
158
159  return { kind: 'other' }
160}
161
162// ── one list answer: classification, then rows ───────────────────────────────
163
164type Classified = { answer: FeedAnswer; rows: Json[] }
165
166function classify(result: McpToolResult | Error, rowsKey: 'runs' | 'sessions'): Classified {
167  const none: Json[] = []
168  // 1. the call itself failed
169  if (result instanceof Error) return { answer: { kind: 'unanswered', reason: short(result) }, rows: none }
170  const text = firstText(result)
171  // 2. an error: the contract's error body, or a server that predates the contract
172  if (result.isError === true) {
173    const code = contractErrorCode(text)
174    return code !== null
175      ? { answer: { kind: 'refused', code }, rows: none }
176      : { answer: { kind: 'precontract', reason: `error answer without a contract error body: ${short(text ?? '')}` }, rows: none }
177  }
178  // 3. not a JSON object
179  const body = parseObject(text)
180  if (!body) return { answer: { kind: 'garbled', reason: 'answer is not a JSON object' }, rows: none }
181  // 4. no contract declaration
182  const version = body.contract_version
183  const caps = body.capabilities
184  if (typeof version !== 'number' || !Number.isInteger(version)
185    || !Array.isArray(caps) || !caps.every(c => typeof c === 'string')) {
186    return { answer: { kind: 'precontract', reason: 'answer carries no contract_version and capabilities' }, rows: none }
187  }
188  // 5. a version this mapping does not read, or no list capability
189  if (version !== CONTRACT_VERSION) return { answer: { kind: 'declines', reason: `contract version ${version}` }, rows: none }
190  const has = (c: string) => (caps as string[]).includes(c)
191  if (!has('list')) return { answer: { kind: 'declines', reason: 'no list capability' }, rows: none }
192  // 6. the row array
193  const rows = body[rowsKey]
194  if (!Array.isArray(rows)) return { answer: { kind: 'garbled', reason: `answer has no ${rowsKey} array` }, rows: none }
195  // 7. speaks
196  const capture = has('capture') && has('capture_since_seq')
197  return {
198    answer: { kind: 'speaks', version: 1, can: { cancel: has('cancel'), capture, spans: capture && has('capture_spans'), resize: capture && has('resize') } },
199    rows: rows.filter(isObject),
200  }
201}
202
203/** The failure in the provider's own words (`reason_detail`), present only when claudish sends one. */
204function detailOf(row: Json): { detail?: string } {
205  const detail = str(row.reason_detail, 160)
206  return detail ? { detail } : {}
207}
208
209/**
210 * The agent asked for and the one loaded, each present only when claudish sends a name that is
211 * display-safe as it stands. Rejected, never repaired: a repaired identifier names an agent that does not exist.
212 */
213function agentsOf(row: Json): { agentRequested?: string; agent?: string } {
214  const name = (v: unknown) => (typeof v === 'string' && v.length <= AGENT_MAX && AGENT_NAME.test(v) ? v : null)
215  const requested = name(row.agent_requested)
216  const loaded = name(row.agent)
217  return { ...(requested ? { agentRequested: requested } : {}), ...(loaded ? { agent: loaded } : {}) }
218}
219
220const RECENT_KINDS = new Set(['text', 'thinking', 'tool', 'ask'])
221/** claudish sends at most 20; a longer list is cut to its newest. */
222const RECENT_MAX = 20
223
224/**
225 * claudish's `recent`: the slot's last steps, each with its start time and one line. Present only when
226 * claudish sends a list (a row read from disk sends null); a step with no time or kind is skipped.
227 */
228function recentOf(row: Json): { recent?: ClaudishRecentStep[] } {
229  if (!Array.isArray(row.recent)) return {}
230  const recent: ClaudishRecentStep[] = []
231  for (const r of row.recent.slice(-RECENT_MAX)) {
232    if (!isObject(r) || typeof r.kind !== 'string' || !RECENT_KINDS.has(r.kind)) continue
233    const at = typeof r.at === 'string' ? Date.parse(r.at) : NaN
234    if (!Number.isFinite(at)) continue
235    recent.push({ at, kind: r.kind as ClaudishRecentStep['kind'], tool: str(r.tool, 60) || null, summary: str(r.summary, 120) ?? '' })
236  }
237  return { recent }
238}
239
240function mapSlot(row: Json): ClaudishSlot | null {
241  if (typeof row.slot !== 'string' || !isSafeId(row.slot)) return null
242  const model = typeof row.model === 'string' ? sanitize(row.model, 80) : ''
243  const state: ClaudishSlotState = typeof row.state === 'string' && SLOT_STATES.has(row.state)
244    ? (row.state as ClaudishSlotState)
245    : 'UNKNOWN'
246  const activity = str(row.activity, 60) || null
247  const lastAt = typeof row.last_activity_at === 'string' ? Date.parse(row.last_activity_at) : NaN
248  return {
249    slot: row.slot,
250    model: MODEL_ID.test(model) ? model : 'unknown model',
251    provider: str(row.provider, 40) || null,
252    state,
253    reason: typeof row.reason === 'string' && FAILURE_REASONS.has(row.reason) ? row.reason : null,
254    ...detailOf(row),
255    ...agentsOf(row),
256    tokensIn: num(row.tokens_in),
257    tokensOut: num(row.tokens_out),
258    toolCalls: num(row.tool_calls),
259    turnsCompleted: num(row.turns_completed),
260    costUsd: num(row.cost_usd),
261    idleSeconds: num(row.idle_seconds),
262    lastActivityAt: Number.isFinite(lastAt) ? lastAt : null,
263    activity,
264    asked: state === 'AWAITING_INPUT' && row.activity === QUESTION_ACTIVITY,
265    ...recentOf(row),
266  }
267}
268
269/** A watched run's row, matched by its own per-start id, exactly. */
270function pollResult(kind: ClaudishRunKind, rows: readonly Json[], token: string): PollResult {
271  if (kind === 'panel') {
272    const row = rows.find(r => r.run_id === token)
273    if (!row) return { kind: 'missing', reason: null }
274    if (!Array.isArray(row.slots)) return { kind: 'missing', reason: 'run row has no slots array' }
275    const slots: ClaudishSlot[] = []
276    for (const s of row.slots) {
277      const mapped = isObject(s) ? mapSlot(s) : null
278      if (!mapped) return { kind: 'missing', reason: 'a slot row has no slot id' }
279      slots.push(mapped)
280    }
281    return { kind: 'ok', slots }
282  }
283  const row = rows.find(r => r.session_id === token)
284  if (!row) return { kind: 'missing', reason: null }
285  const mapped = mapSlot(row)
286  return mapped ? { kind: 'ok', slots: [mapped] } : { kind: 'missing', reason: 'session row has no slot id' }
287}
288
289// ── stop ──────────────────────────────────────────────────────────────────────
290
291function stopResult(result: McpToolResult | Error, ref: ClaudishRunRef, slot: string): StopResult {
292  if (result instanceof Error) return { kind: 'failed', reason: short(result) }
293  const text = firstText(result)
294  if (result.isError === true) return { kind: 'failed', reason: contractErrorCode(text) ?? short(text ?? '') }
295  const body = parseObject(text)
296  if (!body) return { kind: 'failed', reason: 'cancel answer is not a JSON object' }
297  if (ref.kind === 'delegation') {
298    return typeof body.changed === 'boolean'
299      ? { kind: 'stopped', changed: body.changed }
300      : { kind: 'failed', reason: 'cancel answer has no changed flag' }
301  }
302  const entry = Array.isArray(body.results) ? body.results.find(r => isObject(r) && r.slot === slot) : undefined
303  return isObject(entry) && typeof entry.changed === 'boolean'
304    ? { kind: 'stopped', changed: entry.changed }
305    : { kind: 'failed', reason: `cancel answer has no result for slot ${slot}` }
306}
307
308// ── resize ────────────────────────────────────────────────────────────────────
309
310function resizeResult(result: McpToolResult | Error): ResizeResult {
311  if (result instanceof Error) return { kind: 'failed', reason: short(result) }
312  const text = firstText(result)
313  if (result.isError === true) {
314    const code = contractErrorCode(text)
315    if (code !== null && GONE_CODES.has(code)) return { kind: 'gone' }
316    return { kind: 'failed', reason: code ?? short(text ?? '') }
317  }
318  const body = parseObject(text)
319  if (!body) return { kind: 'failed', reason: 'resize answer is not a JSON object' }
320  const { cols, rows } = body
321  return typeof cols === 'number' && typeof rows === 'number'
322    ? { kind: 'resized', cols, rows }
323    : { kind: 'failed', reason: 'resize answer has no cols and rows' }
324}
325
326// ── capture ───────────────────────────────────────────────────────────────────
327
328const SGR_OR_CSI = /\u001b\[[0-?]*[ -/]*[@-~]/g
329const C0 = /[\u0000-\u0008\u000a-\u001f\u007f]/g
330
331function cleanLine(line: string, cols: number): string {
332  let out = ''
333  for (const ch of line.replace(SGR_OR_CSI, '').replace(C0, '')) {
334    if (ch === '\t') out += ' '.repeat(8 - (out.length % 8))
335    else out += ch
336  }
337  return out.slice(0, cols).replace(/\s+$/, '')
338}
339
340function color(c: number): ClaudishColor | null {
341  if (c >= 0 && c <= 255) return { index: c }
342  if (c >= 16_777_216) return { rgb: c & 0xffffff }
343  return null
344}
345
346function sameStyle(a: ClaudishStyleSpan, b: ClaudishStyleSpan): boolean {
347  const eq = (x: ClaudishColor | null, y: ClaudishColor | null) => JSON.stringify(x) === JSON.stringify(y)
348  return a.bold === b.bold && eq(a.fg, b.fg) && eq(a.bg, b.bg)
349}
350
351/** One line's span tuples → sorted, non-overlapping, merged spans, at most STYLE_SPANS_PER_LINE. */
352function decodeLine(raw: unknown, cols: number): ClaudishStyleSpan[] {
353  if (!Array.isArray(raw)) return []
354  const spans: ClaudishStyleSpan[] = []
355  for (const t of raw) {
356    if (!Array.isArray(t) || t.length !== 5 || !t.every(n => Number.isInteger(n))) continue
357    const [col, len, fg, bg, attr] = t as [number, number, number, number, number]
358    if (col < 0 || len < 1 || col >= cols) continue
359    const span: ClaudishStyleSpan = { col, len: Math.min(col + len, cols) - col, fg: color(fg), bg: color(bg), bold: (attr & 1) === 1 }
360    if (span.fg === null && span.bg === null && !span.bold) continue
361    spans.push(span)
362  }
363  spans.sort((a, b) => a.col - b.col)
364  const kept: ClaudishStyleSpan[] = []
365  for (const s of spans) {
366    const prev = kept[kept.length - 1]
367    if (prev && s.col < prev.col + prev.len) continue
368    if (prev && prev.col + prev.len === s.col && sameStyle(prev, s)) {
369      kept[kept.length - 1] = { ...prev, len: prev.len + s.len }
370      continue
371    }
372    kept.push(s)
373  }
374  return kept.slice(0, STYLE_SPANS_PER_LINE)
375}
376
377function decodeSpans(raw: unknown, rows: number, cols: number): ClaudishStyleSpan[][] | undefined {
378  if (!Array.isArray(raw) || raw.length !== rows) return undefined
379  return raw.map(line => decodeLine(line, cols))
380}
381
382function captureResult(result: McpToolResult | Error, withSpans: boolean): CaptureResult {
383  if (result instanceof Error) return { kind: 'unavailable', reason: short(result) }
384  const text = firstText(result)
385  if (result.isError === true) {
386    const code = contractErrorCode(text)
387    if (code !== null && GONE_CODES.has(code)) return { kind: 'gone' }
388    return { kind: 'unavailable', reason: code ?? short(text ?? '') }
389  }
390  const body = parseObject(text)
391  if (!body) return { kind: 'unavailable', reason: 'capture answer is not a JSON object' }
392  const final = body.final === true
393  if (body.unchanged === true) return { kind: 'unchanged', final }
394  const { seq, cols, rows, lines } = body
395  if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 0
396    || typeof cols !== 'number' || !Number.isInteger(cols) || cols < 1
397    || typeof rows !== 'number' || !Number.isInteger(rows) || rows < 1
398    || !Array.isArray(lines) || !lines.every(l => typeof l === 'string')) {
399    return { kind: 'unavailable', reason: 'capture answer is malformed' }
400  }
401  if (seq === 0) return { kind: 'unchanged', final }
402  const kept = (lines as string[]).slice(0, rows).map(l => cleanLine(l, cols))
403  while (kept.length < rows) kept.push('')
404  const cur = isObject(body.cursor) ? body.cursor : null
405  const x = cur ? num(cur.x) : null
406  const y = cur ? num(cur.y) : null
407  const frame: ClaudishFrame = {
408    seq,
409    cols,
410    rows,
411    cursor: x !== null && y !== null && x >= 0 && y >= 0 && x < cols && y < rows ? { row: y, col: x } : null,
412    lines: kept,
413  }
414  if (withSpans) {
415    const styles = lines.length === rows ? decodeSpans(body.spans, rows, cols) : undefined
416    if (styles) frame.styles = styles
417  }
418  return { kind: 'frame', frame, final }
419}
420
421// ── wording the wake text borrows ────────────────────────────────────────────
422
423/** A quoted value of the wake text: JSON string syntax, so no quote inside can end it early. */
424const q = (s: string): string => JSON.stringify(s)
425
426function runLine(ref: ClaudishRunRef, label: string): string {
427  return ref.kind === 'panel'
428    ? `Run ${label} (path ${q(ref.address)}, run_id ${q(ref.token)}):`
429    : `Delegation ${label} (session_id ${q(ref.token)}):`
430}
431
432function delegationHint(id: string, s: FetchSlot): string {
433  const sid = `session_id=${q(id)}`
434  switch (s.state) {
435    case 'COMPLETED':
436      return `get_output(${sid})`
437    case 'AWAITING_INPUT':
438      return s.asked
439        ? `Read its answer with get_output(${sid}); reply with send_input(${sid}, …): it is asking a question; send_input declines the question and sends your text as its next prompt`
440        : `Read its answer with get_output(${sid}); reply with send_input(${sid}, …)`
441    case 'AWAITING_PERMISSION':
442      return `it is waiting on a permission dialog; get_output(${sid}) shows it; send_input declines the dialog and sends your text as its next prompt; cancel_session(${sid}) stops it`
443    case 'STARTING':
444    case 'RUNNING':
445    case 'UNKNOWN':
446      return `get_output(${sid}) once it finishes`
447    default:
448      return `get_diagnostics(${sid})`
449  }
450}
451
452function fetchHint(ref: ClaudishRunRef, slots: readonly FetchSlot[]): string {
453  if (ref.kind === 'panel') {
454    return `team(mode="status", path=${q(ref.address)}, run_id=${q(ref.token)}) then read each finished slot's response file`
455  }
456  const s = slots[0] ?? { slot: ref.token, state: 'COMPLETED' as const, asked: false }
457  return delegationHint(ref.token, s)
458}
459
460// ── the adapter ───────────────────────────────────────────────────────────────
461
462const settleCall = (p: Promise<McpToolResult>): Promise<McpToolResult | Error> =>
463  p.then(
464    r => r,
465    (e: unknown) => (e instanceof Error ? e : new Error(String(e))),
466  )
467
468/** The one RunSource. register.tsx passes its one MCP closure; tests may pass a stub. */
469export function makeClaudishSource(call: McpCall): RunSource {
470  return {
471    recognizeCall,
472
473    async poll(runs: readonly WatchedRun[]): Promise<PollBatch> {
474      const byFeed = new Map<string, WatchedRun[]>()
475      for (const r of runs) {
476        const key = feedKey(r.ref)
477        byFeed.set(key, [...(byFeed.get(key) ?? []), r])
478      }
479      const feeds = new Map<string, FeedAnswer>()
480      const results = new Map<string, PollResult>()
481      await Promise.all([...byFeed.entries()].map(async ([key, watched]) => {
482        const first = watched[0]
483        if (!first) return
484        const { kind, server } = first.ref
485        const answer = kind === 'panel'
486          ? await settleCall(call(server, 'team', { mode: 'list' }))
487          : await settleCall(call(server, 'list_sessions', { include_completed: true }))
488        const { answer: feed, rows } = classify(answer, kind === 'panel' ? 'runs' : 'sessions')
489        feeds.set(key, feed)
490        if (feed.kind !== 'speaks') return
491        for (const w of watched) results.set(w.id, pollResult(kind, rows, w.ref.token))
492      }))
493      return { feeds, runs: results }
494    },
495
496    async stop(ref: ClaudishRunRef, slot: string): Promise<StopResult> {
497      const answer = ref.kind === 'panel'
498        ? await settleCall(call(ref.server, 'team', { mode: 'cancel', path: ref.address, slot, run_id: ref.token }))
499        : await settleCall(call(ref.server, 'cancel_session', { session_id: ref.token }))
500      return stopResult(answer, ref, slot)
501    },
502
503    async capture(ref: ClaudishRunRef, slot: string, sinceSeq: number, withSpans: boolean): Promise<CaptureResult> {
504      const spans = withSpans ? { spans: true } : {}
505      const answer = ref.kind === 'panel'
506        ? await settleCall(call(ref.server, 'team', { mode: 'capture', path: ref.address, slot, run_id: ref.token, since_seq: sinceSeq, ...spans }))
507        : await settleCall(call(ref.server, 'capture_session', { session_id: ref.token, since_seq: sinceSeq, ...spans }))
508      return captureResult(answer, withSpans)
509    },
510
511    async resize(ref: ClaudishRunRef, slot: string, cols: number, rows: number): Promise<ResizeResult> {
512      const answer = ref.kind === 'panel'
513        ? await settleCall(call(ref.server, 'team', { mode: 'resize', path: ref.address, slot, run_id: ref.token, cols, rows }))
514        : await settleCall(call(ref.server, 'resize_session', { session_id: ref.token, cols, rows }))
515      return resizeResult(answer)
516    },
517
518    runLine,
519    fetchHint,
520  }
521}
522
hooks/status/host.ts 124 lines
1// The shapes register.tsx fills with closures over a dispatch's engine interface, and
2// four pure helpers. No engine-interface spelling and no state reference live here: the
3// engine's static scan reads a state reference only where its plugin and key are
4// literals of the file that uses it, and follows the engine interface into no import.
5
6import type { PromptSubmitResult, Timer, UiOpenResult, UiPane } from 'claude-code'
7import type {
8  ClaudishShowTab,
9  ClaudishEarlier,
10  ClaudishFeedSupport,
11  ClaudishLedger,
12  ClaudishPaneView,
13  ClaudishRuns,
14  ClaudishStopRequest,
15  ClaudishTurn,
16} from '../../types'
17import type { RunSource } from './run-source'
18
19/** One atom, through closures over one dispatch. */
20export type Cell<T> = {
21  read(): Promise<T>
22  /** resolves what it wrote */
23  update(fn: (v: T) => T): Promise<T>
24  /** one update whose fn also returns a claim; resolves [written, the claim of the pass that wrote] */
25  claim<C>(fn: (v: T) => readonly [T, C]): Promise<readonly [T, C]>
26}
27
28/** One family, member by computed id. */
29export type Member<T> = {
30  read(id: string): Promise<T>
31  update(id: string, fn: (v: T) => T): Promise<T>
32  claim<C>(id: string, fn: (v: T) => readonly [T, C]): Promise<readonly [T, C]>
33}
34
35export type Store = {
36  runs: Cell<ClaudishRuns>
37  feeds: Cell<Record<string, ClaudishFeedSupport>>
38  stopRequests: Cell<Record<string, ClaudishStopRequest>>
39  ledger: Cell<ClaudishLedger>
40  turn: Cell<ClaudishTurn>
41  earlier: Cell<ClaudishEarlier>
42  showTab: Cell<ClaudishShowTab>
43  panes: Member<ClaudishPaneView | null>
44}
45
46export type SubmitOutcome = { accepted: true } | { accepted: false; reason: string }
47
48export type TranscriptRow = { role: string; text: string }
49
50/** Everything timer code may do, bound once per load in session.start. */
51export type Host = {
52  /** bound to the session.start dispatch; what timer code uses */
53  store: Store
54  source: RunSource
55  /** the engine's clock.now */
56  now(): Promise<number>
57  /** the engine's clock.after */
58  after(ms: number, fn: () => void): Timer
59  toast(text: string, timeoutMs?: number): void
60  /** the engine's ui.status: one pinned line per plugin; undefined clears it */
61  status(text: string | undefined): void
62  /** the engine's prompt.submit; a drop and a rejection both read as not accepted */
63  submit(text: string): Promise<SubmitOutcome>
64  /** the engine's ui.log to the debug log */
65  debug(text: string): void
66  panes(): Promise<readonly UiPane[]>
67  /** the engine's ui.close, for tabs of runs the band no longer shows (a close needs no press behind it) */
68  close(id: string): Promise<void>
69  /** the engine's session.messages; recovery only */
70  messages(): Promise<readonly TranscriptRow[]>
71}
72
73const MAX_PASSES = 8
74
75/** The fn an update retries, throwing once it has been asked more than MAX_PASSES times. */
76export function capped<T>(fn: (v: T) => T): (v: T) => T {
77  let passes = 0
78  return v => {
79    passes += 1
80    if (passes > MAX_PASSES) throw new Error(`state update did not converge in ${MAX_PASSES} passes`)
81    return fn(v)
82  }
83}
84
85/** One update through the given closure, keeping the claim of the pass that wrote: every pass
86 *  assigns (never appends to) the claim, so the last pass, whose write landed, wins. */
87export async function claimVia<T, C>(
88  apply: (fn: (v: T) => T) => Promise<T>,
89  fn: (v: T) => readonly [T, C],
90): Promise<readonly [T, C]> {
91  let claimed!: C
92  const written = await apply(v => {
93    const [next, c] = fn(v)
94    claimed = c
95    return next
96  })
97  return [written, claimed] as const
98}
99
100/** A submit's answer: the prompt that entered, or a drop. */
101export function toAccepted(result: PromptSubmitResult | { drop: string }): SubmitOutcome {
102  return 'drop' in result && typeof result.drop === 'string'
103    ? { accepted: false, reason: result.drop }
104    : { accepted: true }
105}
106
107/** A submit that rejected. */
108export function rejected(err: unknown): SubmitOutcome {
109  const reason = err instanceof Error ? err.message : String(err)
110  return { accepted: false, reason: reason.slice(0, 120) || 'rejected' }
111}
112
113/**
114 * The pane calls a press makes, bound to the render dispatch whose tree held the button. They
115 * must not go through the session-bound Host: Claude Code places a pane at any width only when
116 * the person's press is behind its open, and below 144 columns it keeps an unasked one undrawn.
117 */
118export type PressUi = {
119  panes(): Promise<readonly UiPane[]>
120  /** the engine's ui.open; columns: the body width asked for while docked, rows: the height inline (requests) */
121  open(id: string, title: string, size: { columns: number; rows: number }): Promise<UiOpenResult>
122  close(id: string): Promise<void>
123}
124
hooks/status/domain.ts 625 lines
1// Pure domain functions and constants: state classes, ids and hashes, sanitising, the
2// run merge (LOST rules, wait entries, settlement), stop-request pruning and compaction.
3// No engine interface, no state reference, no claudish vocabulary.
4
5import type { ThemeKey } from 'claude-code'
6import type {
7  ClaudishEarlier,
8  ClaudishFeedSupport,
9  ClaudishLedger,
10  ClaudishRecentStep,
11  ClaudishRun,
12  ClaudishRunKind,
13  ClaudishRunRef,
14  ClaudishRuns,
15  ClaudishSlot,
16  ClaudishSlotState,
17  ClaudishStopRequest,
18  ClaudishTrailKind,
19  ClaudishTrailStep,
20  ClaudishWait,
21} from '../../types'
22
23// ── constants ─────────────────────────────────────────────────────────────────
24
25/** Styled runs kept per captured line, the leftmost; the rest of the line draws plain. */
26export const STYLE_SPANS_PER_LINE = 24
27/** A run missing from its list is LOST only after this many misses spanning MISSING_LOST_MS. */
28export const MISSING_LOST_POLLS = 5
29export const MISSING_LOST_MS = 30_000
30/** A speaking feed that keeps failing ends its runs LOST after this long. */
31export const UNREACHABLE_LOST_MS = 5 * 60_000
32/** A slot in a state outside the closed set ends LOST after this long. */
33export const UNKNOWN_LOST_MS = 10 * 60_000
34/** Past this many runs, the oldest settled, fully delivered runs fold into `earlier`. */
35export const RUNS_CAP = 100
36export const STOP_CONFIRM_MS = 4_000
37export const STOP_SENT_TIMEOUT_MS = 20_000
38/** A tab whose slot ended keeps capturing this long for its final screen. */
39export const FINAL_GRACE_MS = 30_000
40export const QUIET_AFTER_S = 120
41export const NO_SCREEN_NOTE = 'Run ended before a screen was captured'
42export const NO_CAPTURE_NOTE = 'Live screen not available from this claudish version'
43
44/** The theme keys the mod's text uses; the badges take raw colours from palette.ts, by the person's theme. */
45export const THEME_KEYS = [
46  'claude', 'permission', 'success', 'error', 'warning', 'inactive', 'subtle', 'inverseText', 'ide', 'suggestion',
47] as const satisfies readonly ThemeKey[]
48export type StatusColor = (typeof THEME_KEYS)[number]
49
50/** A badge's tone: its hue (palette.ts). Loud tones (ask, fail, format) mean the row needs the person, or it failed. */
51export type BadgeTone = 'run' | 'ask' | 'done' | 'fail' | 'format' | 'stopped' | 'unclear'
52
53/** The stale-meter: one cell fills at each of these seconds of silence; the last is QUIET_AFTER_S. */
54export const STALE_STEPS_S = [5, 30, 60, 90, 120] as const
55/** Below this much silence the slot counts as streaming (the meter animates); from it, the meter
56 *  fills and prints how long the slot has been silent. */
57export const STALE_NUMBER_S = 5
58
59/** The Show panel: one pane, its tabs drawn by the mod (one per slot of the runs the band shows). */
60export const SHOW_PANE_ID = 'claudish-show'
61export const SHOW_PANE_TITLE = 'claudish'
62
63/** The body columns a Show tab asks for when docked: a request, the person's own width wins. */
64export const SHOW_COLUMNS = 120
65/** The body rows a Show tab asks for while inline above the prompt: a request, as the columns are. */
66export const SHOW_ROWS = 24
67/** Surfaces that paint the child's colours in a Show tab; the others draw its screen plain. */
68export const PAINT_SURFACES: readonly string[] = ['terminal', 'desktop']
69/** Surfaces that draw a `Client` (the live cell). vscode's resolve still hands one over, and draws nothing for it. */
70export const CLIENT_SURFACES: readonly string[] = ['terminal', 'desktop']
71/** What one frame line and one styled segment cost, estimated, against the style budget. */
72export const PANE_LINE_COST = 64
73export const PANE_SEGMENT_COST = 128
74/** Past this estimate a frame draws plain: half the engine's 100,000-character tree bound. */
75export const PANE_STYLE_BUDGET = 50_000
76
77export const PANE_ID_PATTERN = /^cl_[0-9a-f]{8}$/
78
79/** While the main loop's turn runs (for at most this long), notices wait for its end. */
80export const WAKE_HOLD_GUARD_MS = 30 * 60_000
81/** A refused notice is retried after attempts × this, up to WAKE_QUICK_ATTEMPTS attempts. */
82export const WAKE_RETRY_MS = 30_000
83export const WAKE_QUICK_ATTEMPTS = 3
84/** A parked notice is retried this often, and at every main-loop turn end. */
85export const PARKED_RETRY_MS = 10 * 60_000
86
87// ── state classes ─────────────────────────────────────────────────────────────
88
89const TERMINAL: ReadonlySet<ClaudishSlotState> = new Set<ClaudishSlotState>([
90  'COMPLETED', 'FAILED', 'CANCELLED', 'TIMEOUT', 'EMPTY', 'LOST',
91])
92
93export function isTerminal(state: ClaudishSlotState): boolean {
94  return TERMINAL.has(state)
95}
96
97export function isWaiting(state: ClaudishSlotState): boolean {
98  return state === 'AWAITING_INPUT' || state === 'AWAITING_PERMISSION'
99}
100
101export type Group = 'needs you' | 'running' | 'done' | 'wrong format' | 'failed' | 'stopped'
102export type StateLook = { code: string; tone: BadgeTone; glyph: string; word: string; color: StatusColor; group: Group }
103
104/** The badge code (three letters, as tt draws them), its tone, the word, and the header group, per state. */
105export const STATE_LOOK: Readonly<Record<ClaudishSlotState, StateLook>> = {
106  STARTING: { code: 'NEW', tone: 'run', glyph: '◌', word: 'starting', color: 'success', group: 'running' },
107  RUNNING: { code: 'RUN', tone: 'run', glyph: '▶', word: 'running', color: 'success', group: 'running' },
108  AWAITING_INPUT: { code: 'ASK', tone: 'ask', glyph: '◇', word: 'input', color: 'permission', group: 'needs you' },
109  AWAITING_PERMISSION: { code: 'ASK', tone: 'ask', glyph: '◇', word: 'permit', color: 'permission', group: 'needs you' },
110  COMPLETED: { code: 'END', tone: 'done', glyph: '✓', word: 'done', color: 'success', group: 'done' },
111  FAILED: { code: 'ERR', tone: 'fail', glyph: '✕', word: 'failed', color: 'error', group: 'failed' },
112  TIMEOUT: { code: 'TMO', tone: 'fail', glyph: '✕', word: 'timeout', color: 'error', group: 'failed' },
113  EMPTY: { code: 'NIL', tone: 'fail', glyph: '✕', word: 'empty', color: 'error', group: 'failed' },
114  CANCELLED: { code: 'STP', tone: 'stopped', glyph: '■', word: 'stopped', color: 'inactive', group: 'stopped' },
115  LOST: { code: 'LST', tone: 'fail', glyph: '?', word: 'lost', color: 'error', group: 'failed' },
116  UNKNOWN: { code: '???', tone: 'unclear', glyph: '?', word: 'unknown', color: 'inactive', group: 'running' },
117}
118
119/** An answer that exists but missed the required shape: not empty, and not a crash. */
120const WRONG_FORMAT: StateLook = { code: 'FMT', tone: 'format', glyph: '!', word: 'wrong format', color: 'warning', group: 'wrong format' }
121
122/** A slot's look: its state's, except an EMPTY slot whose answer only missed the required shape. */
123export function lookOf(state: ClaudishSlotState, reason: string | null): StateLook {
124  return state === 'EMPTY' && reason === 'shape_mismatch' ? WRONG_FORMAT : STATE_LOOK[state]
125}
126
127// ── ids and hashes ────────────────────────────────────────────────────────────
128
129/** FNV-1a, 32-bit, over UTF-16 code units. */
130export function fnv1a32(text: string): number {
131  let h = 0x811c9dc5
132  for (let i = 0; i < text.length; i++) {
133    h ^= text.charCodeAt(i)
134    h = Math.imul(h, 0x01000193) >>> 0
135  }
136  return h >>> 0
137}
138
139export function hex8(n: number): string {
140  return (n >>> 0).toString(16).padStart(8, '0')
141}
142
143/** One id per start, because claudish's token is per start. */
144export function runId(ref: ClaudishRunRef): string {
145  return hex8(fnv1a32(`${ref.kind}|${ref.server}|${ref.token}`))
146}
147
148/** A feed is one server × one run kind: one list call per tick. */
149export function feedKey(ref: { server: string; kind: ClaudishRunKind }): string {
150  return `${ref.server}#${ref.kind}`
151}
152
153/** A Show tab's pane id: stable across reloads, one per slot of a run. */
154export function paneId(id: string, slot: string): string {
155  return `cl_${hex8(fnv1a32(`${id}/${slot}`))}`
156}
157
158/** `${runId}/${slot}`: the key of a stop request and of a terminal wake. */
159export function slotKey(id: string, slot: string): string {
160  return `${id}/${slot}`
161}
162
163/** `${runId}/${slot}#w${n}`: the key of a delegation slot's n-th wait entry. */
164export function waitKey(id: string, slot: string, n: number): string {
165  return `${id}/${slot}#w${n}`
166}
167
168/** A wake ledger key taken apart; `wait` is the entry number of a wait key, null for a terminal key. */
169export function parseWakeKey(key: string): { runId: string; slot: string; wait: number | null } {
170  const cut = key.indexOf('/')
171  const rest = key.slice(cut + 1)
172  const m = /^(.*)#w(\d+)$/.exec(rest)
173  return m ? { runId: key.slice(0, cut), slot: m[1] ?? '', wait: Number(m[2]) } : { runId: key.slice(0, cut), slot: rest, wait: null }
174}
175
176/** The label a run is shown and named by: `label`, or `label·N` for the N-th start at its address. */
177export function runLabel(run: ClaudishRun): string {
178  return run.generation > 1 ? `${run.label}·${run.generation}` : run.label
179}
180
181/** A run is drawn while it has a slot, or while its feed speaks the contract. */
182export function isDrawn(run: ClaudishRun, feeds: Readonly<Record<string, ClaudishFeedSupport>>): boolean {
183  return run.slots.length > 0 || feeds[feedKey(run.ref)]?.kind === 'speaks'
184}
185
186/**
187 * The runs the band draws: the most recent drawn run, plus every older one still live (its
188 * Stop must stay reachable). Older settled runs are counted in the header, not drawn.
189 */
190export function shownRuns(drawn: readonly ClaudishRun[]): { shown: ClaudishRun[]; older: number } {
191  const latest = drawn[drawn.length - 1]
192  const shown = drawn.filter(r => r === latest || r.settledAt === null)
193  return { shown, older: drawn.length - shown.length }
194}
195
196// ── agents ────────────────────────────────────────────────────────────────────
197
198/** A slot's agent: what was asked for, what loaded, the name the row is about, and whether they disagree. */
199export type SlotAgent = { requested: string | null; loaded: string | null; name: string | null; mismatch: boolean }
200
201export function slotAgent(slot: Pick<ClaudishSlot, 'state' | 'agentRequested' | 'agent'>): SlotAgent {
202  const requested = slot.agentRequested ?? null
203  const loaded = slot.agent ?? null
204  // claudish fills `agent` only once it has read the child's transcript, seconds into RUNNING.
205  // Until the slot settles, no loaded agent is "not read yet", not a disagreement.
206  const pending = loaded === null && !isTerminal(slot.state)
207  const mismatch = requested !== null && loaded !== requested && !pending
208  return { requested, loaded, name: loaded ?? requested, mismatch }
209}
210
211/** One agent for every row under the header, several, or none at all. */
212export type BatchAgent = { kind: 'none' } | { kind: 'one'; name: string } | { kind: 'mixed' }
213
214/** The batch is every slot under the one header; the `*` placeholder of a run never listed is not a row's agent. */
215export function batchAgent(slots: readonly ClaudishSlot[]): BatchAgent {
216  const names = slots.filter(s => s.slot !== '*').map(s => slotAgent(s).name)
217  if (names.every(n => n === null)) return { kind: 'none' }   // also the empty list
218  const first = names[0] ?? null
219  return first !== null && names.every(n => n === first) ? { kind: 'one', name: first } : { kind: 'mixed' }
220}
221
222// ── text ──────────────────────────────────────────────────────────────────────
223
224// SGR and other CSI sequences, OSC sequences, lone escapes, C0/C1 controls and bidi overrides.
225const CSI = /\u001b\[[0-?]*[ -/]*[@-~]/g
226const OSC = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g
227const CONTROLS = /[\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩]/g
228
229/** Display-safe text from a server string: no escapes, no controls, one line, at most `max` characters. */
230export function sanitize(text: string, max: number): string {
231  return text.replace(CSI, '').replace(OSC, '').replace(CONTROLS, ' ').replace(/\s+/g, ' ').trim().slice(0, max)
232}
233
234/** Structural equality of plain JSON data. */
235export function sameData(a: unknown, b: unknown): boolean {
236  if (a === b) return true
237  if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return false
238  if (Array.isArray(a) !== Array.isArray(b)) return false
239  if (Array.isArray(a)) {
240    const bb = b as unknown[]
241    return a.length === bb.length && a.every((v, i) => sameData(v, bb[i]))
242  }
243  const ao = a as Record<string, unknown>
244  const bo = b as Record<string, unknown>
245  const ak = Object.keys(ao)
246  const bk = Object.keys(bo)
247  return ak.length === bk.length && ak.every(k => Object.prototype.hasOwnProperty.call(bo, k) && sameData(ao[k], bo[k]))
248}
249
250// ── runs ──────────────────────────────────────────────────────────────────────
251
252export function newRun(args: {
253  id: string
254  ref: ClaudishRunRef
255  label: string
256  epoch: number
257  generation: number
258  now: number
259}): ClaudishRun {
260  return {
261    id: args.id,
262    epoch: args.epoch,
263    ref: args.ref,
264    label: args.label,
265    generation: args.generation,
266    slots: [],
267    startedAt: args.now,
268    activityAt: args.now,
269    missedPolls: 0,
270    missingSince: null,
271    unreachableSince: null,
272    unknownSince: {},
273    personStops: [],
274    waits: {},
275    lostReason: null,
276    settledAt: null,
277  }
278}
279
280/** What one tick observed about one run. */
281export type RunObservation =
282  | { kind: 'ok'; slots: readonly ClaudishSlot[] }
283  | { kind: 'missing' }
284  /** its feed spoke the contract but answered badly this tick */
285  | { kind: 'unreachable' }
286  /** its feed withdrew the contract */
287  | { kind: 'withdrawn' }
288
289function lostSlot(s: ClaudishSlot): ClaudishSlot {
290  return { ...s, state: 'LOST', idleSeconds: null, activity: null, asked: false }
291}
292
293/** LOST at run level: every non-terminal slot, or a synthetic `*` slot for a run never listed. */
294export function applyLost(run: ClaudishRun, reason: string): ClaudishRun {
295  const slots: ClaudishSlot[] = run.slots.length === 0
296    ? [{
297        slot: '*', model: run.label, provider: null, state: 'LOST', reason: null,
298        tokensIn: null, tokensOut: null, toolCalls: null, turnsCompleted: null, costUsd: null,
299        idleSeconds: null, lastActivityAt: null, activity: null, asked: false,
300      }]
301    : run.slots.map(s => (isTerminal(s.state) ? s : lostSlot(s)))
302  return { ...run, slots, unknownSince: {}, lostReason: run.lostReason ?? reason }
303}
304
305function waitSig(s: ClaudishSlot): string {
306  return `${s.state}|${s.activity ?? ''}|${s.turnsCompleted ?? ''}|${s.toolCalls ?? ''}`
307}
308
309/** Wait entries for a delegation's slots: a new entry whenever a waiting slot's signature changes. */
310function nextWaits(prev: Readonly<Record<string, ClaudishWait>>, slots: readonly ClaudishSlot[]): Record<string, ClaudishWait> {
311  const waits: Record<string, ClaudishWait> = { ...prev }
312  for (const s of slots) {
313    const w = prev[s.slot] ?? { entries: 0, sig: null }
314    if (isWaiting(s.state)) {
315      const sig = waitSig(s)
316      waits[s.slot] = sig === w.sig ? w : { entries: w.entries + 1, sig }
317    } else if (w.sig !== null || prev[s.slot] !== undefined) {
318      waits[s.slot] = { entries: w.entries, sig: null }
319    }
320  }
321  return waits
322}
323
324function isActivity(prev: readonly ClaudishSlot[], next: readonly ClaudishSlot[]): boolean {
325  if (prev.length !== next.length) return true
326  return next.some(n => {
327    const p = prev.find(x => x.slot === n.slot)
328    if (!p) return true
329    return p.state !== n.state
330      || p.tokensIn !== n.tokensIn
331      || p.tokensOut !== n.tokensOut
332      || p.toolCalls !== n.toolCalls
333      || p.turnsCompleted !== n.turnsCompleted
334      || (n.lastActivityAt !== null && (p.lastActivityAt === null || n.lastActivityAt > p.lastActivityAt))
335  })
336}
337
338function settle(run: ClaudishRun, now: number): ClaudishRun {
339  if (run.settledAt !== null) return run
340  const done = run.slots.length > 0 && run.slots.every(s => isTerminal(s.state))
341  return done ? { ...run, settledAt: now } : run
342}
343
344// ── the timeline: what each slot did, one step per change ─────────────────────
345
346/** A trail keeps at most this many steps per slot; later changes still end it (its final step). */
347export const TRAIL_MAX_STEPS = 400
348
349/** What a slot is doing now, as a trail step's kind and tool. */
350export function trailKindOf(slot: ClaudishSlot): { kind: ClaudishTrailKind; tool: string | null } {
351  switch (slot.state) {
352    case 'STARTING': return { kind: 'start', tool: null }
353    case 'AWAITING_INPUT':
354    case 'AWAITING_PERMISSION': return { kind: 'wait', tool: null }
355    case 'COMPLETED': return { kind: 'done', tool: null }
356    case 'CANCELLED': return { kind: 'stop', tool: null }
357    case 'FAILED':
358    case 'EMPTY':
359    case 'TIMEOUT':
360    case 'LOST': return { kind: 'fail', tool: null }
361    case 'RUNNING': {
362      const a = slot.activity
363      if (a === null) return { kind: 'idle', tool: null }
364      if (a === 'thinking') return { kind: 'think', tool: null }
365      if (a === 'finishing') return { kind: 'finish', tool: null }
366      if (a === 'background') return { kind: 'background', tool: null }
367      return { kind: 'tool', tool: a }
368    }
369    default: return { kind: 'idle', tool: null }
370  }
371}
372
373/** A recent step's kind on the trail: the words a model writes and its thinking are told apart. */
374const RECENT_KIND: Readonly<Record<ClaudishRecentStep['kind'], ClaudishTrailKind>> = { text: 'say', thinking: 'think', tool: 'tool', ask: 'wait' }
375
376/** A failed slot's line on its trail: the reason, then the provider's words when claudish sends them. */
377function failText(slot: ClaudishSlot): string | undefined {
378  const reason = slot.reason ?? ''
379  if (slot.detail) return reason ? `${reason}: ${slot.detail}` : slot.detail
380  return reason || undefined
381}
382
383const isFinal = (k: ClaudishTrailKind) => k === 'done' || k === 'fail' || k === 'stop'
384
385/**
386 * Each slot's trail with this tick's observation. When claudish sends `recent`, its steps (with
387 * their words and exact times) stand for the current turn: steps older than its first one stay,
388 * the rest is replaced. Without it, a new step when the kind or the tool changes, or when the
389 * tool-call count rose (the same tool again is a new call). An ended slot gets one final step.
390 * The previous trails themselves when nothing changed.
391 */
392export function nextTrails(
393  prev: Readonly<Record<string, ClaudishTrailStep[]>> | undefined,
394  before: readonly ClaudishSlot[],
395  slots: readonly ClaudishSlot[],
396  now: number,
397): Record<string, ClaudishTrailStep[]> | undefined {
398  let out: Record<string, ClaudishTrailStep[]> | undefined = prev ? { ...prev } : undefined
399  let changed = false
400  const put = (slot: string, trail: ClaudishTrailStep[]) => {
401    out = out ?? {}
402    out[slot] = trail.slice(-TRAIL_MAX_STEPS)
403    changed = true
404  }
405  for (const s of slots) {
406    if (s.slot === '*') continue
407    const trail = out?.[s.slot] ?? []
408    const last = trail[trail.length - 1]
409    if (last && isFinal(last.kind)) continue // ended: final
410    const { kind, tool } = trailKindOf(s)
411    if (s.recent && s.recent.length > 0) {
412      const first = s.recent[0]!.at
413      const turn = s.recent.map(r => ({ at: r.at, kind: RECENT_KIND[r.kind], tool: r.tool, text: r.summary }))
414      const next = [...trail.filter(t => t.at < first), ...turn]
415      if (isFinal(kind)) next.push({ at: now, kind, tool: null, ...(kind === 'fail' && failText(s) ? { text: failText(s)! } : {}) })
416      const same = next.length === trail.length && next.every((t, i) => t.at === trail[i]!.at && t.kind === trail[i]!.kind && t.text === trail[i]!.text)
417      if (!same) put(s.slot, next)
418      continue
419    }
420    const was = before.find(b => b.slot === s.slot)
421    const newCall = kind === 'tool' && was?.toolCalls !== null && s.toolCalls !== null && was !== undefined && s.toolCalls > (was.toolCalls ?? 0)
422    if (last && last.kind === kind && last.tool === tool && !newCall) continue
423    const final = isFinal(kind)
424    if (trail.length >= TRAIL_MAX_STEPS && !final) continue
425    put(s.slot, [...trail, { at: now, kind, tool, ...(kind === 'fail' && failText(s) ? { text: failText(s)! } : {}) }])
426  }
427  return changed ? out : prev as Record<string, ClaudishTrailStep[]> | undefined
428}
429
430function mergeOk(prev: ClaudishRun, observed: readonly ClaudishSlot[], now: number): ClaudishRun {
431  // LOST is terminal and final in the mod: a slot that reappears keeps it.
432  const seen = observed.map(s => {
433    const p = prev.slots.find(x => x.slot === s.slot)
434    return p?.state === 'LOST' ? p : s
435  })
436  // A slot the answer no longer lists keeps what it last showed, until the missing bound.
437  const kept = prev.slots.filter(p => !seen.some(s => s.slot === p.slot))
438  let slots = [...seen, ...kept]
439
440  // One clock per slot whose state cannot be read: an unknown state word, or a live slot
441  // its still-listed run stopped listing (else it would show running forever).
442  const unknownSince: Record<string, number> = {}
443  let lostReason = prev.lostReason
444  slots = slots.map(s => {
445    const missing = kept.includes(s) && !isTerminal(s.state)
446    if (s.state !== 'UNKNOWN' && !missing) return s
447    const since = prev.unknownSince[s.slot] ?? now
448    if (now - since >= (missing ? MISSING_LOST_MS : UNKNOWN_LOST_MS)) {
449      lostReason = lostReason ?? (missing ? 'slot missing' : 'unknown state')
450      return lostSlot(s)
451    }
452    unknownSince[s.slot] = since
453    return s
454  })
455
456  const run: ClaudishRun = {
457    ...prev,
458    slots,
459    unknownSince,
460    lostReason,
461    missedPolls: 0,
462    missingSince: null,
463    unreachableSince: null,
464    activityAt: isActivity(prev.slots, slots) ? now : prev.activityAt,
465    waits: prev.ref.kind === 'delegation' ? nextWaits(prev.waits, slots) : prev.waits,
466  }
467  const trails = nextTrails(prev.trails, prev.slots, slots, now)
468  if (trails !== undefined) run.trails = trails
469  return settle(run, now)
470}
471
472/**
473 * The next record of one run from what this tick observed. Returns `prev` itself when
474 * no persisted field changed, so an unchanged tick writes nothing.
475 */
476export function mergeRun(prev: ClaudishRun, observed: RunObservation, now: number): ClaudishRun {
477  if (prev.settledAt !== null) return prev
478  let next: ClaudishRun
479  switch (observed.kind) {
480    case 'ok':
481      next = mergeOk(prev, observed.slots, now)
482      break
483    case 'missing': {
484      const missedPolls = prev.missedPolls + 1
485      const missingSince = prev.missingSince ?? now
486      next = { ...prev, missedPolls, missingSince }
487      if (missedPolls >= MISSING_LOST_POLLS && now - missingSince >= MISSING_LOST_MS) {
488        next = settle(applyLost(next, prev.slots.length === 0 ? 'never listed' : 'vanished'), now)
489      }
490      break
491    }
492    case 'unreachable': {
493      const unreachableSince = prev.unreachableSince ?? now
494      next = { ...prev, unreachableSince }
495      if (now - unreachableSince >= UNREACHABLE_LOST_MS) next = settle(applyLost(next, 'unreachable'), now)
496      break
497    }
498    case 'withdrawn':
499      next = settle(applyLost(prev, 'contract withdrawn'), now)
500      break
501    default:
502      return assertNever(observed)
503  }
504  return sameData(prev, next) ? prev : next
505}
506
507export function assertNever(x: never): never {
508  throw new Error(`unexpected value: ${JSON.stringify(x)}`)
509}
510
511// ── wake units ────────────────────────────────────────────────────────────────
512
513export type WakeUnit = { key: string; state: ClaudishSlotState }
514
515function waitEntryState(w: ClaudishWait, n: number): ClaudishSlotState {
516  const state = n === w.entries && w.sig !== null ? w.sig.slice(0, w.sig.indexOf('|')) : ''
517  return state === 'AWAITING_PERMISSION' ? 'AWAITING_PERMISSION' : 'AWAITING_INPUT'
518}
519
520/**
521 * Every wake unit the given (drawn) runs owe: the terminal key of each terminal slot, and
522 * the key of every wait entry 1..entries of each slot whatever it is doing now. The ledger
523 * decides which are new; this only lists them, so an entry a throwing tick never noticed is
524 * listed again on the next.
525 */
526export function wakeUnits(runs: readonly ClaudishRun[]): WakeUnit[] {
527  const out: WakeUnit[] = []
528  for (const run of runs) {
529    for (const [slot, w] of Object.entries(run.waits)) {
530      for (let n = 1; n <= w.entries; n++) out.push({ key: waitKey(run.id, slot, n), state: waitEntryState(w, n) })
531    }
532    for (const s of run.slots) if (isTerminal(s.state)) out.push({ key: slotKey(run.id, s.slot), state: s.state })
533  }
534  return out
535}
536
537/** The person's Stop provenance on one slot, set or removed; the same value when nothing changes. */
538export function withPersonStop(runs: ClaudishRuns, id: string, slot: string, on: boolean): ClaudishRuns {
539  let changed = false
540  const list = runs.list.map(r => {
541    if (r.id !== id || r.personStops.includes(slot) === on) return r
542    changed = true
543    return { ...r, personStops: on ? [...r.personStops, slot] : r.personStops.filter(s => s !== slot) }
544  })
545  return changed ? { ...runs, list } : runs
546}
547
548// ── stop requests ─────────────────────────────────────────────────────────────
549
550/**
551 * Drops each stop request whose run is gone or whose slot is terminal, and each `sent`
552 * one answered more than STOP_SENT_TIMEOUT_MS ago while its slot is still live (those are
553 * returned, so the caller can say so). A `sending` one is never timed out: its cancel has
554 * not answered, and Claude Code's own permission question may still be open.
555 */
556export function pruneStops(
557  stops: Readonly<Record<string, ClaudishStopRequest>>,
558  runs: ClaudishRuns,
559  now: number,
560): readonly [Record<string, ClaudishStopRequest>, string[]] {
561  const next: Record<string, ClaudishStopRequest> = {}
562  const timedOut: string[] = []
563  let changed = false
564  for (const [key, req] of Object.entries(stops)) {
565    const cut = key.indexOf('/')
566    const run = runs.list.find(r => r.id === key.slice(0, cut))
567    const slot = run?.slots.find(s => s.slot === key.slice(cut + 1))
568    if (!run || cut < 0 || (slot && isTerminal(slot.state))) {
569      changed = true
570      continue
571    }
572    if (req.kind === 'sent' && now - req.at > STOP_SENT_TIMEOUT_MS) {
573      timedOut.push(key)
574      changed = true
575      continue
576    }
577    next[key] = req
578  }
579  return [changed ? next : (stops as Record<string, ClaudishStopRequest>), timedOut] as const
580}
581
582// ── compaction ────────────────────────────────────────────────────────────────
583
584export type Compaction = { drop: ReadonlySet<string>; added: ClaudishEarlier }
585
586/**
587 * Past RUNS_CAP runs, the oldest settled runs whose ledger entries are all delivered
588 * fold into the `earlier` counters (`added` is what to add). A run with any undelivered
589 * entry is never compacted. `starts` is never touched, so a later start never reuses a
590 * generation already shown.
591 */
592export function compaction(runs: ClaudishRuns, ledger: ClaudishLedger): Compaction | null {
593  const excess = runs.list.length - RUNS_CAP
594  if (excess <= 0) return null
595  const drop = new Set<string>()
596  const added: ClaudishEarlier = { runs: 0, done: 0, failed: 0, stopped: 0 }
597  for (const run of runs.list) {
598    if (drop.size >= excess) break
599    if (run.settledAt === null) continue
600    const prefix = `${run.id}/`
601    const owed = Object.entries(ledger.entries).some(([k, e]) => k.startsWith(prefix) && e.kind !== 'delivered')
602    if (owed) continue
603    drop.add(run.id)
604    added.runs += 1
605    for (const s of run.slots) {
606      if (s.state === 'COMPLETED') added.done += 1
607      else if (s.state === 'CANCELLED') added.stopped += 1
608      else added.failed += 1
609    }
610  }
611  return drop.size === 0 ? null : { drop, added }
612}
613
614export function withoutRuns(runs: ClaudishRuns, drop: ReadonlySet<string>): ClaudishRuns {
615  return { ...runs, list: runs.list.filter(r => !drop.has(r.id)) }
616}
617
618export function withoutLedgerKeys(ledger: ClaudishLedger, drop: ReadonlySet<string>): ClaudishLedger {
619  const entries: ClaudishLedger['entries'] = {}
620  for (const [k, e] of Object.entries(ledger.entries)) {
621    if (!drop.has(k.slice(0, k.indexOf('/')))) entries[k] = e
622  }
623  return { ...ledger, entries }
624}
625
hooks/status/layout.ts 927 lines
1// Pure layout: the band's rows, header and column plan (fitted to the band's own width),
2// and a Show tab's viewport, colour spelling and style budget. Values in, values out:
3// no engine interface, no state reference, no claudish vocabulary. The tree builders
4// (band.tsx, pane.tsx) draw exactly what these return.
5
6import type { Color } from 'claude-code'
7import type {
8  ClaudishColor,
9  ClaudishEarlier,
10  ClaudishFeedSupport,
11  ClaudishFrame,
12  ClaudishLedger,
13  ClaudishPaneView,
14  ClaudishRun,
15  ClaudishRunRef,
16  ClaudishRuns,
17  ClaudishSlot,
18  ClaudishSlotState,
19  ClaudishStopRequest,
20  ClaudishStyleSpan,
21  ClaudishTrailKind,
22} from '../../types'
23import {
24  NO_CAPTURE_NOTE,
25  PAINT_SURFACES,
26  PANE_LINE_COST,
27  PANE_SEGMENT_COST,
28  PANE_STYLE_BUDGET,
29  STALE_NUMBER_S,
30  STALE_STEPS_S,
31  STATE_LOOK,
32  batchAgent,
33  feedKey,
34  isDrawn,
35  shownRuns,
36  isTerminal,
37  isWaiting,
38  lookOf,
39  runLabel,
40  paneId,
41  slotAgent,
42  slotKey,
43  type BadgeTone,
44  type BatchAgent,
45  type Group,
46  type SlotAgent,
47  type StatusColor,
48} from './domain'
49import type { Hue } from './palette'
50
51// ── shared ────────────────────────────────────────────────────────────────────
52
53/** One run of text in the mod's own drawing: theme keys only. */
54export type Segment = { text: string; color?: StatusColor; backgroundColor?: StatusColor; dim?: true; bold?: true }
55
56/** What a Stop or Show press acts on: values the render read. */
57export type SlotTarget = { runId: string; epoch: number; ref: ClaudishRunRef; slot: string; model: string; label: string }
58
59const DASH = '—'
60
61/** A count in at most 6 cells: 850, 12.0k, 2.3M; null → —. */
62export function count(n: number | null): string {
63  if (n === null) return DASH
64  // At most 4 characters past the arrow: a decimal only where it is one of three digits.
65  const a = Math.abs(n)
66  return a < 1000 ? String(Math.round(n)) : a < 9_950 ? `${(n / 1000).toFixed(1)}k` : a < 999_500 ? `${Math.round(n / 1000)}k` : `${(n / 1_000_000).toFixed(1)}M`
67}
68
69/** The provider as the band shows it: claudish's `Anthropic (Native)` reads `Anthropic`. The cost
70 *  cell still reads claudish's own name, where "native" means a subscription. */
71export function providerName(provider: string | null | undefined): string {
72  return (provider ?? '').replace(/\s*\(native\)\s*$/i, '')
73}
74
75/** A cost in at most 6 cells: `<$0.01`, `$0.42`, `$12.3`, `$123`; null → —. */
76export function dollars(usd: number | null | undefined): string {
77  if (typeof usd !== 'number' || !Number.isFinite(usd) || usd < 0) return DASH // undefined: a slot recorded before costs were read
78  if (usd === 0) return '$0'
79  if (usd < 0.01) return '<$0.01'
80  return usd < 10 ? `$${usd.toFixed(2)}` : usd < 100 ? `$${usd.toFixed(1)}` : `$${Math.round(usd)}`
81}
82
83/**
84 * The cost cell: dollars when claudish reports a charge; `SUB` when the slot runs on a subscription
85 * (claudish reports 0, or a native Claude model, which it reports no cost for); — when unknown.
86 */
87function costCell(slot: ClaudishSlot): string {
88  if (slot.costUsd === 0 || ((slot.costUsd ?? null) === null && /native/i.test(slot.provider ?? ''))) return SUB
89  return dollars(slot.costUsd)
90}
91const SUB = 'SUB'
92
93/** Tokens as two values, each in its own unit: `↑12.7k ↓780`, in (sent to the model) then out. Both unknown → —. */
94export function tokenIO(tokensIn: number | null, tokensOut: number | null): string {
95  if (tokensIn === null && tokensOut === null) return DASH
96  return `↑${count(tokensIn)} ↓${count(tokensOut)}`
97}
98
99/** Tool calls and loops as a symbol and a number: `ƒ 8`, `↻ 1`; unknown → —. */
100export function tally(symbol: string, n: number | null): string {
101  return n === null ? DASH : `${symbol} ${n}`
102}
103
104/** 4 → 4s, 125 → 2m, 7300 → 2h; null → —. */
105export function age(seconds: number | null): string {
106  if (seconds === null) return DASH
107  const s = Math.max(0, Math.floor(seconds))
108  if (s < 60) return `${s}s`
109  if (s < 3600) return `${Math.floor(s / 60)}m`
110  return `${Math.floor(s / 3600)}h`
111}
112
113/**
114 * A runtime in at most 5 cells, as tt draws it: 42s, 17m, 3h12m below ten hours, 13h below
115 * a day, 6d02h below ten days, 12d beyond. Null (no start time) is —, never a fake 0.
116 */
117export function runtime(ms: number | null): string {
118  if (ms === null) return DASH
119  const s = Math.max(0, Math.floor(ms / 1000))
120  const m = Math.floor(s / 60)
121  const h = Math.floor(m / 60)
122  const d = Math.floor(h / 24)
123  if (s < 60) return `${s}s`
124  if (m < 60) return `${m}m`
125  if (h < 10) return `${h}h${String(m % 60).padStart(2, '0')}m`
126  if (h < 24) return `${h}h`
127  if (d < 10) return `${d}d${String(h % 24).padStart(2, '0')}h`
128  return `${Math.min(d, 999)}d`
129}
130
131/** Cut to `width` characters, ending in … when cut. */
132export function cut(text: string, width: number): string {
133  if (width <= 0) return ''
134  const chars = Array.from(text)
135  return chars.length <= width ? text : `${chars.slice(0, Math.max(0, width - 1)).join('')}…`
136}
137
138function pad(text: string, width: number): string {
139  const n = Array.from(text).length
140  return n >= width ? text : text + ' '.repeat(width - n)
141}
142
143function padStart(text: string, width: number): string {
144  const n = Array.from(text).length
145  return n >= width ? text : ' '.repeat(width - n) + text
146}
147
148/** The state a row draws: a live slot of an unreachable run is `unknown`, never its stale state. */
149function shownState(run: ClaudishRun, slot: ClaudishSlot): ClaudishSlotState {
150  return run.unreachableSince !== null && !isTerminal(slot.state) ? 'UNKNOWN' : slot.state
151}
152
153/** The activity column: what a live slot does, or why a terminal one ended (not a repeat of its badge). */
154function activityOf(run: ClaudishRun, slot: ClaudishSlot, state: ClaudishSlotState): string {
155  if (state === 'UNKNOWN' && run.unreachableSince !== null) return ''
156  if (!isTerminal(state)) return slot.activity ?? ''
157  if (state === 'LOST') return slot.reason ?? run.lostReason ?? ''
158  const reason = slot.reason ?? ''
159  if (slot.detail) return reason ? `${reason}: ${slot.detail}` : slot.detail // the provider's own words beat the code
160  return reason === 'cancelled' || reason === 'timeout' || reason === 'shape_mismatch' ? '' : reason
161}
162
163/** How long a slot has run: to now while live, to its last activity once it ended. */
164function slotRuntime(run: ClaudishRun, slot: ClaudishSlot, now: number): number | null {
165  if (run.startedAt === undefined) return null
166  const end = isTerminal(slot.state) ? (slot.lastActivityAt ?? run.settledAt) : now
167  return end === null ? null : Math.max(0, end - run.startedAt)
168}
169
170/**
171 * The stale-meter: how long a running slot has been silent, as cells filled; none for any other
172 * slot. Under STALE_NUMBER_S of silence the slot is streaming: `flowing`, which the band animates.
173 * `idle` is the silence in whole seconds, from which the band counts on between polls.
174 */
175export type Meter = { filled: number; number: string; color: StatusColor; flowing: boolean; idle: number }
176export const METER_CELLS = STALE_STEPS_S.length
177/** A space and up to three characters of silence (`59s`, `12m`). */
178const METER_NUMBER_CELLS = 4
179
180/** One step of a slot's timeline as the live cell takes it: ms from the run's start, its kind, the tool, its line. */
181export type TrailMark = { t: number; k: ClaudishTrailKind; tool: string; x: string }
182/**
183 * A slot's timeline: its last TRAIL_SHOWN steps; how long the run has gone (to now while live, to
184 * its end once ended); the silence in whole seconds while live; how long ago it ended.
185 */
186export type TrailView = { steps: TrailMark[]; elapsed: number; live: boolean; idle: number; endedFor: number }
187
188/** Steps the live cell receives: more than either look draws, so a long trail costs the cell nothing. */
189export const TRAIL_SHOWN = 40
190
191/** The slot's timeline, or null when nothing was recorded for it. */
192export function trailView(run: ClaudishRun, slot: ClaudishSlot, now: number): TrailView | null {
193  const steps = run.trails?.[slot.slot]
194  if (!steps || steps.length === 0) return null
195  const start = Math.min(run.startedAt ?? steps[0]!.at, steps[0]!.at)
196  const last = steps[steps.length - 1]!
197  const live = !isTerminal(slot.state)
198  const end = live ? now : last.at
199  const cut = Math.max(0, steps.length - TRAIL_SHOWN)
200  return {
201    steps: steps.slice(cut).map(s => ({ t: Math.max(0, s.at - start), k: s.kind, tool: s.tool ?? '', x: s.text ?? '' })),
202    elapsed: Math.max(1, end - start),
203    live,
204    idle: live && slot.idleSeconds !== null ? Math.max(0, Math.floor(slot.idleSeconds)) : 0,
205    endedFor: live ? 0 : Math.max(0, now - last.at),
206  }
207}
208
209export function staleMeter(slot: ClaudishSlot, state: ClaudishSlotState): Meter | null {
210  if (state !== 'RUNNING' || slot.idleSeconds === null) return null
211  const idle = Math.max(0, Math.floor(slot.idleSeconds))
212  if (idle < STALE_NUMBER_S) return { filled: 0, number: '', color: 'success', flowing: true, idle }
213  const filled = STALE_STEPS_S.filter(s => idle >= s).length
214  return { filled, number: age(idle), color: meterColor(filled), flowing: false, idle }
215}
216
217/** Green while the silence is short, amber from a minute (three cells), red from two (all five). */
218export function meterColor(filled: number): StatusColor {
219  return filled >= METER_CELLS ? 'error' : filled >= 3 ? 'warning' : 'success'
220}
221
222/** The meter's cells as text: ▰ for each filled cell, ▱ for the rest. */
223export function meterCells(m: Meter): string {
224  return '▰'.repeat(m.filled) + '▱'.repeat(METER_CELLS - m.filled)
225}
226
227export { isDrawn, shownRuns }
228
229// ── band ──────────────────────────────────────────────────────────────────────
230
231export type StopCell = 'stop' | 'confirm' | 'stopping' | 'none'
232
233/** A row's status badge: the code on its hue's solid fill, then the runtime on its quiet fill. */
234export type Badge = { code: string; runtime: string; hue: Hue }
235
236const HUE_OF: Readonly<Record<BadgeTone, Hue>> = {
237  run: 'run', ask: 'ask', done: 'done', fail: 'fail', format: 'format', stopped: 'stopped', unclear: 'stopped',
238}
239
240export type BandRow = {
241  /** `${runId}/${slot}`, or `${runId}/` for a run not listed yet */
242  key: string
243  attention: boolean
244  id: string
245  badge: Badge
246  word: string
247  /** the header word it counts under */
248  group: Group
249  model: string
250  provider: string
251  /** `↑12.7k` and `↓780`, the two halves of the tokens badge. tokensOut empty: no badge, tokensIn drawn
252   *  alone (— when both are unknown, empty for a run not listed yet) */
253  tokensIn: string
254  tokensOut: string
255  /** the counts after the ƒ and ↻ marks: `8`, or — when unknown; empty for a run not listed yet */
256  tools: string
257  loops: string
258  /** `$0.12`, — when unknown or billed by a subscription; empty for a run not listed yet */
259  cost: string
260  meter: Meter | null
261  /** the slot's timeline, for the live cell; null for a run not listed yet */
262  trail: TrailView | null
263  activity: string
264  /** the agent cell: '' unless the batch is mixed or the row's agent disagrees */
265  agent: string
266  /** the cell is a disagreement (drawn in the warning colour) */
267  agentMismatch: boolean
268  stop: StopCell
269  show: boolean
270  /** the open Show panel is on this slot's tab */
271  active: boolean
272  terminal: boolean
273  /** when a terminal row ended (its last activity), for the most-recent-first order; null when unknown */
274  endedAt: number | null
275  target: SlotTarget
276}
277
278/** Cells per column; 0 = dropped. `badge` is BADGE_CELLS (code and runtime) or CODE_CELLS (code alone). */
279export type ColumnPlan = {
280  lead: number; id: number; badge: number; model: number; provider: number; tokens: number
281  tools: number; loops: number; cost: number; agent: number; meter: number; activity: number; stop: number; show: number
282  /** the in half's share of `tokens`: the two halves are one block, so this is not a column */
283  tokensIn: number
284}
285
286const COLUMNS = ['lead', 'id', 'badge', 'model', 'provider', 'tokens', 'tools', 'loops', 'cost', 'agent', 'meter', 'activity', 'stop', 'show'] as const
287
288export type BandModel = {
289  header: Segment[]
290  /** null: the band is too narrow for any row, so it draws the header alone */
291  plan: ColumnPlan | null
292  rows: BandRow[]
293  /** `+N more: …` when terminal rows were folded for height */
294  more: string | null
295  /** the Show panel is open: the header carries its Hide button */
296  panelOpen: boolean
297}
298
299export type BandInput = {
300  runs: ClaudishRuns
301  feeds: Readonly<Record<string, ClaudishFeedSupport>>
302  stops: Readonly<Record<string, ClaudishStopRequest>>
303  ledger: ClaudishLedger
304  earlier: ClaudishEarlier
305  bodyColumns: number
306  maxRows: number
307  /** the clock, for each live slot's runtime */
308  now: number
309  /** the Show panel: whether it is open, and which slot's tab (a tab id) it shows */
310  panel: { open: boolean; active: string | null }
311}
312
313/** ` RUN ` then ` 3h12m `: one cell each side of a 3-cell code and a 5-cell runtime, as tt's badge. */
314export const CODE_CELLS = 5
315export const RUNTIME_CELLS = 7
316const BADGE_CELLS = CODE_CELLS + RUNTIME_CELLS
317export const STOP_CELLS = 9 // `[ Stop? ]`
318export const SHOW_CELLS = 8 // `[ Show ]`, `[ Hide ]`
319/** The marks before the tool-call and loop counts. */
320export const TOOLS_MARK = 'ƒ'
321export const LOOPS_MARK = '↻'
322/** A badge half's padding (one cell each side), and a mark, which its number follows with no space (`ƒ8`). */
323const PAD = 2
324const MARK_CELLS = 1
325const ID_MIN = 2
326const MODEL_MIN = 8
327const MODEL_MAX = 28
328const PROVIDER_MAX = 18
329const ACTIVITY_MIN = 12
330/** An agent cell on a row: room for `requested dev:reviewer, loaded none`; cut to AGENT_MIN before the stats go. */
331const AGENT_MAX = 40
332const AGENT_MIN = 12
333/** The agent name in the header, cut with … past this. */
334const AGENT_HEADER_MAX = 32
335export const LEAD_CELLS = 2
336
337const GROUPS: readonly Group[] = ['needs you', 'running', 'done', 'wrong format', 'failed', 'stopped']
338
339/** A row's agent cell: empty unless the batch is mixed or this row's agent disagrees (a single agent is the header's). */
340export function rowAgentText(agent: SlotAgent, batch: BatchAgent): string {
341  if (agent.mismatch) return `requested ${agent.requested}, loaded ${agent.loaded ?? 'none'}`
342  if (batch.kind === 'mixed') return agent.name ?? 'no agent'
343  return ''
344}
345
346function rowsOf(input: BandInput, drawn: readonly ClaudishRun[], batch: BatchAgent): BandRow[] {
347  const severalRuns = drawn.length > 1
348  const rows: BandRow[] = []
349  for (const run of drawn) {
350    const label = runLabel(run)
351    const support = input.feeds[feedKey(run.ref)]
352    const canCancel = support?.kind === 'speaks' && support.can.cancel
353    if (run.slots.length === 0) {
354      const look = STATE_LOOK.STARTING
355      rows.push({
356        key: `${run.id}/`, attention: false, id: label,
357        badge: { code: look.code, runtime: runtime(run.startedAt === undefined ? null : input.now - run.startedAt), hue: HUE_OF[look.tone] },
358        word: look.word, group: look.group,
359        model: '', provider: '', tokensIn: '', tokensOut: '', tools: '', loops: '', cost: '', meter: null, trail: null, activity: '',
360        agent: '', agentMismatch: false,
361        stop: 'none', show: false, active: false, terminal: false, endedAt: null,
362        target: { runId: run.id, epoch: run.epoch, ref: run.ref, slot: '', model: '', label },
363      })
364      continue
365    }
366    for (const slot of run.slots) {
367      const state = shownState(run, slot)
368      const look = lookOf(state, slot.reason)
369      const key = slotKey(run.id, slot.slot)
370      const req = input.stops[key]
371      const terminal = isTerminal(slot.state)
372      const stop: StopCell = terminal || !canCancel ? 'none'
373        : req?.kind === 'armed' ? 'confirm'
374        : req?.kind === 'sending' || req?.kind === 'sent' ? 'stopping'
375        : 'stop'
376      const id = run.ref.kind === 'delegation' ? label
377        : severalRuns ? `${label}/${slot.slot}`
378        : slot.slot
379      const trail = trailView(run, slot, input.now)
380      const agent = slotAgent(slot)
381      rows.push({
382        key,
383        attention: isWaiting(state),
384        id,
385        badge: { code: look.code, runtime: runtime(slotRuntime(run, slot, input.now)), hue: HUE_OF[look.tone] },
386        word: look.word,
387        group: look.group,
388        model: slot.model,
389        provider: providerName(slot.provider),
390        // Both unknown: one — and no badge (tokensOut empty), as the Show tab reads it.
391        tokensIn: slot.tokensIn === null && slot.tokensOut === null ? DASH : `↑${count(slot.tokensIn)}`,
392        tokensOut: slot.tokensIn === null && slot.tokensOut === null ? '' : `↓${count(slot.tokensOut)}`,
393        tools: slot.toolCalls === null ? DASH : String(slot.toolCalls),
394        loops: slot.turnsCompleted === null ? DASH : String(slot.turnsCompleted),
395        cost: costCell(slot),
396        meter: staleMeter(slot, state),
397        trail,
398        // A row drawn as a timeline says what it does there; the column is for a row without one.
399        activity: trail ? '' : activityOf(run, slot, state),
400        agent: rowAgentText(agent, batch),
401        agentMismatch: agent.mismatch,
402        stop,
403        show: slot.slot !== '*',
404        active: input.panel.open && input.panel.active === paneId(run.id, slot.slot),
405        terminal,
406        endedAt: terminal ? slot.lastActivityAt : null,
407        target: { runId: run.id, epoch: run.epoch, ref: run.ref, slot: slot.slot, model: slot.model, label },
408      })
409    }
410  }
411  // Attention first, then live, then terminal rows, the most recently ended first (by run when unknown).
412  const order = (r: BandRow) => (r.attention ? 0 : r.terminal ? 2 : 1)
413  const runIndex = new Map(drawn.map((r, i) => [r.id, i]))
414  return rows
415    .map((r, i) => ({ r, i }))
416    .sort((a, b) => {
417      const oa = order(a.r)
418      const ob = order(b.r)
419      if (oa !== ob) return oa - ob
420      if (oa === 2) {
421        const ea = a.r.endedAt
422        const eb = b.r.endedAt
423        if (ea !== null && eb !== null && ea !== eb) return eb - ea
424        const ra = runIndex.get(a.r.target.runId) ?? 0
425        const rb = runIndex.get(b.r.target.runId) ?? 0
426        if (ra !== rb) return rb - ra
427      }
428      return a.i - b.i
429    })
430    .map(x => x.r)
431}
432
433function width(texts: readonly string[], max = Infinity): number {
434  return Math.min(max, texts.reduce((m, t) => Math.max(m, Array.from(t).length), 0))
435}
436
437/** The row's width: each column and one gap between columns. The provider is the model badge's second half, so no gap. */
438/** Tokens, tool calls, loops and cost: one block of badges, joined with no gap between them. */
439const STATS = ['tokens', 'tools', 'loops', 'cost'] as const
440
441function total(plan: ColumnPlan): number {
442  // The provider and the stats block join the model badge with no gap: one block from model to cost.
443  const stats = STATS.reduce((sum, k) => sum + plan[k], 0)
444  const cols = COLUMNS.filter(k => k !== 'provider' && !(STATS as readonly string[]).includes(k)).map(k => plan[k]).filter(w => w > 0)
445  return cols.reduce((sum, w) => sum + w, 0) + Math.max(0, cols.length - 1) + plan.provider + stats
446}
447
448/** The meter column's text for one row: the cells, then the silence once it is worth a number. */
449function meterText(m: Meter | null): string {
450  return m === null ? '' : m.number === '' ? meterCells(m) : `${meterCells(m)} ${m.number}`
451}
452
453/**
454 * Drops columns in a fixed priority until the row fits `bodyColumns`: activity, provider, loops,
455 * tool calls, tokens; the agent shrinks to 12; cost, the meter; then the badge loses its runtime,
456 * the agent goes, the id shrinks to 2, and last the model shrinks to 8. The model is never
457 * dropped: it is what the row is about. Below that floor, null: header alone.
458 */
459export function fitColumns(bodyColumns: number, rows: readonly BandRow[]): ColumnPlan | null {
460  const content = {
461    id: width(rows.map(r => r.id)),
462    model: width(rows.map(r => r.model), MODEL_MAX),
463    provider: width(rows.map(r => r.provider), PROVIDER_MAX),
464    tokensIn: width(rows.map(r => r.tokensIn)),
465    tokensOut: width(rows.map(r => r.tokensOut)),
466    tools: width(rows.map(r => r.tools)),
467    loops: width(rows.map(r => r.loops)),
468    cost: width(rows.map(r => r.cost)),
469    // A live meter counts on between polls (flow.tsx), so its column keeps room for the number.
470    meter: Math.max(width(rows.map(r => meterText(r.meter))), rows.some(r => r.meter !== null || r.trail !== null) ? METER_CELLS + METER_NUMBER_CELLS : 0),
471    activity: width(rows.map(r => r.activity)),
472    agent: width(rows.map(r => r.agent), AGENT_MAX),
473  }
474  const plan: ColumnPlan = {
475    lead: LEAD_CELLS, id: content.id, badge: BADGE_CELLS,
476    model: content.model > 0 ? content.model + PAD : 0, provider: content.provider > 0 ? content.provider + PAD : 0,
477    // No row with an out half (both counts unknown everywhere): one part, so one padding.
478    tokens: content.tokensIn > 0 ? content.tokensIn + PAD + (content.tokensOut > 0 ? content.tokensOut + PAD : 0) : 0,
479    tokensIn: content.tokensIn + PAD,
480    tools: content.tools > 0 ? MARK_CELLS + content.tools + PAD : 0,
481    loops: content.loops > 0 ? MARK_CELLS + content.loops + PAD : 0,
482    cost: content.cost > 0 ? content.cost + PAD : 0,
483    // Plain text, as the activity; 0 for a batch whose agent is the header's, so no column and no gap.
484    agent: content.agent,
485    meter: content.meter,
486    activity: Math.min(content.activity, ACTIVITY_MIN),
487    // No row can be stopped (the run ended): the Stop column gives its room to the timeline.
488    stop: rows.some(r => r.stop !== 'none') ? STOP_CELLS : 0, show: SHOW_CELLS,
489  }
490  const steps: ((p: ColumnPlan) => void)[] = [
491    p => { p.activity = 0 },
492    p => { p.provider = 0 },
493    p => { p.loops = 0 },
494    p => { p.tools = 0 },
495    p => { p.tokens = 0 },
496    p => { p.agent = Math.min(p.agent, AGENT_MIN) },
497    p => { p.cost = 0 },
498    p => { p.meter = 0 },
499    p => { p.badge = CODE_CELLS },
500    p => { p.agent = 0 },
501    p => { p.id = Math.min(p.id, ID_MIN) },
502    p => { p.model = Math.min(p.model, MODEL_MIN + PAD) },
503  ]
504  for (const step of [null, ...steps]) {
505    step?.(plan)
506    if (total(plan) <= bodyColumns) {
507      // The activity column takes what is left, up to its content.
508      if (plan.activity > 0) plan.activity = Math.min(content.activity, plan.activity + bodyColumns - total(plan))
509      // A timeline takes the rest exactly: its module draws as wide as it is told, so a region
510      // left to size itself pushes the id, status and model columns out of the row.
511      if (plan.meter > 0 && rows.some(r => r.trail !== null)) plan.meter += Math.max(0, bodyColumns - total(plan))
512      return plan
513    }
514  }
515  return null
516}
517
518function headerOf(rows: readonly BandRow[], input: BandInput, shown: readonly ClaudishRun[], older: number, batch: BatchAgent): Segment[] {
519  const counts = new Map<string, number>()
520  for (const r of rows) {
521    counts.set(r.group, (counts.get(r.group) ?? 0) + 1)
522  }
523  const out: Segment[] = [{ text: '◆ claudish', color: 'claude', bold: true }]
524  const only = shown.length === 1 ? shown[0] : undefined
525  if (only && only.ref.kind === 'panel') out.push({ text: `  ${runLabel(only)}`, bold: true })
526  for (const g of GROUPS) {
527    const n = counts.get(g) ?? 0
528    if (n === 0) continue
529    out.push(g === 'needs you' ? { text: ` · ${n} needs you`, color: 'permission', bold: true }
530      : g === 'wrong format' ? { text: ` · ${n} wrong format`, color: 'warning' }
531      : { text: ` · ${n} ${g}`, dim: true })
532  }
533  // After the counts, so a narrow band cuts the agent before what asks for the person; before the
534  // notices and earlier runs, since it describes the shown batch, not those.
535  if (batch.kind === 'one') out.push({ text: ` · ${cut(batch.name, AGENT_HEADER_MAX)}` })
536  else if (batch.kind === 'mixed') out.push({ text: ' · mixed agents', dim: true })
537  const parked = Object.values(input.ledger.entries).filter(e => e.kind === 'parked').length
538  if (parked > 0) out.push({ text: ` · ${parked} ${parked === 1 ? 'notice' : 'notices'} not delivered`, color: 'error' })
539  const earlier = older + input.earlier.runs
540  if (earlier > 0) out.push({ text: ` · ${earlier} earlier ${earlier === 1 ? 'run' : 'runs'}`, dim: true })
541  return out
542}
543
544/**
545 * The band, or null when there is nothing to draw (no drawn run and nothing compacted).
546 * It draws the most recent run and any older run still live; rows fit `bodyColumns` (never
547 * wrapping); past `maxRows`, terminal rows fold into one line.
548 */
549export function bandModel(input: BandInput): BandModel | null {
550  const drawn = input.runs.list.filter(r => isDrawn(r, input.feeds))
551  if (drawn.length === 0 && input.earlier.runs === 0) return null
552  const { shown, older } = shownRuns(drawn)
553  // One batch for the one header: every slot under it, whichever run it belongs to (the Show tab reads the same).
554  const batch = bandAgent(input.runs, input.feeds)
555  const all = rowsOf(input, shown, batch)
556  const header = headerOf(all, input, shown, older, batch)
557  const plan = fitColumns(input.bodyColumns, all)
558  const panelOpen = input.panel.open
559  if (plan === null) return { header, plan: null, rows: [], more: null, panelOpen }
560  if (1 + all.length <= input.maxRows) return { header, plan, rows: all, more: null, panelOpen }
561  const kept = all.filter(r => !r.terminal)
562  const folded = all.filter(r => r.terminal)
563  if (folded.length === 0) return { header, plan, rows: all, more: null, panelOpen }
564  const by = new Map<string, number>()
565  for (const r of folded) {
566    by.set(r.group, (by.get(r.group) ?? 0) + 1)
567  }
568  const parts = GROUPS.filter(g => by.has(g)).map(g => `${by.get(g)} ${g}`)
569  return { header, plan, rows: kept, more: `+${folded.length} more: ${parts.join(' · ')}`, panelOpen }
570}
571
572/** One row's cells as drawn text, each cut and padded to its column. The badge halves carry their own padding. */
573export function rowCells(row: BandRow, plan: ColumnPlan): {
574  lead: string; id: string; code: string; runtime: string; model: string; provider: string
575  tokensIn: string; tokensOut: string; tools: string; loops: string; cost: string; agent: string; meter: string; meterNumber: string; activity: string
576} {
577  const fit = (text: string, w: number, right = false) => {
578    if (w <= 0) return ''
579    const c = cut(text, w)
580    return right ? padStart(c, w) : pad(c, w)
581  }
582  const m = row.meter
583  const meterNumber = m && m.number !== '' && plan.meter > METER_CELLS ? ` ${m.number}` : ''
584  return {
585    lead: row.attention ? '▌ ' : '  ',
586    id: fit(row.id, plan.id),
587    code: ` ${pad(cut(row.badge.code, CODE_CELLS - 2), CODE_CELLS - 2)} `,
588    runtime: plan.badge > CODE_CELLS ? ` ${padStart(cut(row.badge.runtime, RUNTIME_CELLS - 2), RUNTIME_CELLS - 2)} ` : '',
589    model: plan.model > 0 ? ` ${fit(row.model, plan.model - PAD)} ` : '',
590    provider: plan.provider > 0 ? ` ${fit(row.provider, plan.provider - PAD)} ` : '',
591    // The stats block: each part has one space on each side; the parts touch, fill to fill.
592    tokensIn: plan.tokens > 0 ? ` ${fit(row.tokensIn, (row.tokensOut === '' ? plan.tokens : plan.tokensIn) - PAD, true)} ` : '',
593    tokensOut: plan.tokens > 0 && row.tokensOut !== '' ? ` ${fit(row.tokensOut, plan.tokens - plan.tokensIn - PAD, true)} ` : '',
594    tools: plan.tools > 0 ? (row.tools === '' ? ' '.repeat(plan.tools) : ` ${TOOLS_MARK}${fit(row.tools, plan.tools - MARK_CELLS - PAD)} `) : '',
595    loops: plan.loops > 0 ? (row.loops === '' ? ' '.repeat(plan.loops) : ` ${LOOPS_MARK}${fit(row.loops, plan.loops - MARK_CELLS - PAD)} `) : '',
596    cost: plan.cost > 0 ? ` ${fit(row.cost, plan.cost - PAD, true)} ` : '',
597    agent: fit(row.agent, plan.agent),
598    meter: plan.meter <= 0 ? '' : m ? meterCells(m) : ' '.repeat(METER_CELLS),
599    meterNumber: pad(meterNumber, Math.max(0, plan.meter - METER_CELLS)),
600    activity: fit(row.activity, plan.activity),
601  }
602}
603
604/** The planned width of one row, gaps included. */
605export function planWidth(plan: ColumnPlan): number {
606  return total(plan)
607}
608
609// ── Show tab: fit, viewport, colours, budget ─────────────────────────────────
610
611export type PaneFit = { columns: number; rows: number; paint: boolean }
612
613const FALLBACK_COLUMNS = 80
614const FALLBACK_ROWS = 20
615
616function positive(v: unknown, fallback: number): number {
617  return typeof v === 'number' && Number.isFinite(v) && v >= 1 ? Math.floor(v) : fallback
618}
619
620/** The tab's room: its body width, and its height from the scroll window's rows (never a top-level field). */
621export function paneFit(props: { bodyColumns?: unknown; scroll?: { bodyRows?: unknown } | null }, surface: string): PaneFit {
622  return {
623    columns: positive(props.bodyColumns, FALLBACK_COLUMNS),
624    rows: positive(props.scroll?.bodyRows, FALLBACK_ROWS),
625    paint: PAINT_SURFACES.includes(surface),
626  }
627}
628
629/** claudish clamps a resize to at least this size; asking for less would only be clamped again. */
630export const CHILD_MIN_COLS = 40
631export const CHILD_MIN_ROWS = 24
632
633/**
634 * The terminal size a shown child is given: the tab's width, and its height less the header row
635 * (`fit` is the tab's fit, the tab strip already taken off). Clamped as claudish clamps, so a
636 * size already set compares equal and is not asked for again. A panel smaller than the minimum
637 * keeps cropping, as it did before resize existed.
638 */
639export function childSize(fit: PaneFit): { cols: number; rows: number } {
640  return { cols: Math.max(CHILD_MIN_COLS, fit.columns), rows: Math.max(CHILD_MIN_ROWS, fit.rows - 1) }
641}
642
643/** A child's colour as the engine takes a raw colour: `#rrggbb`. */
644export function colorSpelling(c: ClaudishColor): Color {
645  const hex = (r: number, g: number, b: number) => `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`
646  if ('rgb' in c) return `#${(c.rgb & 0xffffff).toString(16).padStart(6, '0')}`
647  const n = c.index
648  if (n >= 16 && n <= 231) {
649    const k = n - 16
650    const v = (x: number) => (x === 0 ? 0 : 55 + 40 * x)
651    return hex(v(Math.floor(k / 36)), v(Math.floor(k / 6) % 6), v(k % 6))
652  }
653  if (n >= 232 && n <= 255) {
654    const v = 8 + 10 * (n - 232)
655    return hex(v, v, v)
656  }
657  return `#${XTERM_16[Math.max(0, Math.min(15, n))]}`
658}
659
660const XTERM_16 = [
661  '000000', 'cd0000', '00cd00', 'cdcd00', '0000ee', 'cd00cd', '00cdcd', 'e5e5e5',
662  '7f7f7f', 'ff0000', '00ff00', 'ffff00', '5c5cff', 'ff00ff', '00ffff', 'ffffff',
663]
664
665/** One styled run of a frame line, its colours already spelled. */
666export type PaneSegment = { text: string; color?: Color; backgroundColor?: Color; bold?: true }
667/** One drawn frame line: plain strings and styled segments, in order. */
668export type PaneLine = (string | PaneSegment)[]
669
670// A wide or astral character makes a line's cells and characters disagree: draw it plain.
671const WIDE = /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꀀ-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]|[\ud800-\udbff]/
672
673function styledLine(chars: readonly string[], spans: readonly ClaudishStyleSpan[]): PaneLine {
674  const out: PaneLine = []
675  let pos = 0
676  for (const s of spans) {
677    const from = Math.max(s.col, pos)
678    const to = Math.min(s.col + s.len, chars.length)
679    if (from >= to) continue
680    if (from > pos) out.push(chars.slice(pos, from).join(''))
681    const seg: PaneSegment = { text: chars.slice(from, to).join('') }
682    if (s.fg !== null) seg.color = colorSpelling(s.fg)
683    if (s.bg !== null) seg.backgroundColor = colorSpelling(s.bg)
684    if (s.bold) seg.bold = true
685    out.push(seg)
686    pos = to
687  }
688  if (pos < chars.length) out.push(chars.slice(pos).join(''))
689  return out.length > 0 ? out : ['']
690}
691
692/** The estimate the style budget is held to: per line, its cost, its text, and each styled segment. */
693export function paneCost(lines: readonly PaneLine[]): number {
694  let cost = 0
695  for (const line of lines) {
696    cost += PANE_LINE_COST
697    for (const part of line) cost += typeof part === 'string' ? part.length : part.text.length + PANE_SEGMENT_COST
698  }
699  return cost
700}
701
702export type PaneFrameLines = { lines: PaneLine[]; painted: boolean }
703
704/**
705 * The drawn frame: trailing blank lines trimmed, the LAST `rows - 1` lines kept (one row is
706 * the header; Claude Code's prompt and newest output are at the bottom), each cut to
707 * `columns + 1` cells so the engine still truncates with …; the child's colours painted
708 * when the frame carries them, the surface paints, and the estimate fits the budget. A
709 * frame shorter than the tab starts right under the header: no blank rows above it.
710 */
711export function paneLines(frame: ClaudishFrame | null, fit: PaneFit): PaneFrameLines {
712  if (!frame) return { lines: [], painted: false }
713  let last = frame.lines.length - 1
714  while (last >= 0 && (frame.lines[last] ?? '').trim() === '') last -= 1
715  const keep = Math.max(0, fit.rows - 1)
716  const first = Math.max(0, last + 1 - keep)
717  const limit = fit.columns + 1
718  const picked: { chars: string[]; spans: readonly ClaudishStyleSpan[] }[] = []
719  for (let i = first; i <= last; i++) {
720    const chars = Array.from(frame.lines[i] ?? '').slice(0, limit)
721    picked.push({ chars, spans: frame.styles?.[i] ?? [] })
722  }
723  const plain = (): PaneLine[] => picked.map(p => [p.chars.join('')])
724  if (!fit.paint || !frame.styles) return { lines: plain(), painted: false }
725  const styled = picked.map(p => (p.spans.length === 0 || WIDE.test(p.chars.join('')) ? [p.chars.join('')] : styledLine(p.chars, p.spans)))
726  if (paneCost(styled) > PANE_STYLE_BUDGET) return { lines: plain(), painted: false }
727  return { lines: styled, painted: styled.some(l => l.some(part => typeof part !== 'string')) }
728}
729
730// ── Show tab: what it draws ───────────────────────────────────────────────────
731
732export type PaneBody =
733  | { kind: 'waiting' }
734  | { kind: 'unavailable'; note: string; numbers: string }
735  | { kind: 'frame'; lines: PaneLine[] }
736  | { kind: 'note'; note: string }
737
738/** `agent`: the line above the header naming the slot's agent; [] when it names none. */
739export type PaneModel = { agent: Segment[]; badge: Badge | null; header: Segment[]; body: PaneBody }
740
741/**
742 * The Show tab's first line. A slot naming no agent has one only in a band whose batch has agents
743 * (`Agent: none`, the row is reserved for every tab then); in a band with none, null: no line at all.
744 */
745export function paneAgentLine(slot: ClaudishSlot, batch: BatchAgent = { kind: 'none' }): { text: string; mismatch: boolean } | null {
746  const a = slotAgent(slot)
747  if (a.requested === null && a.loaded === null) return batch.kind === 'none' ? null : { text: 'Agent: none', mismatch: false }
748  if (a.loaded === null && !isTerminal(slot.state)) return { text: `Agent: ${a.requested} (requested)`, mismatch: false }
749  if (!a.mismatch) return { text: `Agent: ${a.name}`, mismatch: false }
750  // The reason only when it is about the agent: any other failure is the header's, as today.
751  const why = slot.reason === 'agent_rejected' ? ` · ${slot.detail ? `agent_rejected: ${slot.detail}` : 'agent_rejected'}` : ''
752  return { text: `Agent: ${a.loaded ?? 'none'} (requested ${a.requested})${why}`, mismatch: true }
753}
754
755/** The band's batch: every slot under its one header, as bandModel reads it. */
756export function bandAgent(runs: ClaudishRuns, feeds: Readonly<Record<string, ClaudishFeedSupport>>): BatchAgent {
757  const { shown } = shownRuns(runs.list.filter(r => isDrawn(r, feeds)))
758  return batchAgent(shown.flatMap(r => r.slots))
759}
760
761/**
762 * Rows the Show tab keeps for the agent line besides its header: 1 while the band's batch has an
763 * agent, for every tab alike. The panel size is one value every live child is resized to, so a
764 * count that changed per tab would resize every session on each tab switch.
765 */
766export function paneAgentRows(runs: ClaudishRuns, feeds: Readonly<Record<string, ClaudishFeedSupport>>): 0 | 1 {
767  return bandAgent(runs, feeds).kind === 'none' ? 0 : 1
768}
769
770/** The tab's agent line, header (the row's badge, then its text, theme keys only) and its body. */
771export function paneModel(view: ClaudishPaneView, runs: ClaudishRuns, fit: PaneFit, now: number, feeds: Readonly<Record<string, ClaudishFeedSupport>>): PaneModel {
772  const run = runs.list.find(r => r.id === view.runId)
773  const slot = run?.slots.find(s => s.slot === view.slot)
774  const batch = bandAgent(runs, feeds)
775  const agentRows = batch.kind === 'none' ? 0 : 1
776  const line = slot ? paneAgentLine(slot, batch) : null
777  const agent: Segment[] = line ? [{ text: line.text, ...(line.mismatch ? { color: 'warning' as const } : {}) }] : []
778  // The agent line already says why the agent was rejected: the header does not say it twice.
779  const reasonShown = line !== null && line.mismatch && slot?.reason === 'agent_rejected'
780  const header: Segment[] = []
781  let badge: Badge | null = null
782  if (run && slot) {
783    const state = shownState(run, slot)
784    const look = lookOf(state, slot.reason)
785    badge = { code: look.code, runtime: runtime(slotRuntime(run, slot, now)), hue: HUE_OF[look.tone] }
786    header.push({ text: ` ${view.model}`, bold: true })
787    if (slot.provider) header.push({ text: ` · ${providerName(slot.provider)}`, dim: true })
788    const m = staleMeter(slot, state)
789    if (m) header.push({ text: ` · ${meterText(m)}`, color: m.color })
790    const activity = activityOf(run, slot, state)
791    if (activity && !reasonShown) header.push({ text: ` · ${activity}`, dim: true })
792    if (look.tone === 'format') header.push({ text: ' · the answer missed the required format', color: 'warning' })
793  } else {
794    header.push({ text: view.model, bold: true })
795  }
796  if (view.status === 'ended') header.push({ text: ' · ended', dim: true })
797
798  const numbers = slot
799    ? [`tokens ${tokenIO(slot.tokensIn, slot.tokensOut)}`, tally(TOOLS_MARK, slot.toolCalls), tally(LOOPS_MARK, slot.turnsCompleted)].join(' · ')
800    : ''
801
802  let body: PaneBody
803  if (view.status === 'waiting') body = { kind: 'waiting' }
804  else if (view.status === 'unavailable') {
805    const note = view.note === null || view.note === NO_CAPTURE_NOTE ? NO_CAPTURE_NOTE : `Live screen not available right now: ${view.note}`
806    body = { kind: 'unavailable', note, numbers }
807  } else if (view.frame) body = { kind: 'frame', lines: paneLines(view.frame, { ...fit, rows: fit.rows - agentRows }).lines } // the agent line's row, kept for every tab
808  else body = { kind: 'note', note: view.note ?? '' }
809  return { agent, badge, header, body }
810}
811
812// ── Show panel: its tabs ──────────────────────────────────────────────────────
813
814/** One tab of the Show panel: a slot of a run the band shows, its view under `id`. */
815export type ShowTab = { id: string; label: string; hue: Hue; target: SlotTarget }
816
817/**
818 * The panel's tabs: every slot of the runs the band shows, in the band's run order, so a new
819 * run's slots are tabs at once, with no Show pressed for each. A tab reads its model; where two
820 * tabs share a model, each adds its slot (its run and slot across runs) so no two read alike.
821 */
822export function showTabs(runs: ClaudishRuns, feeds: Readonly<Record<string, ClaudishFeedSupport>>): ShowTab[] {
823  const { shown } = shownRuns(runs.list.filter(r => isDrawn(r, feeds)))
824  const severalRuns = shown.length > 1
825  const tabs: (ShowTab & { where: string })[] = []
826  for (const run of shown) {
827    const label = runLabel(run)
828    for (const slot of run.slots) {
829      if (slot.slot === '*') continue
830      const look = lookOf(shownState(run, slot), slot.reason)
831      const where = run.ref.kind === 'delegation' ? label : severalRuns ? `${label}/${slot.slot}` : slot.slot
832      tabs.push({
833        id: paneId(run.id, slot.slot),
834        label: slot.model,
835        hue: HUE_OF[look.tone],
836        target: { runId: run.id, epoch: run.epoch, ref: run.ref, slot: slot.slot, model: slot.model, label },
837        where,
838      })
839    }
840  }
841  const uses = new Map<string, number>()
842  for (const t of tabs) uses.set(t.label, (uses.get(t.label) ?? 0) + 1)
843  return tabs.map(({ where, ...t }) => ((uses.get(t.label) ?? 0) > 1 ? { ...t, label: `${t.label} ${where}` } : t))
844}
845
846/** A label is never cut below this many cells (5 characters + `…`), unless it is shorter (R12.2). */
847export const TAB_FLOOR = 6
848
849/** One tab as the strip draws it: its index into the tabs given, and its label as drawn. */
850export type StripTab = { index: number; label: string }
851
852/** A tab's cells besides its label: ` ●` and a space each side. */
853const TAB_CELLS = 4
854/** The `│` between two tabs of one row. */
855const BAR_CELLS = 1
856
857/**
858 * The tab strip's rows (R12): the tabs in order, wrapped onto the fewest rows that hold every
859 * label at its floor, broken where the largest common cap still gives that row count, then each
860 * row's labels cut as R10.3 cuts them in that row's room (the active one last, never below the
861 * floor). The first row's room is `width − SHOW_CELLS` (Hide ends it); later rows' is `width`.
862 * A first tab that fits the first row at its floor is always there; otherwise the first row holds
863 * only Hide. A later row too narrow for one tab at its floor holds one tab cut below it, to
864 * `width − 4` cells, never below 1. Always at least one row. Lengths are code points.
865 */
866export function wrapTabs(tabs: readonly Pick<ShowTab, 'id' | 'label'>[], active: string | null, width: number): StripTab[][] {
867  const w = Math.max(0, Math.floor(width))
868  const chars = tabs.map(t => Array.from(t.label))
869  const full = chars.map(c => c.length)
870  const floorOf = (i: number) => Math.min(full[i]!, TAB_FLOOR)
871  const room = (r: number) => (r === 0 ? Math.max(0, w - SHOW_CELLS) : w)
872
873  // Next-fit placing in order at a cap: never returns to an earlier row, so the row count is
874  // non-decreasing in the cap and the largest cap keeping the floor's row count is a downward scan.
875  const place = (cap: number): number[][] => {
876    const rows: number[][] = [[]]
877    let used = 0
878    for (let i = 0; i < tabs.length; i++) {
879      for (;;) {
880        const r = rows.length - 1
881        const row = rows[r]!
882        let len = Math.min(full[i]!, cap)
883        if (r === 0 && row.length === 0 && floorOf(i) + TAB_CELLS <= room(0)) len = Math.min(len, room(0) - TAB_CELLS)
884        const need = (row.length > 0 ? BAR_CELLS : 0) + len + TAB_CELLS
885        if (used + need <= room(r)) { row.push(i); used += need; break }
886        if (r > 0 && row.length === 0) { row.push(i); used = room(r); break }
887        rows.push([])
888        used = 0
889      }
890    }
891    return rows
892  }
893
894  const count = place(TAB_FLOOR).length
895  let breaks: number[][] | null = null
896  for (let cap = Math.max(0, ...full); cap > TAB_FLOOR && !breaks; cap--) {
897    const rows = place(cap)
898    if (rows.length <= count) breaks = rows
899  }
900  breaks ??= place(TAB_FLOOR)
901
902  return breaks.map((row, r) => {
903    const len = row.map(i => full[i]!)
904    let cost = len.reduce((s, n) => s + n + TAB_CELLS, 0) + BAR_CELLS * Math.max(0, row.length - 1)
905    const passes = r > 0 && row.length === 1 ? [floorOf, () => 1] : [floorOf]
906    for (const floor of passes) {
907      while (cost > room(r)) {
908        let pick = -1
909        for (let k = 0; k < row.length; k++) {
910          if (len[k]! <= floor(row[k]!) || tabs[row[k]!]!.id === active) continue
911          if (pick < 0 || len[k]! > len[pick]!) pick = k
912        }
913        if (pick < 0) pick = row.findIndex((i, k) => tabs[i]!.id === active && len[k]! > floor(i))
914        if (pick < 0) break
915        len[pick]!--
916        cost--
917      }
918    }
919    return row.map((i, k) => ({ index: i, label: len[k]! >= full[i]! ? tabs[i]!.label : `${chars[i]!.slice(0, len[k]! - 1).join('')}…` }))
920  })
921}
922
923/** The tab the panel shows: the one last asked for while it is still a tab, else the first. */
924export function activeTab(tabs: readonly ShowTab[], asked: string | null): ShowTab | null {
925  return tabs.find(t => t.id === asked) ?? tabs[0] ?? null
926}
927
hooks/status/poll.ts 588 lines
1// The tool.call observer and the poll loop: handshake, cadence, backoff, feed support,
2// the run merge, the hand-off to the wake, stop-request pruning, compaction and captures.
3// Takes a Host only.
4// Names no claudish tool or field: the adapter behind host.source speaks claudish.
5
6import type { Frozen, Next, SessionEndInput, ToolCallInput, ToolCallResult } from 'claude-code'
7import type { ClaudishFeedSupport, ClaudishPaneView, ClaudishRun, ClaudishRuns } from '../../types'
8import {
9  FINAL_GRACE_MS,
10  NO_CAPTURE_NOTE,
11  NO_SCREEN_NOTE,
12  SHOW_PANE_ID,
13  compaction,
14  feedKey,
15  isTerminal,
16  paneId,
17  mergeRun,
18  newRun,
19  pruneStops,
20  runId,
21  sameData,
22  withoutLedgerKeys,
23  withoutRuns,
24  type RunObservation,
25} from './domain'
26import type { Host } from './host'
27import { activeTab, showTabs } from './layout'
28import type { FeedAnswer, PollBatch, ResizeResult } from './run-source'
29import * as wake from './wake'
30
31// ── cadence ───────────────────────────────────────────────────────────────────
32
33export const ACTIVE_MS = 1_000
34export const QUIET_MS = 3_000
35/** No activity change for this long and no shown live tab: the quiet cadence. */
36export const QUIET_AFTER_MS = 30_000
37export const BACKOFF_MAX_MS = 30_000
38/** A feed that never spoke goes silent after this many bad answers. */
39export const PROBE_STRIKES = 3
40/** A speaking feed is withdrawn after this many declarations with no `speaks` between. */
41export const WITHDRAW_DECLARATIONS = 3
42/** A tick that threw is retried, with back-off, this many times in a row before the loop rests. */
43export const TICK_RETRIES = 8
44/** A hidden tab is captured at most this often; an unavailable one, at most this often. */
45export const HIDDEN_CAPTURE_MS = 5_000
46export const UNAVAILABLE_RETRY_MS = 10_000
47/** A tab of a closed panel is captured at most this often, and once more when its slot ends. */
48export const CLOSED_CAPTURE_MS = 10_000
49
50// ── module state: dies with a hot reload, which session.start restarts ───────
51
52type Phase = 'idle' | 'scheduled' | 'running'
53/** gen: the number of the one scheduled tick that may run; an earlier one fires as a no-op. */
54const loop: { phase: Phase; rerun: boolean; failures: number; gen: number } = { phase: 'idle', rerun: false, failures: 0, gen: 0 }
55/** pane id → last capture attempt, whatever its answer. Not drawn, so not in state. */
56const lastAttemptAt = new Map<string, number>()
57/** pane id → the first tick that found its slot terminal. */
58const terminalSeenAt = new Map<string, number>()
59/** tick failure messages already logged once. */
60const loggedFailures = new Set<string>()
61/** The size the Show panel last drew a tab's child at, from its render; null before the first. */
62let panelSize: Size | null = null
63/** pane id → the size its child was last given (or refused). Asked again only when the panel's size moves. */
64const askedSize = new Map<string, Size>()
65/** pane ids whose resize answer is still out. Another capture pass skips them: the pass that sent the
66 *  resize captures the tab once the answer is back, so no capture shows the size before it. */
67const resizing = new Set<string>()
68
69type Size = { cols: number; rows: number }
70const sameSize = (a: Size | null | undefined, b: Size | null | undefined): boolean =>
71  !!a && !!b && a.cols === b.cols && a.rows === b.rows
72
73/** A resize answer later than this counts as failed, so a call that never answers cannot hold its tab. */
74export const RESIZE_TIMEOUT_MS = 5_000
75/** After a new panel size, the shown tab is captured again this long after, to catch its redraw. */
76export const SETTLE_CAPTURE_MS: readonly number[] = [250, 750]
77/** Sizes asked for in one capture of a tab, so a panel dragged without pause still gets captured. */
78const RESIZE_ROUNDS = 3
79
80/** One resize, never rejecting and never longer than RESIZE_TIMEOUT_MS: either becomes a failed answer. */
81function resizeBounded(host: Host, ref: ClaudishRun['ref'], slot: string, size: Size): Promise<ResizeResult> {
82  return new Promise(resolve => {
83    const timer = host.after(RESIZE_TIMEOUT_MS, () => resolve({ kind: 'failed', reason: 'no answer' }))
84    host.source.resize(ref, slot, size.cols, size.rows).then(
85      r => { timer.cancel(); resolve(r) },
86      (e: unknown) => { timer.cancel(); resolve({ kind: 'failed', reason: e instanceof Error ? e.message : String(e) }) },
87    )
88  })
89}
90
91/**
92 * Resizes one session to the panel's size, once per size whatever the answer. The panel can move
93 * again while an answer is out (a drag), so it asks for the newest size before returning.
94 */
95async function fitToPanel(host: Host, id: string, ref: ClaudishRun['ref'], slot: string): Promise<void> {
96  for (let round = 0; round < RESIZE_ROUNDS; round++) {
97    const size = panelSize
98    if (!size || sameSize(askedSize.get(id), size)) return
99    askedSize.set(id, size) // a refusal is not retried until the size moves
100    resizing.add(id)
101    const rs = await resizeBounded(host, ref, slot, size).finally(() => resizing.delete(id))
102    if (rs.kind === 'failed') host.debug(`claudish Show resize to ${size.cols}x${size.rows} failed: ${rs.reason}`)
103  }
104}
105
106/**
107 * Every running session takes the panel's last size, shown or not and panel open or not, so a
108 * session that ends before anyone opens it was already drawing at that size: an ended screen can
109 * no longer redraw. The size is the session's, so a session forgets it only when it is no longer
110 * running.
111 */
112async function fitLive(host: Host, runs: ClaudishRuns, feeds: Readonly<Record<string, ClaudishFeedSupport>>): Promise<void> {
113  const live = new Set<string>()
114  const fits: Promise<void>[] = []
115  for (const run of runs.list) {
116    const support = feeds[feedKey(run.ref)]
117    for (const slot of run.slots) {
118      if (slot.slot === '*' || isTerminal(slot.state)) continue
119      const id = paneId(run.id, slot.slot)
120      live.add(id)
121      // A run whose server is not answering would only spend the 5 s bound; it is asked once it answers.
122      if (run.settledAt !== null || run.unreachableSince !== null) continue
123      if (support?.kind !== 'speaks' || !support.can.resize || resizing.has(id)) continue
124      fits.push(fitToPanel(host, id, run.ref, slot.slot))
125    }
126  }
127  // All at once: one slow answer must not hold the tick's captures behind every other session.
128  await Promise.all(fits)
129  for (const id of [...askedSize.keys()]) if (!live.has(id)) askedSize.delete(id)
130}
131
132/**
133 * The Show panel's render reports the size its tabs' children are drawn at. A new size captures the
134 * shown tab now (resizing its child first), not at the loop's next tick, which can be a back-off
135 * away. Hidden tabs take the new size at their own next capture.
136 */
137export function notePanelSize(host: Host, size: Size, shownId: string | null): void {
138  if (sameSize(panelSize, size)) return
139  panelSize = size
140  if (shownId === null) return ensureLoop(host)
141  void captureOpened(host, shownId)
142  // The session redraws a moment after its resize answer, so the capture right after can still
143  // show the old drawing; these catch the redraw instead of the next tick, a second or two later.
144  for (const ms of SETTLE_CAPTURE_MS) host.after(ms, () => void captureOpened(host, shownId, false))
145}
146
147// ── session boundaries ────────────────────────────────────────────────────────
148
149/** session.end with clear or resume ends the conversation: a new epoch forgets its runs. */
150export async function onSessionEnd(
151  host: Host,
152  e: Frozen<SessionEndInput>,
153  next: Next<'session.end'>,
154): Promise<{ sessionId: string }> {
155  if (e.reason === 'clear' || e.reason === 'resume') {
156    await host.store.runs.update(v => ({ epoch: v.epoch + 1, starts: {}, list: [] }))
157    await host.store.ledger.update(l => ({ epoch: l.epoch + 1, entries: {} }))
158    await host.store.stopRequests.update(() => ({}))
159    await host.store.earlier.update(() => ({ runs: 0, done: 0, failed: 0, stopped: 0 }))
160    await host.store.turn.update(() => ({ isRunning: false, since: 0 }))
161  }
162  return next(e)
163}
164
165// ── the observer ──────────────────────────────────────────────────────────────
166
167const RESERVED = new Set(['tool', 'tool_use_id', 'agentId'])
168
169function argsOf(e: Frozen<ToolCallInput>): Record<string, unknown> {
170  const args: Record<string, unknown> = {}
171  for (const [k, v] of Object.entries(e)) if (!RESERVED.has(k)) args[k] = v
172  return args
173}
174
175/** tool.call on a claudish tool: run it unchanged, then watch a start it answered. */
176export async function onClaudishCall(
177  host: Host,
178  e: Frozen<ToolCallInput>,
179  next: Next<'tool.call'>,
180): Promise<ToolCallResult> {
181  const epoch = (await host.store.runs.read()).epoch
182  const ran = await next(e)
183  try {
184    if (ran.deny !== undefined) return ran
185    const seen = host.source.recognizeCall({
186      tool: String(e.tool),
187      args: argsOf(e),
188      answer: { text: typeof ran.text === 'string' ? ran.text : null, isError: ran.isError === true },
189    })
190    switch (seen.kind) {
191      case 'unidentified':
192        host.debug(`claudish start not watched: ${seen.reason}`)
193        break
194      case 'precontract': {
195        const key = feedKey({ server: seen.server, kind: seen.runKind })
196        const now = await host.now()
197        const [, moved] = await host.store.feeds.claim(f => {
198          const was = f[key]
199          if (was !== undefined && was.kind !== 'probing') return [f, false] as const
200          const support: ClaudishFeedSupport = { kind: 'unsupported', reason: seen.reason, at: now, spoke: false }
201          return [{ ...f, [key]: support }, true] as const
202        })
203        if (moved) host.debug(`claudish ${key}: pre-contract server, not watched (${seen.reason})`)
204        break
205      }
206      case 'start': {
207        const id = runId(seen.ref)
208        const now = await host.now()
209        // A start answer in the contract is the server speaking it now: a feed given up on earlier
210        // (failed probes, a withdrawal, a server since restarted or upgraded) is probed again.
211        const key = feedKey(seen.ref)
212        const [, reopened] = await host.store.feeds.claim(f => {
213          if (f[key]?.kind !== 'unsupported') return [f, false] as const
214          return [{ ...f, [key]: { kind: 'probing', strikes: 0 } }, true] as const
215        })
216        if (reopened) host.debug(`claudish ${key}: a contract start answer, watched again`)
217        await host.store.runs.update(v => {
218          if (v.epoch !== epoch || v.list.some(r => r.id === id)) return v
219          const before = v.starts[seen.ref.address] ?? 0
220          const run = newRun({ id, ref: seen.ref, label: seen.label, epoch, generation: before + 1, now })
221          return { ...v, starts: { ...v.starts, [seen.ref.address]: before + 1 }, list: [...v.list, run] }
222        })
223        ensureLoop(host)
224        break
225      }
226      case 'other':
227        break
228    }
229  } catch (err) {
230    host.debug(`claudish observer failed: ${err instanceof Error ? err.message : String(err)}`)
231  }
232  return ran
233}
234
235// ── feed support policy ───────────────────────────────────────────────────────
236
237type SupportOutcome = { withdrawn: Set<string>; logs: string[] }
238
239/** The core's policy over the adapter's facts, per feed key (architecture §3.4). */
240export function applySupport(
241  feeds: Readonly<Record<string, ClaudishFeedSupport>>,
242  answers: ReadonlyMap<string, FeedAnswer>,
243  now: number,
244): readonly [Record<string, ClaudishFeedSupport>, SupportOutcome] {
245  const next: Record<string, ClaudishFeedSupport> = { ...feeds }
246  const out: SupportOutcome = { withdrawn: new Set(), logs: [] }
247  for (const [key, answer] of answers) {
248    const was: ClaudishFeedSupport = feeds[key] ?? { kind: 'probing', strikes: 0 }
249    if (was.kind === 'unsupported') continue
250    const reason = 'reason' in answer ? answer.reason : 'code' in answer ? `refused: ${answer.code}` : ''
251    if (answer.kind === 'speaks') {
252      next[key] = { kind: 'speaks', version: answer.version, can: answer.can, declined: 0 }
253      continue
254    }
255    const declares = answer.kind === 'precontract' || answer.kind === 'declines'
256    if (was.kind === 'probing') {
257      const strikes = was.strikes + 1
258      if (declares || strikes >= PROBE_STRIKES) {
259        next[key] = { kind: 'unsupported', reason, at: now, spoke: false }
260        out.logs.push(`claudish ${key}: not watched (${answer.kind}: ${reason})`)
261      } else {
262        next[key] = { kind: 'probing', strikes }
263      }
264      continue
265    }
266    // was speaks: a bad answer is a transmission fact; only repeated declarations withdraw it.
267    if (!declares) continue
268    const declined = was.declined + 1
269    if (declined >= WITHDRAW_DECLARATIONS) {
270      next[key] = { kind: 'unsupported', reason: `contract withdrawn (${reason})`, at: now, spoke: true }
271      out.withdrawn.add(key)
272      out.logs.push(`claudish ${key}: contract withdrawn (${reason}); its live slots end LOST`)
273    } else {
274      next[key] = { ...was, declined }
275    }
276  }
277  return [sameData(feeds, next) ? (feeds as Record<string, ClaudishFeedSupport>) : next, out] as const
278}
279
280/** Every run of this tick's merge, from the batch and the feeds as just updated. */
281export function mergeAll(
282  runs: ClaudishRuns,
283  batch: PollBatch,
284  feeds: Readonly<Record<string, ClaudishFeedSupport>>,
285  withdrawn: ReadonlySet<string>,
286  now: number,
287): ClaudishRuns {
288  let changed = false
289  const list = runs.list.map(run => {
290    if (run.settledAt !== null) return run
291    const key = feedKey(run.ref)
292    let observed: RunObservation | null = null
293    if (withdrawn.has(key)) observed = { kind: 'withdrawn' }
294    else if (batch.feeds.has(key) && feeds[key]?.kind === 'speaks') {
295      const result = batch.runs.get(run.id)
296      // A speaking feed answers every run it was asked about: no result means the run started
297      // after this tick's poll went out, so it is not observed until the next tick.
298      if (batch.feeds.get(key)?.kind !== 'speaks') observed = { kind: 'unreachable' }
299      else if (result) observed = result.kind === 'ok' ? { kind: 'ok', slots: result.slots } : { kind: 'missing' }
300    }
301    if (!observed) return run
302    const merged = mergeRun(run, observed, now)
303    if (merged !== run) changed = true
304    return merged
305  })
306  return changed ? { ...runs, list } : runs
307}
308
309// ── the loop ──────────────────────────────────────────────────────────────────
310
311/** From session.start, the observer's start branch, and Show. */
312function schedule(host: Host, ms: number): void {
313  const gen = ++loop.gen
314  loop.phase = 'scheduled'
315  host.after(ms, () => {
316    if (gen === loop.gen) void tick(host)
317  })
318}
319
320export function ensureLoop(host: Host): void {
321  switch (loop.phase) {
322    case 'idle':
323    case 'scheduled': // the pending tick can be a quiet one, seconds away: run now, and it fires as a no-op
324      schedule(host, 0)
325      return
326    case 'running':
327      loop.rerun = true
328      return
329  }
330}
331
332/**
333 * A tab Show (or a tab press) just made active: its first screen is captured now, not at the
334 * loop's next tick, which can be a whole poll interval away while one is already scheduled.
335 * Then the loop carries on. `kick` false (a settle capture after a resize) leaves the loop as it is:
336 * it is not a press, so it must not run a tick of its own (R11.3).
337 */
338export async function captureOpened(host: Host, id: string, kick = true): Promise<void> {
339  try {
340    if (await panelOpen(host)) await captures(host, [{ id, inPanel: true, isShown: true }], await host.store.runs.read(), await host.store.feeds.read(), await host.now(), false)
341  } catch (err) {
342    host.debug(`claudish Show capture failed: ${err instanceof Error ? err.message : String(err)}`)
343  }
344  if (kick) ensureLoop(host)
345}
346
347async function panelOpen(host: Host): Promise<boolean> {
348  return (await host.panes()).some(p => p.id === SHOW_PANE_ID && p.isPlaced)
349}
350
351function isWatched(run: ClaudishRun, feeds: Readonly<Record<string, ClaudishFeedSupport>>): boolean {
352  return run.settledAt === null && feeds[feedKey(run.ref)]?.kind !== 'unsupported'
353}
354
355function delay(watched: readonly ClaudishRun[], shownLive: boolean, now: number): number {
356  if (loop.failures > 0) return Math.min(ACTIVE_MS * 2 ** loop.failures, BACKOFF_MAX_MS)
357  if (loop.rerun) return ACTIVE_MS // something new arrived while this tick ran (a start, a Show)
358  const lastActivity = watched.reduce((m, r) => Math.max(m, r.activityAt), -Infinity)
359  return shownLive || now - lastActivity < QUIET_AFTER_MS ? ACTIVE_MS : QUIET_MS
360}
361
362const EMPTY_BATCH: PollBatch = { feeds: new Map(), runs: new Map() }
363const BAD_ANSWERS: ReadonlySet<FeedAnswer['kind']> = new Set(['refused', 'unanswered', 'garbled'])
364
365/** One tick: poll, support, merge, prune, compact, capture; then decide the next tick. */
366export async function tick(host: Host): Promise<void> {
367  loop.phase = 'running'
368  loop.rerun = false
369  let open: TabRef[] = []
370  let runsNow: ClaudishRuns | null = null
371  let feedsNow: Record<string, ClaudishFeedSupport> = {}
372  let now = 0
373  let tabs: TabsOutcome = { shownLive: false, capturing: 0 }
374  let threw = false
375  try {
376    now = await host.now()
377    runsNow = await host.store.runs.read()
378    const epoch = runsNow.epoch
379    feedsNow = await host.store.feeds.read()
380    const feeds0 = feedsNow
381    const watched = runsNow.list.filter(r => isWatched(r, feeds0))
382    const batch = watched.length > 0 ? await host.source.poll(watched.map(r => ({ id: r.id, ref: r.ref }))) : EMPTY_BATCH
383
384    const at = now
385    const [feedsWritten, support] = await host.store.feeds.claim(f => applySupport(f, batch.feeds, at))
386    feedsNow = feedsWritten
387    for (const line of support.logs) host.debug(line)
388
389    const before = runsNow
390    const feedsAfter = feedsNow
391    if (mergeAll(runsNow, batch, feedsAfter, support.withdrawn, now) !== runsNow) {
392      runsNow = await host.store.runs.update(v => (v.epoch !== epoch ? v : mergeAll(v, batch, feedsAfter, support.withdrawn, at)))
393    }
394    if (runsNow.epoch !== epoch) return // a /clear or resume landed mid-tick: drop this tick's work
395    for (const run of runsNow.list) {
396      const was = before.list.find(r => r.id === run.id)
397      if (run.unreachableSince !== null && was && was.unreachableSince === null) {
398        host.debug(`claudish run ${run.label}: ${feedKey(run.ref)} is not answering; its rows show unknown`)
399      }
400    }
401    // This tick's terminal transitions and wait entries: the ledger keeps each one owed until delivered.
402    await wake.notice(host, epoch, runsNow, feedsNow)
403
404    const settledRuns = runsNow
405    const [, timedOut] = await host.store.stopRequests.claim(m => pruneStops(m, settledRuns, at))
406    for (const key of timedOut) host.toast(`Stop not confirmed for ${key.slice(key.indexOf('/') + 1)}; press Stop again`)
407
408    runsNow = await compact(host, runsNow, epoch)
409
410    await fitLive(host, runsNow, feedsNow)
411    open = await syncTabs(host, runsNow, feedsNow)
412    tabs = await captures(host, open, runsNow, feedsNow, now)
413
414    const polled = [...batch.feeds.values()]
415    loop.failures = polled.length > 0 && polled.every(a => BAD_ANSWERS.has(a.kind)) ? loop.failures + 1 : 0
416  } catch (err) {
417    const message = err instanceof Error ? err.message : String(err)
418    if (!loggedFailures.has(message)) {
419      loggedFailures.add(message)
420      host.debug(`claudish poll tick failed: ${message}`)
421    }
422    loop.failures += 1
423    threw = true
424  } finally {
425    // Every value combined here was awaited above; nothing is awaited between here and the decision.
426    const watchedNow = runsNow ? runsNow.list.filter(r => isWatched(r, feedsNow)) : []
427    const keepGoing = loop.rerun
428      || runsNow === null
429      || watchedNow.length > 0
430      || tabs.capturing > 0                                   // an open tab whose run can still produce frames
431      || (threw && loop.failures <= TICK_RETRIES)             // a throw can land after the last merge, before its wake is owed
432    if (!keepGoing) {
433      loop.phase = 'idle'
434    } else {
435      schedule(host, delay(watchedNow, tabs.shownLive, now))
436    }
437  }
438}
439
440async function compact(host: Host, runs: ClaudishRuns, epoch: number): Promise<ClaudishRuns> {
441  const plan = compaction(runs, await host.store.ledger.read())
442  if (!plan) return runs
443  const written = await host.store.runs.update(v => (v.epoch !== epoch ? v : withoutRuns(v, plan.drop)))
444  if (written.epoch !== epoch) return written
445  const d = plan.added
446  await host.store.earlier.update(e => ({ runs: e.runs + d.runs, done: e.done + d.done, failed: e.failed + d.failed, stopped: e.stopped + d.stopped }))
447  await host.store.ledger.update(l => (l.epoch !== epoch ? l : withoutLedgerKeys(l, plan.drop)))
448  return written
449}
450
451
452/** A tab the capture pass visits: its id (its view's member id), whether the panel is open, and whether it shows the tab. */
453type TabRef = { id: string; inPanel: boolean; isShown: boolean }
454
455/** Tab ids this load has given a view, so a tab whose run left the band has its view cleared. */
456const seeded = new Set<string>()
457
458/**
459 * The panel's tabs follow the runs the band shows: every slot gets a view (`waiting`) as soon as
460 * it is listed, so its tab is there before anyone presses Show, and a tab whose run left the band
461 * loses its view. Returns every tab to capture, the panel open or not: a closed panel's tabs are
462 * captured at the closed rate, so Show opens on a screen already held and a slot that ends while
463 * the panel is closed keeps its last screen. A tab is shown only while the panel is open (the one
464 * last picked, else the first).
465 */
466async function syncTabs(host: Host, runs: ClaudishRuns, feeds: Readonly<Record<string, ClaudishFeedSupport>>): Promise<TabRef[]> {
467  const tabs = showTabs(runs, feeds)
468  const ids = new Set(tabs.map(t => t.id))
469  for (const id of [...seeded]) {
470    if (ids.has(id)) continue
471    seeded.delete(id)
472    await host.store.panes.update(id, () => null)
473  }
474  for (const t of tabs) {
475    if (seeded.has(t.id)) continue
476    seeded.add(t.id)
477    const { runId, slot, model } = t.target
478    await host.store.panes.update(t.id, v => v ?? { runId, slot, model, status: 'waiting', frame: null, note: null })
479  }
480  const inPanel = await panelOpen(host)
481  const active = inPanel ? activeTab(tabs, (await host.store.showTab.read()).active) : null
482  return tabs.map(t => ({ id: t.id, inPanel, isShown: t.id === active?.id }))
483}
484
485// ── captures: the panel's tabs, open or closed ───────────────────────────────────────────────
486
487type TabsOutcome = { shownLive: boolean; capturing: number }
488
489/**
490 * Captures every open tab that is due (architecture §3.4, "Captures"). Returns whether
491 * a shown tab is live, and how many open tabs can still produce frames: those keep the
492 * loop alive; an ended tab, or one whose feed offers no capture, costs nothing.
493 */
494async function captures(
495  host: Host,
496  open: readonly TabRef[],
497  runs: ClaudishRuns,
498  feeds: Readonly<Record<string, ClaudishFeedSupport>>,
499  now: number,
500  everyTab = true,
501): Promise<TabsOutcome> {
502  const out: TabsOutcome = { shownLive: false, capturing: 0 }
503  // A tab closed before its run ended leaves its bookkeeping behind: drop it with the tab. Only a
504  // pass over every open tab knows which are closed.
505  if (everyTab) {
506    const openIds = new Set(open.map(p => p.id))
507    for (const id of [...lastAttemptAt.keys()]) if (!openIds.has(id)) lastAttemptAt.delete(id)
508    for (const id of [...terminalSeenAt.keys()]) if (!openIds.has(id)) terminalSeenAt.delete(id)
509  }
510  const end = (v: ClaudishPaneView | null): ClaudishPaneView | null =>
511    v ? { ...v, status: 'ended', note: v.frame ? null : NO_SCREEN_NOTE } : v
512  for (const p of open) {
513    const view = await host.store.panes.read(p.id)
514    // An ended tab with no screen is asked once more when it is opened: claudish keeps a closed
515    // pane's last screen, so the answer is that screen, not a guess that none exists.
516    const retry = !everyTab && view?.status === 'ended' && view.frame === null
517    if (!view || (view.status === 'ended' && !retry)) {
518      lastAttemptAt.delete(p.id)
519      terminalSeenAt.delete(p.id)
520      continue
521    }
522    const run = runs.list.find(r => r.id === view.runId)
523    if (!run) {
524      await host.store.panes.update(p.id, end)
525      continue
526    }
527    const support = feeds[feedKey(run.ref)]
528    if (support?.kind !== 'speaks' || !support.can.capture) {
529      if (view.status !== 'unavailable' || view.note !== NO_CAPTURE_NOTE) {
530        await host.store.panes.update(p.id, v => (v ? { ...v, status: 'unavailable', note: NO_CAPTURE_NOTE } : v))
531      }
532      continue
533    }
534    if (retry) {
535      // One shot: a screen is stored, anything else leaves the tab ended as it was.
536      const r = await host.source.capture(run.ref, view.slot, 0, support.can.spans)
537      if (r.kind === 'frame') await host.store.panes.update(p.id, v => (v ? { ...v, frame: r.frame, note: null } : v))
538      continue
539    }
540    out.capturing += 1
541    if (p.isShown) out.shownLive = true
542    const slot = run.slots.find(s => s.slot === view.slot)
543    const justEnded = slot !== undefined && isTerminal(slot.state) && !terminalSeenAt.has(p.id)
544    if (justEnded) terminalSeenAt.set(p.id, now)
545    const seenAt = terminalSeenAt.get(p.id)
546    const graceOver = seenAt !== undefined && now - seenAt >= FINAL_GRACE_MS
547    const last = lastAttemptAt.get(p.id)
548    // The tick that first finds the slot ended asks for its final screen whatever the rate.
549    const due = last === undefined || justEnded
550      || (view.status === 'unavailable' ? now - last >= UNAVAILABLE_RETRY_MS
551        : p.isShown || now - last >= (p.inPanel ? HIDDEN_CAPTURE_MS : CLOSED_CAPTURE_MS))
552    if (!due || resizing.has(p.id)) continue
553    lastAttemptAt.set(p.id, now)
554    // Fit the child to the panel before reading its screen, so this capture already shows it reflowed.
555    // A finished slot is left as it is: its pane no longer redraws.
556    if (support.can.resize && !(slot && isTerminal(slot.state))) await fitToPanel(host, p.id, run.ref, view.slot)
557    const r = await host.source.capture(run.ref, view.slot, view.frame?.seq ?? 0, support.can.spans)
558    let ended = false
559    switch (r.kind) {
560      case 'frame':
561        // A finished slot whose pane keeps redrawing still ends at the grace: nothing else would stop it.
562        ended = r.final || graceOver
563        await host.store.panes.update(p.id, v => (v ? { ...v, status: ended ? 'ended' : 'live', frame: r.frame, note: null } : v))
564        break
565      case 'unchanged':
566        if (r.final || graceOver) {
567          ended = true
568          await host.store.panes.update(p.id, end)
569        }
570        break
571      case 'gone':
572        ended = true
573        await host.store.panes.update(p.id, end)
574        break
575      case 'unavailable':
576        ended = graceOver
577        await host.store.panes.update(p.id, v => (graceOver ? end(v) : v ? { ...v, status: 'unavailable', note: r.reason } : v))
578        break
579    }
580    if (ended) {
581      out.capturing -= 1
582      lastAttemptAt.delete(p.id)
583      terminalSeenAt.delete(p.id)
584    }
585  }
586  return out
587}
588
hooks/status/wake.ts 497 lines
1// The completion wake-up: every terminal transition of a drawn run this conversation
2// started, and every entry of one of its delegations into a waiting state, is named in
3// exactly one prompt the engine accepted. The ledger (one atom, through host.store) holds
4// delivery: pending → inflight → delivered, or back to pending / parked on a refusal. A change
5// is due as soon as the mod notices it; only the main loop's running turn defers it.
6//
7// Takes a Host only. Names no claudish tool or field: the run line and the fetch line of
8// the text come from the port's runLine and fetchHint.
9
10import type {
11  Frozen,
12  Next,
13  Timer,
14  TurnCompleteInput,
15  TurnCompleteResult,
16  TurnStartInput,
17  TurnStartResult,
18} from 'claude-code'
19import type {
20  ClaudishFeedSupport,
21  ClaudishLedger,
22  ClaudishRun,
23  ClaudishRuns,
24  ClaudishSlotState,
25  ClaudishWakeEntry,
26} from '../../types'
27import {
28  PARKED_RETRY_MS,
29  WAKE_HOLD_GUARD_MS,
30  WAKE_QUICK_ATTEMPTS,
31  WAKE_RETRY_MS,
32  fnv1a32,
33  hex8,
34  lookOf,
35  isDrawn,
36  isTerminal,
37  isWaiting,
38  parseWakeKey,
39  runLabel,
40  wakeUnits,
41  type WakeUnit,
42} from './domain'
43import type { Host, TranscriptRow } from './host'
44import type { FetchSlot, RunSource } from './run-source'
45
46// ── module state: dies with a hot reload, which session.start rebuilds ───────
47
48/** The one wake timer: cancelled and replaced when an earlier time is asked. */
49let timer: { at: number; t: Timer } | null = null
50let flushSeq = 0
51
52// ── pure ledger moves ─────────────────────────────────────────────────────────
53
54export type Claimed = { key: string; state: ClaudishSlotState; wasParked: boolean }
55
56/** Adds a pending entry for each unit with none; the created units are the claim. */
57export function createPending(
58  l: ClaudishLedger,
59  epoch: number,
60  units: readonly WakeUnit[],
61  now: number,
62): readonly [ClaudishLedger, WakeUnit[]] {
63  if (l.epoch !== epoch) return [l, []] as const
64  const created = units.filter(u => !(u.key in l.entries))
65  if (created.length === 0) return [l, []] as const
66  const entries = { ...l.entries }
67  for (const u of created) {
68    entries[u.key] = { kind: 'pending', state: u.state, at: now, attempts: 0, retryAt: null }
69  }
70  return [{ ...l, entries }, created] as const
71}
72
73/** A pending or parked entry is due once its retry time has come, and at every main-loop turn end. */
74function isDue(e: ClaudishWakeEntry, now: number, atTurnEnd: boolean): boolean {
75  if (e.kind !== 'pending' && e.kind !== 'parked') return false
76  return atTurnEnd || e.retryAt === null || e.retryAt <= now
77}
78
79/** Moves every due pending or parked entry to inflight under `nonce`; they are the claim. */
80export function claimDue(
81  l: ClaudishLedger,
82  now: number,
83  atTurnEnd: boolean,
84  nonce: string,
85): readonly [ClaudishLedger, Claimed[]] {
86  const claimed: Claimed[] = []
87  const entries = { ...l.entries }
88  for (const [key, e] of Object.entries(l.entries)) {
89    if (!isDue(e, now, atTurnEnd) || e.kind === 'delivered' || e.kind === 'inflight') continue
90    entries[key] = { kind: 'inflight', state: e.state, at: e.at, attempts: e.attempts, nonce, since: now }
91    claimed.push({ key, state: e.state, wasParked: e.kind === 'parked' })
92  }
93  return claimed.length === 0 ? [l, claimed] as const : [{ ...l, entries }, claimed] as const
94}
95
96/** The submit carrying `nonce` was accepted: its entries are delivered. */
97export function markDelivered(l: ClaudishLedger, nonce: string, now: number): ClaudishLedger {
98  let changed = false
99  const entries = { ...l.entries }
100  for (const [key, e] of Object.entries(l.entries)) {
101    if (e.kind !== 'inflight' || e.nonce !== nonce) continue
102    entries[key] = { kind: 'delivered', at: now, nonce }
103    changed = true
104  }
105  return changed ? { ...l, entries } : l
106}
107
108/** The submit carrying `nonce` was refused: back to pending with a back-off, or parked after three attempts. */
109export function markRefused(l: ClaudishLedger, nonce: string, now: number, reason: string): ClaudishLedger {
110  let changed = false
111  const entries = { ...l.entries }
112  for (const [key, e] of Object.entries(l.entries)) {
113    if (e.kind !== 'inflight' || e.nonce !== nonce) continue
114    const attempts = e.attempts + 1
115    entries[key] = attempts < WAKE_QUICK_ATTEMPTS
116      ? { kind: 'pending', state: e.state, at: e.at, attempts, retryAt: now + WAKE_RETRY_MS * attempts }
117      : { kind: 'parked', state: e.state, at: e.at, attempts, reason, retryAt: now + PARKED_RETRY_MS }
118    changed = true
119  }
120  return changed ? { ...l, entries } : l
121}
122
123/**
124 * After a reload, each inflight entry is settled from the transcript: a user row holding
125 * its nonce means the prompt entered (delivered); otherwise it is owed again (pending,
126 * attempts kept). `stranded`: the nonces the reload caught inflight. An entry claimed
127 * since, by this load's own flush, is that flush's to settle and is left alone.
128 */
129export function reconcileInflight(
130  l: ClaudishLedger,
131  rows: readonly TranscriptRow[],
132  stranded?: ReadonlySet<string>,
133): ClaudishLedger {
134  let changed = false
135  const entries = { ...l.entries }
136  for (const [key, e] of Object.entries(l.entries)) {
137    if (e.kind !== 'inflight' || (stranded !== undefined && !stranded.has(e.nonce))) continue
138    const seen = rows.some(r => r.role === 'user' && typeof r.text === 'string' && r.text.includes(`(ref ${e.nonce})`))
139    entries[key] = seen
140      ? { kind: 'delivered', at: e.since, nonce: e.nonce }
141      : { kind: 'pending', state: e.state, at: e.at, attempts: e.attempts, retryAt: null }
142    changed = true
143  }
144  return changed ? { ...l, entries } : l
145}
146
147/** The earliest time a pending or parked entry can be claimed, or null when none is owed. */
148export function earliestRetryAt(l: ClaudishLedger, now: number): number | null {
149  let at: number | null = null
150  for (const e of Object.values(l.entries)) {
151    if (e.kind !== 'pending' && e.kind !== 'parked') continue
152    const due = e.retryAt ?? now
153    at = at === null ? due : Math.min(at, due)
154  }
155  return at
156}
157
158// ── wording ───────────────────────────────────────────────────────────────────
159
160type Words = Pick<RunSource, 'runLine' | 'fetchHint'>
161
162/** How a slot is named for the person and the model: its slot id, or a delegation's label. */
163function slotName(run: ClaudishRun, slot: string): string {
164  return run.ref.kind === 'delegation' ? runLabel(run) : slot
165}
166
167function waitWord(state: ClaudishSlotState): string {
168  return state === 'AWAITING_PERMISSION' ? 'permission' : 'input'
169}
170
171/** The toast for one new unit: `03 grok-4.6 done ✓`, `#a1b2c3 haiku-4.5 waiting for input ◇`. */
172export function toastText(runs: readonly ClaudishRun[], unit: WakeUnit): { text: string; timeoutMs: number } {
173  const k = parseWakeKey(unit.key)
174  const run = runs.find(r => r.id === k.runId)
175  const slot = run?.slots.find(s => s.slot === k.slot)
176  const name = run ? (k.slot === '*' ? runLabel(run) : `${slotName(run, k.slot)} ${slot?.model ?? ''}`.trim()) : k.slot
177  if (k.wait !== null) return { text: `${name} waiting for ${waitWord(unit.state)} ◇`, timeoutMs: 4_000 }
178  const look = lookOf(unit.state, slot?.reason ?? null)
179  return { text: `${name} ${look.word} ${look.glyph}`, timeoutMs: look.group === 'failed' ? 6_000 : 4_000 }
180}
181
182/** Short names of claimed keys for a toast or the status line: `03 grok-4.6`, `#a1b2c3 haiku-4.5`. */
183function keyLabels(runs: readonly ClaudishRun[], keys: readonly string[]): string {
184  const names: string[] = []
185  for (const key of keys) {
186    const k = parseWakeKey(key)
187    const run = runs.find(r => r.id === k.runId)
188    const model = run?.slots.find(s => s.slot === k.slot)?.model
189    const name = run ? (k.slot === '*' ? runLabel(run) : `${slotName(run, k.slot)}${model ? ` ${model}` : ''}`) : key
190    if (!names.includes(name)) names.push(name)
191  }
192  return names.join(', ')
193}
194
195/** What one terminal state reads as in the text, with the reason claudish gave (closed set only). */
196function terminalPhrase(run: ClaudishRun, slot: string, state: ClaudishSlotState, reason: string | null, detail: string | null = null): string {
197  switch (state) {
198    case 'CANCELLED':
199      return run.personStops.includes(slot) ? 'CANCELLED (stopped by the person)' : 'CANCELLED'
200    case 'TIMEOUT':
201      return 'TIMEOUT'
202    case 'FAILED':
203    case 'EMPTY':
204      if (reason && detail) return `${state} (${reason}: ${detail})`
205      return reason ? `${state} (${reason})` : detail ? `${state} (${detail})` : state
206    case 'LOST':
207      return 'no longer reported by claudish, so check its status'
208    default:
209      return state
210  }
211}
212
213function waitingPhrase(state: ClaudishSlotState, asked: boolean): string {
214  if (state === 'AWAITING_PERMISSION') return 'is waiting on a permission dialog'
215  return asked ? 'is asking a question and waiting for an answer' : 'finished its turn and is waiting for input'
216}
217
218/** How each terminal state is counted in a run's tally, in the order the tally names them. */
219const OUTCOMES: readonly (readonly [ClaudishSlotState, string])[] = [
220  ['COMPLETED', 'completed'],
221  ['FAILED', 'failed'],
222  ['EMPTY', 'empty'],
223  ['TIMEOUT', 'timed out'],
224  ['CANCELLED', 'cancelled'],
225  ['LOST', 'lost'],
226]
227
228/**
229 * A panel run's standing, said outright: how many slots are done and how they ended, and, once
230 * every slot is terminal, that the run is finished. The model must not infer the end from the
231 * absence of a "still running" line. Null for a run with no slots yet.
232 */
233function progressLine(run: ClaudishRun): string | null {
234  const total = run.slots.length
235  if (total === 0) return null
236  const done = run.slots.filter(s => isTerminal(s.state))
237  const tally = OUTCOMES
238    .map(([state, word]) => [done.filter(s => s.state === state).length, word] as const)
239    .filter(([n]) => n > 0)
240    .map(([n, word]) => `${n} ${word}`)
241    .join(', ')
242  const counted = `${done.length} of ${total} ${total === 1 ? 'slot' : 'slots'} done${tally ? ` (${tally})` : ''}`
243  return done.length === total
244    ? `  run finished: ${counted}. No more messages will arrive for this run.`
245    : `  progress: ${counted}`
246}
247
248type SlotClaim = { slot: string; terminal: ClaudishSlotState | null; wait: { n: number; state: ClaudishSlotState } | null }
249
250function fetchLine(hint: string, states: readonly ClaudishSlotState[]): string {
251  if (/^[A-Z]/.test(hint)) return `${hint}.`
252  return states.every(isTerminal) ? `Fetch the result now: ${hint}.` : `Next: ${hint}.`
253}
254
255/**
256 * The prompt naming every claimed key (pure). Only sanctioned identifiers reach it: the run
257 * line and fetch line from the port, slot ids, sanitised model ids, states, closed-set
258 * reasons, fixed phrases and the nonce. Never activity, provider or screen text.
259 */
260export function composeWake(
261  runs: readonly ClaudishRun[],
262  claimed: readonly { key: string; state: ClaudishSlotState }[],
263  nonce: string,
264  words: Words,
265): string {
266  const byRun = new Map<string, Map<string, SlotClaim>>()
267  const orphans: { key: string; state: ClaudishSlotState }[] = []
268  for (const c of claimed) {
269    const k = parseWakeKey(c.key)
270    if (!runs.some(r => r.id === k.runId)) {
271      orphans.push(c)
272      continue
273    }
274    const slots = byRun.get(k.runId) ?? new Map<string, SlotClaim>()
275    byRun.set(k.runId, slots)
276    const sc = slots.get(k.slot) ?? { slot: k.slot, terminal: null, wait: null }
277    if (k.wait === null) sc.terminal = c.state
278    else if (sc.wait === null || k.wait > sc.wait.n) sc.wait = { n: k.wait, state: c.state }
279    slots.set(k.slot, sc)
280  }
281
282  let finished = 0
283  let waiting = 0
284  const blocks: string[] = []
285  for (const run of runs) {
286    const slots = byRun.get(run.id)
287    if (!slots) continue
288    const lines: string[] = [words.runLine(run.ref, runLabel(run))]
289    const fetch: FetchSlot[] = []
290    for (const sc of slots.values()) {
291      const now = run.slots.find(s => s.slot === sc.slot)
292      const current = now?.state ?? sc.terminal ?? sc.wait?.state ?? 'UNKNOWN'
293      const asked = now?.asked ?? false
294      let phrase: string
295      if (sc.slot === '*') {
296        lines.push(`  - run ${runLabel(run)} never appeared in claudish's list, so check its status`)
297        finished += 1
298        fetch.push({ slot: sc.slot, state: 'LOST', asked: false })
299        continue
300      }
301      if (sc.terminal !== null) {
302        finished += 1
303        phrase = terminalPhrase(run, sc.slot, sc.terminal, now?.reason ?? null, now?.detail ?? null)
304        if (sc.wait !== null) {
305          const had = `it had been waiting for ${waitWord(sc.wait.state)}`
306          phrase = phrase.endsWith(')') ? `${phrase.slice(0, -1)}; ${had})` : `${phrase} (${had})`
307        }
308        fetch.push({ slot: sc.slot, state: sc.terminal, asked: false })
309      } else {
310        const wait = sc.wait ?? { n: 0, state: 'AWAITING_INPUT' as ClaudishSlotState }
311        waiting += 1
312        phrase = isWaiting(current) ? waitingPhrase(current, asked) : `waited for ${waitWord(wait.state)}; now ${current}`
313        fetch.push({ slot: sc.slot, state: current, asked })
314      }
315      const model = now?.model ?? 'unknown model'
316      lines.push(run.ref.kind === 'delegation' ? `  - ${model}: ${phrase}` : `  - slot ${sc.slot} ${model}: ${phrase}`)
317    }
318    const running = run.ref.kind === 'panel'
319      ? run.slots.filter(s => !isTerminal(s.state) && !slots.has(s.slot)).map(s => `${s.slot} ${s.model}`)
320      : []
321    if (running.length > 0) lines.push(`  still running: ${running.join(', ')}`)
322    const progress = run.ref.kind === 'panel' ? progressLine(run) : null
323    if (progress !== null) lines.push(progress)
324    lines.push(fetchLine(words.fetchHint(run.ref, fetch), fetch.map(f => f.state)))
325    if (running.length > 0) lines.push('Another message like this arrives as each running slot finishes.')
326    else if (run.ref.kind === 'delegation' && fetch.some(f => !isTerminal(f.state))) {
327      lines.push('Another message like this arrives each time it waits again, and when it ends.')
328    }
329    blocks.push(lines.join('\n'))
330  }
331  if (orphans.length > 0) {
332    finished += orphans.length
333    blocks.push(['Runs no longer listed here:', ...orphans.map(o => `  - ${o.key}: ${o.state}`)].join('\n'))
334  }
335
336  const heads: string[] = []
337  if (finished > 0) heads.push(`${finished} ${finished === 1 ? 'slot' : 'slots'} finished`)
338  if (waiting > 0) heads.push(waiting === 1 ? 'a delegated session is waiting for you' : `${waiting} delegated sessions are waiting for you`)
339  const head = heads.join('; ')
340  return [`${head.charAt(0).toUpperCase()}${head.slice(1)}. (ref ${nonce})`, ...blocks].join('\n')
341}
342
343// ── the timer ─────────────────────────────────────────────────────────────────
344
345function cancelTimer(): void {
346  timer?.t.cancel()
347  timer = null
348}
349
350/** Keeps one timer armed for the earliest owed time; none when nothing is owed. */
351function armTimer(host: Host, at: number | null, now: number): void {
352  if (at === null) {
353    cancelTimer()
354    return
355  }
356  if (timer !== null && timer.at <= at) return
357  cancelTimer()
358  const armed = { at, t: host.after(Math.max(0, at - now), () => {
359    if (timer === armed) timer = null
360    flushDetached(host)
361  }) }
362  timer = armed
363}
364
365/** A flush nobody awaits (a timer, a turn's end, a load): a failure is one debug line, never an unhandled rejection. */
366export function flushDetached(host: Host, opts: { atTurnEnd?: boolean } = {}): void {
367  flush(host, opts).catch((err: unknown) => {
368    try {
369      host.debug(`claudish wake: flush failed: ${err instanceof Error ? err.message : String(err)}`)
370    } catch {
371      // the environment that armed it is gone (a reload); the next load's flush owns the ledger
372    }
373  })
374}
375
376// ── session boundaries and turns ──────────────────────────────────────────────
377
378/** session.start: the volatile state a reload strands is reset (a stop request never outlives
379 *  the timer that would expire it; a turn flag never holds notices for a turn this load won't see end). */
380export async function resetVolatile(host: Host): Promise<void> {
381  cancelTimer()
382  await host.store.stopRequests.update(m => (Object.keys(m).length === 0 ? m : {}))
383  await host.store.turn.update(t => (t.isRunning ? { isRunning: false, since: 0 } : t))
384}
385
386/** session.start, after the reset: entries a reload caught inflight are settled from the transcript. */
387export async function recover(host: Host): Promise<void> {
388  const l = await host.store.ledger.read()
389  const stranded = new Set(Object.values(l.entries).flatMap(e => (e.kind === 'inflight' ? [e.nonce] : [])))
390  if (stranded.size === 0) return
391  let rows: readonly TranscriptRow[] = []
392  try {
393    rows = await host.messages()
394  } catch (err) {
395    host.debug(`claudish wake: transcript unreadable, re-sending in-flight notices (${err instanceof Error ? err.message : String(err)})`)
396  }
397  await host.store.ledger.update(v => (v.epoch !== l.epoch ? v : reconcileInflight(v, Array.isArray(rows) ? rows : [], stranded)))
398}
399
400/** turn.start is raised by the main loop alone (a subagent's run raises none). */
401export async function onTurnStart(
402  host: Host,
403  e: Frozen<TurnStartInput>,
404  next: Next<'turn.start'>,
405): Promise<TurnStartResult> {
406  const now = await host.now()
407  await host.store.turn.update(() => ({ isRunning: true, since: now }))
408  return next(e)
409}
410
411/** The main loop's turn ended: notices it deferred, and parked ones, are delivered now. */
412export async function onTurnComplete(
413  host: Host,
414  e: Frozen<TurnCompleteInput>,
415  next: Next<'turn.complete'>,
416): Promise<TurnCompleteResult> {
417  const result = await next(e)
418  if (e.agentId === undefined) {
419    await host.store.turn.update(t => (t.isRunning ? { isRunning: false, since: 0 } : t))
420    flushDetached(host, { atTurnEnd: true })
421  }
422  return result
423}
424
425// ── notice and flush ──────────────────────────────────────────────────────────
426
427/**
428 * From the poll tick: creates a pending entry for each owed unit of a drawn run that has
429 * none, toasts each one created, and flushes. Writes nothing when every unit has an entry.
430 */
431export async function notice(
432  host: Host,
433  epoch: number,
434  runs: ClaudishRuns,
435  feeds: Readonly<Record<string, ClaudishFeedSupport>>,
436): Promise<void> {
437  const units = wakeUnits(runs.list.filter(r => isDrawn(r, feeds)))
438  if (units.length === 0) return
439  const before = await host.store.ledger.read()
440  if (before.epoch !== epoch || units.every(u => u.key in before.entries)) return
441  const now = await host.now()
442  const [, created] = await host.store.ledger.claim(l => createPending(l, epoch, units, now))
443  for (const u of created) {
444    const t = toastText(runs.list, u)
445    host.toast(t.text, t.timeoutMs)
446  }
447  if (created.length > 0) await flush(host)
448}
449
450/**
451 * Delivers every due entry in one prompt, unless the main loop's turn runs (then at its
452 * end). Called from notice, the main loop's turn.complete (atTurnEnd), session.start and
453 * the wake timer: the complete trigger set. After it, nothing is owed or the timer is armed.
454 */
455export async function flush(host: Host, { atTurnEnd = false }: { atTurnEnd?: boolean } = {}): Promise<void> {
456  const now = await host.now()
457  const turn = await host.store.turn.read()
458  if (turn.isRunning && now - turn.since < WAKE_HOLD_GUARD_MS) {
459    armTimer(host, turn.since + WAKE_HOLD_GUARD_MS, now)
460    return
461  }
462  const before = await host.store.ledger.read()
463  if (!Object.values(before.entries).some(e => isDue(e, now, atTurnEnd))) {
464    armTimer(host, earliestRetryAt(before, now), now)
465    return
466  }
467  flushSeq += 1
468  const nonce = `w${hex8(fnv1a32(`${now}|${flushSeq}`))}` // all 32 bits: matched as `(ref …)` in the transcript
469  const [ledger, claimed] = await host.store.ledger.claim(l => claimDue(l, now, atTurnEnd, nonce))
470  if (claimed.length === 0) {
471    armTimer(host, earliestRetryAt(ledger, now), now)
472    return
473  }
474  const runsNow = await host.store.runs.read()
475  const text = composeWake(runsNow.list, claimed, nonce, host.source)
476  const epochNow = (await host.store.ledger.read()).epoch
477  if (epochNow !== ledger.epoch) return // a /clear or resume landed: those entries are gone
478  const res = await host.submit(text) // no await between the epoch read and this call
479  let after: ClaudishLedger
480  if (res.accepted) {
481    after = await host.store.ledger.update(l => markDelivered(l, nonce, now))
482    const parkedLeft = Object.values(after.entries).some(e => e.kind === 'parked')
483    if (!parkedLeft && claimed.some(c => c.wasParked)) host.status(undefined)
484  } else {
485    after = await host.store.ledger.update(l => markRefused(l, nonce, now, res.reason))
486    host.toast(`Result notice for ${keyLabels(runsNow.list, claimed.map(c => c.key))} not delivered (${res.reason}); retrying`, 6_000)
487    const parked = Object.entries(after.entries).filter(([, e]) => e.kind === 'parked').map(([k]) => k)
488    if (parked.length > 0) {
489      host.status(`${parked.length} result ${parked.length === 1 ? 'notice' : 'notices'} waiting to be delivered: ${keyLabels(runsNow.list, parked)}`)
490      for (const c of claimed) {
491        if (!c.wasParked && parked.includes(c.key)) host.debug(`claudish wake: notice ${c.key} parked after ${WAKE_QUICK_ATTEMPTS} refusals (${res.reason})`)
492      }
493    }
494  }
495  armTimer(host, earliestRetryAt(after, now), now)
496}
497
hooks/status/controls.ts 139 lines
1// What the band's and the panel's buttons do. State goes through the Store it is handed (bound to
2// the render dispatch whose tree held the button); effects through the Host. No engine
3// interface spelled here, and no claudish tool named: Stop reaches claudish through the
4// port's `stop`.
5
6import type { ClaudishPaneView } from '../../types'
7import { SHOW_COLUMNS, SHOW_PANE_ID, SHOW_PANE_TITLE, SHOW_ROWS, STOP_CONFIRM_MS, assertNever, paneId, slotKey, withPersonStop } from './domain'
8import type { Host, PressUi, Store } from './host'
9import type { SlotTarget } from './layout'
10import type { StopResult } from './run-source'
11
12type StopMove = 'arm' | 'send' | 'none'
13
14/**
15 * Slot keys whose cancel call has not answered yet. A cancel waits on Claude Code's own
16 * permission dialog first, for as long as the person takes to read it; the poll carries on
17 * meanwhile (its read-only calls are allowed before the permission check, so none queues
18 * behind that dialog). Module state: it dies with a reload, as does the closure awaiting
19 * the call.
20 */
21const cancelling = new Set<string>()
22
23function without<T>(m: Readonly<Record<string, T>>, key: string): Record<string, T> {
24  if (!(key in m)) return m as Record<string, T>
25  const next = { ...m }
26  delete next[key]
27  return next
28}
29
30/**
31 * Stop needs two presses within STOP_CONFIRM_MS, and cancels only that slot. ONE update
32 * decides which press this is and claims the move it makes, so two presses in one tick,
33 * or a press racing the expiry timer, can never both send.
34 */
35export async function pressStop(press: Store, host: Host, target: SlotTarget): Promise<void> {
36  const key = slotKey(target.runId, target.slot)
37  const now = await host.now()
38  const until = now + STOP_CONFIRM_MS
39  const [, move] = await press.stopRequests.claim<StopMove>(m => {
40    const r = m[key]
41    if (r?.kind === 'armed' && now < r.until) return [{ ...m, [key]: { kind: 'sending', at: now } }, 'send']
42    if (r?.kind === 'sending' || r?.kind === 'sent') return [m, 'none']
43    return [{ ...m, [key]: { kind: 'armed', until } }, 'arm'] // the first press, or an expired arm
44  })
45  switch (move) {
46    case 'none':
47      return
48    case 'arm':
49      // A timer: the session-bound Store, since this press's dispatch is long gone by then.
50      host.after(STOP_CONFIRM_MS, () => {
51        void host.store.stopRequests.update(m => {
52          const r = m[key]
53          return r?.kind === 'armed' && r.until === until ? without(m, key) : m
54        })
55      })
56      return
57    case 'send': {
58      // However long the first cancel's dialog stays open, a slot never gets a second one: the
59      // claim above already refuses while the request is `sending`; this holds even when the
60      // atom was reset under a pending call (a /clear, a resume).
61      if (cancelling.has(key)) return
62      cancelling.add(key)
63      try {
64        await sendStop(press, host, target, key)
65      } finally {
66        cancelling.delete(key)
67      }
68      return
69    }
70    default:
71      assertNever(move)
72  }
73}
74
75/** The one cancel of a double press, and its answer: a failure of any kind toasts once and gives Stop back. */
76async function sendStop(press: Store, host: Host, target: SlotTarget, key: string): Promise<void> {
77  let res: StopResult
78  try {
79    // Provenance is written BEFORE the cancel is sent, so no poll can see CANCELLED without it.
80    await press.runs.update(v => (v.epoch !== target.epoch ? v : withPersonStop(v, target.runId, target.slot, true)))
81    res = await host.source.stop(target.ref, target.slot)
82  } catch (err) {
83    res = { kind: 'failed', reason: err instanceof Error ? err.message : String(err) }
84  }
85  // The answer can come long after the press (Claude Code asks its own question first), so
86  // what follows writes through the session-bound Store, as a timer does.
87  const after = host.store
88  if (res.kind === 'failed') {
89    try {
90      await after.runs.update(v => withPersonStop(v, target.runId, target.slot, false)) // roll provenance back
91      await after.stopRequests.update(m => without(m, key))
92    } finally {
93      host.toast(`Stop failed for ${target.slot} ${target.model}: ${res.reason}`)
94    }
95    return
96  }
97  // The confirmation timeout starts now that the cancel answered, never while its dialog was open.
98  const answeredAt = await host.now()
99  await after.stopRequests.update(m => (m[key]?.kind === 'sending' ? { ...m, [key]: { kind: 'sent', at: answeredAt } } : m))
100  if (!res.changed) {
101    // already terminal: this press stopped nothing, so the wake never credits the person
102    await after.runs.update(v => withPersonStop(v, target.runId, target.slot, false))
103  }
104}
105
106function seed(target: SlotTarget): () => ClaudishPaneView {
107  return () => ({ runId: target.runId, slot: target.slot, model: target.model, status: 'waiting', frame: null, note: null })
108}
109
110/** Makes a slot's tab the panel's active one, its view seeded `waiting` when it has none yet. Returns the tab's id. */
111export async function pressTab(press: Store, target: SlotTarget): Promise<string> {
112  const id = paneId(target.runId, target.slot)
113  await press.showTab.update(() => ({ active: id }))
114  if ((await press.panes.read(id)) === null) await press.panes.update(id, seed(target))
115  return id
116}
117
118/**
119 * Show opens the panel on this slot's tab; with the panel open, it only moves it to that tab. The
120 * panel holds a tab for every slot the band shows (poll.ts seeds them), so no slot needs a Show
121 * of its own to be there. Should Claude Code keep the panel undrawn, a toast gives its reason
122 * rather than nothing happening. Returns the tab's id, for its first capture.
123 */
124export async function pressShow(press: Store, ui: PressUi, host: Host, target: SlotTarget): Promise<string> {
125  // The open is the press's first call: Claude Code places a pane at any width only while the
126  // person's press is behind it, and an open after an await reads as unasked (measured at 106
127  // columns). Opening the open panel only retitles it.
128  const opening = ui.open(SHOW_PANE_ID, SHOW_PANE_TITLE, { columns: SHOW_COLUMNS, rows: SHOW_ROWS })
129  const id = await pressTab(press, target)
130  const opened = await opening
131  if (!opened.isPlaced) host.toast(`Show ${target.model}: not drawn yet. ${opened.reason}`, 8_000)
132  return id
133}
134
135/** Hide puts the panel away. Its tabs and their views stay: the next Show brings them back as they were. */
136export async function pressHide(ui: PressUi): Promise<void> {
137  await ui.close(SHOW_PANE_ID)
138}
139
hooks/status/band.tsx 174 lines
1// The band above the prompt: a pure tree builder. Values and closures in, a tree out;
2// it reads no state, writes none, and calls only the actions it was given, from onPress.
3// Every Text truncates (never wraps). The live cell is a surface module (flow.tsx), so its
4// timeline animates without the band redrawing.
5
6import type { Elements, RenderElement } from 'claude-code'
7import type { Ink, Palette } from './palette'
8import { STALE_NUMBER_S, STALE_STEPS_S } from './domain'
9import { legendOf, type FlowProps, type LegendProps } from './flow'
10import { LEAD_CELLS, STOP_CELLS, SHOW_CELLS, rowCells, type Badge, type BandModel, type BandRow, type Segment, type SlotTarget } from './layout'
11
12/** How the live cell draws a slot's timeline: the person's pick in /config (the plugin's `timeline` option). */
13export type TimelineLook = FlowProps['look']
14
15/** The elements the band and the panel draw with: in every surface's table, but `Client`, which a
16 *  remote surface leaves out (the meter is then drawn still). */
17export type Els = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Client?: Elements['terminal']['Client'] }
18
19export type BandActions = {
20  stop(target: SlotTarget): void
21  /** opens the Show panel on this slot's tab, or moves the open panel to it */
22  show(target: SlotTarget): void
23  /** puts the Show panel away */
24  hide(): void
25}
26
27function segmentProps(s: Segment): Record<string, unknown> {
28  return {
29    ...(s.color ? { color: s.color } : {}),
30    ...(s.backgroundColor ? { backgroundColor: s.backgroundColor } : {}),
31    ...(s.dim ? { dimColor: true } : {}),
32    ...(s.bold ? { bold: true } : {}),
33  }
34}
35
36/** Segments as one outer Text: one truncation for the whole line, a nested Text per coloured run. */
37export function segmentsText(els: Els, segments: readonly Segment[], lead: RenderElement[] = []): RenderElement {
38  const { Text } = els
39  return (
40    <Text wrap="truncate-end">
41      {lead}
42      {segments.map((s, i) => (
43        <Text key={`seg:${i}`} wrap="truncate-end" {...segmentProps(s)}>
44          {s.text}
45        </Text>
46      ))}
47    </Text>
48  ) as RenderElement
49}
50
51/** One half of a badge: its text on its fill, bold, as madbench draws its badges. */
52function half(els: Els, key: string, text: string, ink: Ink, bold = true): RenderElement {
53  const { Text } = els
54  return (<Text key={key} wrap="truncate-end" color={ink.fg} backgroundColor={ink.bg} {...(bold ? { bold: true } : {})}>{text}</Text>) as RenderElement
55}
56
57/** The status badge: the code on its hue's solid fill, then the runtime as text in the same hue, no fill. */
58export function badgeParts(els: Els, palette: Palette, badge: Badge, code: string, runtime: string): RenderElement[] {
59  const { Text } = els
60  const parts = [half(els, 'code', code, palette.solid[badge.hue])]
61  if (runtime !== '') parts.push((<Text key="runtime" wrap="truncate-end" color={palette.text[badge.hue]}>{runtime}</Text>) as RenderElement)
62  return parts
63}
64
65/**
66 * A button, drawn as one: `[ label ]` in its colour, no fill, so it never reads as a badge. An
67 * armed Stop fills (its second press cancels). Pressed by a click, or Enter once the band has the keys.
68 */
69export function button(els: Els, key: string, label: string, ink: { color: string; backgroundColor?: string; bold?: boolean }, onPress: () => void): RenderElement {
70  const { Button, Text } = els
71  return (
72    <Button key={key} plain label={label} onPress={onPress}>
73      <Text wrap="truncate-end" color={ink.color} {...(ink.backgroundColor ? { backgroundColor: ink.backgroundColor } : {})} {...(ink.bold ? { bold: true } : {})}>{`[ ${label} ]`}</Text>
74    </Button>
75  ) as RenderElement
76}
77
78function row(els: Els, r: BandRow, model: BandModel, actions: BandActions, palette: Palette, look: TimelineLook): RenderElement {
79  const { Box, Client, Text } = els
80  const plan = model.plan!
81  const c = rowCells(r, plan)
82  const t = (text: string, props: Record<string, unknown> = {}) => <Text wrap="truncate-end" {...props}>{text}</Text>
83  const stop = r.stop === 'stop' ? button(els, `stop:${r.key}`, 'Stop', { color: 'error', bold: true }, () => actions.stop(r.target))
84    : r.stop === 'confirm' ? button(els, `stop:${r.key}`, 'Stop?', { color: 'inverseText', backgroundColor: 'error', bold: true }, () => actions.stop(r.target))
85    : r.stop === 'stopping' ? t('stopping…', { dimColor: true })
86    : null
87  return (
88    <Box key={`row:${r.key}`} flexDirection="row" gap={1}>
89      {t(c.lead, r.attention ? { color: 'permission' } : {})}
90      {plan.id > 0 && t(c.id, { dimColor: true })}
91      <Text wrap="truncate-end">{badgeParts(els, palette, r.badge, c.code, c.runtime)}</Text>
92      {/* The model badge, its provider and the stats block: one block, no gap inside. */}
93      <Box flexDirection="row">
94        {plan.model > 0 && (r.model === '' ? t(' '.repeat(plan.model + plan.provider)) : (
95          <Text wrap="truncate-end">
96            {half(els, 'model', c.model, palette.solid.model)}
97            {plan.provider > 0 && half(els, 'provider', c.provider, palette.quiet.model)}
98          </Text>
99        ))}
100        {plan.tokens + plan.tools + plan.loops + plan.cost > 0 && (
101          // One block of badges, no gap inside: tokens on two pale greens, then tool calls, loops
102          // and cost, each on its hue's quiet tint. The cells (rowCells) carry the padding.
103          <Text wrap="truncate-end">
104            {plan.tokens > 0 && (r.tokensOut === ''
105              ? half(els, 'in', c.tokensIn, palette.tokensIn, false)
106              : <Text key="tokens" wrap="truncate-end">{half(els, 'in', c.tokensIn, palette.tokensIn, false)}{half(els, 'out', c.tokensOut, palette.tokensOut, false)}</Text>)}
107            {plan.tools > 0 && half(els, 'tools', c.tools, palette.quiet.tools)}
108            {plan.loops > 0 && half(els, 'loops', c.loops, palette.quiet.loops)}
109            {plan.cost > 0 && half(els, 'cost', c.cost, palette.quiet.cost)}
110          </Text>
111        )}
112      </Box>
113      {/* Only a mixed batch or a disagreement fills it: a single agent is the header's. */}
114      {plan.agent > 0 && t(c.agent, r.agentMismatch ? { color: 'warning' } : { dimColor: true })}
115      {plan.activity > 0 && t(c.activity, { dimColor: true })}
116      {/* The live cell takes every free cell up to the buttons: the slot's timeline, live or ended.
117          Where the surface draws no module, the stale-meter stands still. */}
118      {plan.meter > 0 && r.trail !== null && Client ? (
119        <Client
120          key={`timeline:${r.key}`}
121          module="./flow.tsx"
122          width={plan.meter}
123          props={{
124            look, steps: r.trail.steps, elapsed: r.trail.elapsed, live: r.trail.live, idle: r.trail.idle, endedFor: r.trail.endedFor,
125            staleAfter: STALE_NUMBER_S, staleFull: STALE_STEPS_S[STALE_STEPS_S.length - 1]!, width: plan.meter, c: palette.timeline,
126          } satisfies FlowProps}
127        />
128      ) : plan.meter > 0 ? (
129        <Box flexGrow={1}>{r.meter !== null && t(`${c.meter}${c.meterNumber}`, { color: r.meter.color })}</Box>
130      ) : null}
131      {/* With the meter column dropped there is no spacer (it would cost a gap the plan does not
132          count): the buttons' own box grows and holds them right. */}
133      <Box flexShrink={0} flexDirection="row" gap={1} {...(plan.meter > 0 ? {} : { flexGrow: 1, justifyContent: 'flex-end' })}>
134        {plan.stop > 0 && <Box width={STOP_CELLS} flexShrink={0} justifyContent="flex-end">{stop}</Box>}
135        <Box width={SHOW_CELLS} flexShrink={0}>
136          {r.show && button(els, `show:${r.key}`, 'Show', r.active ? { color: 'inverseText', backgroundColor: 'ide', bold: true } : { color: 'ide', bold: true }, () => actions.show(r.target))}
137        </Box>
138      </Box>
139    </Box>
140  ) as RenderElement
141}
142
143/** What the finished blocks' colours mean, under the rows, while a live row draws them; none once every row has ended. */
144function legend(els: Els, model: BandModel, palette: Palette, look: TimelineLook): RenderElement | null {
145  const { Box, Client } = els
146  if (look !== 'badges' || !Client || !model.plan || model.plan.meter <= 0) return null
147  const live = model.rows.flatMap(r => (r.trail?.live ? [r.trail.steps] : []))
148  const items = legendOf(live, palette.timeline)
149  if (items.length === 0) return null
150  // Drawn by the timeline's module, which owns the faded fills; the band itself draws only theme keys.
151  return (
152    <Box key="legend" flexDirection="row">
153      <Box width={LEAD_CELLS} flexShrink={0} />
154      <Client key="legend" module="./flow.tsx" props={{ legend: items, c: palette.timeline } satisfies LegendProps} />
155    </Box>
156  ) as RenderElement
157}
158
159/** The band: the header (with Hide while the Show panel is open), one row per slot fitted to the band's width, and a fold line. */
160export function bandTree(els: Els, model: BandModel, actions: BandActions, palette: Palette, look: TimelineLook = 'badges'): RenderElement {
161  const { Box, Text } = els
162  return (
163    <Box flexDirection="column">
164      <Box key="header" flexDirection="row">
165        <Box flexGrow={1}>{segmentsText(els, model.header)}</Box>
166        {model.panelOpen && <Box width={SHOW_CELLS} flexShrink={0}>{button(els, 'hide', 'Hide', { color: 'suggestion', bold: true }, () => actions.hide())}</Box>}
167      </Box>
168      {model.plan !== null && model.rows.map(r => row(els, r, model, actions, palette, look))}
169      {model.more !== null && <Text wrap="truncate-end" dimColor>{`  ${model.more}`}</Text>}
170      {model.plan !== null && legend(els, model, palette, look)}
171    </Box>
172  ) as RenderElement
173}
174
hooks/status/palette.ts 141 lines
1// The badges' colours, as madbench draws its badges (madbench internal/tui/theme.go): one hue
2// per meaning, a solid half (the hue, with whichever of white or ink reads better on it) and a
3// quiet half (the hue tinted toward the page). Theme keys carry no tints of blue, teal or violet,
4// so the badges and the value text use these raw colours, picked by the person's Claude Code theme
5// (paletteFor). The rest of the band keeps theme keys.
6
7export type Hue = 'run' | 'ask' | 'done' | 'fail' | 'format' | 'stopped' | 'model' | 'tools' | 'loops' | 'cost'
8export type Ink = { fg: string; bg: string }
9/** solid and quiet: a badge's two halves; text: the hue alone, for coloured text with no fill;
10 *  tokensIn / tokensOut: the tokens badge's two halves, two greens (black text on light, white on dark). */
11export type Palette = {
12  solid: Readonly<Record<Hue, Ink>>; quiet: Readonly<Record<Hue, Ink>>; text: Readonly<Record<Hue, string>>
13  tokensIn: Ink; tokensOut: Ink
14  timeline: TimelineColors
15}
16
17/**
18 * The live cell's colours (flow.tsx), raw, since it draws on its own thread and reads no theme:
19 * each tool family's badge, the kinds' badges, the words, pac-man and the ghost, the silence's
20 * three steps, and the page the legend chips fade toward.
21 */
22export type TimelineColors = {
23  read: string; edit: string; run: string; web: string; agent: string; other: string
24  think: string; say: string; ask: string; done: string; fail: string; finish: string
25  words: string; dim: string; ink: string; timeInk: string; page: string
26  pac: string; pacQuiet: string; ghost: string; ghost2: string
27  ok: string; warn: string; bad: string
28  /** a job's time once its fill turns amber or red for silence */
29  silenceInk: string
30}
31
32// Tool families as the preview settled them: teal reads, gold edits, pink runs, blue reaches the
33// web, orange hands work to an agent or an MCP tool. Pac-man is the
34// orange-gold that reads on a cream page and a dark one.
35const TIMELINE_LIGHT: TimelineColors = {
36  read: '#0D9488', edit: '#A16207', run: '#BE185D', web: '#0369A1', agent: '#C2410C', other: '#4B5563',
37  think: '#7C3AED', say: '#4D7C0F', ask: '#B45309', done: '#166534', fail: '#B91C1C', finish: '#15803D',
38  words: '#4B5068', dim: '#8F94AC', ink: '#FFFFFF', timeInk: '#0B0B12', page: '#FFFFFF',
39  pac: '#E8890C', pacQuiet: '#A8743A', ghost: '#B91C1C', ghost2: '#BE185D',
40  ok: '#166534', warn: '#B45309', bad: '#B91C1C', silenceInk: '#FFFFFF',
41}
42const TIMELINE_DARK: TimelineColors = {
43  read: '#4FD6BE', edit: '#FFD479', run: '#F38BA8', web: '#7DCFFF', agent: '#FF9E64', other: '#D8DAE5',
44  think: '#B794F6', say: '#A3E635', ask: '#FFB454', done: '#22E06B', fail: '#FF4D5E', finish: '#7EE2A0',
45  words: '#9AA0BC', dim: '#5A5E78', ink: '#0B0B12', timeInk: '#0B0B12', page: '#16171D',
46  pac: '#FFD23F', pacQuiet: '#A8743A', ghost: '#FF4D5E', ghost2: '#FF8AD8',
47  ok: '#22E06B', warn: '#FFB454', bad: '#FF4D5E', silenceInk: '#FFFFFF',
48}
49
50// madbench's stops: azure, honey, lime, coral, gold, pending grey; indigo (the model, as madbench's id
51// badge), teal, iris, gold (cost). Tokens take two fixed pale fills instead (TOKENS_LIGHT/DARK).
52const LIGHT: Readonly<Record<Hue, string>> = {
53  run: '#1D4ED8', ask: '#92400E', done: '#166534', fail: '#B91C1C', format: '#A16207',
54  stopped: '#8F94AC', model: '#4338CA', tools: '#0D9488', loops: '#7C3AED', cost: '#A16207',
55}
56const DARK: Readonly<Record<Hue, string>> = {
57  run: '#89B4FA', ask: '#FFB454', done: '#22E06B', fail: '#FF4D5E', format: '#FFD479',
58  stopped: '#5A5E78', model: '#5B6CE0', tools: '#4FD6BE', loops: '#B794F6', cost: '#FFD479',
59}
60const SNOW = '#FFFFFF'
61const INK = '#0B0B12'
62
63// The tokens badge recedes: two pale greens, a diff's added line (sent) and its added word (received),
64// sampled from the person's reference; written in black. On a dark page, the same two sunk dark, in white.
65const TOKENS_LIGHT = { tokensIn: { fg: INK, bg: '#CDFFD3' }, tokensOut: { fg: INK, bg: '#95FFA6' } }
66const TOKENS_DARK = { tokensIn: { fg: SNOW, bg: '#0F592A' }, tokensOut: { fg: SNOW, bg: '#16803D' } }
67
68// How far a hue travels for a light page's quiet half: the fill toward white, the text toward black.
69const LIGHT_FILL_TINT = 0.82
70const LIGHT_QUIET_TEXT = 0.38
71// A dark page's quiet half: the hue sunk toward black, written in white.
72const DARK_QUIET_FILL = 0.55
73
74type Rgb = readonly [number, number, number]
75
76function rgb(hex: string): Rgb {
77  const n = Number.parseInt(hex.slice(1), 16)
78  return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]
79}
80
81function hex([r, g, b]: Rgb): string {
82  return `#${[r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('').toUpperCase()}`
83}
84
85function mix(a: string, b: string, t: number): string {
86  const x = rgb(a)
87  const y = rgb(b)
88  return hex([x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t])
89}
90
91/** WCAG relative luminance. */
92function luminance(c: string): number {
93  const lin = (v: number) => {
94    const s = v / 255
95    return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
96  }
97  const [r, g, b] = rgb(c)
98  return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
99}
100
101function contrast(a: string, b: string): number {
102  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number]
103  return (hi + 0.05) / (lo + 0.05)
104}
105
106/** White or ink, whichever reads better on the fill: madbench's badgeInk. */
107function inkOn(fill: string): string {
108  return contrast(SNOW, fill) >= contrast(INK, fill) ? SNOW : INK
109}
110
111function build(hues: Readonly<Record<Hue, string>>, light: boolean): Palette {
112  const solid = {} as Record<Hue, Ink>
113  const quiet = {} as Record<Hue, Ink>
114  for (const [k, h] of Object.entries(hues) as [Hue, string][]) {
115    solid[k] = { fg: inkOn(h), bg: h }
116    quiet[k] = light
117      ? { fg: mix(h, '#000000', LIGHT_QUIET_TEXT), bg: mix(h, SNOW, LIGHT_FILL_TINT) }
118      : { fg: SNOW, bg: mix(h, '#000000', DARK_QUIET_FILL) }
119  }
120  return { solid, quiet, text: hues, ...(light ? TOKENS_LIGHT : TOKENS_DARK), timeline: light ? TIMELINE_LIGHT : TIMELINE_DARK }
121}
122
123export const LIGHT_PALETTE: Palette = build(LIGHT, true)
124export const DARK_PALETTE: Palette = build(DARK, false)
125
126/**
127 * The palette for the person's Claude Code theme (`light`, `dark-ansi`, …). `auto` follows the
128 * terminal, whose background a mod cannot ask; there, as tt does, TERM_THEME (`light` or `dark`)
129 * decides, then COLORFGBG's background (7 or 15 is light), and dark otherwise.
130 */
131export function paletteFor(theme: unknown, termTheme?: string, colorFgBg?: string): Palette {
132  const name = typeof theme === 'string' ? theme : ''
133  if (name.startsWith('light')) return LIGHT_PALETTE
134  if (name.startsWith('dark')) return DARK_PALETTE
135  const stated = termTheme?.trim().toLowerCase()
136  if (stated === 'light') return LIGHT_PALETTE
137  if (stated === 'dark') return DARK_PALETTE
138  const bg = colorFgBg?.split(';').pop()
139  return bg === '7' || bg === '15' ? LIGHT_PALETTE : DARK_PALETTE
140}
141
hooks/status/pane.tsx 116 lines
1// The Show panel: a pure tree builder over showTabs and paneModel. Its actions are picking a tab
2// and Hide: the child's screen stays read-only (no Input anywhere; the only Buttons are the tabs and
3// Hide).
4// Every frame colour arrives already spelled from layout.ts; the header and notes use theme keys.
5
6import type { RenderElement } from 'claude-code'
7import { badgeParts, button, segmentsText, type Els } from './band'
8import type { Palette } from './palette'
9import { CODE_CELLS, RUNTIME_CELLS, SHOW_CELLS, type PaneLine, type PaneModel, type ShowTab, type SlotTarget, type StripTab } from './layout'
10
11function frameLine(els: Els, line: PaneLine, row: number): RenderElement {
12  const { Text } = els
13  const blank = line.every(part => (typeof part === 'string' ? part : part.text) === '')
14  if (blank) return (<Text key={`line:${row}`} wrap="truncate-end">{' '}</Text>) as RenderElement
15  return (
16    <Text key={`line:${row}`} wrap="truncate-end">
17      {line.map((part, i) => (typeof part === 'string' ? part : (
18        <Text
19          key={`part:${i}`}
20          {...(part.color !== undefined ? { color: part.color } : {})}
21          {...(part.backgroundColor !== undefined ? { backgroundColor: part.backgroundColor } : {})}
22          {...(part.bold ? { bold: true } : {})}
23        >
24          {part.text}
25        </Text>
26      )))}
27    </Text>
28  ) as RenderElement
29}
30
31/**
32 * The tab strip, as tt draws its tabs, on the rows `wrapTabs` gave (R12): each label after a dot
33 * in its slot's status colour, a thin bar between two tabs of one row, the active one bold on a
34 * pale fill; at the right of the first row only, Hide, drawn as the band's Hide (Claude Code's own
35 * close mark is one cell and hard to hit); a rule under the last row. Every tab is drawn at its
36 * exact cost, so nothing shrinks. Pressing a tab shows it; Hide puts the panel away.
37 */
38function tabStrip(els: Els, tabs: readonly ShowTab[], strip: readonly (readonly StripTab[])[], active: string | null, columns: number, palette: Palette, select: (target: SlotTarget) => void, hide: () => void): RenderElement {
39  const { Box, Button, Text } = els
40  return (
41    <Box key="tabs" flexDirection="column">
42      {strip.map((row, r) => (
43        // The panel's width, so Hide sits at the first row's right edge.
44        <Box key={`tabrow:${r}`} flexDirection="row" width={Math.max(1, columns)}>
45          <Box flexDirection="row" flexGrow={1}>
46            {row.map(({ index, label }, k) => {
47              const tab = tabs[index]!
48              const on = tab.id === active
49              return (
50                <Box key={`tab:${tab.id}`} flexDirection="row" flexShrink={0}>
51                  {k > 0 && <Text wrap="truncate-end" color="subtle">│</Text>}
52                  {/* The Button keeps the full label (R6.5); only the drawn text is cut. */}
53                  <Button plain label={tab.label} onPress={() => select(tab.target)}>
54                    <Text wrap="truncate-end" {...(on ? { backgroundColor: palette.quiet.run.bg } : {})}>
55                      <Text color={palette.text[tab.hue]}>{' ●'}</Text>
56                      <Text {...(on ? { color: palette.text.run, bold: true } : { color: 'inactive' })}>{` ${label} `}</Text>
57                    </Text>
58                  </Button>
59                </Box>
60              )
61            })}
62          </Box>
63          {r === 0 && <Box width={SHOW_CELLS} flexShrink={0}>{button(els, 'hide-panel', 'Hide', { color: 'suggestion', bold: true }, hide)}</Box>}
64        </Box>
65      ))}
66      <Text wrap="truncate-end" color="subtle">{'─'.repeat(Math.max(1, columns))}</Text>
67    </Box>
68  ) as RenderElement
69}
70
71/**
72 * The panel: the tab strip (`strip` is `wrapTabs` over `tabs`, computed once by the caller so the
73 * rows it takes off the session view are the rows drawn), then the active tab's header row and its
74 * child's screen, or why there is none.
75 */
76export function panelTree(
77  els: Els,
78  tabs: readonly ShowTab[],
79  strip: readonly (readonly StripTab[])[],
80  active: string | null,
81  model: PaneModel | null,
82  columns: number,
83  palette: Palette,
84  select: (target: SlotTarget) => void,
85  hide: () => void,
86): RenderElement {
87  const { Box, Text } = els
88  return (
89    <Box flexDirection="column">
90      {tabStrip(els, tabs, strip, active, columns, palette, select, hide)}
91      {model ? paneTree(els, model, palette) : <Text wrap="truncate-end" dimColor>No run to show.</Text>}
92    </Box>
93  ) as RenderElement
94}
95
96/** One tab's body: the slot's agent when it names one, a header row, then the child's screen, or why there is none. */
97export function paneTree(els: Els, model: PaneModel, palette: Palette): RenderElement {
98  const { Box, Text } = els
99  const body = model.body
100  return (
101    <Box flexDirection="column">
102      {model.agent.length > 0 && segmentsText(els, model.agent)}
103      {segmentsText(els, model.header, model.badge ? badgeParts(els, palette, model.badge, ` ${model.badge.code.padEnd(CODE_CELLS - 2)} `, ` ${model.badge.runtime.padStart(RUNTIME_CELLS - 2)} `) : [])}
104      {body.kind === 'waiting' && <Text wrap="truncate-end" dimColor>Waiting for the first screen…</Text>}
105      {body.kind === 'unavailable' && <Text wrap="truncate-end" dimColor>{body.note}</Text>}
106      {body.kind === 'unavailable' && body.numbers !== '' && <Text wrap="truncate-end" dimColor>{body.numbers}</Text>}
107      {body.kind === 'note' && body.note !== '' && <Text wrap="truncate-end" dimColor>{body.note}</Text>}
108      {body.kind === 'frame' && (
109        <Box key="frame" flexDirection="column">
110          {body.lines.map((line, row) => frameLine(els, line, row))}
111        </Box>
112      )}
113    </Box>
114  ) as RenderElement
115}
116
hooks/status/run-source.ts 109 lines
1// THE PORT. The mod's core (poll, wake, controls, band, pane) speaks to claudish only
2// through this shape, in the mod's own vocabulary. One adapter implements it
3// (claudish-source.ts); nothing here names a claudish tool, mode, argument, capability
4// or response field. Types only.
5
6import type {
7  ClaudishFeatures,
8  ClaudishFrame,
9  ClaudishRunKind,
10  ClaudishRunRef,
11  ClaudishSlot,
12  ClaudishSlotState,
13} from '../../types'
14
15/** What the model's claudish tool call was, as observed after it ran. Engine envelope already stripped. */
16export type CallSeen = {
17  /** the engine's tool name, e.g. mcp__<server>__<tool> */
18  tool: string
19  /** the tool's own arguments only */
20  args: Readonly<Record<string, unknown>>
21  answer: {
22    /** the result as the model reads it (text blocks joined) */
23    text: string | null
24    isError: boolean
25  }
26}
27
28/** Only run starts matter to the core. Reads, cancels, judges and already-settled answers are 'other'. */
29export type RecognizedCall =
30  | { kind: 'start'; ref: ClaudishRunRef; label: string }
31  /** a start answer that decodes but carries no per-start id: the server predates the contract */
32  | { kind: 'precontract'; server: string; runKind: ClaudishRunKind; reason: string }
33  /** a start answer that does not decode, or lacks its address or per-start id: one debug line */
34  | { kind: 'unidentified'; reason: string }
35  | { kind: 'other' }
36
37/** What one feed (server × run kind) answered this tick. Facts, not policy: poll.ts decides support. */
38export type FeedAnswer =
39  /** the contract version 1, list capability present, answer decodes */
40  | { kind: 'speaks'; version: 1; can: ClaudishFeatures }
41  /** a declaration by the server, not a glitch: no contract version, or a non-contract error body */
42  | { kind: 'precontract'; reason: string }
43  /** the contract declared, but a version other than 1, or no list capability */
44  | { kind: 'declines'; reason: string }
45  /** not an error, but does not decode, or its row array is missing */
46  | { kind: 'garbled'; reason: string }
47  /** an error answer carrying the contract's error body (its code) */
48  | { kind: 'refused'; code: string }
49  /** the call rejected (transport, deny, protocol error) */
50  | { kind: 'unanswered'; reason: string }
51
52export type PollResult =
53  | { kind: 'ok'; slots: ClaudishSlot[] }
54  /** the feed spoke, but no row carries this run's per-start id (ref.token); or its row is too defective to list */
55  | { kind: 'missing'; reason: string | null }
56
57export type PollBatch = {
58  /** key: feedKey(ref) = `${server}#${kind}` */
59  feeds: ReadonlyMap<string, FeedAnswer>
60  /** key: run id; only runs of feeds that answered 'speaks' */
61  runs: ReadonlyMap<string, PollResult>
62}
63
64export type StopResult =
65  /** changed = this call moved the slot to CANCELLED */
66  | { kind: 'stopped'; changed: boolean }
67  | { kind: 'failed'; reason: string }
68
69export type CaptureResult =
70  /** a screen with seq ≥ 1; final = the pane is closed */
71  | { kind: 'frame'; frame: ClaudishFrame; final: boolean }
72  /** nothing new, or seq 0 (no frame yet, or a pane that never spawned) */
73  | { kind: 'unchanged'; final: boolean }
74  /** the run, session or slot is no longer retained */
75  | { kind: 'gone' }
76  /** any other error, a rejection, or an unparseable answer */
77  | { kind: 'unavailable'; reason: string }
78
79export type ResizeResult =
80  /** the size claudish set, after its own clamping */
81  | { kind: 'resized'; cols: number; rows: number }
82  /** the run, session or slot is no longer retained */
83  | { kind: 'gone' }
84  /** any other error (resize_unsupported included), a rejection, or an unparseable answer */
85  | { kind: 'failed'; reason: string }
86
87/** A watched run as poll() needs it: the mod's run id and its ref. */
88export type WatchedRun = { id: string; ref: ClaudishRunRef }
89
90export type FetchSlot = { slot: string; state: ClaudishSlotState; asked: boolean }
91
92export type RunSource = {
93  recognizeCall(call: CallSeen): RecognizedCall
94  /** One list call per feed that has a watched run; answers keyed by feed and by run id. Several runs may
95   *  share a ref.address (one path started twice); each is matched by its own ref.token, exactly. */
96  poll(runs: readonly WatchedRun[]): Promise<PollBatch>
97  stop(ref: ClaudishRunRef, slot: string): Promise<StopResult>
98  /** sinceSeq: the last seq drawn, 0 before the first frame. withSpans: ask for the child's colours;
99   *  poll.ts passes the feed's can.spans, and nothing else may ask. */
100  capture(ref: ClaudishRunRef, slot: string, sinceSeq: number, withSpans: boolean): Promise<CaptureResult>
101  /** Sets the child's terminal size, so it draws to the Show panel's size. poll.ts calls it only
102   *  where the feed's can.resize is true. */
103  resize(ref: ClaudishRunRef, slot: string, cols: number, rows: number): Promise<ResizeResult>
104  /** The wake text's line naming one run for the model: its label plus claudish's own address and id. */
105  runLine(ref: ClaudishRunRef, label: string): string
106  /** One sentence telling the model which call fetches these slots' results, or answers a waiting delegation. */
107  fetchHint(ref: ClaudishRunRef, slots: readonly FetchSlot[]): string
108}
109