A rail of your session's prompts beside the transcript or above the prompt; hover to read one, click to jump to it.

A rail of your prompts for Claude Code. Hover to read one, click to jump back to it.
prompt-rail is a mod: it draws a row of bars above the prompt input, or a pane beside the transcript, with one tick for each prompt you sent in the session. Hovering a tick shows the prompt and a short summary of its turn, and clicking it scrolls the transcript to that prompt. Commands step through the prompts from the keyboard.
It needs Claude Code v2.1.287 or later, in the terminal or in the Code tab of the Claude desktop app. Mouse works best with "tui": "fullscreen".
From the Claude directory, or from the plugin's own marketplace:
claude plugin marketplace add oikon48/prompt-rail
claude plugin install prompt-rail@oikon48
Start a new session and the rail opens on its own.
| Command | |
|---|---|
/prompt-rail horizontal | Bars above the prompt input (the default) |
/prompt-rail vertical | A pane beside the transcript |
/prompt-rail off | Hide the rail |
/prompt-rail next, prev | Jump to the next or previous prompt |
/prompt-rail first, last | Jump to the first or the newest prompt |
/prompt-rail 12, #12 | Jump to prompt #12 |
/prompt-rail find <words> | Jump to the newest prompt that holds the words |
/prompt-rail-next, /prompt-rail-prev | Jump to the next or previous prompt, for a keybinding |
/prompt-rail-toggle | Hide the rail, or bring it back, for a keybinding |
/prompt-rail | Reopen the rail in the current layout |
The layout is also the "Rail mode" row in /config, and it is kept across sessions.
In the horizontal layout, ctrl+x tab moves the focus to the bars: ← → move across them, Enter jumps to the prompt, Esc returns to the prompt input.
This section is prompt-rail's privacy policy: what it reads, runs, and stores.
prompt-rail makes no network requests and sends nothing anywhere, neither the transcript it reads nor your prompts. It collects no analytics, and its author receives no data from it. Everything it does stays on your machine:
.jsonl file Claude Code writes for the session) to list your prompts and their turns.tail -c +N <transcript>, which writes the file from byte N on to the mod, so the rail reads only what is new. On a Windows path where tail cannot start, it runs powershell -NoProfile -NonInteractive with a short script that copies the same file from that position. The output of either goes to the mod alone. It runs no other program.prompt-rail.mode (the "Rail mode" row in /config), when you pick a layout. It sets no other setting and no environment variable.Its hooks watch and do not change what passes through them:
command.run answers only its own commands (/prompt-rail, /prompt-rail-next, /prompt-rail-prev, /prompt-rail-toggle) and passes every other command on unchanged.classic.SessionStart and classic.Stop read the transcript path from the event to refresh the rail, and pass the event on unchanged; the rail adds no context or instructions.prompt.submit and session.receive note that a prompt was sent, and pass it on unchanged.turn.start, turn.complete, and ui.render on transcript rows note which prompt is on screen and which turn is running, and draw those rows as Claude Code does. ui.render, ui.focus, and ui.press on the rail's own pane and band draw the rail and take its clicks and keys./compact command's own row cannot be jumped to.next cannot scroll further.Source, issues, and the full README with screenshots: https://github.com/oikon48/prompt-rail
hooks/index.tsx 1647 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3const PANE = 'prompt-rail'
4// Rows the person typed (terminal composer, desktop/remote bridge, SDK host).
5const PROMPT_KINDS = new Set(['composer', 'bridge', 'sdk'])
6// Columns the docked rail asks for: a tick and a little air.
7const RAIL_COLUMNS = 4
8// Below this many body columns the vertical rail has no room to reveal the
9// prompt beside a tick, so the band above the prompt shows it instead.
10const INLINE_REVEAL_MIN_COLUMNS = 12
11// Cells a hover card keeps for the prompt's text beside the turn's details,
12// and the desktop's label of the prompt being read beside the bars.
13const MIN_CARD_TEXT = 12
14// Cells the desktop's bars keep however narrow the band: one bar and its marks.
15const MIN_DESKTOP_BARS = 3
16// The mode is the plugin's `mode` setting (userConfig), a row in /config. An
17// earlier version kept it in the store under this key, shared by every session.
18const LEGACY_MODE_KEY = 'mode'
19// `session-mode:<session id>` -> a mode the setting could not keep (a session
20// with no /config row for plugin fields), so a module reloaded mid-session
21// starts in it again. Keyed by session, so a later session starts clean.
22const SESSION_MODE_KEY_PREFIX = 'session-mode:'
23// The mode last on (vertical or horizontal), so `prompt-rail-toggle` turned
24// off has a mode to come back to; horizontal until another was written.
25const LAST_ON_KEY = 'last-on'
26// `transcript:<session id>` -> { path, at }, so a hot-reloaded module (whose
27// session.start carries no path) can rebuild its list. One key per session, so
28// sessions starting together never rewrite each other's; the newest few stay.
29const TRANSCRIPT_KEY_PREFIX = 'transcript:'
30const KEPT_TRANSCRIPTS = 20
31// The id a prompt row is drawn under before its message is stored; the stored
32// row follows under its uuid.
33const PROVISIONAL_ID = 'placeholder'
34// User rows the engine writes around its own output (slash commands, bash
35// mode, reminders) or around another agent's message (a peer session, a
36// subagent's hand-back, a teammate, a coordinator's relay), which are not
37// prompts. Builds up to 2.1.304 stored some of the messages with no origin,
38// so only this framing tells them apart.
39const WRAPPER =
40 /^(<(command-|local-command-|bash-|system-reminder|task-notification|user-prompt-submit-hook|cross-session-message|agent-message|teammate-message|relay\b)|Another Claude session sent a message)/
41// Origins the transcript stores on a row no person typed: another session or
42// agent, a background task or relay, the engine's own follow-up, a plugin's
43// prompt. The file names them apart from the hooks (a typed prompt is
44// `human`, not `composer`, and a Remote Control one is unseen), so the rows
45// to leave out are named rather than PROMPT_KINDS kept.
46const OTHER_ORIGINS = new Set(['peer', 'task-notification', 'auto-continuation', 'plugin'])
47// Whether a stored row, or a queued_command attachment, is no person's prompt
48// by how the engine marked it.
49const isOthers = (marked: { isMeta?: unknown; origin?: { kind?: unknown } } | undefined) =>
50 marked?.isMeta === true || OTHER_ORIGINS.has(String(marked?.origin?.kind))
51// The viewer's state the engine puts ahead of a prompt sent while an artifact
52// is open; the typed text follows it. No row field tells it from typed text,
53// so only the engine's layout matches: the artifact id, a JSON line starting
54// with "context", and the closing tag on a line of its own.
55const VIEW_CONTEXT = /^\s*<artifact-view-context artifact="[^"]*">\n\{"context":[\s\S]*?\n<\/artifact-view-context>/
56// The notice the engine stores as a user row when the person interrupts a turn.
57const INTERRUPTED = /^\[Request interrupted by user/
58// A message uuid, as the transcript stores it (see rowKey).
59const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
60// The rail is drawn again this many ms after the last onScreen report, and no
61// later than SETTLE_MAX_MS after the first (see redrawRailSettled). Measured
62// on the terminal: a replayed row is corrected within 13 ms, a layout settles
63// within 18 ms.
64const SETTLE_MS = 40
65const SETTLE_MAX_MS = 120
66// A row added at most this many ms before a prompt's notification may be that
67// prompt's own: the engine draws a queued prompt's first row as it notifies.
68const LATELY_MS = 250
69// Cells kept left of the horizontal rail: off the window's edge, a pointer
70// leaving the first bar crosses a cell and the surface sees the hover end.
71const RAIL_INSET = 2
72// The engine's refusal when no row is drawn under an id, as for a slash
73// command's own row, which the transcript file holds but the surface skips.
74// Other refusals (a race with another move) pass, so they leave the tick be.
75const NOT_DRAWN = /nothing drawn/
76// The engine's refusal where no transcript viewport takes a plugin's scroll,
77// as in the desktop app; said once, in words of the rail's own.
78const UNSCROLLABLE = /not scrollable/
79const UNSCROLLABLE_TOAST = 'jumps cannot land here: this view does not let a plugin scroll the transcript'
80// A count the rail's sites (the pane and the band) read while drawing, so
81// bumping it draws them again, and them alone. `$.ui.invalidate('ui.render')`
82// also draws every transcript row this module hooks, and rows drawn again
83// while the person scrolls just after a jump move the viewport a turn away.
84const MOVED = { plugin: 'prompt-rail', key: 'moved' } as const
85// How long the band's text line shows the card of the bar the focus ring is
86// on after the ring last moved: no event says the ring left the band.
87const RING_CARD_MS = 4000
88const USAGE = '[off|vertical|horizontal|next|prev|first|last|<n>|find <words>]'
89// Commands that step through the prompts, each with the way it steps.
90const STEP_COMMANDS = [
91 ['prompt-rail-next', 'next'],
92 ['prompt-rail-prev', 'previous'],
93] as const
94
95// vertical: ticks in a docked pane; horizontal: ticks in a row above the
96// prompt; off: no rail at all. One setting, so /config keeps a single row.
97type Mode = 'off' | 'vertical' | 'horizontal'
98const isMode = (value: unknown): value is Mode => value === 'off' || value === 'vertical' || value === 'horizontal'
99
100type Entry = { id: string; text: string }
101
102// The key rows are matched by. A message the engine splits into several rows
103// is drawn under ids derived from its stored uuid, the first four groups kept
104// and the last replaced by the row's index, so a uuid is matched by those
105// groups; any other id (a tool_use id, the provisional one) as it is.
106export const rowKey = (id: string) => (UUID.test(id) ? id.slice(0, 24) : id)
107
108// The id a prompt's row was last drawn under, which a jump scrolls to, from a
109// map of row key -> drawn id; its own id while it has not been drawn.
110export const drawnRow = (drawn: Map<string, string>, id: string) => drawn.get(rowKey(id)) ?? id
111
112// Terminal cells a character takes: two for East Asian wide and emoji ranges.
113const cells = (char: string) => {
114 const code = char.codePointAt(0) ?? 0
115 const isWide =
116 (code >= 0x1100 && code <= 0x115f) ||
117 (code >= 0x2e80 && code <= 0xa4cf) ||
118 (code >= 0xac00 && code <= 0xd7a3) ||
119 (code >= 0xf900 && code <= 0xfaff) ||
120 (code >= 0xfe30 && code <= 0xfe4f) ||
121 (code >= 0xff00 && code <= 0xff60) ||
122 (code >= 0xffe0 && code <= 0xffe6) ||
123 (code >= 0x1f300 && code <= 0x1faff) ||
124 (code >= 0x20000 && code <= 0x3fffd)
125 return isWide ? 2 : 1
126}
127
128const cellWidth = (text: string) => [...text].reduce((sum, char) => sum + cells(char), 0)
129
130// `text` padded with spaces to `width` cells, so a card painted over the
131// default line hides it whole.
132const padTo = (text: string, width: number) => text + ' '.repeat(Math.max(0, width - cellWidth(text)))
133
134// The prompt on one line, cut to `width` terminal cells with an ellipsis.
135const oneLine = (text: string, width: number) => {
136 const flat = text.replace(/\s+/g, ' ').trim()
137 const chars = [...flat]
138 if (chars.reduce((sum, char) => sum + cells(char), 0) <= width) return flat
139 let out = ''
140 let used = 0
141 for (const char of chars) {
142 if (used + cells(char) > width - 1) break
143 out += char
144 used += cells(char)
145 }
146 return `${out}…`
147}
148
149// A stacked rail reads rows apart; a row of ticks needs upright bars to. A
150// dotted one marks a prompt the transcript does not draw, so a jump fails.
151export const tick = (isCurrent: boolean, isUnreachable = false) => (isCurrent ? '━' : isUnreachable ? '┄' : '─')
152export const bar = (isCurrent: boolean, isUnreachable = false) => (isCurrent ? '┃' : isUnreachable ? '┆' : '│')
153
154// Record what a jump to `id` answered: a landing makes it reachable, a refusal
155// for want of a drawn row unreachable, any other refusal says nothing. True
156// when the set changed.
157export const noteScroll = (unreachable: Set<string>, id: string, deny: string | undefined) => {
158 const was = unreachable.has(id)
159 if (deny === undefined) unreachable.delete(id)
160 else if (NOT_DRAWN.test(deny)) unreachable.add(id)
161 return unreachable.has(id) !== was
162}
163
164// What a refused jump says: the engine's refusal as it words it, or, where
165// the view cannot scroll the transcript at all, words of the rail's own the
166// first time; undefined once those were said.
167export const jumpNotice = (deny: string, isUnscrollableSaid: boolean) =>
168 UNSCROLLABLE.test(deny) ? (isUnscrollableSaid ? undefined : UNSCROLLABLE_TOAST) : deny
169
170// The prompt one step from `current` in direction `dir`, passing over those
171// `isSkipped` names; from an unknown place (-1), the first or the last. -1
172// when there is none that way.
173export const stepFrom = (current: number, count: number, dir: 1 | -1, isSkipped: (i: number) => boolean) => {
174 let i = current >= 0 ? current + dir : dir > 0 ? 0 : count - 1
175 for (; i >= 0 && i < count; i += dir) if (!isSkipped(i)) return i
176 return -1
177}
178
179// The prompt `/prompt-rail <asked>` names among `texts`: `n` or `#n` by its
180// number, `first`, `last`, or with `find <words>` the newest whose text holds
181// them (case aside). -1 when none does; undefined when `asked` names none.
182export const pickPrompt = (asked: string, texts: string[]) => {
183 const number = /^#?(\d+)$/.exec(asked)
184 if (number) {
185 const i = Number(number[1]) - 1
186 return i < texts.length ? i : -1
187 }
188 if (asked === 'first') return texts.length > 0 ? 0 : -1
189 if (asked === 'last') return texts.length - 1
190 const words = /^find\s+(.+)$/.exec(asked)?.[1]?.toLowerCase()
191 if (words === undefined) return undefined
192 for (let i = texts.length - 1; i >= 0; i--) if (texts[i]?.toLowerCase().includes(words)) return i
193 return -1
194}
195
196// What the transcript records of the turn a prompt started: how long it took
197// (`durationMs` as the engine reported it, else `spanMs` from the prompt to
198// the latest reply), how many tools it called, the paths of the files it
199// edited (Edit and Write), and, unless it simply answered, how it went.
200export type Turn = { durationMs?: number; spanMs?: number; tools: number; files: string[]; outcome?: Outcome }
201// A turn still running, stopped by the person, or ended by an API error.
202type Outcome = 'running' | 'interrupted' | 'error'
203const OUTCOME_WORDS: Record<Outcome, string> = { running: 'running', interrupted: 'interrupted', error: 'API error' }
204
205// A duration as the rail shows it: `7s`, `1m 23s`, `1h 2m`.
206const duration = (ms: number) => {
207 const seconds = Math.floor(ms / 1000)
208 if (seconds < 60) return `${seconds}s`
209 if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
210 return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`
211}
212
213// The files a turn line names before it counts the rest.
214const NAMED_FILES = 3
215
216const EDITING_TOOLS = new Set(['Edit', 'Write'])
217const segments = (path: string) => path.split(/[\\/]/).filter(Boolean)
218
219// Each path by its file name, or by its folder and name where two share one.
220const fileNames = (paths: string[]) => {
221 const base = (path: string) => segments(path).at(-1) ?? path
222 return paths.map(path =>
223 paths.some(other => other !== path && base(other) === base(path)) ? segments(path).slice(-2).join('/') : base(path),
224 )
225}
226
227// A turn on one line: `1m 23s · 4 tools · app.ts, README.md`, each part left
228// out when the transcript has nothing for it; empty when it has nothing.
229// Given `maxCells`, it names fewer files (down to a count) to fit in them.
230export const turnLine = (turn: Turn | undefined, maxCells = Infinity) => {
231 if (!turn) return ''
232 const parts: string[] = []
233 const ms = turn.durationMs ?? turn.spanMs
234 if (ms !== undefined) parts.push(duration(ms))
235 if (turn.outcome) parts.push(OUTCOME_WORDS[turn.outcome])
236 if (turn.tools > 0) parts.push(`${turn.tools} ${turn.tools === 1 ? 'tool' : 'tools'}`)
237 const names = fileNames(turn.files)
238 const withFiles = (named: number) => {
239 if (names.length === 0) return parts.join(' · ')
240 const rest = names.length - named
241 const files =
242 named > 0
243 ? `${names.slice(0, named).join(', ')}${rest > 0 ? ` +${rest}` : ''}`
244 : `${names.length} ${names.length === 1 ? 'file' : 'files'}`
245 return [...parts, files].join(' · ')
246 }
247 for (let named = Math.min(NAMED_FILES, names.length); named > 0; named--) {
248 const line = withFiles(named)
249 if (cellWidth(line) <= maxCells) return line
250 }
251 return withFiles(0)
252}
253
254type TranscriptIndex = {
255 prompts: Entry[]
256 // The turn each prompt started, in the same order.
257 turns: Turn[]
258 // Reply row uuid or tool_use id -> index into prompts of the prompt it answers.
259 owners: [string, number][]
260 // Every row uuid the file holds, live branch or not.
261 known: Set<string>
262}
263
264// The uuids on the live branch: the chain of parents from the last row. A
265// /rewind leaves the abandoned branch in the file; a /compact boundary starts
266// a new chain whose logicalParentUuid links back to the rows before it.
267const liveBranch = (rows: any[]) => {
268 const byId = new Map<string, any>()
269 for (const row of rows) byId.set(row.uuid, row)
270 const live = new Set<string>()
271 let row = [...rows].reverse().find(candidate => !candidate.isSidechain)
272 while (row && !live.has(row.uuid)) {
273 live.add(row.uuid)
274 const parent = row.parentUuid ?? row.logicalParentUuid
275 row = typeof parent === 'string' ? byId.get(parent) : undefined
276 }
277 return live
278}
279
280// What the index reads of a transcript row, and nothing else: a long
281// session's rows are kept between reads, and most of their bytes are tool
282// results and replies the rail never shows. Undefined for a line that is not
283// a row (a torn last line while the engine appends, or no uuid).
284const parseRow = (line: string): any => {
285 let row: any
286 try {
287 row = JSON.parse(line)
288 } catch {
289 return undefined
290 }
291 if (typeof row?.uuid !== 'string') return undefined
292 const content = row.message?.content
293 const blocks = Array.isArray(content)
294 ? content.flatMap((block: any) => {
295 if (block?.type === 'text' && typeof block.text === 'string') return [{ type: 'text', text: block.text }]
296 if (block?.type === 'tool_result') return [{ type: 'tool_result' }]
297 if (block?.type === 'tool_use' && typeof block.id === 'string') {
298 const path = block.input?.file_path
299 return [{ type: 'tool_use', id: block.id, name: block.name, input: typeof path === 'string' ? { file_path: path } : {} }]
300 }
301 return []
302 })
303 : content
304 return {
305 uuid: row.uuid,
306 parentUuid: row.parentUuid,
307 logicalParentUuid: row.logicalParentUuid,
308 isSidechain: row.isSidechain,
309 type: row.type,
310 subtype: row.subtype,
311 durationMs: row.durationMs,
312 isApiErrorMessage: row.isApiErrorMessage,
313 isMeta: row.isMeta,
314 isCompactSummary: row.isCompactSummary,
315 origin: row.origin && { kind: row.origin.kind },
316 timestamp: row.timestamp,
317 message: row.message && { role: row.message.role, content: typeof content === 'string' ? content : blocks },
318 attachment:
319 row.attachment?.type === 'queued_command'
320 ? {
321 type: row.attachment.type,
322 prompt: row.attachment.prompt,
323 isMeta: row.attachment.isMeta,
324 origin: row.attachment.origin && { kind: row.attachment.origin.kind },
325 }
326 : undefined,
327 }
328}
329
330// The rows of a transcript JSONL's text, in order.
331const parseRows = (jsonl: string) => jsonl.split('\n').flatMap(line => (line.trim() ? (parseRow(line) ?? []) : []))
332
333// The person's prompts on the live branch of a transcript's rows, in order,
334// keyed by message uuid, and the prompt each reply row and tool call answers
335// (a tool row is drawn under its tool_use id). Tool results, meta rows,
336// sidechains and the engine's wrapper rows are not prompts.
337const indexRows = (rows: any[]): TranscriptIndex => {
338 const live = liveBranch(rows)
339 const prompts: Entry[] = []
340 const owners: [string, number][] = []
341 const turns: Turn[] = []
342 // When each turn started and when its latest reply was written.
343 const times: { start: number; last: number }[] = []
344 // The prompt that started the turn being read: a prompt delivered into a
345 // turn is listed, but the turn's details stay with the one that started it.
346 let started = -1
347 for (const row of rows) {
348 if (row.isSidechain || !live.has(row.uuid)) continue
349 const turn = turns[started]
350 if (row.type === 'system' && row.subtype === 'turn_duration' && typeof row.durationMs === 'number') {
351 if (turn) turn.durationMs = (turn.durationMs ?? 0) + row.durationMs
352 continue
353 }
354 if (row.type === 'assistant') {
355 if (prompts.length === 0 || !turn) continue
356 // A reply places the reader under the latest prompt, delivered or not.
357 const owner = prompts.length - 1
358 owners.push([row.uuid, owner])
359 if (row.isApiErrorMessage === true) turn.outcome = 'error'
360 const at = Date.parse(row.timestamp)
361 if (Number.isFinite(at)) times[started]!.last = at
362 const blocks = Array.isArray(row.message?.content) ? row.message.content : []
363 for (const block of blocks) {
364 if (block?.type !== 'tool_use' || typeof block.id !== 'string') continue
365 owners.push([block.id, owner])
366 turn.tools++
367 const path = block.input?.file_path
368 if (EDITING_TOOLS.has(block.name) && typeof path === 'string' && !turn.files.includes(path)) turn.files.push(path)
369 }
370 continue
371 }
372 // A prompt typed while a turn ran and delivered into it is stored as a
373 // queued_command attachment, never as a user row of its own; so is another
374 // agent's message delivered into it.
375 if (row.type === 'attachment' && row.attachment?.type === 'queued_command') {
376 if (isOthers(row.attachment)) continue
377 const prompt = row.attachment.prompt
378 const text = typeof prompt === 'string' ? prompt.replace(VIEW_CONTEXT, '').trim() : ''
379 if (!text || WRAPPER.test(text) || text.startsWith('/')) continue
380 prompts.push({ id: row.uuid, text })
381 turns.push({ tools: 0, files: [] })
382 times.push({ start: NaN, last: NaN })
383 continue
384 }
385 if (row.type !== 'user' || isOthers(row) || row.isCompactSummary || row.message?.role !== 'user') continue
386 const content = row.message.content
387 let text = ''
388 if (typeof content === 'string') {
389 text = content
390 } else if (Array.isArray(content)) {
391 text = content
392 .filter((block: any) => block?.type === 'text' && typeof block.text === 'string')
393 .map((block: any) => block.text)
394 .join('\n')
395 }
396 text = text.replace(VIEW_CONTEXT, '').trim()
397 // An interruption notice ends its turn; one mid tool call rides with the
398 // call's result, so it is read before tool results are passed over.
399 if (INTERRUPTED.test(text)) {
400 if (turn) turn.outcome = 'interrupted'
401 continue
402 }
403 if (Array.isArray(content) && content.some((block: any) => block?.type === 'tool_result')) continue
404 // A slash command's own row is not a prompt: the render hook skips it too,
405 // so it is never drawn and could not be scrolled to.
406 if (!text || WRAPPER.test(text) || text.startsWith('/')) continue
407 prompts.push({ id: row.uuid, text })
408 turns.push({ tools: 0, files: [] })
409 started = prompts.length - 1
410 const at = Date.parse(row.timestamp)
411 times.push({ start: at, last: at })
412 }
413 turns.forEach((turn, i) => {
414 const time = times[i]
415 if (time && Number.isFinite(time.start) && time.last > time.start) turn.spanMs = time.last - time.start
416 })
417 return { prompts, turns, owners, known: new Set(rows.map(row => row.uuid)) }
418}
419
420// The engine's cap on one $.fs.read; a larger transcript is streamed.
421const READ_CAP = 4 * 1024 * 1024
422const encoder = new TextEncoder()
423
424// The transcript as last read: its size and modification time, the rows of
425// its complete lines and the byte where they end, and where the last row
426// starts, which a later read of a long session's file checks is still there.
427// Whether a read is under way, and the path whose file could not be read,
428// said once.
429type Seen = {
430 path: string
431 size: number
432 mtimeMs: number
433 rows: any[]
434 offset: number
435 lastStart: number
436 lastUuid: string | undefined
437 isReading: boolean
438 warned: string
439 // What a failed read has to say, said by the next hook to run once the
440 // session is bound (before session.start the engine drops a toast).
441 notice: string | undefined
442}
443const unseen = (): Seen => ({
444 path: '',
445 size: -1,
446 mtimeMs: -1,
447 rows: [],
448 offset: 0,
449 lastStart: 0,
450 lastUuid: undefined,
451 isReading: false,
452 warned: '',
453 notice: undefined,
454})
455
456// Take the complete lines of `text`, which starts at byte `at` of the file,
457// into `seen`, and return the rest: a line the engine is still writing, or
458// the last of a file with no newline at its end.
459const takeLines = (seen: Seen, text: string, at: number) => {
460 const lines = text.split('\n')
461 const rest = lines.pop() ?? ''
462 for (const line of lines) {
463 const row = line.trim() ? parseRow(line) : undefined
464 if (row) {
465 seen.rows.push(row)
466 seen.lastStart = at
467 seen.lastUuid = row.uuid
468 }
469 at += encoder.encode(line).length + 1
470 }
471 seen.offset = at
472 return rest
473}
474
475// The index of the rows read, and of a last line with no newline yet when it
476// parses whole (it is read again once it has one).
477const indexSeen = (seen: Seen, rest: string) => {
478 const last = rest.trim() ? parseRow(rest) : undefined
479 return indexRows(last ? [...seen.rows, last] : seen.rows)
480}
481
482// A Windows path, of a drive (`C:\...`) or a network share (`\\host\...`).
483const isWindowsPath = (path: string) => /^([a-zA-Z]:[\\/]|\\\\)/.test(path)
484
485// The commands that write a file's bytes from `at` on to their standard
486// output, tried in order until one starts: `tail -c +N`, and on a Windows
487// path, where tail is not a given (Git for Windows ships one, off the PATH of
488// most sessions), PowerShell copying the file's stream from that position.
489// The path and position reach the script through its environment, never its
490// text, since PowerShell reads curly quotes as quotes too; the file stays
491// shared for the engine to write, rename or delete; a read that fails ends
492// the script with a non-zero code instead of passing as a short file.
493export const streamRequests = (path: string, at: number): { argv: string[]; env?: Record<string, string> }[] => {
494 const tail = { argv: ['tail', '-c', `+${at + 1}`, path] }
495 if (!isWindowsPath(path)) return [tail]
496 const script = [
497 "$ErrorActionPreference = 'Stop'",
498 "$f = [IO.File]::Open($env:PROMPT_RAIL_FILE, 'Open', 'Read', 'ReadWrite, Delete')",
499 'try { $f.Position = [long]$env:PROMPT_RAIL_AT; $f.CopyTo([Console]::OpenStandardOutput()) } finally { $f.Dispose() }',
500 ].join('; ')
501 const powershell = {
502 argv: ['powershell', '-NoProfile', '-NonInteractive', '-Command', script],
503 env: { PROMPT_RAIL_FILE: path, PROMPT_RAIL_AT: String(at) },
504 }
505 return [tail, powershell]
506}
507
508// Start the first of `requests` whose command can: the engine rejects a
509// stream's first pull when it cannot (no `tail` on the PATH), so that pull is
510// taken here and handed on with the stream. The last request's failure is
511// the caller's.
512async function startStream($: EngineInterface, requests: ReturnType<typeof streamRequests>) {
513 for (const [i, request] of requests.entries()) {
514 const child = $.process.spawn(request)
515 try {
516 return { child, first: await child.next(), argv: request.argv }
517 } catch (err) {
518 if (i === requests.length - 1) throw err
519 }
520 }
521 throw new Error('no command to read with')
522}
523
524// Read the file on from the last row read, with tail or what stands in for
525// it (see streamRequests), since $.fs.read takes no more than READ_CAP. That
526// row comes first and must still be there, else the file was replaced: false
527// then, and nothing is taken. Otherwise the rest after the last complete line.
528async function streamRows($: EngineInterface, path: string, seen: Seen) {
529 let expected = seen.lastUuid
530 let at = expected === undefined ? seen.offset : seen.lastStart
531 let carry = ''
532 const { child, first, argv } = await startStream($, streamRequests(path, at))
533 for (let pull = first; !pull.done; pull = await child.next()) {
534 const piece = pull.value
535 if (piece.stream !== 'stdout') continue
536 let text = carry + piece.text
537 if (expected !== undefined) {
538 const end = text.indexOf('\n')
539 if (end < 0) {
540 carry = text
541 continue
542 }
543 const line = text.slice(0, end)
544 if (parseRow(line)?.uuid !== expected) return false
545 expected = undefined
546 at += encoder.encode(line).length + 1
547 text = text.slice(end + 1)
548 }
549 carry = takeLines(seen, text, at)
550 at = seen.offset
551 }
552 const { code } = await child.result
553 if (code !== 0) throw new Error(`${argv[0]} exited with ${code}`)
554 return carry
555}
556
557// Stream a transcript too large for $.fs.read, from its start when it was
558// replaced; its index, or undefined when it could not be read, which is left
559// in `seen.notice` to be said once for the file (see tellNotice).
560async function readLarge($: EngineInterface, path: string, seen: Seen, size: number, mtimeMs: number) {
561 try {
562 let rest = await streamRows($, path, seen)
563 if (rest === false) {
564 Object.assign(seen, { rows: [], offset: 0, lastStart: 0, lastUuid: undefined })
565 rest = await streamRows($, path, seen)
566 if (rest === false) return undefined
567 }
568 Object.assign(seen, { path, size, mtimeMs })
569 return indexSeen(seen, rest)
570 } catch (err) {
571 if (seen.warned !== path) {
572 seen.warned = path
573 const megabytes = Math.round(size / 1024 / 1024)
574 seen.notice = `the transcript is ${megabytes} MB, too large to read here (${(err as Error).message}); prompts are listed as they are drawn`
575 }
576 return undefined
577 }
578}
579
580// Say what a failed read left in `seen.notice`, once the session is bound:
581// a toast before session.start is dropped, so it waits for the next hook.
582const tellNotice = ($: EngineInterface, seen: Seen, isBound: boolean) => {
583 if (!isBound || seen.notice === undefined) return
584 $.ui.toast(seen.notice)
585 seen.notice = undefined
586}
587
588// The transcript's index, or undefined when it is as `seen` last read it (a
589// long session's file is not parsed again for a turn that wrote nothing),
590// before the file exists (a fresh session), or while another read is under
591// way. Records what it read in `seen`. A file over READ_CAP is read on from
592// where the last read ended; when that is more than READ_CAP, as on resuming a
593// long session, it is read without holding the hook, and `whenLate` gets the
594// index once it is done, or undefined when it could not be read.
595async function readTranscript($: EngineInterface, path: string, seen: Seen, whenLate: (index: TranscriptIndex | undefined) => void) {
596 if (seen.isReading) return undefined
597 try {
598 const { size, mtimeMs } = await $.fs.stat(path)
599 if (seen.path === path && seen.size === size && seen.mtimeMs === mtimeMs) return undefined
600 if (seen.path !== path || size < seen.offset) Object.assign(seen, { ...unseen(), warned: seen.warned, notice: seen.notice })
601 if (size <= READ_CAP) {
602 const text = await $.fs.read(path)
603 Object.assign(seen, { rows: [], lastStart: 0, lastUuid: undefined })
604 const rest = takeLines(seen, text, 0)
605 Object.assign(seen, { path, size, mtimeMs })
606 return indexSeen(seen, rest)
607 }
608 seen.isReading = true
609 const reading = readLarge($, path, seen, size, mtimeMs).finally(() => {
610 seen.isReading = false
611 })
612 if (size - seen.offset <= READ_CAP) return await reading
613 void reading.then(whenLate)
614 return undefined
615 } catch {
616 seen.isReading = false
617 return undefined
618 }
619}
620
621// Remember this session's transcript path under its own key, then drop all
622// but the newest few sessions' keys.
623async function rememberTranscript($: EngineInterface, sessionId: string, transcriptPath: string) {
624 await $.store.set(`${TRANSCRIPT_KEY_PREFIX}${sessionId}`, { path: transcriptPath, at: Date.now() })
625 const keys = (await $.store.keys()).filter(key => key.startsWith(TRANSCRIPT_KEY_PREFIX))
626 if (keys.length <= KEPT_TRANSCRIPTS) return
627 const dated = await Promise.all(
628 keys.map(async key => {
629 const value = (await $.store.get(key)) as { at?: unknown } | undefined
630 return { key, at: typeof value?.at === 'number' ? value.at : 0 }
631 }),
632 )
633 dated.sort((x, y) => y.at - x.at)
634 await Promise.all(dated.slice(KEPT_TRANSCRIPTS).map(({ key }) => $.store.delete(key)))
635}
636
637// Open the pane where the mode draws the rail in it; close it elsewhere (off,
638// or horizontal on the terminal, where the band carries the rail).
639async function seatRail($: EngineInterface, mode: Mode, isTerminal: boolean) {
640 if (mode === 'off' || (mode === 'horizontal' && isTerminal)) {
641 await $.ui.close({ id: PANE })
642 } else {
643 await $.ui.open({ id: PANE, title: 'Prompts', columns: RAIL_COLUMNS })
644 }
645}
646
647// Write the mode setting, as a change in /config would; say so if refused.
648// The key stays fixed text in the call, so the Claude directory's checks can
649// read which setting the mod writes.
650// A session with no /config row for plugin fields (the desktop app's SDK
651// sessions) throws instead of denying, and the mode then holds for this
652// session only.
653async function writeMode($: EngineInterface, mode: Mode) {
654 if (mode !== 'off') await $.store.set(LAST_ON_KEY, mode)
655 try {
656 const result = await $.config.set({ key: 'prompt-rail.mode', value: mode })
657 if (result.deny) $.ui.toast(`the mode was not saved: ${result.deny}`)
658 } catch (err) {
659 await $.store.set(`${SESSION_MODE_KEY_PREFIX}${await $.session.id()}`, mode)
660 $.ui.toast(`${mode} for this session; the mode was not saved: ${(err as Error).message}`)
661 }
662}
663
664// Scroll the transcript to a prompt's row, drawn under `target`, from a
665// dispatch that answers the person's own input (a press, a typed command): a
666// transcript row moves only then. Records whether the prompt could be reached,
667// and returns whether the transcript scrolled to it. Where the view cannot
668// scroll at all, says so once a session (`notices.isUnscrollableSaid`).
669async function jumpTo($: EngineInterface, id: string, target: string, unreachable: Set<string>, notices: { isUnscrollableSaid: boolean }) {
670 try {
671 const result = await $.ui.scroll({ to: { requestId: target }, block: 'start' })
672 if (result.deny) {
673 const notice = jumpNotice(result.deny, notices.isUnscrollableSaid)
674 if (notice !== undefined) $.ui.toast(notice)
675 if (UNSCROLLABLE.test(result.deny)) notices.isUnscrollableSaid = true
676 }
677 if (noteScroll(unreachable, id, result.deny)) await redrawRail($)
678 return !result.deny
679 } catch (err) {
680 $.ui.toast((err as Error).message)
681 return false
682 }
683}
684
685// Draw the rail's sites again, and them alone (see MOVED).
686async function redrawRail($: EngineInterface) {
687 const { value = 0 } = await $.state.get(MOVED)
688 await $.state.set(MOVED, value + 1)
689}
690
691// The same from a render hook, which may not write state: once its dispatch ends.
692function redrawRailLater($: EngineInterface) {
693 $.clock.after(0, () => void redrawRail($))
694}
695
696// The timers of a redraw waiting for onScreen reports to settle.
697type Settle = { quiet?: Timer; latest?: Timer }
698
699// Draw the rail again once onScreen reports settle, if `isStale` then says the
700// drawing no longer shows the prompt being read: SETTLE_MS after the last
701// report, and no later than SETTLE_MAX_MS after the first, so reports that
702// never pause (a scroll held down, a running tool row) still redraw it. A
703// remounted row replays where it was last seen and a layout may settle over
704// two frames; the surface corrects both within a frame or two.
705function redrawRailSettled($: EngineInterface, settle: Settle, isStale: () => boolean) {
706 const fire = () => {
707 settle.quiet?.cancel()
708 settle.latest?.cancel()
709 settle.quiet = undefined
710 settle.latest = undefined
711 if (isStale()) void redrawRail($)
712 }
713 settle.quiet?.cancel()
714 settle.quiet = $.clock.after(SETTLE_MS, fire)
715 settle.latest ??= $.clock.after(SETTLE_MAX_MS, fire)
716}
717
718// After one onScreen report: a row that said it is cut at the viewport's top
719// is confirmed once a replay would have been corrected (see SETTLE_MS), and
720// the rail is drawn again once reports settle.
721function afterReport<Row>($: EngineInterface, settle: Settle, cut: Row | undefined, confirm: (row: Row) => void, isStale: () => boolean) {
722 if (cut !== undefined) $.clock.after(SETTLE_MS, () => confirm(cut))
723 redrawRailSettled($, settle, isStale)
724}
725
726// The transcript path remembered for this session, if any.
727async function rememberedTranscript($: EngineInterface) {
728 const value = (await $.store.get(`${TRANSCRIPT_KEY_PREFIX}${await $.session.id()}`)) as { path?: unknown } | undefined
729 return typeof value?.path === 'string' ? value.path : undefined
730}
731
732export const register: Register = (on, options) => {
733 let entries: Entry[] = []
734 // Assistant row key -> the key of the prompt it answers, from the transcript.
735 let owners = new Map<string, string>()
736 // Prompt id -> the turn it started, from the transcript.
737 let turns = new Map<string, Turn>()
738 // Prompt row key -> how long its turns took as the engine reported them on
739 // ending, for a turn whose turn_duration row the transcript lacks yet.
740 const reported = new Map<string, number>()
741 // Prompt row key -> how its turn ended as the engine reported it, and whether the
742 // newest prompt's turn is running now.
743 const ended = new Map<string, Outcome>()
744 let isRunning = false
745 // How many prompts were listed when the session last came to rest (a turn
746 // ended, or the session started), and whether the running turn is a
747 // continuation with no typed text. A new prompt's turn may start before its
748 // row is stored, so the newest entry is the running turn's own only once a
749 // prompt has been listed since the rest; text alone cannot tell, since the
750 // person may send the same text twice.
751 let listedAtRest = 0
752 let isContinuation = false
753 // The text of the prompt that started the main loop's latest turn, and the
754 // id of its entry once its row is drawn (see listDrawn).
755 let turnText = ''
756 let starter: string | undefined
757 // The entry of the prompt that started the latest turn, not the newest,
758 // since a prompt delivered into the turn comes after it, with the same text
759 // or not.
760 const turnEntry = () => {
761 const started = entries.find(entry => entry.id === starter)
762 if (started) return started
763 for (let i = entries.length - 1; i >= 0; i--) if (turnText && entries[i]!.text === turnText) return entries[i]
764 return entries[entries.length - 1]
765 }
766 const isRunningFor = (id: string) => {
767 if (!isRunning || turnEntry()?.id !== id) return false
768 return isContinuation || entries.length > listedAtRest
769 }
770 // A prompt's turn as the rail shows it: the transcript's record, completed
771 // by what the engine reported before the transcript had it.
772 const turnOf = (id: string): Turn | undefined => {
773 const turn = turns.get(id)
774 const ms = turn?.durationMs ?? reported.get(rowKey(id))
775 const outcome = isRunningFor(id) ? 'running' : (turn?.outcome ?? ended.get(rowKey(id)))
776 if (!turn && ms === undefined && outcome === undefined) return undefined
777 return { tools: 0, files: [], ...turn, ...(ms === undefined ? {} : { durationMs: ms }), ...(outcome ? { outcome } : {}) }
778 }
779 // The transcript rows (prompts, replies, tool rows) the viewport shows, by
780 // component and the id each is drawn under: the key its prompt is found by,
781 // where it is on screen, and when it said so. A row reports only when that
782 // changes, so one that stays whole in the viewport is silent while others
783 // scroll past it; it is dropped once it says it left.
784 type Shown = { name: string; key: string; first: number; order: number }
785 const onScreen = new Map<string, Shown>()
786 let reports = 0
787 // The row key of the prompt being read, kept while no known row shows.
788 let reading: string | undefined
789 // The prompt the rail last drew as being read, and the redraw waiting for
790 // reports to settle.
791 let drawnCurrent = -1
792 const settle: Settle = {}
793 // The prompt a jump landed on, read while the rows that came into view as it
794 // landed are all that show: one near the end cannot reach the viewport's
795 // top, so rows of earlier prompts stay above it. `shown` holds those rows'
796 // prompts; `isSettled` once they had SETTLE_MAX_MS to report.
797 let landed: { key: string; shown: Set<number>; isSettled: boolean } | undefined
798 // Prompts whose rows the surface does not draw, learnt from a refused jump.
799 const unreachable = new Set<string>()
800 // Notices a session gives once (see jumpTo).
801 const notices = { isUnscrollableSaid: false }
802 const seen: Seen = unseen()
803 // Whether session.start has run; before it a toast is dropped (see tellNotice).
804 let isBound = false
805 // Row key -> the id a prompt's row was last drawn under (see drawnRow).
806 const drawn = new Map<string, string>()
807 // The ids of the prompts the last transcript read listed.
808 let filed = new Set<string>()
809
810 const addPrompt = (id: string, text: string) => {
811 // A new prompt is drawn under a provisional id before it is stored, then
812 // again under its uuid: list the stored row only, so a repeated prompt
813 // ("continue" twice) still gets an entry of its own.
814 if (id === PROVISIONAL_ID || entries.some(entry => rowKey(entry.id) === rowKey(id))) return false
815 entries = [...entries, { id, text }]
816 return true
817 }
818
819 // A prompt that does not go straight into a turn (queued behind the running
820 // one, delivered into it, or sent from Remote Control) is drawn under ids the
821 // engine never stores before its stored row comes. Its entry is pending
822 // meanwhile: rows drawn with its text are other names of it (row key ->
823 // entry id), and its stored row takes its place in the list.
824 const pending = new Set<string>()
825 const aliases = new Map<string, string>()
826 // Texts of prompts sent and not stored yet: from prompt.submit or
827 // session.receive until the stored row is drawn or the main loop rests.
828 const waiting = new Set<string>()
829 // The text of the prompt last drawn under the provisional id, until its
830 // stored row is drawn.
831 let provisional: string | undefined
832 // Entries added since the last notification, placeholder or turn edge, and
833 // when: the engine may draw a queued prompt's first row before its
834 // notification, which then takes it for that prompt's.
835 let lately: { id: string; at: number }[] = []
836 // When each waiting text's notification came, and the pending entries
837 // delivered into the running turn: a row of theirs drawn well after the
838 // notification is the attachment the turn read, and no provisional row
839 // follows, so the turn's end leaves them pending no more.
840 const notifiedAt = new Map<string, number>()
841 const delivered = new Set<string>()
842
843 const pendingWith = (text: string) => entries.find(entry => pending.has(entry.id) && entry.text === text)
844 // The entry a drawn row belongs to, by its own key or as another name.
845 const entryKeyOf = (key: string) => {
846 if (entries.some(entry => rowKey(entry.id) === key)) return key
847 const id = aliases.get(key)
848 return id === undefined ? key : rowKey(id)
849 }
850
851 // A prompt with `text` was sent: its rows are pending until the stored one
852 // is drawn. True when the list changed.
853 const noteSent = (text: string) => {
854 waiting.add(text)
855 const now = Date.now()
856 notifiedAt.set(text, now)
857 const fresh = new Set(lately.filter(item => now - item.at <= LATELY_MS).map(item => item.id))
858 lately = []
859 const own = entries.filter(entry => fresh.has(entry.id) && entry.text === text && !pending.has(entry.id))
860 const held = pendingWith(text) ?? own[0]
861 if (!held || own.length === 0) return false
862 pending.add(held.id)
863 const others = new Set(own.filter(entry => entry !== held).map(entry => entry.id))
864 for (const id of others) aliases.set(rowKey(id), held.id)
865 entries = entries.filter(entry => !others.has(entry.id))
866 return others.size > 0
867 }
868
869 // List a prompt row as it is drawn; true when the list changed.
870 const listDrawn = (id: string, text: string) => {
871 if (id === PROVISIONAL_ID) {
872 provisional = text
873 lately = []
874 return false
875 }
876 const key = rowKey(id)
877 if (entries.some(entry => rowKey(entry.id) === key)) {
878 // A stored row a transcript read listed first still ends its prompt.
879 if (provisional === text) {
880 provisional = undefined
881 waiting.delete(text)
882 if (isRunning) starter = entries.find(entry => rowKey(entry.id) === key)?.id
883 }
884 return false
885 }
886 const alias = aliases.get(key)
887 if (alias !== undefined) {
888 drawn.set(rowKey(alias), id)
889 return false
890 }
891 if (provisional === text) {
892 provisional = undefined
893 waiting.delete(text)
894 if (isRunning) starter = id
895 const held = pendingWith(text)
896 if (!held) return addPrompt(id, text)
897 // The stored row takes the place of the entry that waited for it.
898 entries = entries.map(entry => (entry === held ? { id, text } : entry))
899 pending.delete(held.id)
900 for (const [name, target] of aliases) if (target === held.id) aliases.set(name, id)
901 aliases.set(rowKey(held.id), id)
902 return true
903 }
904 if (waiting.has(text)) {
905 const held = pendingWith(text)
906 if (held) {
907 // Another row of the waiting prompt; a jump goes to the one drawn last.
908 aliases.set(key, held.id)
909 drawn.set(rowKey(held.id), id)
910 if (isRunning && Date.now() - (notifiedAt.get(text) ?? Date.now()) > LATELY_MS) delivered.add(held.id)
911 return false
912 }
913 pending.add(id)
914 return addPrompt(id, text)
915 }
916 const isAdded = addPrompt(id, text)
917 if (isAdded) lately = [...lately, { id, at: Date.now() }]
918 // A turn's prompt drawn with no provisional row, as the session's first.
919 if (isAdded && isRunning && starter === undefined && text === turnText) starter = id
920 return isAdded
921 }
922
923 // Record one onScreen report: where a row is on screen, or null once it left.
924 // Rows drawn while a subagent's transcript is in view are not the main
925 // conversation's, which alone the rail lists. Returns the row when it says
926 // it is cut at the viewport's top, for dropAbove to confirm.
927 const see = (component: string, id: string, place: { first: number } | null) => {
928 if (viewAgent !== undefined) return undefined
929 const name = `${component}\u0000${id}`
930 if (place === null) {
931 onScreen.delete(name)
932 if (landed && !isLandedShown()) landed = undefined
933 return undefined
934 }
935 const row = { name, key: rowKey(id), first: place.first, order: ++reports }
936 onScreen.set(name, row)
937 noteLandedRow(row.key)
938 return row.first > 0 ? row : undefined
939 }
940
941 // The index of the prompt a drawn row belongs to, a reply counting as its
942 // prompt's; undefined for a row that places no one.
943 const indexOfRow = (key: string, promptIndex: Map<string, number>) => {
944 if (key === PROVISIONAL_ID) return undefined
945 const id = entryKeyOf(key)
946 const ownerId = owners.get(id)
947 // A reply or tool row the transcript read does not know was written
948 // after it: the Stop hook reads before the turn's last reply is stored,
949 // and a running turn's rows come later still. A turn's start reads the
950 // file again, so only the newest turn can own it.
951 return promptIndex.get(id) ?? (ownerId === undefined ? entries.length - 1 : promptIndex.get(ownerId))
952 }
953 const promptIndexes = () => new Map(entries.map((entry, i) => [rowKey(entry.id), i]))
954
955 const landedIndex = () => (landed ? entries.findIndex(entry => rowKey(entry.id) === landed?.key) : -1)
956 const isLandedShown = () => {
957 const i = landedIndex()
958 const promptIndex = promptIndexes()
959 return i >= 0 && [...onScreen.values()].some(row => indexOfRow(row.key, promptIndex) === i)
960 }
961 // A row of a prompt that was not in view as the jump landed: the person
962 // scrolled, so the top row says who is read again.
963 const noteLandedRow = (key: string) => {
964 if (!landed) return
965 const i = indexOfRow(key, promptIndexes())
966 if (i === undefined) return
967 if (!landed.isSettled) landed.shown.add(i)
968 else if (!landed.shown.has(i)) landed = undefined
969 }
970
971 // The prompt of the row that last said it is cut at the viewport's top: that
972 // row is the top one, so a row of an earlier prompt still listed left
973 // without saying so, as rows do in a jump. Unless a row of an earlier prompt
974 // said it is on screen since: the viewport then moved above the cut row,
975 // which left without saying so itself.
976 const topIndex = (promptIndex: Map<string, number>) => {
977 const rows = [...onScreen.values()].flatMap(row => {
978 const i = indexOfRow(row.key, promptIndex)
979 return i === undefined ? [] : [{ i, first: row.first, order: row.order }]
980 })
981 let top: (typeof rows)[number] | undefined
982 for (const row of rows) {
983 if (row.first <= 0 || (top && row.order < top.order)) continue
984 if (rows.some(other => other.i < row.i && other.order > row.order)) continue
985 top = row
986 }
987 return top?.i
988 }
989
990 // A row still cut at the viewport's top a while after it said so is the top
991 // one: drop the rows of earlier prompts for good, so they cannot come back
992 // when it turns whole. Not sooner: a remounted row replays where it was last
993 // seen and says where it is a frame later. Not when a row of an earlier
994 // prompt said it is on screen since, as then the viewport moved above it.
995 const dropAbove = (cut: Shown) => {
996 const row = onScreen.get(cut.name)
997 if (!row || row.first <= 0) return
998 const promptIndex = promptIndexes()
999 const top = indexOfRow(row.key, promptIndex)
1000 if (top === undefined) return
1001 const isAbove = (other: Shown) => (indexOfRow(other.key, promptIndex) ?? top) < top
1002 if ([...onScreen.values()].some(other => other.order > row.order && isAbove(other))) return
1003 for (const [name, other] of onScreen) if (isAbove(other)) onScreen.delete(name)
1004 }
1005
1006 // Where the person is reading: the prompt that the topmost row on screen
1007 // belongs to. Kept while no known row shows.
1008 const currentIndex = () => {
1009 const jumped = landedIndex()
1010 if (jumped >= 0) {
1011 reading = landed?.key
1012 return jumped
1013 }
1014 landed = undefined
1015 const promptIndex = promptIndexes()
1016 // Rows above the top one are read past until it is confirmed (see dropAbove).
1017 const top = topIndex(promptIndex)
1018 let best = -1
1019 for (const row of onScreen.values()) {
1020 const i = indexOfRow(row.key, promptIndex)
1021 if (i === undefined || (top !== undefined && i < top)) continue
1022 if (best < 0 || i < best) best = i
1023 }
1024 const entry = entries[best]
1025 if (entry) reading = rowKey(entry.id)
1026 if (reading === undefined) return -1
1027 // By key, and through another name, so a stored row that takes a pending
1028 // entry's place, or a rewind that drops an earlier prompt, keeps it.
1029 const key = entryKeyOf(reading)
1030 return entries.findIndex(entry => rowKey(entry.id) === key)
1031 }
1032 // Whether the rail's drawing no longer shows the prompt being read.
1033 const isDrawnStale = () => currentIndex() !== drawnCurrent
1034
1035 // After a jump lands, the rows before it left and the prompt jumped to is
1036 // at the top, though rows may not say so: a row that stays whole is silent,
1037 // and one that unmounts may never report it left.
1038 const landOn = (id: string, target: string, index: number) => {
1039 onScreen.clear()
1040 const name = `UserMessage\u0000${target}`
1041 onScreen.set(name, { name, key: rowKey(target), first: 0, order: ++reports })
1042 reading = rowKey(id)
1043 const jump = { key: rowKey(id), shown: new Set([index]), isSettled: false }
1044 landed = jump
1045 return jump
1046 }
1047
1048 // Whether the transcript read knows a drawn row, as a prompt or a reply.
1049 const isKnownRow = (key: string) => {
1050 const id = entryKeyOf(key)
1051 return entries.some(entry => rowKey(entry.id) === id) || owners.has(id)
1052 }
1053
1054 // The rail's sites say whose transcript is in view; the rows a switch
1055 // leaves were another transcript's, and those it brings report anew.
1056 const noteView = (agentId: string | undefined) => {
1057 if (agentId !== viewAgent) {
1058 onScreen.clear()
1059 landed = undefined
1060 }
1061 viewAgent = agentId
1062 }
1063
1064 // A change of the setting reloads this module with the new value.
1065 let mode: Mode = isMode(options.mode) ? options.mode : 'horizontal'
1066 // The subagent whose transcript is in view, as the rail's sites last drew;
1067 // undefined for the main conversation, whose rows alone the rail lists.
1068 let viewAgent: string | undefined
1069 // Whether the session started on the terminal, whose band carries the
1070 // horizontal rail alone; elsewhere the pane stays open beside it.
1071 let isTerminal = false
1072 // Whether the horizontal band was last drawn on a grid of cells (the
1073 // terminal); the focus event does not say which surface it came from.
1074 let isBandOnGrid = true
1075 let railColumns = 0
1076 // The horizontal bar whose card the text line shows, while the ring is on
1077 // it, and the timer that stops showing it.
1078 let ringed: number | undefined
1079 let ringFade: Timer | undefined
1080 const unring = () => {
1081 ringFade?.cancel()
1082 ringFade = undefined
1083 ringed = undefined
1084 }
1085
1086 on('session.start', async ($, e, next) => {
1087 await $.command.register({
1088 // Named after the plugin: a plugin's commands share one namespace with
1089 // every other plugin's and the built-ins, so a generic name would collide.
1090 name: 'prompt-rail',
1091 description:
1092 'Show the prompt rail: vertical (a pane beside the transcript), horizontal (above the prompt) or off; next, prev, first, last, a number or find <words> jumps to a prompt.',
1093 argumentHint: USAGE,
1094 // Runs while a turn streams, so next and prev move through it then too.
1095 immediate: true,
1096 })
1097 // Argument-free, so a keybinding can name them (`command:prompt-rail-next`):
1098 // a binding runs a command bare.
1099 for (const [name, way] of STEP_COMMANDS) {
1100 await $.command.register({ name, description: `Jump to the ${way} prompt in the prompt rail.`, immediate: true })
1101 }
1102 await $.command.register({
1103 name: 'prompt-rail-toggle',
1104 description: 'Toggle the rail: off ↔ the mode last on (vertical or horizontal).',
1105 immediate: true,
1106 })
1107 isTerminal = e.surface === 'terminal'
1108 isBound = true
1109 tellNotice($, seen, isBound)
1110 // Move a mode an earlier version stored into the setting, once. Writing
1111 // the setting reloads this module, so everything after it is best effort.
1112 const stored = await $.store.get(LEGACY_MODE_KEY)
1113 if (stored !== undefined) await $.store.delete(LEGACY_MODE_KEY)
1114 if (isMode(stored) && stored !== mode) {
1115 mode = stored
1116 await writeMode($, mode)
1117 }
1118 // A mode kept for this session only outlives a reload of this module.
1119 const kept = await $.store.get(`${SESSION_MODE_KEY_PREFIX}${await $.session.id()}`)
1120 if (isMode(kept)) mode = kept
1121 // Also fired after a hot reload, when the list starts empty: rebuild it from
1122 // the transcript this session's classic SessionStart remembered.
1123 const transcriptPath = await rememberedTranscript($)
1124 const index = transcriptPath === undefined ? undefined : await readTranscript($, transcriptPath, seen, index => {
1125 if (index && merge(index)) void redrawRail($)
1126 tellNotice($, seen, isBound)
1127 })
1128 if (index && merge(index)) await redrawRail($)
1129 tellNotice($, seen, isBound)
1130 if (!isRunning) listedAtRest = entries.length
1131 // Unasked, the engine seats a pane only from 144 columns (110 once the
1132 // person has opened it with /prompt-rail); below that it waits undrawn.
1133 await seatRail($, mode, isTerminal)
1134 return next(e)
1135 })
1136
1137 // The prompt a command asks for: its index among the entries, or why none
1138 // (undefined when the command asks for no prompt).
1139 const askedIndex = (command: string, asked: string): number | undefined => {
1140 const way = STEP_COMMANDS.find(([name]) => name === command)?.[1]
1141 if (way !== undefined || asked === 'next' || asked === 'prev') {
1142 const dir = way === 'next' || asked === 'next' ? 1 : -1
1143 return stepFrom(currentIndex(), entries.length, dir, isUnreachable)
1144 }
1145 return pickPrompt(asked, entries.map(entry => entry.text))
1146 }
1147 const missingFor = (command: string, asked: string) => {
1148 if (command === 'prompt-rail-next' || asked === 'next') return 'no later prompt'
1149 if (command === 'prompt-rail-prev' || asked === 'prev') return 'no earlier prompt'
1150 return `no prompt ${asked}`
1151 }
1152
1153 on('command.run', async ($, e, next) => {
1154 const isStep = STEP_COMMANDS.some(([name]) => name === e.command)
1155 if (!isStep && e.command !== 'prompt-rail' && e.command !== 'prompt-rail-toggle') return next(e)
1156 const asked = isStep || e.command === 'prompt-rail-toggle' ? '' : e.args.trim()
1157 unring()
1158 // The toggle, as `/prompt-rail <mode>` does it: switch at once, then write
1159 // the setting, whose change reloads this module in the new mode.
1160 if (e.command === 'prompt-rail-toggle') {
1161 if (mode === 'off') {
1162 const lastOn = await $.store.get(LAST_ON_KEY)
1163 mode = isMode(lastOn) && lastOn !== 'off' ? lastOn : 'horizontal'
1164 } else {
1165 // Remembered here too: the mode may have come from /config or an
1166 // earlier version, neither of which went through writeMode.
1167 await $.store.set(LAST_ON_KEY, mode)
1168 mode = 'off'
1169 }
1170 await seatRail($, mode, isTerminal)
1171 await redrawRail($)
1172 await writeMode($, mode)
1173 return {}
1174 }
1175 const index = askedIndex(e.command, asked)
1176 if (index !== undefined) {
1177 // The main conversation's rows are not drawn beside a subagent's, so a
1178 // jump would be refused and wrongly dot a prompt that can be reached.
1179 if (viewAgent !== undefined) {
1180 $.ui.toast('jumps move through the main conversation; switch back to it first')
1181 return {}
1182 }
1183 const entry = entries[index]
1184 const target = entry && drawnRow(drawn, entry.id)
1185 if (entry && target && (await jumpTo($, entry.id, target, unreachable, notices))) {
1186 const jump = landOn(entry.id, target, index)
1187 $.clock.after(SETTLE_MAX_MS, () => {
1188 jump.isSettled = true
1189 })
1190 if (isDrawnStale()) await redrawRail($)
1191 }
1192 if (!entry) $.ui.toast(missingFor(e.command, asked))
1193 return {}
1194 }
1195 if (asked && !isMode(asked)) {
1196 $.ui.toast(`/prompt-rail ${USAGE}`)
1197 return {}
1198 }
1199 // Reopening a rail that is off would only close it again: say how to turn it on.
1200 if (!asked && mode === 'off') {types/prompt-rail.d.ts 8 lines1declare module 'claude-code' {
2 interface PluginState {
3 // Bumped when the prompt being read moves; the rail's sites read it while
4 // drawing, so a bump draws them again, and them alone.
5 'prompt-rail': { moved: number }
6 }
7}
8