cs's in-session mod: the rotate band above the prompt, forced rotation past CS_ROTATE_FORCE_CTX, and the wrap key

<img src="https://raw.githubusercontent.com/hex/claude-sessions/main/assets/banner.svg" width="100%" alt="cs: a session manager for Claude Code">
cs creates persistent workspaces for Claude Code, with session notes, conversation resume, and local git history.
Requires macOS or Linux, Bash 3.2+, git, jq, perl, Claude Code, and a UTF-8 locale. Remote control needs Claude Code 2.1.299+. Non-UTF-8 locales such as ja_JP.eucJP, ko_KR.eucKR, and zh_CN.eucCN cause syntax errors in cs and two of its hooks.
curl -fsSL https://github.com/hex/claude-sessions/releases/latest/download/install.sh | bash
From a checkout:
git clone https://github.com/hex/claude-sessions.git
cd claude-sessions
./install.sh
Review install.sh before running it. The piped command always installs the release, even inside a checkout. The installer puts the commands in ~/.local/bin/, registers hooks, and installs skills, mods, and Bash and Zsh completions. Updates and prebuilt picker downloads require ssh-keygen with -Y verify support to check the signed release manifest.
cs debug-api
One command, from any terminal: cs <name> creates the session the first time and resumes it every time after. It needs no project or git repository first.
cs debug-api. cs creates a workspace and opens Claude Code.Objective section and keeps notes under .cs/.cs debug-api again and accept the prompt to resume the recorded conversation.When you forget a name, a bare cs opens a picker of your sessions, and cs . reopens the one whose root you are in.
The statusline guide covers the quiet default layout, the band and the capsules, colors, thresholds, font setup, and agent rows.
| Feature | What it does | Details |
|---|---|---|
| Session records | Keeps objectives, per-actor narratives, memory, plans, checkpoints, and a timeline in .cs/. | Session layout |
| Crash recovery | Saves edits to shadow git refs without adding normal branch commits. | Autosave hook |
| Conversation rotation | Hands work to a fresh conversation through /rotate and /clear. | Rotation and queue hooks |
| Existing projects | cs -adopt <name> registers your project without moving it. | Adoption |
| Parallel worktrees | cs <base>@<feature> gives each feature its own checkout and session records. | Worktrees |
| Remote control | cs <name> --remote serves a session for the Claude app or web. | Remote control |
| Task queue | Runs confirmed tasks at turn boundaries, with failure, context, and quota breakers. | Queue behavior |
| Cross-session mail | Delivers local messages and wakes idle sessions for unread arrivals. | Mail wakes |
| Secrets | Uses the macOS keychain or encrypted files, with signed age exports for sync. | Secrets guide |
| Encrypted sessions | Keeps notes, transcripts, plans, and private state in a vault on macOS. | Encrypted sessions |
| Statusline | Shows session, git, model, context, queue, mail, and rate limits. | Statusline guide |
| Prompt grounding | Adds matching files, recent commits, changes, and clarification guidance to code-work prompts. | Scope hook |
| Prompt rewriting | Ctrl+G rewrites a draft in the composer for you to review before sending. | Prompt rewriter |
| Writing skills | Judges prose or drafts from a writing profile. | Skills |
| Session wrap | /wrap saves memory, summarizes the narrative, and archives completed tasks without committing. | Memory checks |
| Inline Mermaid | Draws supported flowcharts in replies, and a show-me skill answers "show me" with one. | Mermaid mod<br><img src="https://raw.githubusercontent.com/hex/claude-sessions/main/assets/mermaid.svg" width="260" alt="Reply prose, then the same prose with a drawn Mermaid chart"> |
| Chat feed | Folds each turn's tool calls into one line beside your messages and Claude's replies, off until you turn it on per session with the band's ctrl+x 3 or /feed on. | Feed mod |
| Release notes | Shows pending release notes in-session through /cs-update. | Update mod |
| Other front ends | Session hooks also work in desktop and IDE conversations opened in a .cs/ workspace. | Session resolution |
cs -uninstall
| Guide | Contents |
|---|---|
| Commands | Command reference, adoption, worktrees, queues, remote control, and completion. |
| Configuration | Every environment variable cs reads and the values it exports. |
| Session layout | Shared and local records, encryption, and merge policy. |
| Hooks | Hook behavior, prompt rewriting, and Claude Code mods. |
| Secrets | Storage backends, backups, and signed sync files. |
| Statusline | Segments, the quiet, band and capsule layouts, colors, thresholds, and agent rows. |
MIT. Contributions can start with an issue or pull request.
hooks/register.tsx 2190 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4// ABOUTME: cs mod: keys above the prompt: rotate past the threshold, wrap up, /clear once a handoff is armed, or start a queue nothing runs.
5// ABOUTME: A turn ending past CS_ROTATE_FORCE_CTX (default 80, off disables) runs /rotate itself, then counts down to the /clear (session colour, amber, crit); session.start writes a heartbeat for doctor.
6// ABOUTME: /queue adds a task to the session's walk-away queue through `cs -queue add`, at once even mid-turn; bare, it prints `cs -queue list`. /finish toasts its start and outcome and, while its gate runs, the band carries the elapsed time.
7// ABOUTME: The band carries a rail: one tick per prompt on the transcript's live branch (read after each turn), the one being read thick; a press or /cs next|prev|first|last|N scrolls the transcript to that prompt.
8import type { On, EngineInterface, PluginOptions, RenderElement, RenderSurface } from 'claude-code'
9
10declare const h: any
11declare const Fragment: any
12
13// KEEP IN SYNC with the ctx warn and crit defaults in bin/cs-statusline
14// (_seg_ctx): by default the band appears where the status bar turns amber and
15// the Stop hook gives its headroom notice. CS_STATUSLINE_CTX_WARN in the
16// process environment moves it, as it moves the bar; CS_ROTATE_BUTTON_CTX moves
17// the band alone. A value that is not a number is ignored.
18export const DEFAULT_PERCENT = 40
19
20// The count's colour ramp, in the status bar's inks. KEEP IN SYNC with _sgr in
21// bin/cs-statusline (tests/test_mod_rotate.sh pins every value here against
22// it): the session palette is Claude Code's /color, the tab colour cs sets;
23// amber and crit are the bar's warning and critical inks. Amber pivots on the
24// measured background's luminance and falls back to the theme; crit follows
25// the theme.
26export const SESSION_PALETTE: Record<string, string> = {
27 red: '220,38,38', blue: '106,155,204', green: '22,163,74', yellow: '202,138,4',
28 purple: '130,125,189', orange: '217,119,87', pink: '196,102,134', cyan: '8,145,178',
29}
30export const AMBER_LIGHT = '180,83,9'
31export const AMBER_DARK = '253,230,138'
32export const CRIT_LIGHT = '215,0,21'
33export const CRIT_DARK = '255,69,58'
34// Seconds left at which the count turns amber, and then crit (below CRIT_AT).
35export const AMBER_AT = 10
36export const CRIT_AT = 5
37
38// The colour the count wears with `left` seconds to go: the session's own
39// colour while there is time (none, so the surrounding ink, when the session
40// has no colour in the palette), amber from AMBER_AT, crit under CRIT_AT.
41export function countdownColor(left: number, session: string | undefined, bg: string | undefined, theme: string | undefined): string | undefined {
42 if (left < CRIT_AT) return `rgb(${theme === 'dark' ? CRIT_DARK : CRIT_LIGHT})`
43 if (left <= AMBER_AT) return amberColor(bg, theme)
44 return paletteColor(session)
45}
46
47// The bar's amber for this terminal: pivoted on the measured background's
48// luminance, and on the theme when there is no measurement.
49export function amberColor(bg: string | undefined, theme: string | undefined): string {
50 const rgb = (bg ?? '').split(';').map(part => (/^\s*\d{1,3}\s*$/.test(part) ? Number(part) : NaN))
51 const measured = rgb.length === 3 && rgb.every(v => v <= 255)
52 const light = measured ? 2126 * rgb[0] + 7152 * rgb[1] + 722 * rgb[2] >= 1530000 : theme !== 'dark'
53 return `rgb(${light ? AMBER_LIGHT : AMBER_DARK})`
54}
55
56// A session colour name as an rgb() the engine paints, or undefined for a name
57// outside the palette (state hand-edited, or from a newer Claude Code).
58export function paletteColor(name: string | undefined): string | undefined {
59 const rgb = name === undefined ? undefined : SESSION_PALETTE[name]
60 return rgb === undefined ? undefined : `rgb(${rgb})`
61}
62
63// Doctor observes the mod RUNNING, not merely installed: under a managed
64// machine's policy a mod can load and never run. Written when the plugin loads
65// (process start or reload; session.start does not fire on /clear). Path is
66// relative to the session's cwd, which under cs is the session directory (or
67// its worktree).
68export const HEARTBEAT = '.cs/local/cs.heartbeat'
69// Written by /wrap's last pass: the conversation it wrapped.
70export const WRAPPED = '.cs/local/wrapped'
71
72// The rotate skill's last step writes the handoff's basename here; cs's
73// SessionStart hook reads it on the next conversation and starts the handoff's
74// next step. While it names a handoff the conversation has nothing left to do
75// but /clear, whatever the context reads. An encrypted session keeps the
76// marker and its handoffs behind .cs/private (a link into its vault).
77export const MARKER = '.cs/local/pending-handoff'
78export const HANDOFFS = '.cs/handoffs'
79export const PRIVATE_MARKER = '.cs/private/pending-handoff'
80export const PRIVATE_HANDOFFS = '.cs/private/handoffs'
81
82// The conversation a forced rotation already ran /rotate for, by id. Written
83// BEFORE the run is scheduled: a rotation that fails must not be retried at
84// the end of every turn. Module state would not do: it survives a /clear
85// (measured; a timer started before one kept firing after it) and is lost
86// on a reload of the mod.
87export const FORCED = '.cs/local/cs.forced'
88// The conversation whose rotate button was pressed, by id, from just before
89// the press runs /rotate until the end of the next main-loop turn: cs
90// -archive-tasks plan reads it, as it reads FORCED, so the one-key rotation
91// does not stop to ask. Emptied at that turn's end, so a /rotate typed later
92// in the conversation asks as a manual one does.
93export const PRESSED = '.cs/local/cs.pressed'
94
95// Once the forced rotation has armed its handoff, how long the band counts
96// down before the mod runs the /clear itself. Pressing the button or sending a
97// prompt stops it.
98export const GRACE_SECONDS = 20
99// The percentage a turn must end past for the mod to rotate on its own. Above
100// the 65% nudge, so the ladder stays suggest -> offer -> force, and below where
101// Claude Code's own auto-compact lands, so a handoff is written while the
102// conversation is still whole.
103export const FORCE_DEFAULT = 80
104// How long cs may take to say whether it trusts the session's control files
105// (`cs -vet-session`, about 0.2 s measured) before the answer counts as a no.
106const VET_TIMEOUT_MS = 10000
107// How often an idle band asks cs for its features again, and how long one
108// answer may take: the readiness walks git and the tree for every feature.
109const FEATURES_POLL_MS = 30000
110const FEATURES_TIMEOUT_MS = 20000
111
112
113// The wrap key's question, and the answer that runs /wrap. `$.ui.ask` opens
114// the engine's own AskUserQuestion dialog and resolves to the label chosen, or
115// to free text typed under Other, so the answer is compared exactly; it rejects
116// when the dialog is dismissed and in a `-p` run, where there is nobody to ask.
117export const WRAP_QUESTION = 'Run /wrap for this session?'
118export const WRAP_YES = 'Yes, wrap up'
119
120// Bare /queue's offer, and the prompt a Start sends when no turn is running.
121// `cs -queue start` only arms the queue: the Stop hook hands over each task as
122// a turn ends, so an idle session needs one turn to reach that first stop.
123export const QUEUE_START = 'Start'
124export const QUEUE_COMPACT = 'Compact'
125// How much of a task a toast shows: a queued one, or the feature /finish lands.
126const TOAST_TASK_CHARS = 60
127
128function cutTask(task: string): string {
129 return task.length > TOAST_TASK_CHARS ? `${task.slice(0, TOAST_TASK_CHARS)}…` : task
130}
131
132// /finish's progress, as cs records it while `cs <base> -integrate-feature`
133// and `-retire-feature` run (_finish_progress_write in lib/30-worktree.sh):
134// one record, replaced whole at each step, behind .cs/private in an encrypted
135// session and in .cs/local otherwise. pid is the cs process that wrote it.
136export const FINISH_RECORD = 'finish-progress.json'
137// How often the watch /finish starts reads the record.
138export const FINISH_POLL_MS = 1000
139export type FinishRecord = {
140 id: string
141 pid: number
142 task: string
143 sha: string
144 step: string
145 gate_started?: number
146 result?: string
147 reason?: string
148}
149const FINISH_OUTCOMES = new Set(['landed', 'refused', 'retired'])
150
151// Asked after Start or Compact: how the tasks run, as the word cs -queue start
152// takes for each (none runs them in this conversation).
153export const QUEUE_MODE_QUESTION = 'How should the queued tasks run?'
154export const QUEUE_HERE = 'In this conversation'
155export const QUEUE_SUBAGENTS = 'In subagents'
156export const QUEUE_WORKFLOWS = 'As workflows'
157const QUEUE_MODE_WORDS: Record<string, string[]> = { [QUEUE_HERE]: [], [QUEUE_SUBAGENTS]: ['subagents'], [QUEUE_WORKFLOWS]: ['workflow'] }
158export const QUEUE_KICK = 'The cs walk-away queue is started. Reply with one short line saying so, then stop: the cs Stop hook hands you each queued task in turn.'
159
160// Every line the mod hands the engine to draw on a surface of the engine's
161// own: its dialogs, toasts, transcript notices, slash command replies and
162// slash menu rows, one table per surface, so a design tool outside cs can draw
163// each from these words. Claude Code leads each toast, notice and reply with the
164// plugin's name, so no line names cs first; one that starts `cs <base>` or
165// `cs -queue` names a cs command. An error arrives as the text its site makes
166// of it: some keep the `Error: ` that String() gives, some only the message.
167export type Ask = { question: string; header: string; options: string[] }
168export const ASKS = {
169 wrap: { question: WRAP_QUESTION, header: 'Wrap', options: [WRAP_YES, 'Not now'] },
170 queueStart: (count: number): Ask => ({ question: `Start the ${count} queued ${count === 1 ? 'task' : 'tasks'} now?`, header: 'Queue', options: [QUEUE_START, 'Not yet', QUEUE_COMPACT] }),
171 queueMode: { question: QUEUE_MODE_QUESTION, header: 'Queue', options: [QUEUE_HERE, QUEUE_SUBAGENTS, QUEUE_WORKFLOWS] },
172} satisfies Record<string, Ask | ((...args: never[]) => Ask)>
173
174export const TOASTS = {
175 queued: (task: string) => `queued: ${cutTask(task)}`,
176 bandOption: (problem: string) => `the band draws no prompt bars: ${problem}. Set it in /config.`,
177 promptNotDrawn: 'that prompt is not on screen yet',
178 scrollRefused: (deny: string) => deny,
179 transcriptTail: () => `the transcript is over ${READ_CAP / 1024 / 1024} MiB; the rail lists the prompts of its tail`,
180 forceBelowStart: (force: number, startPercent: number) => `CS_ROTATE_FORCE_CTX=${force} is below this conversation's starting context (${startPercent}%); not forcing a rotation`,
181 rotateFailed: (err: string) => `/rotate did not run: ${err}`,
182 clearFailed: (err: string) => `/clear did not run: ${err}`,
183 nextStep: (line: string) => `next step: ${line}`,
184 noRotation: (refusal: string) => `no rotation in this session: ${refusal}`,
185 feedFailed: (err: string) => `feed update failed: ${err}`,
186 finishFailed: (task: string, err: string) => `/finish${task === '' ? '' : ` ${task}`} did not run: ${err}`,
187 pressedNotEmptied: (err: string) => `could not empty ${PRESSED}: ${err}`,
188 wrapFailed: (err: string) => `/wrap did not run: ${err}`,
189 queueNoBin: 'the launch did not say where cs is (CS_BIN); run cs -queue start from a shell in this session',
190 queueModeUnknown: (how: string) => `'${how}' is not a way to run the queue; it is not started`,
191 notCompacted: (reason: string) => `the conversation was not compacted (${reason}); the queue is not started`,
192 queueStartFailed: (err: string) => `cs -queue start did not run: ${err}`,
193 queueStartExited: (code: number, tail: string) => `cs -queue start exited ${code}${tail === '' ? '' : `: ${tail}`}`,
194 queueKickFailed: (err: string) => `the queue is armed, but its first turn did not start: ${err}`,
195 finishRecordUnread: (dir: string) => `.cs/${dir}/${FINISH_RECORD} is not a record cs wrote; /finish progress is not shown`,
196 finishPidUnknown: (err: string) => `cannot tell whether /finish is still running: ${err}`,
197} as const
198
199export const LOGS = {
200 featuresUnread: (err: string) => `the features word could not be read: ${err}`,
201 featuresExited: (base: string, code: number, line: string) => `cs ${base} -features exited ${code}: ${line}`,
202 featuresUnreadable: (base: string, record: string) => `cs ${base} -features gave a record the band cannot read: ${record}`,
203 featuresNoAnswer: (base: string, err: string) => `cs ${base} -features did not answer: ${err}`,
204 transcriptUnread: (err: string) => `the transcript could not be read: ${err}`,
205 colorFailed: (color: string, err: string) => `/color ${color} did not run: ${err}`,
206 feedUnread: (message: string) => `the feed setting could not be read: ${message}`,
207} as const
208
209// `what` is the cs command a reply is about: `cs -queue add` or `cs -queue list`.
210export const REPLIES = {
211 queueNoBin: 'The launch did not say where cs is (CS_BIN); run `cs -queue add "<task>"` from a shell in this session.',
212 queueFailed: (what: string, err: string) => `${what} did not run: ${err}`,
213 queueExited: (what: string, code: number, tail: string) => tail === '' ? `${what} exited ${code}.` : `${what} exited ${code}.\n${tail}`,
214 queued: (task: string) => `Queued: ${task}`,
215 csUsage: 'usage: /cs next|prev|first|last|<n>',
216 railEmpty: 'the rail has no prompts',
217 noneAfter: 'no prompt after this one',
218 noneBefore: 'no prompt before this one',
219 railCount: (count: number) => `the rail has ${count} ${count === 1 ? 'prompt' : 'prompts'}`,
220} as const
221
222export const COMMANDS = {
223 queue: { name: 'queue', description: "Add a task to this cs session's walk-away queue, or list it.", argumentHint: '[task]', immediate: true },
224 cs: { name: 'cs', description: "Scroll the transcript along the band's rail of prompts.", argumentHint: 'next|prev|first|last|<n>', immediate: true },
225} as const
226
227// The countdown: seconds left, its ticker, and what the band last saw. Module
228// state survives a /clear (measured), so every path that ends the countdown
229// cancels the ticker; a reload of the mod drops it with its timers.
230let left: number | undefined
231let ticker: { cancel: () => void } | undefined
232let bandIdle = false
233// Whether a turn was running when the band last drew: a queue started then
234// reaches its first stop without a prompt from the mod.
235let turnRunning = false
236// The handoff whose next step the count has toasted, by its text: one toast
237// per armed handoff, so a count restarted for the same handoff (a prompt
238// stopped it, the next turn's end started it again) says nothing, and the
239// successor's own handoff, armed in the same process after the /clear, is
240// toasted in its turn.
241let stepToastedFor: string | undefined
242// Set while the mod's own /clear runs. The marker stays armed until the
243// successor's SessionStart consumes it, so the band still offers the button
244// meanwhile; a second /clear would end the conversation the handoff started,
245// so a press then does nothing.
246let clearing = false
247// cs's last refusal of this session's control files, toasted once: the band
248// asks on every render while a handoff is armed.
249let lastRefusal: string | undefined
250// Whether cs's last answer on this session's control files was a refusal. Set
251// and cleared by every vet (sessionVetted), so the session start's and a feed
252// press's alike; only a passed vet or a reload clears it, never a prompt. The
253// feed key reads off while it is set: the band's label says what cs-feed
254// draws, and cs-feed reads a refused session as off.
255let feedVetRefused = false
256// Counts presses of the clear button: a press acts only if no later press or
257// prompt came while cs was answering it.
258let pressCount = 0
259
260// Which conversation the turns belong to, and whether it is being judged. A
261// conversation that begins past the force threshold did not get there by
262// working: forcing it would rotate again as soon as its successor woke
263// (measured at 1%). Only a conversation born of a /clear seen in this process
264// (`clearSeen`, then `birth`) is judged that way, by the context its first
265// turn ended with (`startPercent`). Any other new id (a launch, a reload, a
266// /resume at 72%) is adopted unjudged, since past the line is exactly where
267// the person asked to be rotated. Module state is kept across /clear, which
268// is what makes the birth visible.
269let adopted: string | undefined
270let clearSeen = false
271let birth: string | undefined
272let startPercent: number | undefined
273// Whether this load has registered /queue: session.start fires at load, and
274// registering the same name again would only replace it.
275let registered = false
276// The /finish watch: its timer, whether the turn that started it has ended,
277// which steps of which runs have been toasted (`<id>:started`,
278// `<id>:<outcome>`), the gate the band shows while one runs under a live pid,
279// and whether a problem reading the record or the pid has been said.
280let finishWatch: { cancel: () => void } | undefined
281let finishTurnOver = false
282let finishShown = new Set<string>()
283let finishGate: { task: string; since: number } | undefined
284let finishProblemShown = false
285
286// The features word: what the band's right edge says of the session's feature
287// worktrees, as cs last answered, and the task a press finishes ('' for bare
288// /finish, which lists them and asks; absent, no press). One reading at a
289// time; the idle clock that reads again; the last complaint logged.
290export type FeaturesWord = { label: string; finish?: string }
291type BandPress = () => void | Promise<unknown>
292export type BandEntry =
293 // A word's ink colours the whole label, or only its `lead` glyph with the rest dim.
294 | { key: string; kind: 'word'; label: string; ink?: { color: string | undefined } | { lead: string; color: string } }
295 | { key: string; kind: 'press'; label: string; onPress: BandPress; ink?: { lead: string; color: string } }
296 | { key: string; kind: 'chord'; label: string; action: string; onPress: BandPress; ink?: { text: string; color: string | undefined } }
297type BandFacts = {
298 featured?: { label: string; onPress?: BandPress }
299 countdown?: { seconds: number; ink: string | undefined }
300 rotating: boolean
301 armed: boolean
302 wrapping: boolean
303 feed?: { on: boolean; color: string | undefined; onPress: BandPress }
304 waiting: number
305 gate?: string
306 queued: number
307 queueRunning: boolean
308 // The queue glyph's amber, as the status line draws its queue count.
309 queueInk: string
310 mail: number
311 rotate: BandPress
312 wrap: BandPress
313 queue: BandPress
314}
315
316const QUEUE_GLYPH = '\u25a4'
317// The queue press's head: its glyph, its verb and its count.
318const QUEUE_COUNT = /^\u25a4 run \d+/
319
320export function buildBandEntries(facts: BandFacts): BandEntry[] {
321 const entries: BandEntry[] = []
322 if (facts.rotating) entries.push({ key: 'cs-rotate', kind: 'chord', label: facts.armed ? '/clear now' : 'rotate', action: ROTATE_ACTION, onPress: facts.rotate })
323 // The grace follows the clear key whose press stops it.
324 if (facts.countdown !== undefined) entries.push({ key: 'cs-countdown', kind: 'word', label: `in ${facts.countdown.seconds}s`, ink: { color: facts.countdown.ink } })
325 if (facts.wrapping) entries.push({ key: 'cs-wrap', kind: 'chord', label: 'wrap', action: WRAP_ACTION, onPress: facts.wrap })
326 if (facts.feed !== undefined) entries.push({ key: 'cs-feed', kind: 'chord', label: facts.feed.on ? 'feed ✓' : 'feed', action: FEED_ACTION, onPress: facts.feed.onPress, ink: facts.feed.on ? { text: '✓', color: facts.feed.color } : undefined })
327 // The queue has no chord: a click or Enter under the band's focus starts it.
328 if (facts.waiting > 0) entries.push({ key: 'cs-queue', kind: 'press', label: `${QUEUE_GLYPH} run ${facts.waiting} queued ${facts.waiting === 1 ? 'task' : 'tasks'}`, onPress: facts.queue, ink: { lead: QUEUE_GLYPH, color: facts.queueInk } })
329 // The features word leads what the session is; only a ready feature can be pressed.
330 if (facts.featured !== undefined) {
331 const { label, onPress } = facts.featured
332 entries.push(onPress === undefined ? { key: 'cs-features', kind: 'word', label } : { key: 'cs-features', kind: 'press', label, onPress })
333 }
334 if (facts.gate !== undefined) entries.push({ key: 'cs-gate', kind: 'word', label: facts.gate })
335 if (facts.queued > 0) entries.push({ key: 'cs-queued', kind: 'word', label: `${QUEUE_GLYPH} queue ${facts.queued}${facts.queueRunning ? ' running' : ''}`, ink: { lead: QUEUE_GLYPH, color: facts.queueInk } })
336 if (facts.mail > 0) entries.push({ key: 'cs-mail', kind: 'word', label: `mail ${facts.mail}` })
337 return entries
338}
339
340let featuresWord: FeaturesWord | undefined
341let featuresReading = false
342let featuresClock: { cancel: () => void } | undefined
343let featuresComplaint: string | undefined
344
345// The rail. A prompt is a row of the transcript's live branch; its requestId
346// is the id the engine drew its UserMessage row under, once seen.
347export type Prompt = { uuid: string; text: string }
348// How much of a prompt's first line a tick carries as its text.
349export const RAIL_TEXT_CHARS = 80
350// The fewest cells before the rail that name a prompt.
351const RAIL_LABEL_MIN = 10
352// `$.fs.read` refuses a file over this; a longer transcript is read from its tail.
353const READ_CAP = 4 * 1024 * 1024
354// What the transcript last read held, and the file it was: the file is parsed
355// again only when its size or mtime moved.
356let railFile: { path: string; size: number; mtimeMs: number } | undefined
357let prompts: Prompt[] = []
358// Row key (a uuid's first four groups, or the id itself) -> the requestId the
359// engine last drew that row under and the row's first line, from the
360// UserMessage renders; requestId -> the latest non-null onScreen report.
361let drawnRows = new Map<string, { requestId: string; text: string }>()
362let shown = new Map<string, { first: number; last: number; of: number }>()
363// Prompts a jump was refused for, by uuid; whether that, a prompt no row has
364// drawn yet, and a transcript read from its tail have been said this session.
365let denied = new Set<string>()
366let denySaid = false
367let notYetSaid = false
368let tailSaid = false
369// The prompt the band last drew thick, and whether a redraw for a moved read
370// prompt is already scheduled.
371let drawnRead = -1
372let redrawPending = false
373// The band's /config rows (plugin.json userConfig), as this activation got
374// them: whether it draws the prompt bars at all (off by default), the prompt
375// it names, `latest` (the newest) or `read` (the one being read), and the
376// most bars it draws before the prompts past them fold into `…N` or `M…`. A
377// change reloads the plugin and register runs again. A stored value the band
378// cannot draw leaves it without bars (undefined), said once, and the rest of
379// the mod running: a throw from register would unload all of it.
380const CS_PLUGIN = 'cs'
381type BandOptions = { prompts: boolean; prompt: 'latest' | 'read'; bars: number }
382let bandOptions: BandOptions | undefined
383let bandProblem: string | undefined
384let bandProblemSaid = false
385let feedPressPending: Promise<void> | undefined
386let feedComplaint: string | undefined
387
388// What is wrong with a value for one of the band's rows, by field name;
389// undefined when the band can draw it, or the field is not the band's.
390function bandOptionProblem(field: string, value: unknown): string | undefined {
391 if (field === 'bandPrompts') return typeof value === 'boolean' ? undefined : `cs.bandPrompts is on or off; got ${String(value)}`
392 if (field === 'bandPrompt') return value === 'latest' || value === 'read' ? undefined : `cs.bandPrompt is latest or read; got ${String(value)}`
393 if (field === 'bandBars') {
394 return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? undefined : `cs.bandBars is the most bars the band draws, a whole number of 1 or more; got ${String(value)}`
395 }
396 return undefined
397}
398
399export function register(on: On, options: PluginOptions) {
400 bandProblem = bandOptionProblem('bandPrompts', options.bandPrompts) ?? bandOptionProblem('bandPrompt', options.bandPrompt) ?? bandOptionProblem('bandBars', options.bandBars)
401 bandOptions = bandProblem === undefined
402 ? { prompts: options.bandPrompts as boolean, prompt: options.bandPrompt as BandOptions['prompt'], bars: options.bandBars as number }
403 : undefined
404 bandProblemSaid = false
405 feedPressPending = undefined
406 feedComplaint = undefined
407 // A (re)load has no countdown: the engine cancelled the old one's timers.
408 left = undefined; ticker = undefined; bandIdle = false; turnRunning = false; stepToastedFor = undefined; adopted = undefined; clearSeen = false; clearing = false; birth = undefined; startPercent = undefined; registered = false
409 finishWatch = undefined; finishTurnOver = false; finishShown = new Set(); finishGate = undefined; finishProblemShown = false
410 lastRefusal = undefined
411 feedVetRefused = false
412 featuresWord = undefined; featuresReading = false; featuresClock = undefined; featuresComplaint = undefined
413 railFile = undefined; prompts = []; drawnRows = new Map(); shown = new Map(); denied = new Set(); denySaid = false; notYetSaid = false; tailSaid = false; drawnRead = -1; redrawPending = false
414 on('session.start', async ($, e, next) => {
415 if (!registered) {
416 registered = true
417 await $.command.register(COMMANDS.queue)
418 await $.command.register(COMMANDS.cs)
419 }
420 await refreshRail($)
421 readFeaturesLater($)
422 // Only in a cs session; anywhere else the mod stays silent. Nor while git
423 // tracks the session's control files: the heartbeat would change them.
424 if ((await $.fs.exists(`${e.cwd}/.cs/local`)) && (await isCsSession($, e.cwd)) && (await sessionVetted($, e.cwd))) {
425 await $.fs.write(`${e.cwd}/${HEARTBEAT}`, `${new Date().toISOString()}\n`)
426 }
427 return next(e)
428 })
429
430 // `/queue <task>` runs `cs -queue add` by the path the launch exported;
431 // `/queue` alone runs `cs -queue list`. The child inherits the claude
432 // process's environment, and CLAUDE_SESSION_META_DIR there picks the queue.
433 // Registered immediate, so the hook may run while a turn streams: it reads
434 // nothing of the turn. cs is the judge of the task: whatever it refuses
435 // (an empty or multi-line body) comes back as its own stderr.
436 on('command.run', { command: 'queue' }, async ($, e) => {
437 const task = e.args.trim()
438 const argv = task === '' ? ['-queue', 'list'] : ['-queue', 'add', e.args]
439 const bin = await $.env.get("CS_BIN")
440 if (!bin) return { text: REPLIES.queueNoBin }
441 const what = `cs ${argv.slice(0, 2).join(' ')}`
442 let result: { exitCode: number; stdout: string; stderr: string }
443 try {
444 result = await $.process.run([bin, ...argv])
445 } catch (err) {
446 return { text: REPLIES.queueFailed(what, String(err instanceof Error ? err.message : err)) }
447 }
448 if (result.exitCode !== 0) {
449 const tail = result.stderr.split('\n').filter(l => l.trim() !== '').slice(-5).join('\n')
450 return { text: REPLIES.queueExited(what, result.exitCode, tail) }
451 }
452 if (task !== '') {
453 // The command's text lands in the transcript, which a running turn
454 // scrolls past; the toast under the prompt confirms the add where the
455 // person is looking. One line, so a long task is cut.
456 $.ui.toast(TOASTS.queued(task))
457 return { text: REPLIES.queued(task) }
458 }
459 const pending = /^Pending \((\d+)\)$/m.exec(result.stdout)
460 if (pending && !(await queueRunning($))) void offerToStart($, bin, Number(pending[1]))
461 return { text: result.stdout.trimEnd() }
462 })
463
464 // `/cs next|prev|first|last|<n>` scrolls the transcript to a prompt of the
465 // rail, counted from the one being read. Immediate: a typed command answers
466 // the person's own input, which is when the engine lets a plugin move a
467 // transcript row, mid-turn too. A move answers with no text: a transcript
468 // row of its own would grow the transcript under the view it just moved.
469 on('command.run', { command: 'cs' }, async ($, e) => {
470 const asked = e.args.trim()
471 const count = prompts.length
472 const current = readIndex()
473 let target: number
474 if (asked === 'next') target = current + 1
475 else if (asked === 'prev') target = current - 1
476 else if (asked === 'first') target = 0
477 else if (asked === 'last') target = count - 1
478 else if (/^\d+$/.test(asked)) target = Number(asked) - 1
479 else return { text: REPLIES.csUsage }
480 if (count === 0) return { text: REPLIES.railEmpty }
481 if (asked === 'next' && target >= count) return { text: REPLIES.noneAfter }
482 if (asked === 'prev' && target < 0) return { text: REPLIES.noneBefore }
483 if (target < 0 || target >= count) return { text: REPLIES.railCount(count) }
484 await jumpTo($, target)
485 return {}
486 })
487
488 // A /config row of the band's takes only a value the band can draw: a bad
489 // one is refused at the menu, where it is typed, not met at the next load.
490 on('config.set', async ($, e, next) => {
491 if (e.provider.plugin !== CS_PLUGIN) return next(e)
492 const problem = bandOptionProblem(e.key.slice(e.key.lastIndexOf('.') + 1), e.value)
493 return problem === undefined ? next(e) : { deny: problem }
494 })
495
496 // The end of a turn is the one moment a rotation can be started for the
497 // person: the answer is in, nothing runs. An aborted or errored turn is no
498 // place to start one, and a subagent's turn ends in the same event. A
499 // press's /rotate runs in the main loop's next turn, so that turn's end,
500 // whatever ended it, is where the press is over.
501 on('turn.complete', async ($, e, next) => {
502 if (e.agentId === undefined) {
503 finishTurnOver = true
504 await clearPressed($)
505 await refreshRail($)
506 readFeaturesLater($)
507 }
508 if (e.reason === 'answer' && e.agentId === undefined) await forceRotation($)
509 return next(e)
510 })
511
512 // /finish is a skill: this fires when it is typed, and when `cs <base>
513 // -finish` launches a conversation on it. Its turn runs cs's integrate and
514 // retire, and the watch follows the record cs writes meanwhile, until that
515 // turn is over and nothing runs.
516 on('skill.prompt', { skill: 'finish' }, async ($, e, next) => {
517 finishTurnOver = false
518 if (!finishWatch) await watchFinish($)
519 return next(e)
520 })
521
522 // A prompt entering the session, from anywhere, means the conversation is
523 // not done with: the countdown stops and the prompt goes through untouched.
524 on('prompt.submit', async ($, e, next) => {
525 if (ticker) stopCountdown($)
526 // A new turn asks afresh, as the Stop hook says it afresh each turn: the
527 // band draws the handoff again, and its press asks cs before it clears.
528 // A press still waiting on cs is dropped.
529 lastRefusal = undefined
530 pressCount += 1
531 return next(e)
532 })
533
534 // A /clear from anywhere else (typed, another plugin) ends the conversation
535 // the count belongs to, so the timer must not outlive it, and makes the
536 // next conversation a birth; a run the engine refuses makes nothing.
537 on('command.run', { command: 'clear' }, async ($, e, next) => {
538 clearSeen = true
539 if (ticker) stopCountdown($)
540 let result
541 try {
542 result = await next(e)
543 } catch (err) {
544 clearSeen = false
545 throw err
546 }
547 // The rail is the conversation's: the next one starts with none, and
548 // reads its own transcript as its first turn ends.
549 railFile = undefined; prompts = []; drawnRows = new Map(); shown = new Map(); denied = new Set(); drawnRead = -1
550 $.ui.invalidate('ui.render')
551 return result
552 })
553
554 // A turn that starts from a prompt is work after any wrap that finished: the
555 // marker that wrap left no longer describes the conversation. A continuation
556 // (no prompt, as a Stop hook's feedback starts one) is the wrap's own turn.
557 on('turn.start', async ($, e, next) => {
558 if (e.text !== '') await clearWrapped($)
559 return next(e)
560 })
561
562 // Every prompt row the engine draws passes through untouched; what it is
563 // drawn under, and what of it is on screen, is kept for the rail. The
564 // composer's echo draws first under `placeholder`, the real id on the next
565 // render (measured), so that id binds nothing. A `null` report on a row's
566 // first render is the row not laid out yet (measured): nothing changes. A
567 // `null` after a report is the row drawn outside the viewport: its report
568 // goes, as the contract's own example does. A report that moves the read
569 // prompt redraws the band from a timer: an invalidate inside a render is a
570 // render loop.
571 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
572 if (e.requestId !== 'placeholder') {
573 drawnRows.set(rowKey(e.requestId), { requestId: e.requestId, text: firstLine(e.props.text) })
574 if (e.props.onScreen) shown.set(e.requestId, e.props.onScreen)
575 else if (e.props.onScreen === null) shown.delete(e.requestId)
576 if (!redrawPending && bandOptions?.prompts === true && prompts.length > 1 && namedIndex() !== drawnRead) {
577 redrawPending = true
578 $.clock.after(0, () => { redrawPending = false; $.ui.invalidate('ui.render') })
579 }
580 }
581 return next(e)
582 })
583
584 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
585 const drawn = await next(e)
586 // The band draws in a new conversation before any of its turns end, so
587 // the birth is settled here: a later /resume is not mistaken for it.
588 await noteConversation($, await $.session.id())
589 // A survey owns the band; a running turn cannot be rotated out of.
590 turnRunning = e.props.isWorking
591 bandIdle = !e.props.hasSurvey && !e.props.isWorking
592 // The /finish gate's word draws mid-turn, since the gate runs inside one,
593 // whatever else the band has to say.
594 const gate = await gateWord($)
595 // The band draws on every redraw and asks cs nothing: it shows the last
596 // answer cs gave (sessionVetted), which every step that acts asks afresh.
597 // An armed handoff makes the rotation due at any context.
598 const handoff = lastRefusal === undefined && (await handoffArmed($))
599 const armed = bandIdle && handoff
600 const { context } = await $.session.usage()
601 const percent = context.percent
602 const due = handoff || (percent !== undefined && percent >= (await threshold($)))
603 let rotating = bandIdle && due
604 // Tasks queued and nothing running them, at any context, draw the start
605 // key; an armed handoff draws its clear key alone. Tasks queued that the
606 // start key does not offer (the queue runs them, a turn runs, or the
607 // clear key stands alone) are said, not pressed.
608 const queue = e.props.hasSurvey ? 0 : await queueLength($)
609 const queueStarted = queue > 0 && (await queueRunning($))
610 let waiting = !bandIdle || armed || queueStarted ? 0 : queue
611 let queued = waiting > 0 ? 0 : queue
612 // Mail from other sessions that `cs -msg` has not read yet.
613 let mail = e.props.hasSurvey ? 0 : await unreadMail($)
614 // The rail draws, once cs.bandPrompts turns it on, whenever the
615 // conversation has two prompts to move between, a turn running or not,
616 // under the same ownership as the keys; its bars draw not at all while a
617 // stored band row is bad, which the lead's band says once.
618 const bars = bandOptions?.bars
619 let railing = !e.props.hasSurvey && prompts.length > 1 && bandOptions?.prompts === true
620 if (bandProblem !== undefined && !bandProblemSaid && (await ownsRotation($))) {
621 bandProblemSaid = true
622 $.ui.toast(TOASTS.bandOption(bandProblem))
623 }
624 // The features word leads what the session is, at the line's right; a
625 // running gate already names the feature it lands.
626 let featured = !e.props.hasSurvey && gate === undefined ? featuresWord : undefined
627 let feedEligible = bandIdle && !armed
628 if ((rotating || waiting > 0 || queued > 0 || mail > 0 || railing || featured || feedEligible) && !(await ownsRotation($))) { rotating = false; waiting = 0; queued = 0; mail = 0; railing = false; featured = undefined; feedEligible = false }
629 // The named tick is remembered on every path, drawn or not, so a row's
630 // report that moves nothing visible schedules no redraw.
631 const named = namedIndex()
632 drawnRead = named
633 const hasContent = rotating || waiting > 0 || queued > 0 || mail > 0 || gate !== undefined || railing || featured !== undefined
634 if (!hasContent && !feedEligible) return drawn
635 // Listing /feed reads availability without queuing a command or adding a status row.
636 const feeding = feedEligible && (await $.command.list()).some(command => command.name === 'feed' && command.source === 'plugin' && command.plugin === 'cs-feed')
637 if (!hasContent && !feeding) return drawn
638 const wrapped = rotating && !armed && (await wrapFinished($))
639 const chords = await boundChords($)
640 const own = paletteColor(await sessionColor($))
641 const { Box, Text, Button } = await $.ui.resolve(e)
642 const wrapping = rotating && !armed && !wrapped
643 const finish = featured?.finish
644 const entries = buildBandEntries({
645 featured: featured === undefined ? undefined : { label: featured.label, onPress: finish === undefined || !bandIdle ? undefined : () => pressFinish($, finish) },
646 countdown: armed && left !== undefined ? { seconds: left, ink: await rampColor($, left) } : undefined,
647 rotating, armed, wrapping, waiting, gate, queued, queueRunning: queueStarted, mail,
648 queueInk: amberColor(await $.env.get("CS_TERM_BG_RGB"), await $.env.get("CS_TERM_THEME")),
649 feed: feeding ? { on: !feedVetRefused && await readFeed($), color: own, onPress: () => pressFeed($) } : undefined,
650 rotate: armed ? () => pressClear($) : () => pressRotate($),
651 wrap: () => askToWrap($),
652 queue: () => pressQueueStart($),
653 })
654 const rail = railing && bars !== undefined ? { prompts, named, denied, bars, jump: (i: number) => jumpTo($, i) } : undefined
655 return drawBand({ drawn, entries, chords, own, bodyColumns: e.props.bodyColumns, surface: e.surface, rail }, { Box, Text, Button })
656 })
657
658 // A rail tick never takes the band's focus ring: the ring draws as an
659 // inverted block that reads as part of the rail, and the band's keyboard
660 // route along the rail is /cs. The band's other buttons keep it.
661 on('ui.focus', { component: 'AbovePrompt', plugin: 'cs' }, async ($, e, next) => {
662 if (e.element?.startsWith('cs-rail-')) return { deny: 'cs: the rail takes clicks and /cs, not the focus ring' }
663 return next(e)
664 })
665}
666
667// What the band's line is drawn from, as the AbovePrompt handler read it: the
668// engine's own tree, the entries, the bound chords by action, the session
669// colour, and the rail when cs.bandPrompts draws one.
670export type BandView = {
671 drawn: RenderElement
672 entries: BandEntry[]
673 chords: Record<string, string>
674 own: string | undefined
675 bodyColumns: number
676 surface: RenderSurface
677 rail?: { prompts: Prompt[]; named: number; denied: Set<string>; bars: number; jump: (i: number) => Promise<void> }
678}
679export type BandElements = Pick<ReturnType<EngineInterface['ui']['resolve']>, 'Box' | 'Text' | 'Button'>
680
681// The words that leave an overrunning line first, first to last, each only as
682// a word: a features word that can be pressed is a press and stays. After
683// them the shared chord prefix goes. The countdown, the presses and the
684// chords leave only whole: last (LEAVE_ORDER), or earlier where what the line
685// would draw of them says nothing (mutedBy).
686const DROP_ORDER = ['cs-mail', 'cs-queued', 'cs-features', 'cs-gate']
687
688// Which side of the line each entry draws on: the actions, what a chord or a
689// press does now, at the left; what the session is, at the
690// right edge beside the rail. The line's free cells stand between the two.
691type Zone = 'actions' | 'status'
692const ZONES = new Map<string, Zone>([
693 ['cs-rotate', 'actions'], ['cs-countdown', 'actions'], ['cs-wrap', 'actions'], ['cs-feed', 'actions'], ['cs-queue', 'actions'], ['cs-queued', 'actions'],
694 ['cs-features', 'status'], ['cs-gate', 'status'], ['cs-mail', 'status'],
695])
696// The cells between two entries of a zone, and the fewest between the zones.
697const GAP = 3
698const SEP = ' '.repeat(GAP)
699// Between the keys (the chords and the clear key's countdown) and the presses
700// and words after them, in the same cells as SEP.
701const KEYS_END = ' \u00b7 '
702
703// The entries of each zone, in the line's order.
704function zonesOf<T extends BandEntry>(entries: T[]): Record<Zone, T[]> {
705 const zones: Record<Zone, T[]> = { actions: [], status: [] }
706 for (const entry of entries) {
707 const zone = ZONES.get(entry.key)
708 if (zone === undefined) throw new Error(`cs: the band has no zone for ${entry.key}`)
709 zones[zone].push(entry)
710 }
711 return zones
712}
713
714// The chords that share a prefix (`ctrl+x 1`, `ctrl+x 2`): the prefix, and
715// each chord's own key after it, or the chord whole when they differ.
716function chordSpelling(entries: BandEntry[], chords: Record<string, string>) {
717 const prefix = sharedPrefix(entries.flatMap(entry => entry.kind === 'chord' ? [chords[entry.action]] : []))
718 return {
719 prefix,
720 spelled: (action: string) => {
721 const chord = chords[action]
722 return chord === undefined ? undefined : prefix === undefined ? chord : chord.slice(prefix.length + 1)
723 },
724 }
725}
726
727const firstChordOf = (entries: BandEntry[], chords: Record<string, string>) =>
728 entries.findIndex(entry => entry.kind === 'chord' && chords[entry.action] !== undefined)
729
730// An entry as the fitted line draws it: a chord with no room for its word
731// draws as its key alone.
732export type FittedEntry = BandEntry & { keyOnly?: true }
733
734// What the words take, in cells, as the tree draws them: in each zone a
735// separator between entries, the prefix once before the first bound chord
736// with its one-cell margin, each chord's key with its one-cell margin, then
737// the label; and the fewest cells between the zones when both draw.
738// `spelling` is the whole line's: a cut that leaves fewer chords keeps them
739// spelled as the full line spells them.
740type ChordSpelling = ReturnType<typeof chordSpelling>
741function wordCellsOf(entries: FittedEntry[], chords: Record<string, string>, { prefix, spelled }: ChordSpelling, prefixed: boolean): number {
742 const cellsOfZone = (zone: FittedEntry[]) => {
743 const firstChord = firstChordOf(zone, chords)
744 return cellWidth(zone.map((entry, index) => {
745 const chord = entry.kind === 'chord' ? spelled(entry.action) : undefined
746 const keyed = chord === undefined ? entry.label : entry.keyOnly ? chord : `${chord} ${entry.label}`
747 return `${index === firstChord && prefixed && prefix !== undefined ? `${prefix} ` : ''}${keyed}`
748 }).join(SEP))
749 }
750 const { actions, status } = zonesOf(entries)
751 const actionCells = cellsOfZone(actions)
752 const statusCells = cellsOfZone(status)
753 return actionCells + statusCells + (actionCells > 0 && statusCells > 0 ? GAP : 0)
754}
755
756// The keepers whose words are free text, shortened first to last before any
757// chord loses its word, each no shorter than one cell and `…`.
758const SHORTEN_ORDER = ['cs-features', 'cs-queue']
759const SHORTEST_CELLS = 2
760
761// The entries that leave whole, first to last, once the words are short and
762// every bound chord is its key: the countdown's free text before the actions,
763// the presses before the chords. Only chords are left after them.
764const LEAVE_ORDER = ['cs-countdown', 'cs-features', 'cs-queue']
765
766// The entries a line of `room` cells draws, and whether it spells the chord
767// prefix. The engine's Buttons never shrink, so a line wider than its room
768// would squeeze the band's Texts to a cell each and wrap them down: the band
769// draws one line. While it overruns, the entries leave in LEAVE_ORDER, then
770// the chords right to left, and the line is fitted again from what stays, so
771// a chord left after one leaves takes its word back when it fits. A Button
772// that leaves the tree takes its chord with it, so the chords leave last. An
773// unbound chord has no key to fall back to: the last one cuts its word to end
774// in `…` before it leaves. An entry that says nothing as fitted (mutedBy)
775// leaves first, overrun or not, and the line is fitted again without it.
776export function fitBand(all: BandEntry[], chords: Record<string, string>, room: number): { entries: FittedEntry[]; prefixed: boolean } {
777 const spelling = chordSpelling(all, chords)
778 for (let kept = all; ;) {
779 const fitted = shortenBand(kept, chords, spelling, room)
780 const mute = mutedBy(fitted.entries, kept)
781 if (mute !== undefined) {
782 kept = kept.filter(entry => entry.key !== mute)
783 continue
784 }
785 const excess = wordCellsOf(fitted.entries, chords, spelling, fitted.prefixed) - room
786 const last = fitted.entries[fitted.entries.length - 1]
787 if (excess <= 0 || last === undefined) return fitted
788 const leaving = LEAVE_ORDER.find(key => fitted.entries.some(entry => entry.key === key))
789 if (leaving === undefined) {
790 if (last.kind !== 'chord') throw new Error(`cs: the band left ${last.key} for last, where only chords stay`)
791 const keep = (last.keyOnly ? 0 : cellWidth(last.label)) - excess
792 if (keep >= 1) return { entries: [...fitted.entries.slice(0, -1), { ...last, label: cutToCells(last.label, keep), ink: undefined }], prefixed: false }
793 }
794 kept = kept.filter(entry => entry.key !== (leaving ?? last.key))
795 }
796}
797
798// The entry a fitted line draws that says nothing, which leaves before the
799// line is fitted again: a status word cut shorter than its head, the words
800// before its first ` · `, and `…`, which names nothing (`1…` of `1 feature ·
801// fix-auth ready`); then the countdown beside a clear key drawn bare (`1 in
802// 18s` counts down to nothing the line names, so it leaves before
803// `/clear now` loses its word). The cut word goes first: the cells it took
804// may be what bared the key. `kept` holds each entry's whole label.
805function mutedBy(fitted: FittedEntry[], kept: BandEntry[]): string | undefined {
806 const stub = fitted.find(entry => {
807 if (ZONES.get(entry.key) !== 'status') return false
808 const whole = kept.find(k => k.key === entry.key)?.label
809 if (whole === undefined) throw new Error(`cs: the band fitted ${entry.key}, an entry it was not given`)
810 const head = whole.split(' · ')[0] ?? whole
811 return entry.label !== whole && cellWidth(entry.label) < cellWidth(head) + 1
812 })
813 if (stub !== undefined) return stub.key
814 const bareClear = fitted.some(entry => entry.key === 'cs-rotate' && entry.keyOnly)
815 return bareClear && fitted.some(entry => entry.key === 'cs-countdown') ? 'cs-countdown' : undefined
816}
817
818// The entries of a line of `room` cells before any leaves whole: each step
819// runs only while the line still overruns. Words leave (DROP_ORDER, then the
820// prefix); the features and queue words shorten (SHORTEN_ORDER); bound chords
821// fall back to their key alone, right to left, so the actions outlive the
822// free text. What it returns may still overrun.
823function shortenBand(all: BandEntry[], chords: Record<string, string>, spelling: ChordSpelling, room: number): { entries: FittedEntry[]; prefixed: boolean } {
824 const over = (entries: FittedEntry[], prefixed: boolean) => wordCellsOf(entries, chords, spelling, prefixed) - room
825 let entries: FittedEntry[] = all
826 for (const key of DROP_ORDER) {
827 if (over(entries, true) <= 0) return { entries, prefixed: true }
828 entries = entries.filter(entry => entry.key !== key || entry.kind !== 'word')
829 }
830 if (over(entries, true) <= 0) return { entries, prefixed: true }
831 for (const key of SHORTEN_ORDER) {
832 const excess = over(entries, false)
833 if (excess <= 0) return { entries, prefixed: false }
834 entries = entries.map(entry => {
835 const cells = cellWidth(entry.label)
836 return entry.key !== key || cells <= SHORTEST_CELLS ? entry : { ...entry, label: shortened(entry.label, Math.max(SHORTEST_CELLS, cells - excess)) }
837 })
838 }
839 for (let i = entries.length - 1; i >= 0; i--) {
840 if (over(entries, false) <= 0) return { entries, prefixed: false }
841 entries = entries.map((entry, j) => (j === i && entry.kind === 'chord' && spelling.spelled(entry.action) !== undefined ? { ...entry, keyOnly: true } : entry))
842 }
843 return { entries, prefixed: false }
844}
845
846export function drawBand(v: BandView, el: BandElements): RenderElement {
847 const { Box, Text, Button } = el
848 const { chords, own } = v
849 // The line starts two cells in; the words have the rest.
850 const room = v.bodyColumns - 2
851 // A rail keeps its least, the named bar alone, the older prompts folded
852 // into `…N ` before it and the newer into ` M…` after it, and the three
853 // cells before it: the words fit what that leaves, so the status words drop
854 // and the keys shorten before the rail goes. The actions outrank the rail:
855 // where the words beside its least lose an action the whole line would
856 // keep, they fit the whole line, and the rail takes what they leave, or
857 // nothing. An action the whole line drops too (the count beside a bare
858 // clear key) is no reason for the rail to go, nor is a word the band drops
859 // (the queue word draws among the actions, but leaves before the rail).
860 const reserved = v.rail === undefined ? 0 : railCells(v.rail.prompts.length, leastWindow(v.rail.named)) + GAP
861 const actionKeys = (all: BandEntry[]) => zonesOf(all).actions.filter(entry => entry.kind !== 'word' || !DROP_ORDER.includes(entry.key)).map(entry => entry.key)
862 const besideRail = fitBand(v.entries, chords, room - reserved)
863 const keptActions = actionKeys(besideRail.entries)
864 const wholeLine = fitBand(v.entries, chords, room)
865 const { entries, prefixed } = actionKeys(wholeLine.entries).every(key => keptActions.includes(key)) ? besideRail : wholeLine
866 // The Buttons carry no hotkey: a bare digit pressed them from an empty
867 // composer, where a digit typed as the answer to a numbered question
868 // belongs. A chord bound to each Button's action presses it instead, and
869 // the engine draws a Button with no hotkey as its label alone, so the key
870 // is spelled beside it, and only when keybindings.json binds one. Chords
871 // that share a prefix (`ctrl+x 1`, `ctrl+x 2`) spell it once, bold in the theme's light gray, and
872 // each Button its own key; chords that differ are spelled whole.
873 const spelling = chordSpelling(v.entries, chords)
874 const { spelled } = spelling
875 const prefix = prefixed ? spelling.prefix : undefined
876 const key = (action: string) => {
877 const text = spelled(action)
878 return text !== undefined && <Box marginRight={1}><Text bold color={own}>{text}</Text></Box>
879 }
880 // A chord with no room for its word is its key alone, still the Button its
881 // action presses; fitBand keys only a bound chord.
882 const keyButton = (entry: Extract<BandEntry, { kind: 'chord' }>) => {
883 const text = spelled(entry.action)
884 if (text === undefined) throw new Error(`cs: the band drew ${entry.key} as a key it has no chord for`)
885 return <Button key={entry.key} action={entry.action} plain label={text} onPress={entry.onPress}><Text bold color={own}>{text}</Text></Button>
886 }
887 // What the words take, in cells, so the rail knows what the line leaves it.
888 const wordCells = wordCellsOf(entries, chords, spelling, prefixed)
889 // The rail: one upright bar per prompt, flush at the line's right edge, `┃`
890 // for the one the band names, `┆` for one a jump was refused, `│`
891 // otherwise (side by side, flat ticks run together into one line), each a
892 // Button (the named one a Text, as dim as the rest: there is nowhere to
893 // jump, and its heavier stroke alone marks it). It draws at most
894 // cs.bandBars bars in what the line leaves after the inset, the gaps and
895 // the words, always the named one among them (railTicks); the older prompts
896 // collapse into one `…N` run, a cell before the first bar, and any newer
897 // than the drawn bars into one `M…` run, a cell after the last. The named
898 // tick is remembered so a report that moves it can redraw the band.
899 const budget = room - (wordCells > 0 ? GAP + wordCells : 0)
900 const rail = v.rail
901 const shown = rail === undefined ? undefined : railTicks(rail.prompts.length, budget, rail.bars, rail.named)
902 const ticks = rail === undefined || shown === undefined ? undefined : { ...rail, ...shown }
903 const drawnTick = (i: number) => ticks !== undefined && i >= ticks.from && i < ticks.to
904 // Left of the rail, GAP cells before it so the `…N` run never reads as
905 // the cut name's own `…`, the band names a prompt in what the line leaves:
906 // the newest or the one being read (cs.bandPrompt), or the one under the
907 // pointer. Too little left to name one names none.
908 const railWidth = ticks === undefined ? 0 : railCells(ticks.prompts.length, ticks)
909 const labelRoom = ticks === undefined ? 0 : budget - railWidth - GAP
910 const labeled = labelRoom >= RAIL_LABEL_MIN
911 // A bar under the pointer swaps its prompt in over the named one, on the
912 // terminal only: the desktop app paints a card over a line without hiding
913 // what is under it, so both prompts would show at once.
914 const hovering = labeled && v.surface === 'terminal'
915 const name = (prompts: Prompt[], i: number) => {
916 const p = prompts[i]
917 if (p === undefined) throw new Error(`cs: the band named prompt ${i} of ${prompts.length}`)
918 return `#${i + 1} ${p.text}`
919 }
920 // The name is as wide as the widest prompt it can show, the named one or a
921 // drawn bar's under the pointer, and no wider than the room: a name sized
922 // to the one it shows would move the words before it whenever a swap shows
923 // a longer or shorter one. It is padded on its left, so it hugs the gap
924 // before the bars.
925 const labelCells = ticks === undefined || !labeled ? 0 : Math.min(labelRoom, Math.max(...[ticks.named, ...(hovering ? ticks.prompts.map((_, i) => i).filter(drawnTick) : [])]
926 .map(i => cellWidth(name(ticks.prompts, i)))))
927 // Each name fills the width, so a card over the named one paints every
928 // cell of it: a shorter one would leave the named one's head showing.
929 const label = (prompts: Prompt[], i: number) => fitRight(name(prompts, i), labelCells)
930 // A line too narrow for any tick, with nothing else to say, draws nothing.
931 if (entries.length === 0 && ticks === undefined) return v.drawn
932 // One thin line, a blank line above it so it reads apart from the
933 // transcript, in two zones: at the left the actions, only the words that
934 // need a key now, the keys in the session colour and the rest dim; at the
935 // right edge what the session is, dim, then the prompt's name, then the
936 // rail, ending in the line's last cell. A spacer that grows
937 // takes the line's free cells between them, so the rail stays put as the
938 // actions come and go; the row is the line's whole width for it to grow
939 // into, and a line with nothing at the right draws no spacer. The context
940 // percentage is the bar's to carry; the band does not repeat it. It starts
941 // two columns in, where Claude Code draws the bar and the mode line under
942 // the prompt. A Button is a block: nested in a Text the engine refuses the
943 // whole tree (measured), so each separator stands beside its Button.
944 const { actions, status } = zonesOf(entries)
945 const right = status.length > 0 || ticks !== undefined
946 const drawZone = (zone: FittedEntry[]) => {
947 const firstChord = firstChordOf(zone, chords)
948 const afterKeys = zone.findLastIndex(entry => entry.kind === 'chord' || entry.key === 'cs-countdown') + 1
949 return zone.flatMap((entry, index) => [
950 index > 0 && <Text dimColor>{index === afterKeys ? KEYS_END : SEP}</Text>,
951 index === firstChord && prefix !== undefined && <Box marginRight={1}><Text bold color="subtle">{prefix}</Text></Box>,
952 entry.kind === 'chord' && !entry.keyOnly && key(entry.action),
953 entry.kind === 'word'
954 ? entry.ink === undefined ? <Text dimColor>{entry.label}</Text>
955 : 'lead' in entry.ink ? <Text><Text color={entry.ink.color}>{entry.ink.lead}</Text><Text dimColor>{entry.label.slice(entry.ink.lead.length)}</Text></Text>
956 : <Text bold color={entry.ink.color}>{entry.label}</Text>
957 : entry.kind === 'chord'
958 ? entry.keyOnly ? keyButton(entry) : entry.ink === undefined
959 ? <Button key={entry.key} action={entry.action} plain label={entry.label} onPress={entry.onPress} />
960 : <Button key={entry.key} action={entry.action} plain label={entry.label} onPress={entry.onPress}>{entry.label.slice(0, -entry.ink.text.length)}<Text color={entry.ink.color}>{entry.ink.text}</Text></Button>
961 : entry.ink === undefined
962 ? <Button key={entry.key} plain label={entry.label} onPress={entry.onPress} />
963 : <Button key={entry.key} plain label={entry.label} onPress={entry.onPress}><Text color={entry.ink.color}>{entry.ink.lead}</Text>{entry.label.slice(entry.ink.lead.length)}</Button>,
964 ])
965 }
966 return (
967 <Box flexDirection="column">
968 {v.drawn}
969 <Box marginTop={1}>
970 <Box key="cs-rotate-band" marginLeft={2} {...(right ? { width: v.bodyColumns - 2 } : {})}>
971 {drawZone(actions)}
972 {right && <Box key="cs-spacer" flexGrow={1} />}
973 {right && (
974 <Box key="cs-status" marginLeft={actions.length > 0 ? GAP : 0}>
975 {drawZone(status)}
976 {ticks !== undefined && labeled && (
977 <Box width={labelCells} marginLeft={status.length > 0 ? GAP : 0}>
978 {/* the theme's lightest text gray, `subtle`, which follows light and dark: the name stays quieter than the dim words before it */}
979 <Text color="subtle" italic wrap="truncate-end">{label(ticks.prompts, ticks.named)}</Text>
980 {/* a card for each drawn bar but the named one: a prompt folded into `…N` or `M…` has no bar to hover */}
981 {hovering && ticks.prompts.map((_, i) => drawnTick(i) && i !== ticks.named && (
982 <Box position="absolute" top={0} left={0} display="none" hover={{ scope: `cs-rail-${i}`, display: 'flex' }}>
983 <Text color="subtle" italic wrap="truncate-end">{label(ticks.prompts, i)}</Text>
984 </Box>
985 ))}
986 </Box>
987 )}
988 {ticks !== undefined && (
989 <Box key="cs-rail" marginLeft={status.length > 0 || labeled ? GAP : 0}>
990 {ticks.from > 0 && <Box marginRight={1}><Text dimColor>{`…${ticks.from}`}</Text></Box>}
991 {ticks.prompts.slice(ticks.from, ticks.to).map((p, j) => {
992 const i = ticks.from + j
993 if (i === ticks.named) return <Text dimColor>{'┃'}</Text>
994 return <Button key={`cs-rail-${i}`} plain dimColor label={ticks.denied.has(p.uuid) ? '┆' : '│'}
995 hover={hovering ? { scope: `cs-rail-${i}`, dimColor: false } : undefined} onPress={() => ticks.jump(i)} />
996 })}
997 {ticks.to < ticks.prompts.length && <Box marginLeft={1}><Text dimColor>{`${ticks.prompts.length - ticks.to}\u2026`}</Text></Box>}
998 </Box>
999 )}
1000 </Box>
1001 )}
1002 </Box>
1003 </Box>
1004 </Box>
1005 )
1006}
1007
1008// The chord prefix every bound key shares, up to its last space (`ctrl+x` of
1009// `ctrl+x 1` and `ctrl+x 2`); undefined when none are bound, the bound chords
1010// differ before their last word, or a bound chord is one word.
1011export function sharedPrefix(chords: (string | undefined)[]): string | undefined {
1012 const bound = chords.filter((chord): chord is string => chord !== undefined)
1013 if (bound.length === 0) return undefined
1014 const prefixes = bound.map(chord => {
1015 const at = chord.lastIndexOf(' ')
1016 return at <= 0 ? undefined : chord.slice(0, at)
1017 })
1018 const first = prefixes[0]
1019 return first !== undefined && prefixes.every(prefix => prefix === first) ? first : undefined
1020}
1021
1022// One `-features --porcelain` record, as _feature_readiness prints it.
1023export type FeatureRecord = { task: string; ahead: number; state: string }
1024// Every state _feature_readiness prints (lib/30-worktree.sh).
1025const FEATURE_STATES = new Set(['ready', 'staged', 'locked', 'dirty', 'untracked', 'vault-locked', 'base-dirty', 'merged'])
1026
1027// The records of `-features --porcelain`, or what is wrong with the first line
1028// that is not one: ten tab-separated fields, a whole `ahead`, a known state.
1029export function parseFeatures(stdout: string): FeatureRecord[] | { unreadable: string } {
1030 const records: FeatureRecord[] = []
1031 for (const line of stdout.split('\n')) {
1032 if (line === '') continue
1033 const fields = line.split('\t')
1034 const [task, , ahead, , , , , , , state] = fields
1035 if (fields.length !== 10 || task === undefined || task === '' || !/^\d+$/.test(ahead ?? '') || !FEATURE_STATES.has(state ?? '')) return { unreadable: line }
1036 records.push({ task, ahead: Number(ahead), state: state as string })
1037 }
1038 return records
1039}
1040
1041// A record's state as the band says it: `ready` only with work ahead of the
1042// base to land.
1043function stateWord(record: FeatureRecord): string {
1044 return record.state === 'ready' && record.ahead === 0 ? 'no commits' : record.state
1045}
1046
1047// The word for a base's records.
1048export function featuresWordOf(records: FeatureRecord[]): FeaturesWord | undefined {
1049 if (records.length === 0) return undefined
1050 const count = `${records.length} ${records.length === 1 ? 'feature' : 'features'}`
1051 const ready = records.filter(r => stateWord(r) === 'ready')
1052 const only = ready[0]
1053 if (ready.length === 1 && only !== undefined) return { label: `${count} \u00b7 ${cutTask(only.task)} ready`, finish: only.task }
1054 if (ready.length > 1) return { label: `${count} \u00b7 ${ready.length} ready`, finish: '' }
1055 const one = records[0]
1056 if (records.length === 1 && one !== undefined) return { label: `${count} \u00b7 ${cutTask(one.task)} ${stateWord(one)}` }
1057 return { label: `${count} \u00b7 none ready` }
1058}
1059
1060// The hooks do not wait on cs: a base's readiness walks git for every
1061// feature (1.4 s measured for one), so the band redraws when it answers.
1062function readFeaturesLater($: EngineInterface) {
1063 refreshFeatures($).catch(err => $.ui.log(LOGS.featuresUnread(String(err instanceof Error ? err.message : err))))
1064}
1065
1066// Asks cs for the session's features and redraws the band when the word
1067// moved. Only the lead conversation of a base session asks (cs never admits
1068// `@` in a name it creates, so `@` marks a feature); a reading still running
1069// is not doubled.
1070async function refreshFeatures($: EngineInterface) {
1071 if (featuresReading) return
1072 featuresReading = true
1073 try {
1074 const word = await readFeatures($)
1075 if (word?.label !== featuresWord?.label || word?.finish !== featuresWord?.finish) {
1076 featuresWord = word
1077 $.ui.invalidate('ui.render')
1078 }
1079 } finally {
1080 featuresReading = false
1081 }
1082}
1083
1084async function readFeatures($: EngineInterface): Promise<FeaturesWord | undefined> {
1085 const bin = await $.env.get("CS_BIN")
1086 if (!bin || !(await ownsRotation($))) return undefined
1087 const base = await csSessionName($, await $.session.cwd())
1088 // A feature (`base@task`) draws no word: /finish lands it from its base,
1089 // and asked from here cs reads the base conversation's own lock as `locked`.
1090 if (base === undefined || base.includes('@')) return undefined
1091 // A base with no `<base>@<task>` directory beside it has no features: cs is
1092 // not asked, and no clock asks again. /feature runs in the base's own
1093 // conversation, so the turn it ends in reads the new feature.
1094 if (!(await hasFeatureDirs($, base))) return undefined
1095 featuresClock ??= $.clock.every(FEATURES_POLL_MS, () => { if (bandIdle) return refreshFeatures($) })
1096 let complaint: string | undefined
1097 let word: FeaturesWord | undefined
1098 try {
1099 const result = await $.process.run([bin, base, '-features', '--porcelain'], { timeoutMs: FEATURES_TIMEOUT_MS })
1100 const parsed = result.exitCode === 0 ? parseFeatures(result.stdout) : undefined
1101 if (parsed === undefined) {
1102 complaint = LOGS.featuresExited(base, result.exitCode, result.stderr.split('\n').filter(l => l.trim() !== '').slice(-1)[0] ?? '')
1103 } else if ('unreadable' in parsed) {
1104 complaint = LOGS.featuresUnreadable(base, parsed.unreadable)
1105 } else {
1106 word = featuresWordOf(parsed)
1107 }
1108 } catch (err) {
1109 complaint = LOGS.featuresNoAnswer(base, String(err instanceof Error ? err.message : err))
1110 }
1111 if (complaint !== undefined && complaint !== featuresComplaint) $.ui.log(complaint)
1112 featuresComplaint = complaint
1113 return word
1114}
1115
1116// Whether the sessions root holds a feature of `base`: cs names each one's
1117// directory `<base>@<task>` there.
1118async function hasFeatureDirs($: EngineInterface, base: string): Promise<boolean> {
1119 const root = await sessionsRoot($)
1120 if (root === undefined) return false
1121 let entries: { name: string }[]
1122 try {
1123 entries = await $.fs.list(root)
1124 } catch {
1125 return false // no sessions root to list: no features
1126 }
1127 return entries.some(entry => entry.name.startsWith(`${base}@`))
1128}
1129
1130// The prompts the rail draws a bar for, `from` up to but not including
1131// `to`: those before fold into its `…N` run, those after into its `M…` run.
1132type RailWindow = { from: number; to: number }
1133
1134// The bars the rail draws of `count` prompts: the most, up to `most`, that
1135// fit `budget` cells with their runs, and always the named one. They end at
1136// the newest prompt, slid back only as far as the named one, where it is the
1137// first; undefined when not even the named bar fits.
1138export function railTicks(count: number, budget: number, most: number, named: number): RailWindow | undefined {
1139 if (!Number.isInteger(named) || named < 0 || named >= count) throw new Error(`cs: the rail named prompt ${named} of ${count}`)
1140 for (let drawn = Math.min(most, count); drawn >= 1; drawn--) {
1141 const from = Math.min(count - drawn, named)
1142 const shown = { from, to: from + drawn }
1143 if (railCells(count, shown) <= budget) return shown
1144 }
1145 return undefined
1146}
1147
1148// The rail's least: the named bar alone.
1149function leastWindow(named: number): RailWindow {
1150 return { from: named, to: named + 1 }
1151}
1152
1153// The cells the rail takes: its bars, and each run with the space between it
1154// and the bars.
1155function railCells(count: number, { from, to }: RailWindow): number {
1156 return foldCells(from) + to - from + foldCells(count - to)
1157}
1158
1159// The cells of a run of folded prompts, `…N ` before the bars or ` N…`
1160// after them, the space included; none when no prompt folds.
1161function foldCells(folded: number): number {
1162 return folded > 0 ? `\u2026${folded}`.length + 1 : 0
1163}
1164
1165// The prompt the band names: the newest, or the one being read (cs.bandPrompt).
1166function namedIndex(): number {
1167 return bandOptions?.prompt === 'read' ? readIndex() : prompts.length - 1
1168}
1169
1170// The prompt being read: of the prompts whose drawn row has reported what of
1171// it is on screen, the one drawn highest (the row cut at the viewport's top
1172// reports the rows scrolled away as `first`; every other visible row reports
1173// 0, and of those the earliest prompt is the higher); when none has reported,
1174// the prompt last read (the reader is inside a reply, its prompt scrolled
1175// away), else the newest.
1176function readIndex(): number {
1177 let best = -1
1178 let bestFirst = -1
1179 prompts.forEach((p, i) => {
1180 const id = requestIdOf(p)
1181 const report = id === undefined ? undefined : shown.get(id)
1182 if (report !== undefined && report.first > bestFirst) { best = i; bestFirst = report.first }
1183 })
1184 if (best >= 0) return best
1185 return drawnRead >= 0 && drawnRead < prompts.length ? drawnRead : prompts.length - 1
1186}
1187
1188// The id the engine drew a prompt's row under: by the row's uuid (the engine
1189// keys a message row by its message id; a message split into rows keeps the
1190// uuid's first four groups), else by the first line's text when no other
1191// prompt carries it, as a row drawn before the transcript stored it is
1192// matched (a repeated "continue" would bind every one to the same row);
1193// undefined while no row has.
1194function requestIdOf(p: Prompt): string | undefined {
1195 const byKey = drawnRows.get(rowKey(p.uuid))
1196 if (byKey !== undefined) return byKey.requestId
1197 if (prompts.filter(q => q.text === p.text).length > 1) return undefined
1198 for (const drawn of drawnRows.values()) if (drawn.text === p.text) return drawn.requestId
1199 return undefined
1200}