SLOPSHOPPER

Prompt Marks

Marks your prompts in the transcript with a colored bar and tinted row, and jumps between them with Option+Up and Option+Down

bandrowsprompttimer
★ 1v0.5.0MITupdated 2026-10-21AdamCaviness/prompt-marks
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · prompt-marks
❯ fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩
Your message
❯ fix the failing auth test and add an audit log call
README

Prompt Marks

In a long Claude Code session, your own prompts get buried under pages of output. Prompt Marks puts a colored bar and a tinted background behind every prompt you type, and lets you jump from one prompt to the next with the keyboard.

  • Option+Up and Option+Down on macOS, Ctrl+Up and Ctrl+Down on Windows and Linux.
  • Nothing extra is drawn on screen. Only your prompt rows change.

Needs Claude Code v2.1.287 or later. Jumping needs fullscreen rendering.

Install

/plugin install prompt-marks --marketplace adamcaviness/prompt-marks

Then turn on auto-update: /plugin → Marketplaces → prompt-marks → Enable auto-update. Claude Code leaves it off for marketplaces outside Anthropic's, so without it you keep the version you first installed.

It's also in agentic-marketplace, and agentic-toolkit installs it for you.

Configure

Open /config and look for the rows starting with Prompt Marks:.

| Option | Default | What it does | | :- | :- | :- | | accent_color | Purple | Bar color: type Purple, Indigo, Blue, Teal, Green, Olive, Amber, Orange, Red, Pink, Slate, or Custom (case doesn't matter). Anything else falls back to Purple. The row tint is mixed from it. | | custom_color | #5b2a86 | Hex color used when accent_color is Custom. | | enabled | on | Turns Prompt Marks off entirely. If agentic-toolkit installed it, use this rather than disabling the plugin, since disabling it also disables the toolkit. | | navigation | on | Jumps between prompts with the keys below. | | styling | on | Draws the bar, with the ❯ pointer on its first row, and the tinted row behind each prompt. The pointer is the accent lightened toward white. | | tint_strength | 22 | Percent of the accent mixed into the background behind each prompt. |

Terminals can't do transparency, so the tint is the accent blended with #1e1e1e on dark themes and #ffffff on light ones. If it looks off against your background, adjust tint_strength.

Keys

Mods can't add their own keybinding actions, so Prompt Marks listens on two that already exist: app:diffFileListUp and app:diffFileListDown. Both Ctrl and Option (Alt) with Up/Down are bound to them by default. While the /diff panel is open, the keys scroll its file list as usual.

| Platform | Use | Why | | :- | :- | :- | | macOS | Option+Up/Down | macOS reserves Ctrl+Up/Down for Mission Control | | Windows | Ctrl+Up/Down | Windows Terminal uses Alt+arrows to move between split panes |

Any other key can be bound to the same actions in ~/.claude/keybindings.json. Cmd+Up/Down only works if your terminal passes Cmd through (in iTerm2: Profiles > Keys > Report keys using CSI u) and doesn't already use those keys:

{
  "bindings": [
    { "context": "Global", "bindings": { "cmd+up": "app:diffFileListUp", "cmd+down": "app:diffFileListDown" } }
  ]
}

How jumping finds prompts

Claude Code draws only the newest part of a long transcript and draws older prompts when you scroll toward the top, so Prompt Marks learns the prompts as they are drawn. Each batch of older prompts goes before the ones it already knows, a prompt you send goes after them, and the order is kept in session memory so reloading the mod (for example after changing a setting in /config) does not lose it. Previews of prompts you queued while Claude was working are ignored until the prompt is stored.

When Up reaches the oldest prompt drawn so far, it waits a moment for Claude Code to draw older ones before it stops.

At either end a press does nothing. Pause there, then press the same key twice quickly to wrap to the other end: Up twice at the oldest prompt goes to the newest, and Down twice at the newest goes to the oldest drawn so far. Holding the key down stops at the end without wrapping.

Slash commands you run (/doctor some words, a skill) are jump targets too, from the moment you run them. Claude Code draws their rows itself with no hook for mods, so they keep the default gray row, and commands from before a resume are not known.

Each jump starts from the topmost prompt on screen. Claude Code does not report every prompt that leaves the screen during a long jump or when you send a prompt, so after a jump Prompt Marks treats the prompt it just revealed as the topmost, and after you send a prompt it starts again from the newest.

What it hooks

Prompt Marks runs no programs, reads and writes no files, and sends nothing off your machine. Its only stored data is the list of prompt ids, kept in the session's memory and discarded when the session ends or on /clear and /resume. It never changes a setting or a permission decision. Each hook:

| Hook | When | What it does | | :- | :- | :- | | session.start | A session starts, or the mod reloads | Reads your theme setting to pick the dark or light tint, and restores the prompt order saved in session memory. | | session.end | The session ends, including on /clear and resume | Forgets the prompts it was tracking for navigation, then passes the event on unchanged. | | config.set (key theme only) | You change the theme | Reads the new theme to recompute the tint and redraws, then passes the change on unchanged. It never blocks or alters the setting. | | session.append (doors prompt, command and queue only) | A prompt or slash command is stored, or queued behind a running turn | Notes which prompt or command is newest and which rows only preview a queued prompt, then passes the row on unchanged. | | prompt.submit | You press Enter in the prompt box | Notes that the transcript scrolled to its end, then passes the prompt on unchanged. It never blocks or alters a prompt. | | ui.render (UserMessage) | A prompt row is drawn | Draws your own typed prompts with the accent bar and tint, and records where they are for navigation. Notifications and agent messages keep the default row. | | ui.render (AbovePrompt) | The area above the prompt is drawn | Adds two hidden buttons bound to the navigation keys. Nothing visible is drawn. |

Develop

claude --plugin-dir .          # load this checkout for one session
claude plugin validate --strict .
claude plugin test .
npx -p typescript tsc -p .     # after one load has written .claude-plugin/types
Source 5 files
hooks/register.tsx 218 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { ACCENTS, blend, resolveAccent } from './color'
4import { createViewport, type EndPress, pressAtEnd, type Visible } from './navigation'
5import { commandLine, createOrder } from './order'
6
7const DEFAULT_TINT_STRENGTH = 22
8// Assumed terminal backgrounds for the theme family; the tint is mixed over these.
9const DARK_BACKGROUND = '#1e1e1e'
10const LIGHT_BACKGROUND = '#ffffff'
11// The ❯ pointer sits on the accent bar, so it is lightened toward white to read against the accent on any theme.
12const POINTER = '❯'
13const POINTER_LIGHTNESS = 0.65
14// Engine keybinding actions borrowed for navigation: Ctrl+Up/Down and Option(Alt)+Up/Down by default.
15const ACTION_PREVIOUS = 'app:diffFileListUp'
16const ACTION_NEXT = 'app:diffFileListDown'
17// Rows the person typed (or sent from Remote Control); notifications and agent messages stay unstyled.
18const OWN_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge'])
19// A command that only prints (`/context`) is stored with the engine as its origin, though the person typed it.
20const COMMAND_ORIGINS: ReadonlySet<string> = new Set([...OWN_ORIGINS, 'engine'])
21// The order is saved this long after it last changed, so the rows of one chunk make one write.
22const SAVE_DELAY_MS = 100
23// Where the order survives a reload of the mod; `plugin` and `key` are literals for `claude plugin validate`.
24const ORDER_STATE = { plugin: 'prompt-marks', key: 'order' } as const
25// Reaching the oldest drawn prompt makes the engine draw older rows within a few milliseconds; Up waits this long for them.
26const OLDER_ROWS_WAIT_MS = 150
27
28let accent = ACCENTS.Purple!
29let strength = DEFAULT_TINT_STRENGTH
30let tint = blend(accent, DARK_BACKGROUND, DEFAULT_TINT_STRENGTH / 100)
31let pointer = blend('#ffffff', accent, POINTER_LIGHTNESS)
32
33// Prompt message ids in transcript order, and where they sit relative to the viewport.
34const order = createOrder()
35const viewport = createViewport(() => order.ids)
36// Jumps run one at a time, so a second key press sees where the first one left the viewport.
37let pending: Promise<void> = Promise.resolve()
38// When the last key press came, and the last one that found no prompt past an end after a pause.
39let lastPressAt = Number.NEGATIVE_INFINITY
40let endPress: EndPress | null = null
41let saveQueued = false
42
43function reset() {
44  order.reset()
45  viewport.reset()
46  endPress = null
47}
48
49function applyTheme(theme: unknown) {
50  const isLight = typeof theme === 'string' && theme.startsWith('light')
51  tint = blend(accent, isLight ? LIGHT_BACKGROUND : DARK_BACKGROUND, strength / 100)
52}
53
54async function loadTheme($: EngineInterface) {
55  applyTheme((await $.config.list()).find(row => row.key === 'theme')?.value)
56}
57
58// A ui.render hook may not write state, so the save runs from a timer.
59function saveOrderSoon($: EngineInterface) {
60  if (saveQueued) return
61  saveQueued = true
62  $.clock.after(SAVE_DELAY_MS, async () => {
63    saveQueued = false
64    await $.state.set(ORDER_STATE, [...order.ids])
65  })
66}
67
68function track($: EngineInterface, id: string, text: string, onScreen: Visible | null | undefined) {
69  const known = order.ids.length
70  order.add(id, text, Date.now())
71  if (!order.has(id)) return
72  if (order.ids.length !== known) saveOrderSoon($)
73  viewport.report(id, onScreen)
74}
75
76// A target whose row is not drawn (refused by the engine) is forgotten, and the
77// jump picks again, so it ends only when no prompt is left in that direction.
78// At an end nothing moves, and a second press there soon after wraps to the other end.
79async function jump($: EngineInterface, direction: -1 | 1, at: number, sincePress: number) {
80  let target = viewport.pick(direction)
81  if (target === -1 && direction === -1) {
82    const known = order.ids.length
83    await $.clock.sleep(OLDER_ROWS_WAIT_MS)
84    if (order.ids.length !== known) target = viewport.pick(direction)
85  }
86  if (target !== -1) endPress = null
87  else {
88    const end = pressAtEnd(endPress, direction, at, sincePress)
89    endPress = end.last
90    if (end.wrap && order.ids.length > 0) target = direction === -1 ? order.ids.length - 1 : 0
91  }
92  while (target !== -1) {
93    const id = order.ids[target]!
94    const since = viewport.mark()
95    const result = await $.ui.scroll({ to: { requestId: id }, block: 'start' })
96    if (!result.deny) {
97      viewport.landed(id, since)
98      return
99    }
100    order.remove(id)
101    saveOrderSoon($)
102    viewport.forget(id)
103    target = viewport.pick(direction)
104  }
105}
106
107const queueJump = ($: EngineInterface, direction: -1 | 1) => {
108  const at = Date.now()
109  const sincePress = at - lastPressAt
110  lastPressAt = at
111  const run = () => jump($, direction, at, sincePress)
112  pending = pending.then(run, run)
113  return pending
114}
115
116export const register: Register = (on, options) => {
117  // A change in /config reloads the module, so options are read once here.
118  if (options.enabled === false) return
119  accent = resolveAccent(options.accent_color, options.custom_color)
120  pointer = blend('#ffffff', accent, POINTER_LIGHTNESS)
121  if (typeof options.tint_strength === 'number') strength = options.tint_strength
122
123  on('session.start', async ($, e, next) => {
124    await loadTheme($)
125    order.restore((await $.state.get(ORDER_STATE)).value ?? [])
126    return next(e)
127  })
128
129  // The session this order belongs to ends on /clear and resume, and the process goes on under a new one. A classic
130  // hook is not used: an organization's security default moves classic events past a person's plugins.
131  on('session.end', async ($, e, next) => {
132    reset()
133    return next(e)
134  }).catch(($, e, next) => (next.called ? undefined : next(e)))
135
136  // Reads the theme being set to recompute the tint, then passes the change on unchanged.
137  on('config.set', { key: 'theme' }, async ($, e, next) => {
138    applyTheme(e.value)
139    $.ui.invalidate('ui.render')
140    return next(e)
141  }).catch(($, e, next) => (next.called ? undefined : next(e)))
142
143  const styling = options.styling !== false
144  const navigation = options.navigation !== false
145
146  // A stored prompt is newer than every prompt drawn so far, and its row is drawn after this runs. A queued one
147  // is previewed by rows that are no prompts until it is stored.
148  // Each door is matched by a literal, never a pattern: the engine cannot tell that a pattern leaves out the doors an
149  // organization's security default moves past a person's plugins, so it reports a pattern hook as skipped.
150  // The queue door is in newer builds only, and older builds' declarations do not list it, hence the cast.
151  const textOf = (message: { content: readonly { type: string; text?: string }[] }) =>
152    message.content.flatMap(block => (block.type === 'text' && block.text !== undefined ? [block.text] : [])).join('')
153
154  if (navigation) {
155    on('session.append', { door: 'prompt' }, async ($, e, next) => {
156      if (OWN_ORIGINS.has(e.origin.kind)) order.announce(e.uuid, textOf(e.message))
157      return next(e)
158    }).catch(($, e, next) => (next.called ? undefined : next(e)))
159
160    // A slash command's row is drawn by no hook, so it is learned when stored. Its output is stored the same way.
161    on('session.append', { door: 'command' }, async ($, e, next) => {
162      const line = COMMAND_ORIGINS.has(e.origin.kind) ? commandLine(textOf(e.message)) : undefined
163      if (line !== undefined) {
164        order.command(e.uuid, line)
165        saveOrderSoon($)
166      }
167      return next(e)
168    }).catch(($, e, next) => (next.called ? undefined : next(e)))
169
170    // Enter in the prompt box scrolls the transcript to its end, past rows the engine does not report gone.
171    // Older builds' declarations do not list the slash command a submission runs, hence the `in` check.
172    on('prompt.submit', async ($, e, next) => {
173      if (e.origin.kind === 'composer' && !('command' in e && e.command)) viewport.toEnd()
174      return next(e)
175    }).catch(($, e, next) => (next.called ? undefined : next(e)))
176
177    on('session.append', { door: 'queue' as 'prompt' }, async ($, e, next) => {
178      const previews = order.queue(textOf(e.message), Date.now())
179      previews.forEach(id => viewport.forget(id))
180      if (previews.length > 0) saveOrderSoon($)
181      return next(e)
182    }).catch(($, e, next) => (next.called ? undefined : next(e)))
183  }
184
185  // Navigation learns the prompts from these rows, so the hook runs when either feature is on.
186  if (styling || navigation) on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
187    if (!OWN_ORIGINS.has(e.props.origin.kind)) return next(e)
188    if (navigation) track($, e.requestId, e.props.text, e.props.onScreen)
189    if (!styling) return next(e)
190    const { Box, Text } = $.ui.resolve(e)
191    return (
192      <Box flexDirection="row" marginTop={1} width="100%">
193        <Box width={1} backgroundColor={accent}>
194          <Text color={pointer} backgroundColor={accent}>{POINTER}</Text>
195        </Box>
196        <Box flexGrow={1} paddingX={1} backgroundColor={tint}>
197          <Text>{e.props.text}</Text>
198        </Box>
199      </Box>
200    )
201  })
202
203  // Hidden Buttons hold the navigation chords without drawing anything.
204  if (navigation) on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
205    const theirs = await next(e)
206    const { Box, Button } = $.ui.resolve(e)
207    return (
208      <Box flexDirection="column">
209        {theirs}
210        <Box display="none">
211          <Button key="previous-prompt" label="previous prompt" action={ACTION_PREVIOUS} onPress={() => queueJump($, -1)} />
212          <Button key="next-prompt" label="next prompt" action={ACTION_NEXT} onPress={() => queueJump($, 1)} />
213        </Box>
214      </Box>
215    )
216  })
217}
218
hooks/color.ts 51 lines
1// Terminals have no alpha channel, so a "translucent" tint is computed by
2// mixing the accent color into the background the terminal is assumed to show.
3
4const HEX = /^#?([0-9a-f]{6})$/i
5
6export const isHex = (value: string): boolean => HEX.test(value)
7
8const channels = (hex: string): [number, number, number] => {
9  const digits = HEX.exec(hex)?.[1] ?? '000000'
10  return [0, 2, 4].map(at => parseInt(digits.slice(at, at + 2), 16)) as [number, number, number]
11}
12
13const toHex = (rgb: readonly number[]): string =>
14  '#' + rgb.map(c => Math.round(c).toString(16).padStart(2, '0')).join('')
15
16/** Mixes `amount` (0..1) of `color` over `background`. */
17export const blend = (color: string, background: string, amount: number): string => {
18  const top = channels(color)
19  const bottom = channels(background)
20  const a = Math.min(1, Math.max(0, amount))
21  return toHex(top.map((c, i) => c * a + bottom[i]! * (1 - a)))
22}
23
24// Named accents offered in /config, each dark enough to tint over a dark or light background.
25export const ACCENTS: Readonly<Record<string, string>> = {
26  Purple: '#5b2a86',
27  Indigo: '#3f3d9e',
28  Blue: '#1f5fae',
29  Teal: '#127a7a',
30  Green: '#2e7d32',
31  Olive: '#6b7a1f',
32  Amber: '#b7791f',
33  Orange: '#c2571a',
34  Red: '#b3261e',
35  Pink: '#b0306a',
36  Slate: '#4a5568',
37}
38
39export const CUSTOM = 'Custom'
40
41/**
42 * The hex for a named accent, or `custom` when Custom is picked and valid, else Purple.
43 * The name is typed freely in /config, so case and surrounding spaces are ignored.
44 */
45export const resolveAccent = (name: unknown, custom: unknown): string => {
46  const typed = typeof name === 'string' ? name.trim().toLowerCase() : ''
47  if (typed === CUSTOM.toLowerCase() && typeof custom === 'string' && isHex(custom)) return custom.startsWith('#') ? custom : `#${custom}`
48  const match = Object.keys(ACCENTS).find(key => key.toLowerCase() === typed)
49  return (match && ACCENTS[match]) || ACCENTS.Purple!
50}
51
hooks/navigation.ts 137 lines
1// Which prompt a jump reveals, from where the prompts sit relative to the viewport.
2
3export type Visible = { first: number; last: number; of: number }
4
5/**
6 * Index of the prompt to reveal, or -1 when there is none in that direction.
7 *
8 * Relative to the topmost prompt on screen: Up reveals that prompt when its top
9 * is scrolled away, else the one before it; Down reveals the one after it. With
10 * no prompt on screen, it steps from the last jump, or starts at the newest.
11 *
12 * Down steps past the last jump's prompt when it would pick that prompt again: near
13 * the bottom the viewport cannot move it to the top, so the prompt above it stays
14 * the topmost on screen and would otherwise be picked forever.
15 */
16export function pickTarget(
17  prompts: readonly string[],
18  visible: ReadonlyMap<string, Visible>,
19  cursor: number,
20  direction: -1 | 1,
21): number {
22  const top = prompts.findIndex(id => visible.has(id))
23  const target =
24    top === -1
25      ? cursor === -1
26        ? prompts.length - 1
27        : cursor + direction
28      : direction === 1
29        ? top + 1
30        : visible.get(prompts[top]!)!.first > 0
31          ? top
32          : top - 1
33  const next = direction === 1 && target === cursor ? target + 1 : target
34  return next >= 0 && next < prompts.length ? next : -1
35}
36
37// At an end a press moves nothing. Pressed again soon after, toward the same end, it wraps to the other end. The
38// first press must come after a pause at that end, so steady presses that walk to an end stop there, and the second
39// must be farther from it than a held key repeats.
40export const DOUBLE_PRESS_MS = 500
41export const KEY_REPEAT_MS = 120
42
43/** A press that found no prompt in `direction`, at time `at`, after a pause. */
44export type EndPress = { direction: -1 | 1; at: number }
45
46/**
47 * What a press at `at`, `sincePress` after the press before it, that found no prompt in `direction` does: whether it
48 * wraps, and the end press the next press compares with.
49 */
50export function pressAtEnd(
51  last: EndPress | null,
52  direction: -1 | 1,
53  at: number,
54  sincePress: number,
55): { wrap: boolean; last: EndPress | null } {
56  if (last !== null && last.direction === direction && at - last.at <= DOUBLE_PRESS_MS && sincePress >= KEY_REPEAT_MS)
57    return { wrap: true, last: null }
58  return { wrap: false, last: sincePress > DOUBLE_PRESS_MS ? { direction, at } : null }
59}
60
61// Where the prompts sit, from the engine's reports, and the prompt the last jump revealed.
62//
63// The engine reports a row again when a scroll moves it past an edge of the viewport, after the scroll resolves. A
64// jump moves the viewport farther than that: a prompt it moves off screen past a long reply is never reported gone,
65// and one that stays on screen is not reported again. So a jump drops the reports made before it and records its
66// prompt at the top of the viewport, where `block: 'start'` puts it.
67export type Viewport = {
68  /** Records where the engine reports prompt `id`: `null` off screen, `undefined` where the surface does not say. */
69  report(id: string, onScreen: Visible | null | undefined): void
70  /** Index of the prompt a jump in `direction` reveals, or -1 when there is none. */
71  pick(direction: -1 | 1): number
72  /** A point in the reports, taken before a jump scrolls. */
73  mark(): number
74  /** The jump begun at `since` revealed `id` at the top: reports made before it may be of rows it moved off screen. */
75  landed(id: string, since: number): void
76  /** Forgets `id`, a prompt that turned out not to be drawn. */
77  forget(id: string): void
78  /** The viewport snapped to the end of the transcript: what was on screen before says nothing. */
79  toEnd(): void
80  reset(): void
81}
82
83// Where a jump's prompt sits once revealed: its first row at the top of the viewport.
84const AT_TOP: Visible = { first: 0, last: 0, of: 1 }
85
86export function createViewport(prompts: () => readonly string[]): Viewport {
87  let shown = new Map<string, { at: Visible; seq: number }>()
88  let seq = 0
89  let cursorId: string | null = null
90
91  return {
92    report(id, onScreen) {
93      seq++
94      if (!onScreen) {
95        shown.delete(id)
96        return
97      }
98      shown.set(id, { at: onScreen, seq })
99      // A prompt cut off at the top of the viewport has nothing older on screen; one cut off at the bottom, nothing newer.
100      const ids = prompts()
101      const index = ids.indexOf(id)
102      const cutTop = onScreen.first > 0
103      const cutBottom = onScreen.last < onScreen.of - 1
104      if (!cutTop && !cutBottom) return
105      for (const other of [...shown.keys()]) {
106        const at = ids.indexOf(other)
107        if ((cutTop && at < index) || (cutBottom && at > index)) shown.delete(other)
108      }
109    },
110    pick(direction) {
111      const ids = prompts()
112      const visible = new Map([...shown].map(([id, entry]) => [id, entry.at]))
113      return pickTarget(ids, visible, cursorId === null ? -1 : ids.indexOf(cursorId), direction)
114    },
115    mark() {
116      return seq
117    },
118    landed(id, since) {
119      cursorId = id
120      shown = new Map([...shown].filter(([, entry]) => entry.seq > since))
121      if (!shown.has(id)) shown.set(id, { at: AT_TOP, seq })
122    },
123    forget(id) {
124      shown.delete(id)
125    },
126    toEnd() {
127      shown = new Map()
128      cursorId = null
129    },
130    reset() {
131      shown = new Map()
132      seq = 0
133      cursorId = null
134    },
135  }
136}
137
hooks/order.ts 132 lines
1// The prompts of the transcript in transcript order, learned from the order their rows are first drawn.
2//
3// The transcript draws its newest rows first, and later draws older chunks as the viewport nears the top.
4// A chunk arrives in one burst, in transcript order, and is older than every prompt already known. A prompt
5// the person just sent is announced by `session.append` before its row is drawn, and is newer than all.
6//
7// A slash command the person runs is stored by `session.append` too, but its row is drawn by no hook, so it goes at the
8// end when stored. Commands stored before the session was resumed are never announced, so they are not in the order.
9//
10// A prompt typed while the engine works is drawn as a preview row, under an id that changes whenever the queue
11// does, until it is stored. `session.append` announces the queued text just after the first preview is drawn, so a
12// row with that text, drawn then or shortly before, is no prompt.
13
14// The engine draws a row under `placeholder`, or `placeholder-1` and so on for prompts queued while it works,
15// while a sent prompt is still being stored; the real row follows under its own id.
16// A preview row can be drawn this long before its queued text is announced.
17export const PREVIEW_LOOKBACK_MS = 2000
18// Texts of prompts waiting behind a turn that are never stored as a prompt (a notification's) would stay forever.
19const MAX_QUEUED = 20
20const PLACEHOLDER_PREFIX = 'placeholder'
21export const isPlaceholder = (id: string): boolean => id.startsWith(PLACEHOLDER_PREFIX)
22// Rows first drawn within this many milliseconds of the previous one belong to the same chunk.
23export const CHUNK_MS = 50
24
25export type PromptOrder = {
26  /** Prompt message ids, oldest first. */
27  readonly ids: readonly string[]
28  /**
29   * Notes a prompt with `text` waiting behind the running turn: rows showing it are previews, not prompts.
30   * Returns the ids it takes back out of the order, for rows drawn just before the note.
31   */
32  queue(text: string, now: number): string[]
33  /** Marks `id`, a prompt just stored with `text`, so its first draw goes at the end. */
34  announce(id: string, text: string): void
35  /** Puts `id`, a slash command just stored as `line`, at the end: no hook draws its row. */
36  command(id: string, line: string): void
37  /** Records a drawn row; a known, placeholder, preview or removed id changes nothing. */
38  add(id: string, text: string, now: number): void
39  /** Whether `id` is a prompt in the order. */
40  has(id: string): boolean
41  /** Takes the order saved before a reload; prompts drawn since go after it. */
42  restore(saved: readonly string[]): void
43  /** Forgets `id` for good, for a prompt that turned out not to be drawn. */
44  remove(id: string): void
45  reset(): void
46}
47
48const normalize = (text: string): string => text.trim().replace(/\s+/g, ' ')
49
50// A stored slash command's text names it in tags, as `<command-name>/doctor</command-name>` and `<command-args>`.
51const COMMAND_NAME = /<command-name>([^<]*)<\/command-name>/
52const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/
53
54/** The command line a stored slash command ran, as typed; `undefined` for a row that runs none, such as its output. */
55export const commandLine = (text: string): string | undefined => {
56  const name = COMMAND_NAME.exec(text)?.[1]
57  if (name === undefined) return undefined
58  const args = COMMAND_ARGS.exec(text)?.[1]?.trim()
59  return args ? `${name} ${args}` : name
60}
61
62export function createOrder(): PromptOrder {
63  let ids: string[] = []
64  const queued: string[] = []
65  let recent: { id: string; text: string; at: number }[] = []
66  const announced = new Set<string>()
67  const removed = new Set<string>()
68  let chunkAt = 0
69  let lastAt = Number.NEGATIVE_INFINITY
70
71  return {
72    get ids() {
73      return ids
74    },
75    queue(text, now) {
76      const shown = normalize(text)
77      queued.push(shown)
78      if (queued.length > MAX_QUEUED) queued.shift()
79      const previews = recent.filter(row => row.text === shown && now - row.at <= PREVIEW_LOOKBACK_MS).map(row => row.id)
80      previews.forEach(id => removed.add(id))
81      ids = ids.filter(id => !previews.includes(id))
82      recent = recent.filter(row => !previews.includes(row.id))
83      return previews
84    },
85    announce(id, text) {
86      announced.add(id)
87      const waiting = queued.indexOf(normalize(text))
88      if (waiting !== -1) queued.splice(waiting, 1)
89    },
90    command(id, line) {
91      const waiting = queued.indexOf(normalize(line))
92      if (waiting !== -1) queued.splice(waiting, 1)
93      if (!removed.has(id) && !ids.includes(id)) ids.push(id)
94    },
95    has(id) {
96      return ids.includes(id)
97    },
98    add(id, text, now) {
99      if (isPlaceholder(id) || removed.has(id) || ids.includes(id)) return
100      if (announced.delete(id)) {
101        ids.push(id)
102        return
103      }
104      if (queued.includes(normalize(text))) {
105        removed.add(id)
106        return
107      }
108      if (now - lastAt > CHUNK_MS) chunkAt = 0
109      lastAt = now
110      ids.splice(chunkAt++, 0, id)
111      recent = [...recent.filter(row => now - row.at <= PREVIEW_LOOKBACK_MS), { id, text: normalize(text), at: now }]
112    },
113    restore(saved) {
114      const known = new Set(saved)
115      ids = [...saved, ...ids.filter(id => !known.has(id))]
116    },
117    remove(id) {
118      removed.add(id)
119      ids = ids.filter(known => known !== id)
120    },
121    reset() {
122      ids = []
123      announced.clear()
124      removed.clear()
125      queued.length = 0
126      recent = []
127      chunkAt = 0
128      lastAt = Number.NEGATIVE_INFINITY
129    },
130  }
131}
132
types/index.d.ts 10 lines
1declare module 'claude-code' {
2  interface PluginState {
3    'prompt-marks': {
4      // Prompt message ids in transcript order. Module variables are lost when the mod reloads, and the engine
5      // draws only some of the transcript's rows again, so the order is kept here between reloads.
6      order: string[]
7    }
8  }
9}
10