SLOPSHOPPER

redpen

Line-by-line review pane: comment on what Claude changed, then send every comment back as one prompt.

paneguardcommandtoastprompt
★ 4v0.5.1MITupdated 2026-10-11joonhyukyim/redpen
A shopper browsing a rack in a slop shop
README

Redpen

Redpen is a Claude Code plugin that lets you read and review documents line by line without leaving the terminal.

  • Read Claude's last reply or any file, line by line.
  • Comment on a single line or a range of lines you want changed.
  • Send all your comments back to Claude in a single prompt.

Installation

From a Claude Code session

/plugin install redpen --marketplace joonhyukyim/redpen
# Answer `y` when asked "Add marketplace?", then choose a scope.

From a shell

claude plugin install redpen --marketplace joonhyukyim/redpen
# Use `-s` to choose a scope (defaults to user).

Usage

CommandWhat it does
/redpenOpens Redpen with a list of Claude's last reply, the files Claude changed in its last turn, and any files you've commented on.
/redpen <path>Opens the file at <path>. Shows the diff if Claude changed it in its last turn, or the whole file otherwise.

Redpen takes keyboard focus when it opens. Press Esc to return to the prompt and Ctrl+X Tab to switch back to Redpen. Press Ctrl+X X to close it.

Browsing the list

The list has two sections:

  • 최근 수정 (recently changed): files Claude changed in its last turn. Open one to see the diff from that turn.
  • 전송 대기 (pending): files with comments, in the order you first commented on them.

The list is cleared after /clear, /resume, or restarting Claude.

HotkeyAction
↑↓, EnterSelect an entry and open it
1Open another file
0Open the confirmation screen

Press 1 (파일 열기) to replace the hotkey bar with a path input. Enter a path the same way as with /redpen <path> and press Enter to open it. Pressing Enter on an empty input closes it, and paths that aren't files won't open. While the input is empty, it suggests files changed in this session (most recent first, marked ↺); once you start typing, it suggests matching paths. Use ↓ to move to a suggestion and Enter to select it.

Reviewing a document

HotkeyAction
1Back to the list
2Toggle between changes only (diff) and the whole file
3Start a range at the current line. Press Enter to comment on it, or 3 again to cancel
0Open the confirmation screen

To write a comment, press Enter to open the input and Enter again to save. Pressing Enter on an empty input cancels.

Each line can have one comment. A range comment is attached to the last line of the range. Press Enter on a line that already has a comment to edit it.

Comments on lines that aren't visible in the diff appear under 표시되지 않은 코멘트 N개 (N comments not shown). Press Enter on one to edit it.

Sending

Press 0 on the list or a document to open the confirmation screen.

HotkeyAction
↑↓Move between comments
EnterEdit the selected comment in place
1Return to the previous screen without sending
2Jump to the comment in its document
0Send all comments to Claude as one prompt and return to the list

When you send, Claude receives a prompt like this:

다음 리뷰 코멘트를 모두 반영해서 수정해줘. 코멘트가 지적한 부분 외에는 건드리지 마.

1. src/foo.ts:12-18
   > (the lines commented on, up to 8)
   This helper is used only once; inline it.
2. src/bar.ts:40 (삭제된 줄, 변경 전 기준)
   > ...
   Remove the comment.
3. src/baz.ts (위치 불명, 원래 7행)
   > ...
   ...

Limitations and caveats

  • The list includes files Claude changes with Edit, Write, or NotebookEdit. Files changed earlier in the session, or that have comments, also appear at the end of a turn if they're changed some other way (Bash, an MCP tool, or a subagent). Other files don't appear; open them with 1 or /redpen <path>.
  • Files larger than 4 MiB can't be opened. Very large changes are shown as a single block of deleted lines followed by a single block of added lines.
  • Notebook diffs show the raw .ipynb JSON.
  • Esc doesn't cancel; it moves focus back to the prompt.
  • Works in the terminal only. Mobile, the VS Code panel, claude -p, and WSL aren't supported.
