Types out the code the agent writes, live, in a side pane with keyboard sounds

A Claude Code mod that makes it feel like you are typing while the agent codes.
When the agent calls Write, Edit, MultiEdit, NotebookEdit or Bash, Ghost Typist catches the code in the model's stream as it is generated and types it out in a side pane at a human pace, with a cursor and keyboard sounds. A keyboard under the code lights up the key of each character as it is typed.
It only shows things: the agent never waits for the typing.

Full-resolution video: docs/guide.mp4. The recording is silent; the keyboard sounds play in your terminal.
/plugin install ghost-typist --marketplace gaupoit/ghost-typist
The pane opens on its own when the agent starts writing, on a terminal at least 144 columns wide. On a narrower one, type /typist to open it.
| Command | What it does |
|---|---|
/typist | Open the pane |
/typist on / off | Turn typing on or off for this session |
/typist mode hacker | Hacker Typer mode: you type it (see below) |
/typist mode watch | Back to typing by itself |
/typist speed 140 | Base speed in words per minute |
/typist sound clicky | clicky, thock or off |
/typist keyboard off | Hide the on-screen keyboard (on brings it back) |
/typist status | Show the current settings |
Defaults are in /config (mode, speed, sound, keyboard, which tools to type, auto-open).
A US keyboard sits at the bottom of the pane. As each character is typed, its key lights up, with shift held for capitals and symbols like { or ", and Enter at the end of a line. Indentation lights nothing, since your editor would have typed it. Narrow panes get a compact keyboard; panes under 16 rows hide it.
/typist mode hacker opens the pane with the keyboard in it. Every letter or digit key you press types the next 3 to 5 characters of the agent's code (indentation comes for free). Stop pressing and the code waits for you. When the agent starts its next call, the one you were on finishes by itself, so you never fall behind. The keyboard lights the keys of the code that appears, not the keys you pressed: you mash asdf and it shows you typing const. Esc returns to the prompt; click the pane or press ctrl+x tab to come back.
turn.step hook passes every chunk of the model's stream on unchanged, and copies the tool call's argument pieces (incomplete JSON) into a queue.content, new_string, new_source or command as it arrives, escapes and all.afplay; Linux terminals stay silent).Subagent calls are not typed. For Edit, only the new text is typed.
claude --plugin-dir .
claude plugin validate .
claude plugin test .
The clips in sounds/ are synthesised (scripts/gen_sounds.py). The guide video is recorded with VHS: vhs docs/guide.tape.
MIT
hooks/register.tsx 475 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { GhostJob, GhostSettings } from '../types'
5import { readToolText, TOOL_FIELDS } from './extract'
6import { litKeys, ROWS } from './keyboard'
7import { advance, DEFAULT_PACE, measuredWpm, revealForKeys } from './typist'
8import type { Progress } from './typist'
9
10const PANE = 'ghost-typist'
11// Hacker mode listens through hidden Buttons, one per letter and digit: a
12// text field would keep every key typed into it on screen.
13const KEY_PREFIX = 'key-'
14const HOTKEYS = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('')
15const TICK_MS = 50
16const SOUNDS = ['clicky', 'thock', 'off'] as const
17type Sound = (typeof SOUNDS)[number]
18const MODES = ['watch', 'hacker'] as const
19type Mode = (typeof MODES)[number]
20// In hacker mode the clicks stop this long after the last key.
21const KEY_SOUND_MS = 250
22// A lit key stays lit this many ticks after its character, so slow typing
23// does not flicker.
24const LIT_TICKS = 5
25// The keyboard is drawn only in a pane at least this tall, and wide keys only
26// in a pane at least this wide.
27const KEYBOARD_MIN_ROWS = 16
28const KEYBOARD_MIN_COLUMNS = { narrow: 34, wide: 50 }
29// Its rows, with the border.
30const KEYBOARD_ROWS = 7
31
32const jobAtom = atom({ plugin: 'ghost-typist', key: 'job' } as const, null)
33const queuedAtom = atom({ plugin: 'ghost-typist', key: 'queued' } as const, 0)
34const settingsAtom = atom({ plugin: 'ghost-typist', key: 'settings' } as const, {
35 isEnabled: true,
36})
37
38// A tool call being typed out. `raw` is its arguments' JSON as it streams in.
39type Pending = {
40 id: string
41 tool: string
42 raw: string
43 parsedLength: number
44 text: string
45 path?: string
46 isStreamDone: boolean
47 progress: Progress
48 typingMs: number
49 lit: string[]
50 litTicks: number
51}
52
53const basename = (path: string) => path.split('/').at(-1) ?? path
54
55type Defaults = {
56 wpm: number
57 sound: Sound
58 mode: Mode
59 tools: Set<string>
60 autoOpen: boolean
61 keyboard: boolean
62}
63
64let defaults: Defaults = {
65 wpm: DEFAULT_PACE.wpm,
66 sound: 'clicky',
67 mode: 'watch',
68 tools: new Set(Object.keys(TOOL_FIELDS)),
69 autoOpen: true,
70 keyboard: true,
71}
72const queue: Pending[] = []
73let ticker: Timer | undefined
74let isTicking = false
75let sound: AbortController | undefined
76let soundOff: Timer | undefined
77let hasOpened = false
78
79const settingsOf = (s: GhostSettings) => ({
80 isEnabled: s.isEnabled,
81 wpm: s.wpm ?? defaults.wpm,
82 sound: s.sound ?? defaults.sound,
83 mode: s.mode ?? defaults.mode,
84 keyboard: s.keyboard ?? defaults.keyboard,
85})
86
87function setSound($: EngineInterface, isTyping: boolean, kind: Sound) {
88 if (isTyping && sound === undefined && kind !== 'off') {
89 sound = new AbortController()
90 $.audio
91 .play({ asset: `sounds/${kind}.wav` }, { shouldLoop: true, gain: 0.5, signal: sound.signal })
92 .catch(() => undefined)
93 } else if (!isTyping && sound !== undefined) {
94 sound.abort()
95 sound = undefined
96 }
97}
98
99function stop($: EngineInterface) {
100 ticker?.cancel()
101 ticker = undefined
102 setSound($, false, 'off')
103 $.ui.status(undefined)
104}
105
106function parse(job: Pending) {
107 if (job.raw.length === job.parsedLength) return
108 const read = readToolText(job.tool, job.raw)
109 job.text = job.tool === 'Bash' ? `$ ${read.text}` : read.text
110 job.path = read.path ?? job.path
111 job.parsedLength = job.raw.length
112}
113
114// Lights the keys for the characters typed since `before`, or lets the last
115// ones fade when nothing new was typed.
116function light(job: Pending, before: number) {
117 if (job.progress.shown > before) {
118 job.lit = litKeys(job.text, before, job.progress.shown)
119 job.litTicks = LIT_TICKS
120 } else if (job.litTicks > 0) {
121 job.litTicks -= 1
122 if (job.litTicks === 0) job.lit = []
123 }
124}
125
126// Shows the job's progress, and moves on once it is fully typed.
127async function publish($: EngineInterface, job: Pending, mode: Mode) {
128 const isFinished = job.isStreamDone && job.progress.shown >= job.text.length
129 const name = job.path ? basename(job.path) : job.tool
130 $.ui.status(
131 isFinished ? undefined : mode === 'hacker' ? `⌨ hacker mode · type to write ${name}` : `⌨ typing ${name}`,
132 )
133
134 const snapshot: GhostJob = {
135 id: job.id,
136 tool: job.tool,
137 path: job.path,
138 text: job.text.slice(0, job.progress.shown),
139 total: job.text.length,
140 isStreamDone: job.isStreamDone,
141 wpm: measuredWpm(job.progress.shown, job.typingMs),
142 keys: isFinished ? [] : job.lit,
143 }
144 await update($, jobAtom, () => snapshot)
145 await update($, queuedAtom, () => Math.max(0, queue.length - 1))
146
147 // The last finished job stays on screen until the next one starts.
148 if (isFinished && queue[0] === job) {
149 queue.shift()
150 if (queue.length === 0) stop($)
151 }
152}
153
154async function tick($: EngineInterface) {
155 const job = queue[0]
156 if (job === undefined) return stop($)
157 parse(job)
158
159 const settings = settingsOf(await read($, settingsAtom))
160 // Hacker mode waits for keys, unless another call is waiting behind this one.
161 const isAuto = settings.mode === 'watch' || queue.length > 1
162 const before = job.progress.shown
163 if (isAuto) {
164 const pace = {
165 ...DEFAULT_PACE,
166 wpm: settings.wpm,
167 finishWithinMs: queue.length > 1 ? 500 : DEFAULT_PACE.finishWithinMs,
168 }
169 job.progress = advance(job.text, job.progress, TICK_MS, job.isStreamDone, pace, Math.random)
170 if (job.progress.shown > before) job.typingMs += TICK_MS
171 }
172 light(job, before)
173 if (settings.mode === 'watch') {
174 setSound($, job.progress.shown < job.text.length, settings.sound)
175 }
176
177 await publish($, job, settings.mode)
178}
179
180// Hacker mode: the person pressed `presses` keys in the pane.
181async function pressKeys($: EngineInterface, presses: number) {
182 const job = queue[0]
183 if (job === undefined) return
184 parse(job)
185 const settings = settingsOf(await read($, settingsAtom))
186
187 const before = job.progress.shown
188 job.progress = { ...job.progress, shown: revealForKeys(job.text, before, presses, Math.random) }
189 // Count about one keystroke's time per press, so the footer shows a real WPM.
190 job.typingMs += presses * 120
191 light(job, before)
192
193 setSound($, job.progress.shown > before, settings.sound)
194 soundOff?.cancel()
195 soundOff = $.clock.after(KEY_SOUND_MS, () => setSound($, false, 'off'))
196
197 await publish($, job, settings.mode)
198}
199
200function ensureTicker($: EngineInterface) {
201 if (ticker !== undefined) return
202 ticker = $.clock.every(TICK_MS, () => {
203 if (isTicking) return
204 isTicking = true
205 tick($)
206 .catch(() => undefined)
207 .finally(() => {
208 isTicking = false
209 })
210 })
211}
212
213// Each row is indented a little more, like a real keyboard's stagger.
214const STAGGER = { wide: [0, 1, 2, 3], narrow: [0, 1, 1, 2] }
215
216// The on-screen keyboard, with the keys in `lit` drawn pressed. A wide pane
217// gets three columns a key, a narrow one two.
218function drawKeyboard(elements: Pick<Elements['terminal'], 'Box' | 'Text'>, lit: string[], isWide: boolean) {
219 const { Box, Text } = elements
220 const on = new Set(lit)
221 const width = isWide ? 3 : 2
222 const cap = (id: string, label: string, i: string) => {
223 const face = isWide ? ` ${label} ` : `${label} `
224 return on.has(id) ? (
225 <Text key={i} inverse bold color="claude">
226 {face}
227 </Text>
228 ) : (
229 // The space bar is underlined so it reads as a bar, not a word.
230 <Text key={i} dimColor underline={id === 'space'}>
231 {face}
232 </Text>
233 )
234 }
235
236 return (
237 <Box flexDirection="column" alignSelf="flex-start" borderStyle="round" borderDimColor paddingX={1}>
238 {ROWS.slice(0, -1).map((row, r) => (
239 <Box key={`row-${r}`} flexDirection="row" paddingLeft={STAGGER[isWide ? 'wide' : 'narrow'][r]}>
240 {row.map((k, i) => cap(k.id, k.label, `${r}-${i}`))}
241 </Box>
242 ))}
243 <Box flexDirection="row" paddingLeft={width * 4}>
244 {cap('space', isWide ? ' space ' : ' space ', 'space')}
245 </Box>
246 </Box>
247 )
248}
249
250export const register: Register = (on, options) => {
251 defaults = {
252 wpm: Number(options.wpm ?? DEFAULT_PACE.wpm),
253 sound: (SOUNDS.includes(options.sound as Sound) ? options.sound : 'clicky') as Sound,
254 tools: new Set(
255 String(options.tools ?? Object.keys(TOOL_FIELDS).join(','))
256 .split(',')
257 .map(t => t.trim())
258 .filter(t => t in TOOL_FIELDS),
259 ),
260 mode: (MODES.includes(options.mode as Mode) ? options.mode : 'watch') as Mode,
261 autoOpen: options.autoOpen !== false,
262 keyboard: options.keyboard !== false,
263 }
264
265 on('session.start', async ($, e, next) => {
266 await $.command.register({
267 name: 'typist',
268 description:
269 'Ghost Typist: open the pane, or on | off | mode watch|hacker | keyboard on|off | speed <wpm> | sound clicky|thock|off',
270 })
271
272 return next(e)
273 })
274
275 on('command.run', { command: 'typist' }, async ($, e) => {
276 const [word = '', value = ''] = e.args.trim().split(/\s+/)
277 const current = settingsOf(await read($, settingsAtom))
278
279 if (word === '' || word === 'open') {
280 await $.ui.open({ id: PANE, title: 'Ghost Typist' })
281 return { text: 'Ghost Typist pane opened.' }
282 }
283 if (word === 'on' || word === 'off') {
284 await update($, settingsAtom, s => ({ ...s, isEnabled: word === 'on' }))
285 if (word === 'off') stop($)
286 return { text: `Ghost Typist is ${word}.` }
287 }
288 if (word === 'speed') {
289 const wpm = Number(value)
290 if (!Number.isFinite(wpm) || wpm < 10 || wpm > 2000) {
291 return { text: `Speed must be a number of WPM from 10 to 2000 (now ${current.wpm}).` }
292 }
293 await update($, settingsAtom, s => ({ ...s, wpm }))
294 return { text: `Ghost Typist types at ${wpm} WPM.` }
295 }
296 if (word === 'mode') {
297 if (!MODES.includes(value as Mode)) {
298 return { text: `Mode is watch or hacker (now ${current.mode}).` }
299 }
300 await update($, settingsAtom, s => ({ ...s, mode: value as Mode }))
301 if (value === 'hacker') {
302 // Asked for, so the pane may take the keyboard.
303 await $.ui.open({ id: PANE, title: 'Ghost Typist', focus: true })
304 return { text: 'Hacker mode: each letter key you press in the pane types the agent\'s code. Esc returns to the prompt.' }
305 }
306 return { text: 'Watch mode: Ghost Typist types by itself.' }
307 }
308 if (word === 'keyboard') {
309 if (value !== 'on' && value !== 'off') {
310 return { text: `Keyboard is on or off (now ${current.keyboard ? 'on' : 'off'}).` }
311 }
312 await update($, settingsAtom, s => ({ ...s, keyboard: value === 'on' }))
313 return { text: `Ghost Typist keyboard ${value}.` }
314 }
315 if (word === 'sound') {
316 if (!SOUNDS.includes(value as Sound)) {
317 return { text: `Sound is one of ${SOUNDS.join(', ')} (now ${current.sound}).` }
318 }
319 await update($, settingsAtom, s => ({ ...s, sound: value as Sound }))
320 if (value === 'off') setSound($, false, 'off')
321 return { text: `Ghost Typist sound: ${value}.` }
322 }
323
324 return {
325 text: `Ghost Typist is ${current.isEnabled ? 'on' : 'off'} · ${current.mode} mode · ${current.wpm} WPM · sound ${current.sound} · keyboard ${current.keyboard ? 'on' : 'off'}. Usage: /typist [open | on | off | mode watch|hacker | keyboard on|off | speed <wpm> | sound clicky|thock|off]`,
326 }
327 })
328
329 // Watches the model's stream and copies tool arguments into the queue.
330 // Every chunk is passed on unchanged.
331 on('turn.step', async function* ($, e, next) {
332 const stream = next(e)
333 const settings = await read($, settingsAtom)
334 if (!settings.isEnabled || e.agentId !== undefined) return yield* stream
335
336 const byIndex = new Map<number, Pending>()
337 const finishAll = () => {
338 for (const job of byIndex.values()) job.isStreamDone = true
339 }
340 try {
341 for await (const chunk of stream) {
342 if (chunk.kind === 'tool') {
343 finishAll()
344 if (defaults.tools.has(chunk.name)) {
345 const job: Pending = {
346 id: chunk.id,
347 tool: chunk.name,
348 raw: '',
349 parsedLength: -1,
350 text: '',
351 isStreamDone: false,
352 progress: { shown: 0, carry: 0 },
353 typingMs: 0,
354 lit: [],
355 litTicks: 0,
356 }
357 byIndex.set(chunk.index, job)
358 queue.push(job)
359 if (defaults.autoOpen && !hasOpened) {
360 hasOpened = true
361 void $.ui.open({ id: PANE, title: 'Ghost Typist' })
362 }
363 ensureTicker($)
364 }
365 } else if (chunk.kind === 'input') {
366 const job = byIndex.get(chunk.index)
367 if (job !== undefined) job.raw += chunk.json
368 }
369 yield chunk
370 }
371 } finally {
372 finishAll()
373 }
374
375 return await stream.result
376 })
377
378 // Hacker mode: every edit of the pane's key field is a key press.
379 // Answered here: each key redraws the pane, so by the time the press
380 // would reach its Button the handler it was drawn with is gone.
381 on('ui.press', async ($, e, next) => {
382 if (e.plugin !== 'ghost-typist' || e.requestId !== PANE || !e.element.startsWith(KEY_PREFIX)) {
383 return next(e)
384 }
385 await pressKeys($, 1)
386
387 return { element: e.element }
388 })
389
390 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
391 const elements = $.ui.resolve(e)
392 const { Box, Text, Code } = elements
393 const job = await read($, jobAtom)
394 const queued = await read($, queuedAtom)
395 const { mode, keyboard } = settingsOf(await read($, settingsAtom))
396 // Surfaces without buttons stay in watch mode.
397 const Button = mode === 'hacker' && 'Button' in elements ? elements.Button : undefined
398 const keyField =
399 Button === undefined ? null : (
400 <Box flexDirection="column">
401 <Text dimColor>
402 {e.props.isFocused ? 'mash any letter key…' : 'focus the pane (click, or ctrl+x tab) and mash letters'}
403 </Text>
404 <Box display="none">
405 {HOTKEYS.map(ch => (
406 <Button key={`${KEY_PREFIX}${ch}`} hotkey={ch} label={ch} onPress={() => undefined} />
407 ))}
408 </Box>
409 </Box>
410 )
411
412 if (job === null) {
413 return (
414 <Box flexDirection="column">
415 <Text bold>Ghost Typist</Text>
416 <Text dimColor>Waiting for the agent to write some code…</Text>
417 {keyboard && e.props.bodyColumns >= KEYBOARD_MIN_COLUMNS.narrow
418 ? drawKeyboard(elements, [], e.props.bodyColumns >= KEYBOARD_MIN_COLUMNS.wide)
419 : null}
420 {keyField}
421 </Box>
422 )
423 }
424
425 const columns = Math.max(20, e.props.bodyColumns - 6)
426 const showsKeyboard =
427 keyboard &&
428 e.props.scroll.bodyRows >= KEYBOARD_MIN_ROWS &&
429 e.props.bodyColumns >= KEYBOARD_MIN_COLUMNS.narrow
430 const room = Math.max(
431 3,
432 e.props.scroll.bodyRows - (keyField === null ? 4 : 6) - (showsKeyboard ? KEYBOARD_ROWS : 0),
433 )
434 const isTyping = !job.isStreamDone || job.text.length < job.total
435 // Keep the cursor in view: the tail of the text that fits, counting wrapped rows.
436 const lines = job.text.split('\n')
437 let used = 0
438 let first = lines.length
439 while (first > 0) {
440 const rows = Math.max(1, Math.ceil(lines[first - 1]!.length / columns))
441 if (used + rows > room) break
442 used += rows
443 first -= 1
444 }
445 const source = lines.slice(first).join('\n') + (isTyping ? '▌' : '')
446 const pct = job.total === 0 ? 0 : Math.round((job.text.length / job.total) * 100)
447
448 // With a keyboard, the pane fills its height so the keyboard sits at the
449 // bottom and stays put while the code grows above it.
450 return (
451 <Box flexDirection="column" height={showsKeyboard ? e.props.scroll.bodyRows : undefined}>
452 <Box flexDirection="row" gap={1}>
453 <Text bold color="claude">
454 {job.tool}
455 </Text>
456 <Text>{job.path ?? ''}</Text>
457 </Box>
458 <Code
459 source={source}
460 path={job.path}
461 language={job.tool === 'Bash' ? 'bash' : undefined}
462 startLine={job.path !== undefined && job.tool === 'Write' ? first + 1 : undefined}
463 />
464 {showsKeyboard ? <Box flexGrow={1} /> : null}
465 <Text dimColor>
466 {isTyping ? (Button === undefined ? 'typing' : 'hacker mode') : 'done'} · {job.wpm} WPM ·{' '}
467 {pct}%{queued > 0 ? ` · ${queued} queued` : ''}
468 </Text>
469 {showsKeyboard ? drawKeyboard(elements, job.keys, e.props.bodyColumns >= KEYBOARD_MIN_COLUMNS.wide) : null}
470 {keyField}
471 </Box>
472 )
473 })
474}
475hooks/extract.ts 113 lines1// Reads string fields out of a tool call's arguments while they are still
2// streaming, so the JSON is usually incomplete: `{"file_path":"a.ts","content":"imp`.
3
4export type Field = { value: string; isComplete: boolean }
5
6const ESCAPES: Record<string, string> = {
7 '"': '"',
8 '\\': '\\',
9 '/': '/',
10 b: '\b',
11 f: '\f',
12 n: '\n',
13 r: '\r',
14 t: '\t',
15}
16
17// Decodes the JSON string whose opening quote is at `start`. Stops cleanly
18// at the end of the input, dropping an escape that is cut in half.
19const readString = (raw: string, start: number): Field & { end: number } => {
20 let value = ''
21 let i = start + 1
22 while (i < raw.length) {
23 const ch = raw[i]!
24 if (ch === '"') return { value, isComplete: true, end: i + 1 }
25 if (ch !== '\\') {
26 value += ch
27 i += 1
28 continue
29 }
30 const esc = raw[i + 1]
31 if (esc === undefined) break
32 if (esc === 'u') {
33 const hex = raw.slice(i + 2, i + 6)
34 if (hex.length < 4) break
35 value += String.fromCharCode(parseInt(hex, 16))
36 i += 6
37 continue
38 }
39 value += ESCAPES[esc] ?? esc
40 i += 2
41 }
42
43 return { value, isComplete: false, end: raw.length }
44}
45
46// Every string value of `key`, at any depth, in order (MultiEdit's
47// `edits[].new_string` gives several). The last may be incomplete.
48export const extractFields = (raw: string, key: string): Field[] => {
49 const found: Field[] = []
50 const stack: Array<'{' | '['> = []
51 let isKeyNext = false
52 let lastKey: string | undefined
53 let i = 0
54 while (i < raw.length) {
55 const ch = raw[i]!
56 if (ch === '"') {
57 const str = readString(raw, i)
58 if (isKeyNext && stack.at(-1) === '{') {
59 lastKey = str.value
60 isKeyNext = false
61 } else if (lastKey === key) {
62 found.push({ value: str.value, isComplete: str.isComplete })
63 }
64 i = str.end
65 continue
66 }
67 if (ch === '{' || ch === '[') {
68 stack.push(ch)
69 isKeyNext = ch === '{'
70 } else if (ch === '}' || ch === ']') {
71 stack.pop()
72 isKeyNext = false
73 } else if (ch === ',') {
74 isKeyNext = stack.at(-1) === '{'
75 } else if (ch === ':') {
76 isKeyNext = false
77 }
78 i += 1
79 }
80
81 return found
82}
83
84export const extractField = (raw: string, key: string): Field | undefined =>
85 extractFields(raw, key)[0]
86
87// What each tool types, and where its target path lives.
88export const TOOL_FIELDS: Record<string, { text: string; path?: string }> = {
89 Write: { text: 'content', path: 'file_path' },
90 Edit: { text: 'new_string', path: 'file_path' },
91 MultiEdit: { text: 'new_string', path: 'file_path' },
92 NotebookEdit: { text: 'new_source', path: 'notebook_path' },
93 Bash: { text: 'command' },
94}
95
96export const EDIT_SEPARATOR = '\n\n⋯\n\n'
97
98// The text a tool call has typed so far, and whether its arguments are done.
99export const readToolText = (
100 tool: string,
101 raw: string,
102): { text: string; path?: string } => {
103 const spec = TOOL_FIELDS[tool]
104 if (spec === undefined) return { text: '' }
105 const parts = extractFields(raw, spec.text).map(f => f.value)
106 const path = spec.path === undefined ? undefined : extractField(raw, spec.path)
107
108 return {
109 text: parts.join(EDIT_SEPARATOR),
110 path: path?.isComplete ? path.value : undefined,
111 }
112}
113hooks/keyboard.ts 55 lines1// The on-screen keyboard: which key types a character, and which keys to
2// light for the characters just typed. Pure, so tests drive it directly.
3
4export type Key = { id: string; label: string }
5
6const keys = (chars: string): Key[] => chars.split('').map(ch => ({ id: ch, label: ch }))
7
8// US QWERTY, top row first. The last row is the space bar.
9export const ROWS: Key[][] = [
10 [...keys('`1234567890-='), { id: 'backspace', label: '⌫' }],
11 [{ id: 'tab', label: '⇥' }, ...keys('qwertyuiop[]\\')],
12 [{ id: 'caps', label: '⇪' }, ...keys("asdfghjkl;'"), { id: 'enter', label: '⏎' }],
13 [{ id: 'shift', label: '⇧' }, ...keys('zxcvbnm,./'), { id: 'shift', label: '⇧' }],
14 [{ id: 'space', label: 'space' }],
15]
16
17const PLAIN = new Set(ROWS.flat().map(k => k.id))
18const SHIFTED: Record<string, string> = {
19 '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8',
20 '(': '9', ')': '0', '_': '-', '+': '=', '{': '[', '}': ']', '|': '\\', ':': ';', '"': "'",
21 '<': ',', '>': '.', '?': '/',
22}
23
24// The key that types `ch`, and whether shift is held; undefined for
25// characters the keyboard has no key for (emoji, accents).
26export const keyFor = (ch: string): { key: string; isShifted: boolean } | undefined => {
27 if (ch === '\n') return { key: 'enter', isShifted: false }
28 if (ch === '\t') return { key: 'tab', isShifted: false }
29 if (ch === ' ') return { key: 'space', isShifted: false }
30 if (/^[A-Z]$/.test(ch)) return { key: ch.toLowerCase(), isShifted: true }
31 if (ch in SHIFTED) return { key: SHIFTED[ch]!, isShifted: true }
32 if (PLAIN.has(ch)) return { key: ch, isShifted: false }
33
34 return undefined
35}
36
37// Keys to light for text[from, to): the last `max` characters typed, skipping
38// indentation the editor would have put in (it costs no keystroke).
39export const litKeys = (text: string, from: number, to: number, max = 2): string[] => {
40 const lit = new Set<string>()
41 let count = 0
42 for (let i = to - 1; i >= Math.max(0, from) && count < max; i -= 1) {
43 const ch = text[i]!
44 const prev = text[i - 1]
45 if ((ch === ' ' || ch === '\t') && (prev === '\n' || prev === ' ' || prev === '\t')) continue
46 const hit = keyFor(ch)
47 if (hit === undefined) continue
48 lit.add(hit.key)
49 if (hit.isShifted) lit.add('shift')
50 count += 1
51 }
52
53 return [...lit]
54}
55hooks/typist.ts 92 lines1// Pacing: how many characters a human-ish typist gets through in `dtMs`.
2// Pure, so tests drive it with a fixed random source.
3
4export type Pace = {
5 wpm: number
6 // How far behind the model the typist may fall before speeding up.
7 maxLagChars: number
8 // Once the model has finished the call, the rest is typed within this.
9 finishWithinMs: number
10}
11
12export const DEFAULT_PACE: Pace = { wpm: 110, maxLagChars: 600, finishWithinMs: 8000 }
13
14// Cost of one character, in units of a plain keystroke.
15export const charCost = (ch: string, prev: string | undefined, rand: number): number => {
16 const jitter = 0.6 + rand * 0.8
17 // Auto-indent: leading whitespace after a newline costs almost nothing.
18 if ((ch === ' ' || ch === '\t') && (prev === '\n' || prev === ' ' || prev === '\t')) {
19 return 0.08
20 }
21 if (ch === '\n') return 3.5 * jitter
22 if (';{}()'.includes(ch)) return 1.8 * jitter
23 if (ch === ' ') return 1.3 * jitter
24
25 return jitter
26}
27
28export type Progress = {
29 shown: number
30 // Keystroke budget carried over between ticks.
31 carry: number
32 // Time spent typing since the model finished the call.
33 sinceDoneMs?: number
34}
35
36export const advance = (
37 text: string,
38 progress: Progress,
39 dtMs: number,
40 isStreamDone: boolean,
41 pace: Pace,
42 random: () => number,
43): Progress => {
44 const left = text.length - progress.shown
45 if (left <= 0) return { shown: text.length, carry: 0 }
46
47 const keysPerMs = (pace.wpm * 5) / 60_000
48 const speedUp = Math.max(1, left / pace.maxLagChars)
49 let budget = progress.carry + dtMs * keysPerMs * speedUp
50 let shown = progress.shown
51 while (shown < text.length) {
52 const cost = charCost(text[shown]!, text[shown - 1], random())
53 if (cost > budget) break
54 budget -= cost
55 shown += 1
56 }
57
58 // Once the call is complete, spread what is left over the time remaining
59 // in the window, so it ends on time whatever the speed.
60 const sinceDoneMs = isStreamDone ? (progress.sinceDoneMs ?? 0) + dtMs : undefined
61 if (sinceDoneMs !== undefined) {
62 const remainingMs = Math.max(dtMs, pace.finishWithinMs - sinceDoneMs + dtMs)
63 shown = Math.max(shown, progress.shown + Math.ceil((left * dtMs) / remainingMs))
64 }
65 shown = Math.min(shown, text.length)
66
67 return { shown, carry: shown === text.length ? 0 : budget, sinceDoneMs }
68}
69
70// Words per minute actually reached, for the footer.
71export const measuredWpm = (chars: number, ms: number): number =>
72 ms <= 0 ? 0 : Math.round(chars / 5 / (ms / 60_000))
73
74// Hacker Typer mode: each key the person presses reveals a few characters,
75// and indentation after a newline comes along for free.
76export const revealForKeys = (
77 text: string,
78 shown: number,
79 presses: number,
80 random: () => number,
81): number => {
82 let next = shown
83 for (let i = 0; i < presses && next < text.length; i += 1) {
84 next += 3 + Math.floor(random() * 3)
85 if (text[next - 1] === '\n') {
86 while (next < text.length && /[ \t]/.test(text[next]!)) next += 1
87 }
88 }
89
90 return Math.min(next, text.length)
91}
92types/index.d.ts 32 lines1export type GhostJob = {
2 id: string
3 tool: string
4 path?: string
5 // The part typed out so far.
6 text: string
7 // Characters received from the model so far.
8 total: number
9 isStreamDone: boolean
10 wpm: number
11 // Keys lit on the on-screen keyboard (ids from ROWS).
12 keys: string[]
13}
14
15export type GhostSettings = {
16 isEnabled: boolean
17 wpm?: number
18 sound?: 'clicky' | 'thock' | 'off'
19 mode?: 'watch' | 'hacker'
20 keyboard?: boolean
21}
22
23declare module 'claude-code' {
24 interface PluginState {
25 'ghost-typist': {
26 job: GhostJob | null
27 queued: number
28 settings: GhostSettings
29 }
30 }
31}
32