Lists your prompts in a pane, with fuzzy search, and jumps the transcript to a selected prompt.

A pane that lists the prompts you sent this session. Press one and the transcript jumps to it — useful once a session is long enough that scrolling back to "what did I ask an hour ago" takes a while.
The pane opens with a search field focused: type to keep only the prompts that match (fuzzy, so ath finds auth; every word you type must match), each with its own number. Enter jumps to the newest match; Esc closes the pane.
Each row reads number time prompt: the time it was sent, HH:MM, with the date in front (MM-DD HH:MM) when it was not today. Prompts read back after a resume take the time the transcript file gives.
New sessions show one line above the prompt with the count and newest prompt. Press the line to expand the pane. Press the frame's close mark to collapse it back to the line for this session. /turn-nav is the only off switch: it stays off in new sessions until you run /turn-nav again.
Jumping needs the fullscreen layout ("tui": "fullscreen" in settings); without it the list still shows, and a press says why it cannot jump. The list keeps the newest 200.
The list also holds the prompts sent before this process started or the mod was reloaded (a --resume, a /reload-plugins), read from the session's own transcript file each time the mod starts: found by the session id under ~/.claude/projects/ (or $CLAUDE_CONFIG_DIR), then grep and tail on the host keep the newest 4 MB of prompt rows (through /bin/sh with set -o pipefail; where a shell refuses that, the pane says the read failed). A session with no transcript yet shows nothing more. The file's format is Claude Code's own and undocumented: when the read fails, finds no prompt of yours, or had to drop the oldest, the pane says so in a dim line at the top. A prompt from before a /compact or on a branch /rewind left may no longer be in the transcript on screen; pressing it says it cannot jump.
language: en (default) or zh-TW, from /config or settings:
"pluginConfigs": { "turn-nav@claude-code-mods": { "options": { "language": "zh-TW" } } }hooks/register.tsx 254 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { HistoryNote, Turn, TurnNavChip } from '../types'
4import { denyMessage, fitLine, historyTurns, navLabel, promptText, rowLabel } from './turns'
5import { fuzzyScore } from './fuzzy'
6import { stringsFor } from './strings'
7import type { Strings } from './strings'
8
9const PANE = 'turn-nav'
10// rows sizes the block seated above the prompt (narrow or main-screen terminals);
11// columns sizes the dock beside a fullscreen transcript (110 columns and up).
12const turns = atom({ plugin: 'turn-nav', key: 'turns' } as const, [] as Turn[])
13// Bumped on every open and close so the prompt band re-reads whether the pane is drawn.
14const paneTick = atom({ plugin: 'turn-nav', key: 'paneTick' } as const, 0)
15// This mod's line as the prompt-band mod draws it in the row it shares; null while
16// there is nothing to show. prompt-band cannot list this mod's panes, so it is told.
17// ponytail: a pane waiting undrawn that a widened terminal places leaves the line up
18// until the next publish (no event says so); the press then just reopens it.
19const chip = atom({ plugin: 'turn-nav', key: 'chip' } as const, null as TurnNavChip | null)
20const query = atom({ plugin: 'turn-nav', key: 'query' } as const, '')
21// Set when a resumed session's earlier prompts could not all be listed; the pane says so.
22const history = atom({ plugin: 'turn-nav', key: 'history' } as const, null as HistoryNote | null)
23
24// The transcript file the classic SessionStart named; kept so a reload reads the same file.
25const transcriptPath = atom({ plugin: 'turn-nav', key: 'transcriptPath' } as const, null as string | null)
26
27// The prompts sent before this process started (a resume, or a reload of the mod) are only in the
28// session's transcript file, which can run to gigabytes: `$2` itself (`$1` = path), or found by the
29// session id (`$1` = id) as `<config>/projects/<project>/<id>.jsonl`, the newest if two projects hold
30// one. grep keeps the rows whose origin is the person and tail the newest 4 MB of those (under
31// $.process.run's 4 MiB stdout). Exit 3: no file yet; 4: no user row in it yet (both a session that
32// has not started talking); 2: a file there but unreadable; with pipefail grep's own 1 (user rows,
33// none the person's: the file's format may have moved) and 2 come through.
34const TAIL_BYTES = 4_000_000
35const READ_HISTORY = [
36 'if [ "$1" = path ]; then f=$2; [ -e "$f" ] || exit 3',
37 'else f=$(ls -t "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"/projects/*/"$2".jsonl 2>/dev/null | head -n 1); [ -n "$f" ] || exit 3; fi',
38 `LC_ALL=C grep -qm1 '"type":"user"' "$f"; rc=$?`,
39 '[ $rc -eq 1 ] && exit 4',
40 '[ $rc -eq 0 ] || exit $rc',
41 'set -o pipefail',
42 `LC_ALL=C grep -E '"origin":\\{"kind":"(human|composer|bridge)"' "$f" | tail -c ${TAIL_BYTES}`,
43].join('\n')
44
45// Only the newest read may write: a slower earlier one (a start, then a reload) is dropped.
46let lastRead = 0
47
48async function loadHistory($: EngineInterface, s: Strings): Promise<void> {
49 const mine = ++lastRead
50 let note: HistoryNote | null = null
51 let found: Turn[] = []
52 try {
53 const path = await read($, transcriptPath)
54 const target = path ? ['path', path] : ['id', await $.session.id()]
55 const run = await $.process.run(['/bin/sh', '-c', READ_HISTORY, 'turn-nav', ...target], { timeoutMs: 15_000 })
56 if (run.exitCode === 3 || run.exitCode === 4) {
57 note = null
58 } else if (run.exitCode === 1 && run.stdout === '') {
59 note = { kind: 'none' }
60 } else if (run.exitCode !== 0) {
61 note = { kind: 'failed', reason: run.stderr.trim().split('\n')[0] || `exit ${run.exitCode}` }
62 } else {
63 const rows = historyTurns(run.stdout)
64 found = rows.turns
65 // tail keeping all it may means older rows were left behind, whether or not it cut one in half
66 const isCut = new TextEncoder().encode(run.stdout).length >= TAIL_BYTES
67 if (found.length === 0) note = { kind: 'none' }
68 else if (isCut || rows.unreadable > 0 || run.isStdoutTruncated) note = { kind: 'cut' }
69 }
70 } catch (error) {
71 note = { kind: 'failed', reason: error instanceof Error ? error.message : String(error) }
72 }
73 if (mine !== lastRead) return
74 await update($, history, () => note)
75 if (found.length > 0) {
76 await update($, turns, list => {
77 const seen = new Set(list.map(turn => turn.id))
78 return [...found.filter(turn => !seen.has(turn.id)), ...list].slice(-200)
79 })
80 }
81 await publish($, s)
82}
83
84// Keep the newest turn in view; a pane not drawn yet has nothing to scroll.
85async function showNewest($: EngineInterface): Promise<void> {
86 await $.ui.scroll({ in: PANE, to: 'end' }).catch(() => undefined)
87}
88
89// Only /turn-nav remembers off across sessions.
90type Mode = 'open' | 'off'
91
92async function readMode($: EngineInterface): Promise<Mode> {
93 const mode = await $.store.get('mode')
94 return mode === 'off' ? 'off' : 'open'
95}
96
97async function setMode($: EngineInterface, mode: Mode, s: Strings): Promise<void> {
98 await $.store.set('mode', mode)
99 await update($, paneTick, n => n + 1)
100 await publish($, s)
101}
102
103async function publish($: EngineInterface, s: Strings): Promise<void> {
104 const isPlaced = (await $.ui.panes()).some(p => p.id === PANE && p.isPlaced)
105 const next = isPlaced || (await readMode($)) === 'off' ? null : { label: navLabel(await read($, turns), s) }
106 await update($, chip, () => next)
107}
108
109// Set by the prompt-band mod, which then draws this mod's line in the row it shares.
110async function hasPromptBand($: EngineInterface): Promise<boolean> {
111 return (await $.env.get('PROMPT_BAND')) === '1'
112}
113
114async function openPane($: EngineInterface, open: { id: typeof PANE; title: string; rows: 6; columns: 32; focus: true; closeOnEscape: true }, s: Strings): Promise<void> {
115 // Every open is the person's own: it starts unfiltered and takes the keys, so typing searches at once.
116 await update($, query, () => '')
117 await $.ui.open(open)
118 await showNewest($)
119 await update($, paneTick, n => n + 1)
120 await publish($, s)
121}
122
123async function turnOff($: EngineInterface, s: Strings): Promise<void> {
124 if ((await $.ui.panes()).some(p => p.id === PANE)) await $.ui.close({ id: PANE })
125 await setMode($, 'off', s)
126}
127
128export const register: Register = (on, options) => {
129 const s = stringsFor(options?.language)
130 // Esc closes the pane while it holds the keys; its line above the prompt opens it again.
131 const open = { id: PANE, title: s.title, rows: 6, columns: 32, focus: true, closeOnEscape: true } as const
132 // session.start runs when the process starts (new, resumed, forked) and on every reload of this
133 // mod, which keeps the list but not what came before the process: so the list is filled from the
134 // transcript file each time. Not awaited: reading a long file must not hold up the start. Past the
135 // read's own try only bookkeeping can fail (a state write, the band's line); the catch leaves the
136 // list as it was and no unhandled rejection.
137 on('session.start', async ($, e, next) => {
138 await $.command.register({ name: 'turn-nav', description: 'Show or hide the prompt navigator (remembered for new sessions)' })
139 await publish($, s)
140 const result = await next(e)
141 void loadHistory($, s).catch(() => undefined)
142 return result
143 })
144
145 // A resume names its transcript file outright: kept for this read and every reload's, so the list
146 // does not hang on the session id matching the file name.
147 on('classic.SessionStart', async ($, e, next) => {
148 const result = await next(e)
149 if (e.transcript_path && e.transcript_path !== (await read($, transcriptPath))) {
150 await update($, transcriptPath, () => e.transcript_path)
151 void loadHistory($, s).catch(() => undefined)
152 }
153 return result
154 })
155
156 on('session.append', { door: 'prompt' }, async ($, e, next) => {
157 const stored = await next(e)
158 try {
159 const id = 'uuid' in stored ? stored.uuid : undefined
160 const isPersons = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
161 if (id && isPersons && !e.agentId) {
162 const text = promptText(e.message.content)
163 if (text) {
164 const at = await $.clock.now().catch(() => undefined)
165 await update($, turns, list => [...list, { id, text, ...(at === undefined ? {} : { at }) }].slice(-200))
166 await publish($, s)
167 void showNewest($)
168 }
169 }
170 } catch {
171 // Navigation bookkeeping must not interrupt the transcript append.
172 }
173 return stored
174 })
175
176 on('command.run', { command: 'turn-nav' }, async $ => {
177 // Only a drawn pane is turned off; off or waiting undrawn opens it.
178 if ((await $.ui.panes()).some(p => p.id === PANE && p.isPlaced)) {
179 await turnOff($, s)
180 return { text: s.off }
181 }
182 await openPane($, open, s)
183 await setMode($, 'open', s)
184 return { text: s.on }
185 })
186
187 on('ui.close', async ($, e, next) => {
188 // The engine skips a hook that returns nothing and says so in the transcript.
189 const result = await next(e)
190 if (e.id === PANE) {
191 await update($, paneTick, n => n + 1)
192 await publish($, s)
193 }
194 return result
195 })
196
197 // prompt-band's line for this mod: opened here, inside the person's press, the pane is
198 // placed at any width (opened from any later event it would wait below 144 columns).
199 on('ui.press', { plugin: 'prompt-band', element: 'turn-nav' }, async ($, e, next) => {
200 await openPane($, open, s)
201 return next(e)
202 })
203
204 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
205 if (e.props.hasSurvey || (await hasPromptBand($))) return next(e)
206 await read($, paneTick)
207 if ((await readMode($)) === 'off') return next(e)
208 const pane = (await $.ui.panes()).find(p => p.id === PANE)
209 if (pane?.isPlaced) return next(e)
210 const { Box, Button } = $.ui.resolve(e)
211 const list = await read($, turns)
212 const below = await next(e)
213 return (
214 <Box flexDirection="column">
215 {/* No hotkey: a plain Button draws one as `n: ` ahead of the label. */}
216 <Button key="nav-open" plain dimColor label={fitLine(navLabel(list, s), Math.max(24, e.props.bodyColumns - 4))} onPress={() => openPane($, open, s)} />
217 {below}
218 </Box>
219 )
220 })
221
222 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
223 const table = $.ui.resolve(e)
224 const { Box, Button, Text } = table
225 // A phone's table has no Input: there the list shows unfiltered.
226 const Input = 'Input' in table ? table.Input : undefined
227 const list = await read($, turns)
228 const now = await $.clock.now().catch(() => Date.now())
229 const note = await read($, history)
230 const typed = Input ? await read($, query) : ''
231 // A match keeps its prompt's own number and place, so the list still reads in order.
232 const shown = list.map((turn, i) => ({ turn, i })).filter(({ turn }) => !typed.trim() || fuzzyScore(typed, turn.text) >= 0)
233 const width = e.props.bodyColumns
234 const jump = async (turn: Turn) => {
235 const result = await $.ui.scroll({ to: { requestId: turn.id }, block: 'start' })
236 if (result.deny) $.ui.toast(denyMessage(result.deny, s))
237 }
238 return <Box flexDirection="column">
239 {e.viewport?.isFullscreen === false && <Text dimColor wrap="truncate-end">{s.notFullscreen}</Text>}
240 {note && <Text key="history-note" dimColor>{s.history(note)}</Text>}
241 {Input && list.length > 0 && <Input key="search" autoFocus placeholder={s.placeholder} value={typed} submitLabel={s.submit}
242 onInput={value => { void update($, query, () => value) }}
243 onSubmit={async value => {
244 const newest = (await read($, turns)).filter(turn => fuzzyScore(value, turn.text) >= 0).at(-1)
245 if (newest) await jump(newest)
246 }} />}
247 {typed.trim() !== '' && <Text dimColor>{s.count(shown.length, list.length)}</Text>}
248 {list.length === 0 && <Text dimColor>{s.empty}</Text>}
249 {list.length > 0 && shown.length === 0 && <Text dimColor>{s.noMatch}</Text>}
250 {shown.map(({ turn, i }) => <Button key={`turn-${i}`} plain label={rowLabel(i + 1, turn.text, width - 1, turn.at, now)} onPress={() => jump(turn)} />)}
251 </Box>
252 })
253}
254hooks/turns.ts 117 lines1export function promptText(content: unknown): string {
2 try {
3 const text = typeof content === 'string' ? content : Array.isArray(content)
4 ? content.filter(block => block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
5 .map(block => block.text).join('\n')
6 : ''
7 return text.replace(/^\s*<system-reminder>[\s\S]*?<\/system-reminder>\s*/, '')
8 } catch {
9 return ''
10 }
11}
12
13// How a transcript file marks a row the person sent: `human` as the file writes it today; the live
14// event's own kinds too, in case the file follows them. `peer` (another session) and notices are not.
15const PERSON = new Set(['human', 'composer', 'bridge'])
16
17/**
18 * The person's prompts in transcript-file lines (JSONL), oldest first, the newest `max` kept: rows of
19 * the main conversation (no subagent's, no meta row) whose origin is the person. A line that does not
20 * parse (the last one when the read was cut) is counted in `unreadable`.
21 */
22export function historyTurns(lines: string, max = 200): { turns: { id: string; text: string; at?: number }[]; unreadable: number } {
23 const turns: { id: string; text: string; at?: number }[] = []
24 let unreadable = 0
25 for (const line of lines.split('\n')) {
26 if (!line.trim()) continue
27 let row: any
28 try {
29 row = JSON.parse(line)
30 } catch {
31 unreadable += 1
32 continue
33 }
34 if (row?.type !== 'user' || row.isSidechain || row.isMeta || typeof row.uuid !== 'string') continue
35 if (!PERSON.has(row.origin?.kind)) continue
36 const text = promptText(row.message?.content)
37 const at = typeof row.timestamp === 'string' ? Date.parse(row.timestamp) : NaN
38 if (text) turns.push({ id: row.uuid, text, ...(Number.isFinite(at) ? { at } : {}) })
39 }
40 return { turns: turns.slice(-max), unreadable }
41}
42
43// East Asian wide and fullwidth ranges plus emoji: a terminal cell pair each.
44const WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F300}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u
45
46/** Terminal cells a string takes: wide characters count two. */
47export function cellWidth(text: string): number {
48 let width = 0
49 for (const char of text) width += WIDE.test(char) ? 2 : 1
50 return width
51}
52
53const pad = (v: number) => String(v).padStart(2, '0')
54
55/** `HH:MM` in local time; `MM-DD HH:MM` when `at` is not on the same day as `now`. Twin of link-nav's stamp. */
56export function stamp(at: number, now: number): string {
57 const d = new Date(at)
58 const n = new Date(now)
59 const time = `${pad(d.getHours())}:${pad(d.getMinutes())}`
60 const sameDay = d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()
61 return sameDay ? time : `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${time}`
62}
63
64/** `n [time] first-line`, cut to `width` terminal cells (at least 8) with an ellipsis. */
65export function label(n: number, text: string, width: number, at?: number, now?: number): string {
66 const first = text.split(/\r?\n/).map(line => line.replace(/\s+/g, ' ').trim()).find(Boolean) ?? ''
67 const when = at === undefined ? '' : `${stamp(at, now ?? at)} `
68 const full = `${n} ${when}${first}`
69 const limit = Math.max(8, width)
70 if (cellWidth(full) <= limit) return full
71 let out = ''
72 for (const char of full) {
73 if (cellWidth(out + char) > limit - 1) break
74 out += char
75 }
76 return `${out}…`
77}
78
79/**
80 * A turn's row of exactly `width` cells, `›` at the right end. Drawn as one Button,
81 * the whole row is the tap target; a phone column is about 4px wide, too narrow to
82 * aim at the short label alone.
83 */
84/** The one-line summary: how many prompts, and the newest one's first line. */
85export function navLabel(list: { text: string }[], s: import('./strings').Strings): string {
86 const newest = list.at(-1)?.text.split(/\r?\n/).map(line => line.replace(/\s+/g, ' ').trim()).find(Boolean)
87 return s.navLabel(list.length, newest)
88}
89
90/** Cut with … when needed, then pad the whole tap target to `width` cells. */
91export function fitLine(text: string, width: number): string {
92 let body = text
93 if (cellWidth(body) > width) {
94 let out = ''
95 for (const char of body) {
96 if (cellWidth(out + char) > width - 1) break
97 out += char
98 }
99 body = `${out}…`
100 }
101 return body + ' '.repeat(Math.max(0, width - cellWidth(body)))
102}
103
104export function rowLabel(n: number, text: string, width: number, at?: number, now?: number): string {
105 const base = label(n, text, width - 2, at, now)
106 return base + ' '.repeat(Math.max(1, width - 1 - cellWidth(base))) + '›'
107}
108
109// The engine moves transcript rows only in the fullscreen layout; on the main screen
110// the terminal's own scrollback holds them and it answers this deny.
111const NOT_FULLSCREEN = 'transcript not scrollable here'
112
113/** What to tell the person when a jump is refused, naming fullscreen only when that is why. */
114export function denyMessage(deny: string, s: import('./strings').Strings): string {
115 return deny === NOT_FULLSCREEN ? s.denyFullscreen : `${s.denyPrefix}${deny}`
116}
117hooks/fuzzy.ts 22 lines1/**
2 * How well `query` matches `text`, or -1: each whitespace-separated token must appear in order (letters may
3 * have gaps); adjacent letters, letters opening a word and a token found whole score more.
4 * Twin of link-nav's fuzzyScore in hooks/links.ts: change both.
5 */
6export function fuzzyScore(query: string, text: string): number {
7 const hay = text.toLowerCase()
8 let total = 0
9 for (const token of query.toLowerCase().split(/\s+/).filter(Boolean)) {
10 let at = -1
11 let prev = -2
12 for (const char of token) {
13 at = hay.indexOf(char, at + 1)
14 if (at < 0) return -1
15 total += 1 + (at === prev + char.length ? 3 : 0) + (at === 0 || /[\s/._\-·:#]/.test(hay[at - 1] ?? '') ? 2 : 0)
16 prev = at
17 }
18 if (hay.includes(token)) total += 2 * token.length
19 }
20 return total
21}
22hooks/strings.ts 63 lines1import type { HistoryNote } from '../types'
2
3export type Strings = {
4 title: string
5 off: string
6 on: string
7 empty: string
8 notFullscreen: string
9 navLabel: (count: number, newest: string | undefined) => string
10 denyFullscreen: string
11 denyPrefix: string
12 history: (note: HistoryNote) => string
13 placeholder: string
14 submit: string
15 noMatch: string
16 count: (shown: number, total: number) => string
17}
18
19export const STRINGS: Record<'en' | 'zh-TW', Strings> = {
20 en: {
21 title: 'Prompts',
22 off: 'Prompt navigator off (stays off in new sessions; /turn-nav turns it back on)',
23 on: 'Prompt navigator on',
24 empty: 'No prompts yet',
25 notFullscreen: 'Not fullscreen: the list works, jumping does not',
26 navLabel: (count, newest) => `🧭 Prompts · ${count}${newest ? ` · ${newest}` : ''}`,
27 denyFullscreen: "Can't jump: this session is not fullscreen (panes opened after enabling it are)",
28 denyPrefix: "Can't jump: ",
29 history: note => note.kind === 'none'
30 ? 'No earlier prompts found in the session file'
31 : note.kind === 'cut'
32 ? 'Earlier prompts: the session file is long, the newest are listed'
33 : `Earlier prompts could not be read: ${note.reason}`,
34 placeholder: 'fuzzy search',
35 submit: 'jump to newest',
36 noMatch: 'Nothing matches',
37 count: (shown, total) => `${shown} of ${total}`,
38 },
39 'zh-TW': {
40 title: '導覽',
41 off: '導覽已關閉(新 session 也不再開啟,/turn-nav 可再開)',
42 on: '導覽已開啟',
43 empty: '還沒有對話',
44 notFullscreen: '非全螢幕:只能看清單,不能跳轉',
45 navLabel: (count, newest) => `🧭 導覽 · ${count} 則${newest ? ` · ${newest}` : ''}`,
46 denyFullscreen: '跳不過去:這個 session 不是全螢幕(設定後新開的窗格才是)',
47 denyPrefix: '跳不過去:',
48 history: note => note.kind === 'none'
49 ? 'session 檔裡找不到先前的對話'
50 : note.kind === 'cut'
51 ? '先前的對話:session 檔太長,只列出最新的'
52 : `先前的對話讀不到:${note.reason}`,
53 placeholder: '模糊搜尋',
54 submit: '跳到最新一則',
55 noMatch: '沒有符合的',
56 count: (shown, total) => `${shown} / ${total}`,
57 },
58}
59
60export function stringsFor(language: unknown): Strings {
61 return language === 'zh-TW' ? STRINGS['zh-TW'] : STRINGS.en
62}
63types/index.d.ts 17 lines1/** A prompt: its row id, its text, and when it was sent (ms since the epoch; absent where nothing said). */
2export type Turn = { id: string; text: string; at?: number }
3/** One line above the prompt: its text as one tap target. */
4export type TurnNavChip = { label: string }
5/**
6 * What reading a resumed session's earlier prompts from its transcript file came to, when it did
7 * not give a full list: `none` (the file holds no prompt this mod recognises), `cut` (more than one
8 * read could carry; the newest are listed), `failed` (the read itself failed, with why).
9 */
10export type HistoryNote = { kind: 'none' } | { kind: 'cut' } | { kind: 'failed'; reason: string }
11
12declare module 'claude-code' {
13 interface PluginState {
14 'turn-nav': { turns: Turn[]; paneTick: number; chip: TurnNavChip | null; history: HistoryNote | null; query: string; transcriptPath: string | null }
15 }
16}
17