Source 5 files
hooks/register.tsx 1357 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Comment, Composing, Held, RecentTurn, SendView, SessionFile, Source, TurnFile, View } from '../types'
5import { diffRows, splitLines } from './diff'
6import { completions, expand, splitTyped } from './paths'
7import type { Row } from './diff'
8import { cells, cut, wrapRows } from './text'
9
10type Engine = EngineInterface
11type Doc = Extract<View, { screen: 'doc' }>
12
13const PANE = 'redpen'
14const REPLY = 'Claude 마지막 답변'
15const EXCERPT_MAX = 8
16// Keys described beside the hotkey Buttons, drawn as a Button draws its own: the key in a
17// theme color (a theme key, so it follows the theme), a colon, the text.
18type KeyHint = readonly [key: string, text: string]
19const LIST_KEYS: KeyHint[] = [
20  ['↑↓', '이동'],
21  ['Enter', '열기'],
22]
23const DOC_KEYS: KeyHint[] = [
24  ['↑↓', '이동'],
25  ['Enter', '코멘트 작성/수정'],
26]
27const SEND_KEYS: KeyHint[] = [
28  ['↑↓', '이동'],
29  ['Enter', '수정'],
30]
31// Claude Code's keys for the pane itself, the same on every screen, under each screen's own.
32const PANE_KEYS: KeyHint[] = [
33  ['Esc', '프롬프트로'],
34  ['Ctrl+X Tab', 'Redpen으로'],
35  ['Ctrl+X X', 'Redpen 닫기'],
36]
37const hintWidth = ([key, text]: KeyHint) => cells(`${key}: ${text}`)
38const HEADER = '다음 리뷰 코멘트를 모두 반영해서 수정해줘. 코멘트가 지적한 부분 외에는 건드리지 마.'
39
40// The turn running now, the turn that last changed files, every file changed this session, and
41// what the files the list knows held when the running turn began. All last the session: /clear,
42// a resume and a restart start them anew.
43const turn = atom({ plugin: 'redpen', key: 'turn' } as const, null as string | null)
44const recent = atom({ plugin: 'redpen', key: 'recent' } as const, null as RecentTurn | null)
45const edited = atom({ plugin: 'redpen', key: 'edited' } as const, [] as SessionFile[])
46const snapshot = atom({ plugin: 'redpen', key: 'snapshot' } as const, [] as Held[])
47// Files opened by path, and when: offered again, with the files changed this session.
48const opened = atom({ plugin: 'redpen', key: 'opened' } as const, [] as SessionFile[])
49const OPENED_MAX = 10
50const OFFERS_MAX = 8
51const view = atom({ plugin: 'redpen', key: 'view' } as const, { screen: 'list' } as View)
52const comments = atom({ plugin: 'redpen', key: 'comments' } as const, [] as Comment[])
53
54// The path's stat with where it lands: absolute, links followed, . and .. folded.
55const statPath = ($: Engine, path: string) => $.fs.stat(path, { resolve: true }).catch(() => undefined)
56
57// Puts a change into the turn running now, the moment it is made, so a turn cut short keeps its
58// changes: the turn's first change makes it the recent turn, and a file keeps what it held
59// before the turn first changed it. The session's list takes the file as changed last.
60async function recordEdit($: Engine, filePath: string, base: string | null) {
61  // Kept as /redpen <path> resolves it, so both name a file the same way.
62  await record($, (await statPath($, filePath))?.realPath ?? filePath, base)
63}
64
65async function record($: Engine, path: string, base: string | null) {
66  const turnId = (await read($, turn)) ?? ''
67  await update($, recent, r => {
68    const files = r?.turnId === turnId ? r.files : []
69    return { turnId, files: files.some(f => f.path === path) ? files : [...files, { path, base }] }
70  })
71  const at = await $.clock.now()
72  await update($, edited, list => [...list.filter(f => f.path !== path), { path, at }])
73}
74
75// A file gone from disk leaves the list and the offers.
76async function forget($: Engine, path: string) {
77  await update($, recent, r => (r === null ? r : { ...r, files: r.files.filter(f => f.path !== path) }))
78  await update($, edited, list => list.filter(f => f.path !== path))
79  await update($, opened, list => list.filter(f => f.path !== path))
80}
81
82// The files the list knows: those changed this session and those with comments.
83async function known($: Engine) {
84  const commented = (await read($, comments)).filter(c => c.kind !== 'reply').map(c => c.path)
85  return [...new Set([...(await read($, edited)).map(f => f.path), ...commented])]
86}
87
88// The last diff computed, by what it was computed from. A module variable: a reload drops it.
89let lastDiff: { path: string; base: string; text: string; whole: boolean; rows: Row[] } | null = null
90
91const plainRows = (lines: string[]): Row[] => lines.map((text, i) => ({ kind: 'ctx', text, newLine: i + 1 }))
92
93type Loaded = { lines: string[]; rows: Row[]; note?: string }
94
95async function loadDoc($: Engine, source: Source, whole = false): Promise<Loaded> {
96  if (source.kind === 'reply') {
97    const lines = splitLines(source.text)
98    return { lines, rows: plainRows(lines) }
99  }
100  let text: string
101  try {
102    text = await $.fs.read(source.path)
103  } catch {
104    return { lines: [], rows: [], note: '파일을 읽을 수 없습니다 (없거나 4 MiB 초과).' }
105  }
106  const lines = splitLines(text)
107  if (source.kind === 'file') return { lines, rows: plainRows(lines) }
108  if (source.base === null) return { lines, rows: plainRows(lines), note: '변경 전 내용이 없어 파일 전체를 보여줍니다.' }
109  // Every arrow key redraws; the file is read again, the diff reused while nothing changed.
110  const key = { path: source.path, base: source.base, text, whole }
111  if (!lastDiff || Object.entries(key).some(([k, value]) => lastDiff![k as keyof typeof key] !== value)) {
112    lastDiff = { ...key, rows: diffRows(splitLines(source.base), lines, whole ? Infinity : 3) }
113  }
114  const rows = lastDiff.rows
115  return { lines, rows, note: rows.every(r => r.kind === 'ctx') ? '변경분이 없습니다.' : undefined }
116}
117
118// The lines each listed diff adds and removes, by what they were counted from. A module
119// variable: a reload drops it. The list reads its files at every drawing; the counts are
120// reused while neither a file nor its base changed.
121const counted = new Map<string, { base: string; text: string; added: number; removed: number }>()
122
123async function changeCounts($: Engine, f: TurnFile) {
124  if (f.base === null) return null
125  const text = await $.fs.read(f.path).catch(() => null)
126  if (text === null) return null
127  let c = counted.get(f.path)
128  if (!c || c.base !== f.base || c.text !== text) {
129    const rows = diffRows(splitLines(f.base), splitLines(text), 0)
130    c = {
131      base: f.base,
132      text,
133      added: rows.filter(r => r.kind === 'add').length,
134      removed: rows.filter(r => r.kind === 'del').length,
135    }
136    counted.set(f.path, c)
137  }
138  return c
139}
140
141// The document as last drawn. The pane redraws on state, not when a file changes, so the
142// keys act on these rows, the ones on screen, rather than on the file read again.
143// A reply is not kept: its text is in the view already.
144let drawn: { key: string | null; doc: Loaded } | null = null
145const drawnKey = (v: Doc) => (v.source.kind === 'reply' ? null : `${v.source.kind}:${v.whole === true}:${v.source.path}`)
146
147async function shown($: Engine, v: Doc): Promise<Loaded> {
148  const key = drawnKey(v)
149  return key !== null && drawn?.key === key ? drawn.doc : loadDoc($, v.source, v.whole === true)
150}
151
152const docPath = (source: Source) => (source.kind === 'reply' ? REPLY : source.path)
153
154// Where the comment's excerpt stands now: its saved line, else the nearest exact match.
155// `lines` undefined means the text cannot have moved (a deleted line, a reply snapshot).
156function locate(c: Comment, lines: string[] | null | undefined): number | null {
157  if (lines === undefined || c.side === 'old') return c.start
158  if (lines === null) return null
159  const at = (i: number) => c.excerpt.every((text, k) => lines[i + k] === text)
160  if (at(c.start - 1)) return c.start
161  let best: number | null = null
162  for (let i = 0; i + c.excerpt.length <= lines.length; i++) {
163    if (at(i) && (best === null || Math.abs(i + 1 - c.start) < Math.abs(best - c.start))) best = i + 1
164  }
165  return best
166}
167
168const span = (start: number, c: Comment) => (c.end === c.start ? `${start}` : `${start}-${start + c.end - c.start}`)
169
170function relative(path: string, cwd: string) {
171  return path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path
172}
173
174function where(c: Comment, start: number | null, cwd: string) {
175  const name = c.kind === 'reply' ? REPLY : relative(c.path, cwd)
176  if (start === null) return `${name} (위치 불명, 원래 ${span(c.start, c)}행)`
177  if (c.kind === 'reply') return `${name} ${span(start, c)}행`
178  if (c.side === 'old') return `${name}:${span(start, c)} (삭제된 줄, 변경 전 기준)`
179  return `${name}:${span(start, c)}`
180}
181
182// A comment and the line it starts on now (null once its lines are gone).
183type Placed = { c: Comment; start: number | null }
184
185// The comments in the order the send screen shows them and the prompt sends them: those on the
186// reply first, then each file's, the files in the order of their first comment, and in a file
187// by line as it stands now, a comment that lost its place after the rest. A deleted line is
188// placed by its number before the change.
189async function arrange($: Engine, list: Comment[]): Promise<Placed[]> {
190  const files = new Map<string, string[] | null>()
191  const placed: Placed[] = []
192  for (const c of list) {
193    let lines: string[] | null | undefined
194    if (c.kind !== 'reply' && c.side === 'new') {
195      if (!files.has(c.path)) files.set(c.path, await $.fs.read(c.path).then(splitLines, () => null))
196      lines = files.get(c.path)
197    }
198    placed.push({ c, start: locate(c, lines) })
199  }
200  const first = new Map<string, number>()
201  for (const c of list) first.set(c.path, Math.min(first.get(c.path) ?? Infinity, c.at ?? 0))
202  const rank = ({ c }: Placed) => (c.kind === 'reply' ? -1 : first.get(c.path)!)
203  const line = ({ start }: Placed) => start ?? Number.MAX_SAFE_INTEGER
204  return placed.sort((a, b) => rank(a) - rank(b) || a.c.path.localeCompare(b.c.path) || line(a) - line(b))
205}
206
207export async function buildPrompt($: Engine, list: Comment[]): Promise<string> {
208  const cwd = await $.session.cwd()
209  const items = (await arrange($, list)).map(({ c, start }, i) => {
210    const shown = c.excerpt.slice(0, EXCERPT_MAX).map(text => `   > ${text}`)
211    if (c.excerpt.length > EXCERPT_MAX) shown.push(`   > …(${c.excerpt.length - EXCERPT_MAX}줄 생략)`)
212    return [`${i + 1}. ${where(c, start, cwd)}`, ...shown, ...c.text.split('\n').map(text => `   ${text}`)].join('\n')
213  })
214  return [HEADER, '', ...items].join('\n')
215}
216
217async function submit($: Engine) {
218  // Taken in the same write that empties the list: a second 0 finds nothing to send, and a
219  // comment saved while the prompt is built stays for the next send.
220  let list: Comment[] = []
221  await update($, comments, now => ((list = now), []))
222  if (list.length === 0) {
223    $.ui.toast('보낼 코멘트가 없습니다.')
224    return
225  }
226  const putBack = () => update($, comments, now => [...list, ...now])
227  let text: string
228  try {
229    text = await buildPrompt($, list)
230  } catch {
231    await putBack()
232    $.ui.toast('프롬프트를 만들지 못했습니다.')
233    return
234  }
235  const undo = async (message: string) => {
236    await putBack()
237    $.ui.toast(message)
238  }
239  // Resolves only when the turn starts, so it is not awaited while Claude may be working.
240  void $.prompt.submit({ text, asUser: true }).then(
241    result => ('drop' in result && result.drop !== undefined ? undo(`전송이 거절되었습니다: ${result.drop}`) : undefined),
242    () => undo('전송하지 못했습니다.'),
243  )
244}
245
246async function lastReply($: Engine): Promise<string | null> {
247  const messages = await $.session.messages()
248  for (let i = messages.length - 1; i >= 0; i--) {
249    const m = messages[i]!
250    if (m.role === 'assistant' && m.text.trim() !== '') return m.text
251  }
252  return null
253}
254
255async function openDoc($: Engine, source: Source) {
256  await update($, view, (): View => ({ screen: 'doc', source, cursor: 0, anchor: null, composing: null, focused: null }))
257}
258
259async function openReply($: Engine) {
260  const text = await lastReply($)
261  if (text === null) $.ui.toast('Claude의 답변이 아직 없습니다.')
262  else await openDoc($, { kind: 'reply', text })
263}
264
265// The Buttons the pane drew last, in order, and whether the next try at putting the ring
266// back is the one retry a denied try gets. See pinRing.
267let lastRing = ''
268let retrying = false
269
270// Opens the file a typed path names: the recent turn's diff if that turn changed it, else the
271// whole file, and keeps it in the opened files. Says why when it opens nothing.
272async function openPath($: Engine, typed: string): Promise<string | null> {
273  const given = expand(typed, await $.session.cwd(), (await $.env.get('HOME')) ?? '')
274  const stat = await statPath($, given)
275  if (stat === undefined) return `${typed} 파일이 없습니다.`
276  if (stat.kind !== 'file') return `${typed} 은(는) 파일이 아닙니다.`
277  const path = stat.realPath ?? given
278  const at = await $.clock.now()
279  await update($, opened, list => [{ path, at }, ...list.filter(f => f.path !== path)].slice(0, OPENED_MAX))
280  const changed = (await read($, recent))?.files.find(f => f.path === path)
281  await openDoc($, changed ? { kind: 'diff', path, base: changed.base } : { kind: 'file', path })
282  return null
283}
284
285// `recent`: a file this session changed or opened by path, marked ↺.
286type Offer = { label: string; open: string; isDir: boolean; recent: boolean }
287
288// What a typed path offers. With nothing typed, the files this session changed or opened by
289// path, latest first, those the list shows left out (the recent turn's and those waiting to be
290// sent). Once a path is typed, the entries of its directory that complete it, read anew each
291// time so a new file shows at once. A directory's offer fills the input, a file's opens.
292async function pathOffers($: Engine, typed: string, cwd: string, home: string): Promise<Offer[]> {
293  if (typed !== '') {
294    const split = splitTyped(typed)
295    const entries = await $.fs.list(expand(split.dir, cwd, home)).catch(() => [])
296    return completions(split, entries, OFFERS_MAX).map(c => ({ label: c.text, open: c.text, isDir: c.isDir, recent: false }))
297  }
298  const listed = new Set([
299    ...((await read($, recent))?.files.map(f => f.path) ?? []),
300    ...(await read($, comments)).filter(c => c.kind !== 'reply').map(c => c.path),
301  ])
302  const latest = new Map<string, number>()
303  for (const f of [...(await read($, edited)), ...(await read($, opened))]) {
304    if (!listed.has(f.path)) latest.set(f.path, Math.max(latest.get(f.path) ?? 0, f.at))
305  }
306  return [...latest]
307    .sort((a, b) => b[1] - a[1])
308    .slice(0, OFFERS_MAX)
309    .map(([path]) => ({ label: tilde(relative(path, cwd), home), open: path, isDir: false, recent: true }))
310}
311
312type PathInput = Extract<View, { screen: 'list' }>['path']
313
314async function setPath($: Engine, path: PathInput) {
315  await update($, view, v => (v.screen === 'list' ? { ...v, path } : v))
316}
317
318async function submitPath($: Engine, typed: string) {
319  const text = typed.trim()
320  // An empty Enter closes the input, as it cancels a new comment.
321  if (text === '') return setPath($, undefined)
322  const error = await openPath($, text)
323  if (error !== null) {
324    await setPath($, { text: typed, error })
325    focus($, 'path-input')
326  }
327}
328
329async function pickOffer($: Engine, offer: Offer) {
330  if (!offer.isDir) return submitPath($, offer.open)
331  await setPath($, { text: offer.open, error: null })
332  focus($, 'path-input')
333}
334
335async function openReview($: Engine, args: string) {
336  const arg = args.trim()
337  if (arg === '') {
338    await update($, view, (): View => ({ screen: 'list' }))
339  } else {
340    const error = await openPath($, arg)
341    if (error !== null) return { text: error }
342  }
343  // Above the prompt the pane asks for 20 rows rather than a third of the screen.
344  await $.ui.open({ id: PANE, title: 'redpen', focus: true, rows: 20 })
345  return {}
346}
347
348const isLine = (row: Row | undefined) => row !== undefined && row.kind !== 'gap'
349
350function step(rows: Row[], from: number, by: number) {
351  let i = from + by
352  while (i >= 0 && i < rows.length && !isLine(rows[i])) i += by
353  return i < 0 || i >= rows.length ? from : i
354}
355
356function normalize(rows: Row[], cursor: number) {
357  const c = Math.max(0, Math.min(cursor, rows.length - 1))
358  if (isLine(rows[c])) return c
359  const down = step(rows, c, 1)
360  return down !== c ? down : step(rows, c, -1)
361}
362
363async function setDoc($: Engine, fn: (v: Doc) => Doc) {
364  await update($, view, v => (v.screen === 'doc' ? fn(v) : v))
365}
366
367// `{ deny }` when the ring did not move (the pane not holding the keyboard, the element not
368// drawn in time, another move first); null when the engine could not take the call at all.
369const tryFocus = ($: Engine, key: string) => $.ui.focus({ requestId: PANE, key }).catch(() => null)
370
371const focus = ($: Engine, key: string) => void tryFocus($, key)
372
373// The pane keeps the ring on a Button by its place among the Buttons drawn, not by its key:
374// when a window gains or loses a Button above the cursor's, the ring lands on a neighbour and
375// no ui.focus is raised. Whenever the drawn Buttons (`ring`, their keys in order) change, put
376// the ring back on `start` once this drawing is on screen. A denied try gets one more after a
377// fresh drawing, aimed at the cursor as it stands then.
378function pinRing($: Engine, ring: string, start: string | null, isFocused: boolean) {
379  if (ring !== lastRing && isFocused && start !== null) {
380    const key = start
381    const retry = retrying
382    retrying = false
383    void $.clock
384      .sleep(0)
385      .then(() => tryFocus($, key))
386      .then(result => {
387        if (result?.deny === undefined || retry) return
388        retrying = true
389        lastRing = ''
390        $.ui.invalidate('ui.render')
391      })
392  }
393  lastRing = ring
394}
395
396// Fits a path into `width` cells, keeping the file name: the home directory becomes ~,
397// and the directories that do not fit give way to one … from the middle.
398// The home directory as ~.
399const tilde = (path: string, home: string) => (home !== '' && path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path)
400
401function fitPath(path: string, home: string, width: number) {
402  const shown = tilde(path, home)
403  if (cells(shown) <= width) return shown
404  const parts = shown.split('/')
405  const name = parts.pop()!
406  const tail = `…/${name}`
407  if (cells(tail) > width) return cut(name, width)
408  let head = ''
409  for (const part of parts) {
410    if (cells(`${head}${part}/${tail}`) > width) break
411    head += `${part}/`
412  }
413  return head + tail
414}
415
416// Rows a wrapping row of items takes: each item `widths[i]` cells, `gap` cells apart.
417function flowRows(widths: number[], gap: number, width: number) {
418  let rows = 1
419  let used = 0
420  for (const w of widths) {
421    if (used > 0 && used + gap + w > width) {
422      rows++
423      used = 0
424    }
425    used += (used > 0 ? gap : 0) + w
426  }
427  return rows
428}
429
430// Rows the pane's keys take at `width` columns, laid out as the hotkeys are.
431const paneKeyRows = (width: number) => flowRows(PANE_KEYS.map(hintWidth), 2, width)
432
433function layout(v: Doc, all: Comment[], doc: Loaded) {
434  const { rows, lines } = doc
435  const cursor = normalize(rows, v.cursor)
436  const [selFrom, selTo] = v.anchor === null ? [cursor, cursor] : [Math.min(v.anchor, cursor), Math.max(v.anchor, cursor)]
437
438  const attached = new Map<number, { c: Comment; start: number }[]>()
439  const away: { c: Comment; why: string }[] = []
440  // A comment sits on its last line: by new line number, or a deleted line's old one.
441  const byNew = new Map<number, number>()
442  const byOld = new Map<number, number>()
443  rows.forEach((r, i) => {
444    if (r.kind === 'gap') return
445    if (r.newLine !== undefined && !byNew.has(r.newLine)) byNew.set(r.newLine, i)
446    if (r.kind === 'del' && r.oldLine !== undefined && !byOld.has(r.oldLine)) byOld.set(r.oldLine, i)
447  })
448  const path = docPath(v.source)
449  for (const c of all.filter(c => c.path === path)) {
450    const start = locate(c, c.kind === 'reply' && v.source.kind !== 'reply' ? undefined : lines)
451    const end = start === null ? null : start + c.end - c.start
452    const row = end === null ? -1 : ((c.side === 'old' ? byOld : byNew).get(end) ?? -1)
453    if (row === -1) away.push({ c, why: start === null ? '위치 불명' : `${span(start, c)}행, 표시 범위 밖` })
454    else attached.set(row, [...(attached.get(row) ?? []), { c, start: start! }])
455  }
456
457  // Line numbers rise down the rows, so a selection's first and last numbers bound it.
458  const selected = rows.slice(selFrom, selTo + 1).filter(r => r.kind !== 'gap')
459  const newLines = selected.flatMap(r => (r.newLine === undefined ? [] : [r.newLine]))
460  const range =
461    newLines.length > 0
462      ? { side: 'new' as const, start: newLines[0]!, end: newLines[newLines.length - 1]! }
463      : { side: 'old' as const, start: selected[0]?.oldLine ?? 0, end: selected[selected.length - 1]?.oldLine ?? 0 }
464  // The row a comment on the range sits on, by the same rule the comments above are placed.
465  const endRow = (range.side === 'old' ? byOld : byNew).get(range.end) ?? -1
466  const excerpt =
467    range.side === 'new'
468      ? lines.slice(range.start - 1, range.end)
469      : selected.filter(r => r.kind === 'del').map(r => r.text)
470  return { doc, rows, lines, cursor, selFrom, selTo, attached, away, range, endRow, excerpt }
471}
472
473const lineSpan = (r: { start: number; end: number }) => (r.end === r.start ? `${r.start}` : `${r.start}-${r.end}`)
474
475async function compose($: Engine, composing: Composing) {
476  await setDoc($, d => ({ ...d, composing }))
477  focus($, 'comment-input')
478}
479
480async function save($: Engine, text: string) {
481  const v = await read($, view)
482  if (v.screen !== 'doc' || v.composing === null) return
483  const composing = v.composing
484  const body = text.trim()
485  if ('editId' in composing) {
486    const { editId } = composing
487    // Emptying a comment's text and saving deletes it.
488    await update($, comments, list =>
489      body === '' ? list.filter(c => c.id !== editId) : list.map(c => (c.id === editId ? { ...c, text: body } : c)),
490    )
491  } else if ('lines' in composing && body !== '') {
492    const comment: Comment = {
493      id: Math.random().toString(36).slice(2, 10),
494      kind: v.source.kind,
495      path: docPath(v.source),
496      ...composing.lines,
497      text: body,
498      at: await $.clock.now(),
499    }
500    await update($, comments, list => [...list, comment])
501  }
502  await setDoc($, d => ({ ...d, composing: null, anchor: null, focused: 'editId' in composing ? null : d.focused }))
503  focus($, `L${normalize((await shown($, v)).rows, v.cursor)}`)
504}
505
506// Enter on (or a click of) a line number: ▶ moves there and the line's comment opens. One
507// comment per line, on the selection's last line: that line's comment opens for editing if it
508// has one; else the line or range gets a new one, its lines and excerpt taken now from the
509// rows on screen. One write, since a drawing in between would read the file again.
510async function pressLine($: Engine, row: number) {
511  const v = await read($, view)
512  if (v.screen !== 'doc') return
513  const at: Doc = { ...v, cursor: row, focused: null }
514  const l = layout(at, await read($, comments), await shown($, at))
515  const here = l.attached.get(l.endRow)?.[0]?.c
516  const composing: Composing = here ? { editId: here.id } : { lines: { ...l.range, excerpt: l.excerpt } }
517  await setDoc($, d => ({ ...d, cursor: row, focused: null, composing }))
518  focus($, 'comment-input')
519}
520
521// Switches a diff between its changes alone and the whole file, ▶ staying on its line.
522async function toggleWhole($: Engine) {
523  const v = await read($, view)
524  if (v.screen !== 'doc' || v.composing !== null || v.source.kind !== 'diff') return
525  const { rows } = await shown($, v)
526  const at = rows[normalize(rows, v.cursor)]
527  const whole = !v.whole
528  const next = (await loadDoc($, v.source, whole)).rows
529  const same = (r: Row) =>
530    at !== undefined && at.kind !== 'gap' && r.kind === at.kind && r.newLine === at.newLine && r.oldLine === at.oldLine
531  let cursor = next.findIndex(same)
532  if (cursor === -1) {
533    // The line folds away with the changes alone: ▶ goes to the changed line nearest it in the
534    // whole file, the upper one of two as near. Both drawings come from one diff, so a row's
535    // kind and numbers name the same line in each.
536    const id = (r: Row) => (r.kind === 'gap' ? '' : `${r.kind}:${r.newLine}:${r.oldLine}`)
537    const place = new Map(rows.map((r, i) => [id(r), i]))
538    const from = normalize(rows, v.cursor)
539    const distance = (r: Row) => Math.abs((place.get(id(r)) ?? Infinity) - from)
540    next.forEach((r, i) => {
541      if ((r.kind === 'add' || r.kind === 'del') && (cursor === -1 || distance(r) < distance(next[cursor]!))) cursor = i
542    })
543  }
544  cursor = Math.max(0, cursor)
545  await setDoc($, d => ({ ...d, whole, cursor, anchor: null, focused: null }))
546}
547
548async function toggleRange($: Engine) {
549  const v = await read($, view)
550  if (v.screen !== 'doc' || v.composing !== null) return
551  const { rows } = await shown($, v)
552  await setDoc($, d => ({ ...d, anchor: d.anchor === null ? normalize(rows, d.cursor) : null }))
553}
554
555// 0 on the list or a document: the comments to be sent, for a second 0 to send. With none,
556// it says so and stays.
557async function openSend($: Engine) {
558  if ((await read($, comments)).length === 0) {
559    $.ui.toast('보낼 코멘트가 없습니다.')
560    return
561  }
562  await update($, view, (v): View => (v.screen === 'send' ? v : { screen: 'send', editing: null, from: v }))
563}
564
565// 0 on the send screen: everything goes, and the list comes back.
566async function sendAll($: Engine) {
567  await submit($)
568  await update($, view, (): View => ({ screen: 'list' }))
569}
570
571async function setSend($: Engine, fn: (v: SendView) => SendView) {
572  await update($, view, v => (v.screen === 'send' ? fn(v) : v))
573}
574
575// Enter on (or a click of) a comment's number: its text opens for editing where it is.
576async function editSent($: Engine, id: string) {
577  await setSend($, s => ({ ...s, cursor: id, editing: id }))
578  focus($, 'comment-input')
579}
580
581// Saves the text edited on the send screen; emptied, the comment goes, ▶ to the one after it
582// (or before it, the last gone). With none left, the screen 0 was pressed on comes back.
583async function saveSent($: Engine, text: string) {
584  const v = await read($, view)
585  if (v.screen !== 'send' || v.editing === null) return
586  const id = v.editing
587  const body = text.trim()
588  let cursor = id
589  if (body === '') {
590    const order = (await arrange($, await read($, comments))).map(({ c }) => c.id)
591    const i = order.indexOf(id)
592    cursor = order[i + 1] ?? order[i - 1] ?? id
593    await update($, comments, list => list.filter(c => c.id !== id))
594  } else {
595    await update($, comments, list => list.map(c => (c.id === id ? { ...c, text: body } : c)))
596  }
597  if ((await read($, comments)).length === 0) {
598    await update($, view, () => v.from)
599    return
600  }
601  await setSend($, s => ({ ...s, cursor, editing: null }))
602  focus($, `S${cursor}`)
603}
604
605// 2 on the send screen: the document the comment is on, ▶ on the comment. A file the recent
606// turn changed opens as that diff, any other whole; a comment on a reply opens on the last.
607async function openComment($: Engine, id: string) {
608  const all = await read($, comments)
609  const c = all.find(x => x.id === id)
610  if (c === undefined) return
611  let source: Source
612  if (c.kind === 'reply') {
613    const text = await lastReply($)
614    if (text === null) return $.ui.toast('Claude의 답변이 아직 없습니다.')
615    source = { kind: 'reply', text }
616  } else {
617    const changed = (await read($, recent))?.files.find(f => f.path === c.path)
618    source = changed ? { kind: 'diff', path: c.path, base: changed.base } : { kind: 'file', path: c.path }
619  }
620  const doc: Doc = { screen: 'doc', source, cursor: 0, anchor: null, composing: null, focused: id }
621  // A comment not on screen (its lines folded or gone) is listed above the lines, ▶ on it there.
622  const row = [...layout(doc, all, await loadDoc($, source)).attached].find(([, list]) => list.some(x => x.c.id === id))?.[0]
623  await update($, view, (): View => ({ ...doc, cursor: row ?? 0 }))
624}
625
626export const register: Register = on => {
627  on('session.start', async ($, e, next) => {
628    await $.command.register({
629      name: 'redpen',
630      description: '마지막 턴의 변경이나 파일을 줄 단위로 리뷰하고 코멘트를 한 번에 보냄',
631      argumentHint: '[path]',
632    })
633    return next(e)
634  })
635
636  on('command.run', { command: 'redpen' }, ($, e) => openReview($, e.args))
637
638  // In the prompt, /redpen <path> completes the path typed: the session's files that hold it and
639  // the entries of its directory join the typeahead, a directory's taken to type on in.
640  on('prompt.autocomplete', async ($, e, next) => {
641    const answered = await next(e)
642    if (e.text.slice(0, e.start).trimEnd() !== '/redpen') return answered
643    const offers = await pathOffers($, e.token, await $.session.cwd(), (await $.env.get('HOME')) ?? '')
644    return {
645      suggestions: [
646        ...answered.suggestions,
647        ...offers.map(o => ({ text: o.label, ...(o.isDir ? { description: '디렉토리' } : {}) })),
648      ],
649    }
650  })
651
652  // Edit, Write and NotebookEdit say what they changed; a file the list knows that Bash or an
653  // MCP tool changed shows only in its content. So what each known file holds is kept as the
654  // turn begins, and compared as the turn ends.
655  on('turn.start', async ($, e, next) => {
656    await update($, turn, () => e.turnId)
657    const paths = await known($)
658    const texts = await Promise.all(paths.map(path => $.fs.read(path).catch(() => null)))
659    await update($, snapshot, () => paths.flatMap((path, i) => (texts[i] === null ? [] : [{ path, text: texts[i]! }])))
660    return next(e)
661  })
662
663  on('turn.complete', async ($, e, next) => {
664    if (e.agentId === undefined) {
665      const held = await read($, snapshot)
666      await update($, snapshot, () => [])
667      const turnId = await read($, turn)
668      const r = await read($, recent)
669      const recorded = r !== null && r.turnId === turnId ? r.files.map(f => f.path) : []
670      const now = await Promise.all(held.map(({ path }) => $.fs.read(path).catch(() => null)))
671      for (const [i, { path, text }] of held.entries()) {
672        if (now[i] === null) {
673          if ((await statPath($, path)) === undefined) await forget($, path)
674        } else if (now[i] !== text && !recorded.includes(path)) {
675          // A file the turn's own tools recorded keeps the content before their first change.
676          await record($, path, text)
677        }
678      }
679    }
680    return next(e)
681  })
682
683  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
684    const ran = await next(e)
685    if (ran.deny === undefined && ran.isError !== true && ran.result.staged !== true) {
686      await recordEdit($, ran.result.filePath, ran.result.originalFile ?? '')
687    }
688    return ran
689  }).catch(($, e, next) => next(e))
690
691  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
692    const ran = await next(e)
693    if (ran.deny === undefined && ran.isError !== true && ran.result.staged !== true) {
694      await recordEdit($, ran.result.filePath, ran.result.type === 'create' ? '' : ran.result.originalFile)
695    }
696    return ran
697  }).catch(($, e, next) => next(e))
698
699  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
700    const ran = await next(e)
701    if (ran.deny === undefined && ran.isError !== true && ran.result.error === undefined) {
702      await recordEdit($, ran.result.notebook_path, ran.result.original_file)
703    }
704    return ran
705  }).catch(($, e, next) => next(e))
706
707  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
708    // The footer keys answer their hotkeys only; the ring stays on the lines.
709    if (e.element?.startsWith('key-')) return { deny: 'redpen: 단축키 안내는 포커스를 받지 않습니다.' }
710    // The ring moves first, ▶ after it, and only where it landed. Moving ▶ first redraws the
711    // window before the move, and the move then lands by its place among the redrawn Buttons.
712    const moved = await next(e)
713    if (moved.deny !== undefined) return moved
714    // ▶ is where the ring is: one position, so Enter always acts where ▶ points.
715    const line = /^L(\d+)$/.exec(e.element ?? '')
716    const comment = /^C(.+)$/.exec(e.element ?? '')
717    if (line) await setDoc($, v => ({ ...v, cursor: Number(line[1]), focused: null }))
718    // The list keeps its own cursor, so its window can follow the ring.
719    const file = /^F(\d+)$/.exec(e.element ?? '')
720    const entry = e.element === 'reply' ? 0 : file ? Number(file[1]) + 1 : null
721    if (entry !== null) await update($, view, v => (v.screen === 'list' ? { ...v, cursor: entry, at: undefined } : v))
722    // The send screen keeps the comment the ring is on, so its window can follow the ring.
723    const sending = /^S(.+)$/.exec(e.element ?? '')
724    if (sending) await setSend($, s => ({ ...s, cursor: sending[1]! }))
725    if (comment) {
726      const v = await read($, view)
727      if (v.screen === 'doc') {
728        // The cursor goes to the comment's line, so the title and a range follow it.
729        const l = layout(v, await read($, comments), await shown($, v))
730        const row =[...l.attached].find(([, list]) => list.some(({ c }) => c.id === comment[1]))?.[0]
731        await setDoc($, d => ({ ...d, cursor: row ?? d.cursor, focused: comment[1]! }))
732      }
733    }
734    return moved
735  })
736
737  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
738    if (e.surface === 'mobile') {
739      const { Text } = $.ui.resolve(e)
740      return <Text dimColor>redpen은 터미널과 데스크톱에서만 동작합니다.</Text>
741    }
742    const { Box, Text, Button, Input } = $.ui.resolve(e)
743    const width = e.props.bodyColumns
744    const bodyRows = e.props.scroll.bodyRows
745    const v = await read($, view)
746    const all = await read($, comments)
747    const cwd = await $.session.cwd()
748
749    const header = (
750      <Text bold wrap="truncate-end">
751        Redpen
752      </Text>
753    )
754    // A described key, as Texts: a Button would join the ring that ↑ and ↓ move along.
755    const keyHint = ([key, text]: KeyHint) => (
756      <Box>
757        <Text color="suggestion">{key}</Text>
758        <Text>{`: ${text}`}</Text>
759      </Box>
760    )
761    const paneKeys = (
762      <Box flexWrap="wrap" columnGap={2}>
763        {PANE_KEYS.map(keyHint)}
764      </Box>
765    )
766    const paneKeysRows = paneKeyRows(width)
767    // Too short to draw a screen in: one row saying so (and what must stay, as an open input).
768    const tooShort = (stays?: JSX.Element) => {
769      lastRing = ''
770      return (
771        <Box flexDirection="column">
772          <Text color="warning" wrap="truncate-end">
773            pane 높이가 부족합니다. 창을 키우거나 Ctrl+X X로 닫으세요.
774          </Text>
775          {stays}
776        </Box>
777      )
778    }
779
780    if (v.screen === 'send') {
781      // The comments as they will be sent, numbered as the prompt numbers them.
782      const items = await arrange($, all)
783      // Sent or deleted elsewhere meanwhile: nothing left but the way back.
784      if (items.length === 0) {
785        lastRing = ''
786        return (
787          <Box flexDirection="column">
788            <Text dimColor>보낼 코멘트가 없습니다.</Text>
789            <Button plain key="key-1" hotkey="1" label="뒤로가기" onPress={() => void update($, view, w => (w.screen === 'send' ? w.from : w))} />
790          </Box>
791        )
792      }
793      const at = Math.max(0, items.findIndex(({ c }) => c.id === v.cursor))
794      const keyOf = (i: number) => `S${items[i]!.c.id}`
795      const editing = all.find(c => c.id === v.editing)
796      // Each comment in one of three forms, the room deciding: whole (its place, the first line
797      // it is on, its text split to the pane's width), brief (its place, its text in one row),
798      // or one row holding both. A place whose lines are gone is drawn as a warning.
799      type Form = 'whole' | 'brief' | 'line'
800      const textWidth = Math.max(1, width - 4)
801      const textOf = (i: number) => items[i]!.c.text.replace(/\n/g, ' ')
802      const height = (i: number, form: Form) =>
803        form === 'line' ? 1 : form === 'brief' ? 2 : 1 + (items[i]!.c.excerpt.length > 0 ? 1 : 0) + wrapRows(textOf(i), textWidth).length
804      const textStyle = { color: 'suggestion', wrap: 'truncate-end' } as const
805      const item = (i: number, form: Form) => {
806        const { c, start } = items[i]!
807        const head = (
808          <Box>
809            <Text color="claude">{i === at ? '▶' : ' '}</Text>
810            <Button
811              plain
812              key={keyOf(i)}
813              autoFocus={(i === at && editing === undefined) || undefined}
814              dimColor={i !== at}
815              label={`${i + 1}.`}
816              onPress={() => editSent($, c.id)}
817            />
818            <Text color={start === null ? 'warning' : undefined} wrap="truncate-end">{` ${where(c, start, cwd)}`}</Text>
819            {form === 'line' && <Text {...textStyle}>{` · ${textOf(i)}`}</Text>}
820          </Box>
821        )
822        if (form === 'line') return [head]
823        const excerpt = form === 'whole' && c.excerpt.length > 0 ? [<Text dimColor wrap="truncate-end">{`   > ${c.excerpt[0]}`}</Text>] : []
824        const text = form === 'whole' ? wrapRows(textOf(i), textWidth) : [textOf(i)]
825        return [head, ...excerpt, ...text.map(row => <Text {...textStyle}>{`   ${row}`}</Text>)]
826      }
827
828      // The footer: the input while a comment is edited, else the keys.
829      const editTitle = '코멘트 수정 · 모두 지우고 Enter 삭제'
830      const keys: [string, string, () => unknown][] = [
831        ['1', '뒤로가기', () => update($, view, w => (w.screen === 'send' ? w.from : w))],
832        ['2', '문서 열기', () => openComment($, items[at]!.c.id)],
833        ['0', `전송 (${all.length})`, () => sendAll($)],
834      ]
835      const keyWidths = keys.map(([hotkey, label]) => cells(`${hotkey}: ${label}`))
836      const footerRows = (hint: boolean) =>
837        editing !== undefined
838          ? wrapRows(editTitle, width).length + 1
839          : flowRows([...(hint ? SEND_KEYS.map(hintWidth) : []), ...keyWidths], 2, width)
840      const footer = (hint: boolean) =>
841        editing !== undefined ? (
842          <Box flexDirection="column">
843            <Text>{editTitle}</Text>
844            <Input
845              key="comment-input"
846              placeholder="코멘트 입력 후 Enter"
847              value={editing.text}
848              submitLabel="저장"
849              autoFocus
850              onSubmit={value => saveSent($, value)}
851            />
852          </Box>
853        ) : (
854          <Box flexWrap="wrap" columnGap={2}>
855            {hint && SEND_KEYS.map(keyHint)}
856            {keys.map(([hotkey, label, run]) => (
857              <Button plain key={`key-${hotkey}`} hotkey={hotkey} label={label} onPress={() => void run()} />
858            ))}
859          </Box>
860        )
861
862      // As on the other screens, the tree must never be taller than the pane. The plans, tried
863      // in order: every comment whole, then brief; then a window of brief comments around the
864      // cursor, then of one-row ones, the window holding the cursor's and one past each end.
865      // The question under the header always shows; the blank row under it gives way first.
866      type Parts = { header: boolean; gap: boolean; hint: boolean; keys: boolean }
867      const chrome = (p: Parts) =>
868        (p.header ? 1 : 0) + 1 + (p.gap ? 1 : 0) + footerRows(p.hint) + (p.keys ? 1 + paneKeysRows : 0)
869      const every: Parts = { header: true, gap: true, hint: true, keys: true }
870      const lean: Parts = { ...every, gap: false }
871      const total = items.length
872      const least = Math.min(3, total)
873      const plans: [Form, Parts, boolean][] = [
874        ['whole', every, false],
875        ['whole', lean, false],
876        ['brief', lean, false],
877        ['brief', lean, true],
878        ['line', lean, true],
879        ['line', { ...lean, keys: false }, true],
880        ['line', { ...lean, keys: false, header: false }, true],
881        ['line', { header: false, gap: false, hint: false, keys: false }, true],
882      ]
883      const indexes = Array.from({ length: total }, (_, i) => i)
884      // One spare row in case the footer wraps one row more than counted.
885      const fits = ([form, p, windowed]: [Form, Parts, boolean]) => {
886        const room = bodyRows - chrome(p) - 1
887        return windowed ? room >= least * height(0, form) : indexes.reduce((n, i) => n + height(i, form), 0) <= room
888      }
889      const plan = plans.find(fits)
890      if (plan === undefined) return tooShort(editing !== undefined ? footer(false) : undefined)
891      const [form, parts, windowed] = plan
892      const room = windowed ? Math.min(total, Math.floor((bodyRows - chrome(parts) - 1) / height(0, form))) : total
893      const top = Math.max(0, Math.min(at - Math.floor((room - 1) / 2), total - room))
894      const shownItems = Array.from({ length: room }, (_, k) => top + k)
895      pinRing($, shownItems.map(keyOf).join(' '), editing === undefined ? keyOf(at) : null, e.props.isFocused)
896
897      return (
898        <Box flexDirection="column">
899          {parts.header && header}
900          <Text bold wrap="truncate-end">
901            전송하시겠습니까?
902          </Text>
903          {parts.gap && <Text> </Text>}
904          {shownItems.flatMap(i => item(i, form))}
905          {parts.keys && (
906            <Text dimColor wrap="truncate-end">
907              {'-'.repeat(width)}
908            </Text>
909          )}
910          {footer(parts.hint)}
911          {parts.keys && paneKeys}
912        </Box>
913      )
914    }
915
916    if (v.screen === 'list') {
917      // Two parts: the files the recent turn changed, each opening as that turn's diff; then the
918      // other files with comments, waiting to be sent, in the order they got their first comment,
919      // each opening whole. A file keeps its place as more comments come, and a new one goes
920      // last. The session's other files are offered by 1, as files to open.
921      const changed = (await read($, recent))?.files ?? []
922      const firstComment = new Map<string, number>()
923      for (const c of all) {
924        if (c.kind !== 'reply') firstComment.set(c.path, Math.min(firstComment.get(c.path) ?? Infinity, c.at ?? 0))
925      }
926      const earlier = [...firstComment.keys()]
927        .filter(path => !changed.some(f => f.path === path))
928        .sort((a, b) => firstComment.get(a)! - firstComment.get(b)!)
929      const entries: { path: string; source: Source }[] = [
930        ...changed.map(f => ({ path: f.path, source: { kind: 'diff', path: f.path, base: f.base } as Source })),
931        ...earlier.map(path => ({ path, source: { kind: 'file', path } as Source })),
932      ]
933      // What each entry says after its path: a diff's lines added and removed (a file the turn
934      // created as new), then its comments, when it has any.
935      const counts = new Map<string, number>()
936      for (const c of all) counts.set(c.path, (counts.get(c.path) ?? 0) + 1)
937      const changes = new Map<string, string>()
938      const tallies = await Promise.all(changed.map(f => changeCounts($, f)))
939      changed.forEach((f, i) => {
940        const t = tallies[i]
941        if (t) changes.set(f.path, f.base === '' ? `신규 +${t.added}` : `+${t.added} -${t.removed}`)
942      })
943      const suffix = (path: string) =>
944        [changes.get(path), counts.has(path) ? `코멘트 ${counts.get(path)}` : undefined]
945          .flatMap(part => (part === undefined ? [] : [` · ${part}`]))
946          .join('')
947      const home = (await $.env.get('HOME')) ?? ''
948      // The counts always show; the path takes the room left.
949      const entryLabel = (path: string) =>
950        `${fitPath(relative(path, cwd), home, Math.max(1, width - 1 - cells(suffix(path))))}${suffix(path)}`
951      // The entries the ring moves along, one row each: the reply, then the files. Back from a
952      // document, the ring starts on the entry it opened from, wherever that entry now stands.
953      const total = 1 + entries.length
954      // Back from a document the list does not show (one opened by 1), the ring starts on the reply.
955      const back = v.at === REPLY ? 0 : entries.findIndex(x => x.path === v.at) + 1
956      const cursor = v.at !== undefined && (v.at === REPLY || back > 0) ? back : Math.max(0, Math.min(v.cursor ?? 0, total - 1))
957      const keyOf = (k: number) => (k === 0 ? 'reply' : `F${k - 1}`)
958      const typing = v.path
959      const offers = typing === undefined ? [] : await pathOffers($, typing.text, cwd, home)
960      // The ring starts on the cursor's entry, as it starts on the cursor line in a document;
961      // on the path input while it is open.
962      const item = (k: number) => (
963        <Button
964          plain
965          key={keyOf(k)}
966          autoFocus={(k === cursor && typing === undefined) || undefined}
967          label={k === 0 ? cut(`${REPLY}${suffix(REPLY)}`, Math.max(1, width - 1)) : entryLabel(entries[k - 1]!.path)}
968          onPress={() => (k === 0 ? openReply($) : openDoc($, entries[k - 1]!.source))}
969        />
970      )
971
972      // As in a document, the tree must never be taller than the pane, or the arrows scroll it.
973      // The plans below, tried in order: the list whole, then its entries in a window around
974      // the cursor, the window keeping five entries while the pane's keys show, then the least
975      // ↑ and ↓ need, the cursor's entry and one past each end of it.
976      type Parts = { header: boolean; gaps: boolean; hint: boolean; keys: boolean }
977      const pathTitle = typing?.error ?? '파일 열기 · 경로 입력 또는 ↓로 선택 · 빈 Enter 취소'
978      const pathTitleRows = wrapRows(pathTitle, width).length
979      const keyRows = (hint: boolean) =>
980        flowRows([...(hint ? LIST_KEYS.map(hintWidth) : []), cells('1: 파일 열기'), cells(`0: 전송 (${all.length})`)], 2, width)
981      const [withHint, withoutHint] = [keyRows(true), keyRows(false)]
982      const footerRows = (p: Parts) =>
983        typing !== undefined ? pathTitleRows + 1 + (p.keys ? offers.length : 0) : p.hint ? withHint : withoutHint
984      // Each part's title, the first's note when it is empty; a blank row before the second.
985      const titleRows = (changed.length === 0 ? 2 : 1) + (earlier.length > 0 ? 1 : 0)
986      const gapRows = earlier.length > 0 ? 4 : 3
987      const chrome = (p: Parts, windowed: boolean) =>
988        (p.header ? 1 : 0) +
989        (p.gaps ? gapRows : 0) +
990        (windowed ? 0 : titleRows) +
991        footerRows(p) +
992        (p.keys ? paneKeysRows : 0)
993      const every: Parts = { header: true, gaps: true, hint: true, keys: true }
994      const bare: Parts = { ...every, gaps: false }
995      const least = Math.min(3, total)
996      const plans: [Parts, boolean, number][] = [
997        [every, false, total],
998        [bare, false, total],
999        [bare, true, Math.min(5, total)],
1000        [{ ...bare, keys: false }, true, least],
1001        [{ ...bare, keys: false, header: false }, true, least],
1002        [{ header: false, gaps: false, hint: false, keys: false }, true, least],
1003      ]
1004      // One spare row in case the footer wraps one row more than counted.
1005      const plan = plans.find(([p, windowed, need]) => bodyRows - chrome(p, windowed) - 1 >= need)
1006      if (plan === undefined) return tooShort()
1007      const [parts, windowed] = plan
1008      // The window: as many entries as the room holds, the cursor's away from its ends.
1009      const room = windowed ? Math.min(total, bodyRows - chrome(parts, true) - 1) : total
1010      const top = Math.max(0, Math.min(cursor - Math.floor((room - 1) / 2), total - room))
1011      const shown = Array.from({ length: room }, (_, k) => top + k)
1012      // While the path input is open the ring is the person's to move, as in a comment input.
1013      pinRing($, shown.map(keyOf).join(' '), typing === undefined ? keyOf(cursor) : null, e.props.isFocused)
1014
1015      return (
1016        <Box flexDirection="column">
1017          {parts.header && header}
1018          {parts.gaps && <Text> </Text>}
1019          {windowed ? (
1020            shown.map(item)
1021          ) : (
1022            <Box flexDirection="column">
1023              {item(0)}
1024              {parts.gaps && <Text> </Text>}
1025              <Text bold>최근 수정</Text>
1026              {changed.length === 0 && <Text dimColor>  없음.</Text>}
1027              {changed.map((_, i) => item(i + 1))}
1028              {earlier.length > 0 && parts.gaps && <Text> </Text>}
1029              {earlier.length > 0 && <Text bold>전송 대기</Text>}
1030              {earlier.map((_, i) => item(changed.length + i + 1))}
1031            </Box>
1032          )}
1033          {parts.gaps && <Text> </Text>}
1034          {typing !== undefined ? (
1035            <Box flexDirection="column">
1036              <Text color={typing.error === null ? undefined : 'warning'}>{pathTitle}</Text>
1037              <Input
1038                key="path-input"
1039                placeholder="경로 입력 후 Enter"
1040                value={typing.text}
1041                submitLabel="열기"
1042                autoFocus
1043                onInput={value => void setPath($, { text: value, error: null })}
1044                onSubmit={value => void submitPath($, value)}
1045              />
1046              {parts.keys &&
1047                offers.map((offer, i) => (
1048                  <Button
1049                    plain
1050                    key={`O${i}`}
1051                    dimColor
1052                    label={cut(`${offer.recent ? '↺' : ' '} ${offer.label}`, Math.max(1, width - 1))}
1053                    onPress={() => void pickOffer($, offer)}
1054                  />
1055                ))}
1056            </Box>
1057          ) : (
1058            <Box flexWrap="wrap" columnGap={2}>
1059              {parts.hint && LIST_KEYS.map(keyHint)}
1060              <Button
1061                plain
1062                key="key-1"
1063                hotkey="1"
1064                label="파일 열기"
1065                onPress={() => void (setPath($, { text: '', error: null }).then(() => focus($, 'path-input')))}
1066              />
1067              <Button plain key="key-0" hotkey="0" label={`전송 (${all.length})`} onPress={() => void openSend($)} />
1068            </Box>
1069          )}
1070          {parts.keys && paneKeys}
1071        </Box>
1072      )
1073    }
1074
1075    const loaded = await loadDoc($, v.source, v.whole === true)
1076    drawn = { key: drawnKey(v), doc: loaded }
1077    const { doc, rows, cursor, selFrom, selTo, attached, away, range } = layout(v, all, loaded)
1078
1079    // Where the ring starts when the pane takes the keyboard (ctrl+x tab, a click):
1080    // the focused comment, else the cursor line. An open Input keeps its own autoFocus.
1081    // ▶ sits on the focused comment's row while a comment row has the ring, else on the cursor line.
1082    const focusedHere = all.some(c => c.id === v.focused)
1083    const start = v.composing !== null ? null : focusedHere ? `C${v.focused}` : `L${cursor}`
1084
1085    // A comment's rows: the marker takes the focus ring, the text in its own color so it
1086    // reads apart from the document, split to the pane's width under the marker.
1087    const commentRows = (c: Comment, indent: string, text: string) =>
1088      wrapRows(`${text}${c.text.replace(/\n/g, ' ')}`, width - cells(indent) - 5)
1089    // A comment as screen rows, one element each.
1090    const commentLines = (c: Comment, indent: string, mark: string, text: string) => {
1091      const style = { color: 'suggestion', bold: c.id === v.focused, wrap: 'truncate-end' } as const
1092      const [first, ...more] = commentRows(c, indent, text)
1093      return [
1094        <Box>
1095          <Text color="claude">{c.id === v.focused ? '▶' : ' '}</Text>
1096          <Text>{indent.slice(1)}</Text>
1097          <Button
1098            plain
1099            key={`C${c.id}`}
1100            autoFocus={start === `C${c.id}` || undefined}
1101            dimColor={c.id !== v.focused}
1102            label={mark}
1103            onPress={() => compose($, { editId: c.id })}
1104          />
1105          <Text {...style}>{` ${first}`}</Text>
1106        </Box>,
1107        ...more.map(row => <Text {...style}>{`${indent}  ${row}`}</Text>),
1108      ]
1109    }
1110
1111    // The footer, with or without the hint before the hotkeys, and the rows each takes.
1112    let footer: (hint: boolean) => JSX.Element
1113    let footerRows: (hint: boolean) => number
1114    const rangeText = lineSpan(range)
1115    if (v.composing !== null) {
1116      const composing = v.composing
1117      const editing = 'editId' in composing ? all.find(c => c.id === composing.editId) : undefined
1118      // The lines fixed when Enter opened the input, which ▶ moving since does not change.
1119      const target = 'lines' in composing ? composing.lines : range
1120      const composeTitle = editing
1121        ? '코멘트 수정 · 모두 지우고 Enter 삭제'
1122        : `코멘트 ${target.side === 'old' ? '(삭제된 줄) ' : ''}L${lineSpan(target)} · 빈 Enter 취소`
1123      const input = (
1124        <Box flexDirection="column">
1125          <Text>{composeTitle}</Text>
1126          <Input
1127            key="comment-input"
1128            placeholder="코멘트 입력 후 Enter"
1129            value={editing?.text ?? ''}
1130            submitLabel="저장"
1131            autoFocus
1132            onSubmit={value => save($, value)}
1133          />
1134        </Box>
1135      )
1136      const inputRows = wrapRows(composeTitle, width).length + 1
1137      footer = () => input
1138      footerRows = () => inputRows
1139    } else {
1140      // Digits, which the Korean input method passes through as typed. Moving and
1141      // commenting take ↑↓ and Enter.
1142      const keys: [string, string, () => unknown][] = [
1143        // Back to the list, the ring on the entry this document opened from.
1144        ['1', '뒤로가기', () => update($, view, (): View => ({ screen: 'list', at: docPath(v.source) }))],
1145        ...(v.source.kind === 'diff'
1146          ? [['2', v.whole ? '바뀐 부분만' : '전체 보기', () => toggleWhole($)] as [string, string, () => unknown]]
1147          : []),
1148        ['3', v.anchor === null ? '범위' : '범위 해제', () => toggleRange($)],
1149        ['0', `전송 (${all.length})`, () => openSend($)],
1150      ]
1151      const keyWidths = keys.map(([hotkey, label]) => cells(`${hotkey}: ${label}`))
1152      const [withHint, withoutHint] = [
1153        flowRows([...DOC_KEYS.map(hintWidth), ...keyWidths], 2, width),
1154        flowRows(keyWidths, 2, width),
1155      ]
1156      footer = hint => (
1157        <Box flexWrap="wrap" columnGap={2}>
1158          {hint && DOC_KEYS.map(keyHint)}
1159          {keys.map(([hotkey, label, run]) => (
1160            <Button plain key={`key-${hotkey}`} hotkey={hotkey} label={label} onPress={() => void run()} />
1161          ))}
1162        </Box>
1163      )
1164      footerRows = hint => (hint ? withHint : withoutHint)
1165    }
1166
1167    const lineNo = (r: Row) => (r.kind === 'gap' ? '' : String(r.newLine ?? r.oldLine))
1168    // reduce, not Math.max(...): spreading a hundred thousand rows overflows the call stack.
1169    const gutter = rows.reduce((n, r) => Math.max(n, lineNo(r).length), 1)
1170    const title = v.source.kind === 'reply' ? REPLY : relative(v.source.path, cwd)
1171    const mine = all.filter(c => c.path === docPath(v.source)).length
1172    // The note and the count of comments that lost their place.
1173    const noteRows = (doc.note ? wrapRows(doc.note, width).length : 0) + (away.length > 0 ? 1 : 0)
1174    const awayLines = away.slice(0, 5).flatMap(({ c, why }) => commentLines(c, '  ', '?', `${why} · `))
1175    // The tree must never be taller than the pane: past it the arrows scroll the pane instead
1176    // of moving the ring, and the ring leaves ▶ behind. The plans below, tried in order, give
1177    // way part by part; the first two keep five lines' room, the rest the ▶ line and one past
1178    // each end of it, the least ↑ and ↓ need to move.
1179    type Parts = { away: boolean; gap: boolean; keys: boolean; notes: boolean; header: boolean; hint: boolean }
1180    const chrome = (p: Parts) =>
1181      (p.header ? 1 : 0) +
1182      1 +
1183      (p.gap ? 1 : 0) +
1184      (p.notes ? noteRows : 0) +
1185      (p.away ? awayLines.length : 0) +
1186      footerRows(p.hint) +
1187      (p.keys ? 1 + paneKeysRows : 0)
1188    const every: Parts = { away: true, gap: true, keys: true, notes: true, header: true, hint: true }
1189    // The blank row under the title gives way first.
1190    const lean: Parts = { ...every, gap: false }
1191    // Up to three lines are needed; counting stops at the third, whatever the file's length.
1192    let least = 0
1193    for (const r of rows) if (isLine(r) && ++least === 3) break
1194    least = Math.max(1, least)
1195    const plans: [Parts, number][] = [
1196      [every, 5],
1197      [lean, 5],
1198      [{ ...lean, away: false }, 5],
1199      [{ ...lean, away: false, keys: false }, least],
1200      [{ ...lean, away: false, keys: false, notes: false }, least],
hooks/diff.ts 79 lines
1export type Row =
2  | { kind: 'gap' }
3  | { kind: 'ctx' | 'add' | 'del'; text: string; oldLine?: number; newLine?: number }
4
5// Above this many LCS cells the changed middle is shown as a block replace.
6const MAX_CELLS = 2_000_000
7
8export function splitLines(text: string): string[] {
9  return text === '' ? [] : text.replace(/\n$/, '').split('\n')
10}
11
12// `context` lines are kept around each change, the rest folded into gaps; Infinity keeps all.
13export function diffRows(before: string[], after: string[], context = 3): Row[] {
14  let head = 0
15  while (head < before.length && head < after.length && before[head] === after[head]) head++
16  let tail = 0
17  while (
18    tail < before.length - head &&
19    tail < after.length - head &&
20    before[before.length - 1 - tail] === after[after.length - 1 - tail]
21  )
22    tail++
23
24  const a = before.slice(head, before.length - tail)
25  const b = after.slice(head, after.length - tail)
26  const ops: ('=' | '-' | '+')[] = []
27  if (a.length * b.length > MAX_CELLS) {
28    // A loop, not push(...): spreading a hundred thousand lines overflows the call stack.
29    for (let i = 0; i < a.length; i++) ops.push('-')
30    for (let j = 0; j < b.length; j++) ops.push('+')
31  } else {
32    const w = b.length + 1
33    const lcs = new Uint32Array((a.length + 1) * w)
34    for (let i = a.length - 1; i >= 0; i--)
35      for (let j = b.length - 1; j >= 0; j--)
36        lcs[i * w + j] =
37          a[i] === b[j] ? lcs[(i + 1) * w + j + 1]! + 1 : Math.max(lcs[(i + 1) * w + j]!, lcs[i * w + j + 1]!)
38    let i = 0
39    let j = 0
40    while (i < a.length || j < b.length) {
41      if (i < a.length && j < b.length && a[i] === b[j]) {
42        ops.push('=')
43        i++
44        j++
45      } else if (j < b.length && (i === a.length || lcs[i * w + j + 1]! >= lcs[(i + 1) * w + j]!)) {
46        ops.push('+')
47        j++
48      } else {
49        ops.push('-')
50        i++
51      }
52    }
53  }
54
55  const all: Row[] = []
56  let oldLine = 1
57  let newLine = 1
58  for (const op of [...Array<'='>(head).fill('='), ...ops, ...Array<'='>(tail).fill('=')]) {
59    if (op === '=') all.push({ kind: 'ctx', text: after[newLine - 1]!, oldLine: oldLine++, newLine: newLine++ })
60    else if (op === '-') all.push({ kind: 'del', text: before[oldLine - 1]!, oldLine: oldLine++ })
61    else all.push({ kind: 'add', text: after[newLine - 1]!, newLine: newLine++ })
62  }
63
64  if (context === Infinity) return all
65  const keep = all.map(() => false)
66  all.forEach((row, i) => {
67    if (row.kind === 'ctx') return
68    for (let k = Math.max(0, i - context); k <= Math.min(all.length - 1, i + context); k++) keep[k] = true
69  })
70  const rows: Row[] = []
71  all.forEach((row, i) => {
72    if (!keep[i]) return
73    if (i > 0 && !keep[i - 1]) rows.push({ kind: 'gap' })
74    rows.push(row)
75  })
76  if (rows.length > 0 && !keep[all.length - 1]) rows.push({ kind: 'gap' })
77  return rows
78}
79
hooks/paths.ts 27 lines
1// A path as typed: absolute, under ~, or relative to the working directory.
2export function expand(typed: string, cwd: string, home: string) {
3  if (typed.startsWith('/')) return typed
4  if ((typed === '~' || typed.startsWith('~/')) && home !== '') return home + typed.slice(1)
5  return `${cwd}/${typed}`
6}
7
8// The directory part of a typed path, as typed (with its last /, or empty), and the start of
9// the name being typed in it.
10export function splitTyped(typed: string) {
11  const slash = typed.lastIndexOf('/')
12  return { dir: typed.slice(0, slash + 1), stem: typed.slice(slash + 1) }
13}
14
15export type Entry = { name: string; kind: 'file' | 'dir' | 'other' }
16
17// The entries of the typed directory that complete the typed name, as the typed path would
18// read with them: directories first, then by name, each directory ending in /. A hidden entry
19// shows only once its leading dot is typed.
20export function completions({ dir, stem }: ReturnType<typeof splitTyped>, entries: Entry[], max: number) {
21  return entries
22    .filter(e => e.name.startsWith(stem) && (stem.startsWith('.') || !e.name.startsWith('.')))
23    .sort((a, b) => Number(b.kind === 'dir') - Number(a.kind === 'dir') || a.name.localeCompare(b.name))
24    .slice(0, max)
25    .map(e => ({ text: `${dir}${e.name}${e.kind === 'dir' ? '/' : ''}`, isDir: e.kind === 'dir' }))
26}
27
hooks/text.ts 64 lines
1// Terminal cells a character takes: Hangul and other wide glyphs take two.
2// East Asian Ambiguous characters (·, …, ↑, ▶, └, ①, ...) count as two as well: a terminal
3// set for Korean may draw them two wide, and a row one cell too wide wraps and pushes every
4// row below it down, parting ▶ from the line it marks.
5const WIDE =
6  /[¡¤§¨ª­®°-´¶-º¼-¿×÷ᄀ-ᅟ‐-‧‰-‾←-⇿∀-⋿①-⓿─-◿☀-⛿❶-❿⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/
7
8// Every wide range starts at U+00A1, so ASCII skips the regex.
9export const cellOf = (ch: string) => (ch < '¡' ? 1 : WIDE.test(ch) ? 2 : 1)
10
11export const cells = (text: string) => {
12  let n = 0
13  for (const ch of text) n += cellOf(ch)
14  return n
15}
16
17// Splits text into rows of at most `width` cells, breaking at a space in the row's second
18// half when there is one. redpen splits rows itself so it knows how many each line takes.
19export function wrapRows(text: string, width: number): string[] {
20  const w = Math.max(1, width)
21  const out: string[] = []
22  let rest = text
23  for (;;) {
24    let row = ''
25    let n = 0
26    let over = false
27    for (const ch of rest) {
28      const c = cellOf(ch)
29      if (n + c > w) {
30        over = true
31        break
32      }
33      row += ch
34      n += c
35    }
36    if (!over) break
37    // A two-cell character wider than the row still takes a row of its own, so the loop ends.
38    if (row === '') row = [...rest][0]!
39    const space = row.lastIndexOf(' ')
40    const take = space > row.length / 2 ? space : row.length
41    out.push(row.slice(0, take))
42    rest = rest.slice(take === space ? take + 1 : take)
43  }
44  if (rest !== '' || out.length === 0) out.push(rest)
45  return out
46}
47
48// Cuts text to `width` cells, ending in … when it does not fit. … itself takes two cells,
49// so a width below two leaves nothing.
50export function cut(text: string, width: number) {
51  if (cells(text) <= width) return text
52  const room = width - cells('…')
53  if (room < 0) return ''
54  let out = ''
55  let n = 0
56  for (const ch of text) {
57    const c = cellOf(ch)
58    if (n + c > room) break
59    out += ch
60    n += c
61  }
62  return `${out}…`
63}
64
types/index.d.ts 87 lines
1export type TurnFile = { path: string; base: string | null }
2
3/** The turn that last changed files, and each file's content before the turn first changed it. */
4export type RecentTurn = { turnId: string; files: TurnFile[] }
5
6/** A file changed this session, and when it was changed last. */
7export type SessionFile = { path: string; at: number }
8
9/** A file's content when the running turn began. */
10export type Held = { path: string; text: string }
11
12export type Source =
13  | { kind: 'diff'; path: string; base: string | null }
14  | { kind: 'file'; path: string }
15  | { kind: 'reply'; text: string }
16
17/**
18 * What the open comment input saves: an existing comment's new text, or a new comment on the
19 * lines and excerpt fixed when Enter opened it, wherever ▶ or the file goes meanwhile.
20 */
21export type Composing = { editId: string } | { lines: Pick<Comment, 'side' | 'start' | 'end' | 'excerpt'> }
22
23export type ListView = {
24  screen: 'list'
25  /** The entry the focus ring is on: 0 the reply, i + 1 the i-th file. */
26  cursor?: number
27  /**
28   * The entry to put the focus ring on when the list is drawn, by what it opens (a path, or
29   * the reply): the document 1 went back from. Left once the ring moves.
30   */
31  at?: string
32  /** The path input, while open: the text typed, and why the last Enter opened nothing. */
33  path?: { text: string; error: string | null }
34}
35
36export type DocView = {
37  screen: 'doc'
38  source: Source
39  cursor: number
40  anchor: number | null
41  composing: Composing | null
42  /** The comment row the focus ring is on: ▶ is drawn there instead of on the cursor line. */
43  focused: string | null
44  /** A diff shown whole, every unchanged line in place, rather than its changes alone. */
45  whole?: boolean
46}
47
48/** The comments to be sent, each to edit in place before a second 0 sends them. */
49export type SendView = {
50  screen: 'send'
51  /** The comment the focus ring is on, by id: the first when absent or gone. */
52  cursor?: string
53  /** The comment whose text the input edits, while it is open. */
54  editing: string | null
55  /** The screen 0 was pressed on, which 1 goes back to as it was. */
56  from: ListView | DocView
57}
58
59export type View = ListView | DocView | SendView
60
61export type Comment = {
62  id: string
63  kind: Source['kind']
64  path: string
65  side: 'new' | 'old'
66  start: number
67  end: number
68  excerpt: string[]
69  text: string
70  /** When the comment was written: a file with comments alone takes its place in the list by it. */
71  at?: number
72}
73
74declare module 'claude-code' {
75  interface PluginState {
76    redpen: {
77      turn: string | null
78      recent: RecentTurn | null
79      edited: SessionFile[]
80      snapshot: Held[]
81      opened: SessionFile[]
82      view: View
83      comments: Comment[]
84    }
85  }
86}
87