hooks/register.tsx 528 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { DiffMode, ReviewView } from '../types'
5
6const PANE = 'human-review'
7const TITLE = 'Review'
8const TOOL = 'mcp__human-review-pane__show'
9const view = atom({ plugin: 'human-review-pane', key: 'view' } as const, null as ReviewView | null)
10const isBandHidden = atom({ plugin: 'human-review-pane', key: 'isBandHidden' } as const, false)
11const diffMode = atom({ plugin: 'human-review-pane', key: 'diffMode' } as const, 'unified' as DiffMode)
12const isDoneArmed = atom({ plugin: 'human-review-pane', key: 'isDoneArmed' } as const, false)
13const DIFF_MODE_STORE_KEY = 'diffMode'
14// done は1回目で確認待ちにし、この時間内にもう一度押されたときだけ送る
15const DONE_CONFIRM_MS = 4000
16// split は左右それぞれにコードが収まる幅がないと読めないので、狭いときは unified で描く
17const SPLIT_MIN_COLUMNS = 100
18
19const STATUS_MARK = { done: '✓', current: '▶', todo: '·' } as const
20const PHASE_LABEL = { map: '🗺 マップ', chunk: '📖 解説中', summary: '📋 まとめ', finished: '✅ 完了' } as const
21const BAR_WIDTH = 20
22
23type FileDiff = { path: string; renamedFrom?: string; hunks: string[] }
24type Side = { no: number; text: string; kind: 'context' | 'removed' | 'added' }
25type SplitRow = { left?: Side; right?: Side } | { header: string }
26
27// git diff の出力から diff --git / index / rename 等のヘッダを除き、ファイルごとのハンクだけを取り出す。
28// Code の diff 表示は --- / +++ 以外のヘッダがあるとハンクとして読めず、ただのコードとして描いてしまう。
29const parseDiff = (diff: string, fallbackPath: string): FileDiff[] => {
30 const files: FileDiff[] = []
31 const lines = diff.split('\n')
32 let file: FileDiff | undefined
33 let isInHunk = false
34 const startFile = (path: string) => {
35 file = { path, hunks: [] }
36 files.push(file)
37 isInHunk = false
38 }
39
40 for (let i = 0; i < lines.length; i++) {
41 const line = lines[i] ?? ''
42 const following = lines[i + 1] ?? ''
43 if (line.startsWith('diff --git ')) {
44 startFile(line.split(' b/').pop() ?? fallbackPath)
45 continue
46 }
47 if (line.startsWith('--- ') && following.startsWith('+++ ')) {
48 const newPath = following.slice(4).replace(/^b\//, '')
49 const oldPath = line.slice(4).replace(/^a\//, '')
50 const path = newPath === '/dev/null' ? oldPath : newPath
51 if (file === undefined || file.hunks.length > 0) {
52 startFile(path)
53 } else {
54 file.path = path
55 }
56 i++
57 continue
58 }
59 if (line.startsWith('@@')) {
60 if (file === undefined) {
61 startFile(fallbackPath)
62 }
63 isInHunk = true
64 file?.hunks.push(line)
65 continue
66 }
67 if (file !== undefined && !isInHunk) {
68 if (line.startsWith('rename from ')) {
69 file.renamedFrom = line.slice('rename from '.length)
70 }
71 continue
72 }
73 if (isInHunk && file !== undefined) {
74 file.hunks.push(line === '' ? ' ' : line)
75 }
76 }
77
78 // 末尾の改行で生じた空のコンテキスト行を落とす
79 for (const one of files) {
80 while (one.hunks.at(-1) === ' ') {
81 one.hunks.pop()
82 }
83 }
84
85 return files
86}
87
88// 削除行の塊と直後の追加行の塊を、GitHub の split 表示と同じく上から順に左右へ対応させる
89const toSplitRows = (hunks: string[]): SplitRow[] => {
90 const rows: SplitRow[] = []
91 let oldNo = 0
92 let newNo = 0
93 let removed: Side[] = []
94 let added: Side[] = []
95 const flush = () => {
96 for (let i = 0; i < Math.max(removed.length, added.length); i++) {
97 rows.push({ left: removed[i], right: added[i] })
98 }
99 removed = []
100 added = []
101 }
102
103 for (const line of hunks) {
104 const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
105 if (header !== null) {
106 flush()
107 oldNo = Number(header[1])
108 newNo = Number(header[2])
109 rows.push({ header: line })
110 } else if (line.startsWith('-')) {
111 removed.push({ no: oldNo++, text: line.slice(1), kind: 'removed' })
112 } else if (line.startsWith('+')) {
113 added.push({ no: newNo++, text: line.slice(1), kind: 'added' })
114 } else if (!line.startsWith('\\')) {
115 flush()
116 const text = line.slice(1)
117 rows.push({ left: { no: oldNo++, text, kind: 'context' }, right: { no: newNo++, text, kind: 'context' } })
118 }
119 }
120 flush()
121
122 return rows
123}
124
125// 背景を塗るとハイライトされた文字が読みにくくなるため、行頭の縦バー・記号・行番号の色で変更行を示す。
126// 色は 256 色に丸められても変わらないよう、パレットにそのまま在るパステルピンクとミントを使う
127const SIDE_ACCENT = { context: undefined, removed: '#ff87af', added: '#87d7af' } as const
128// 行の背景は catppuccin Mocha の赤・緑を背景色に薄く溶かした色。
129// tmux 内では CLAUDE_CODE_TMUX_TRUECOLOR が無いと 256 色に丸められ、両方とも灰色に潰れる
130// 本体はペインを明るめの面の色で描くため、本文全体を端末(catppuccin Mocha)の背景色で塗り潰す
131const PANE_BACKGROUND = '#1e1e2e'
132const SIDE_BACKGROUND = { context: undefined, removed: '#45293a', added: '#283f33' } as const
133const SIDE_BAR = { context: ' ', removed: '▌', added: '▌' } as const
134const SIDE_SIGN = { context: ' ', removed: '-', added: '+' } as const
135
136type UnifiedRow = { oldNo?: number; newNo?: number; text: string; kind: Side['kind'] } | { header: string }
137
138// unified も Code の diff 表示に任せず split と同じ見た目で描く(テーマ次第で追加・削除の背景がほぼ見えないため)
139const toUnifiedRows = (hunks: string[]): UnifiedRow[] => {
140 const rows: UnifiedRow[] = []
141 let oldNo = 0
142 let newNo = 0
143 for (const line of hunks) {
144 const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
145 if (header !== null) {
146 oldNo = Number(header[1])
147 newNo = Number(header[2])
148 rows.push({ header: line })
149 } else if (line.startsWith('-')) {
150 rows.push({ oldNo: oldNo++, text: line.slice(1), kind: 'removed' })
151 } else if (line.startsWith('+')) {
152 rows.push({ newNo: newNo++, text: line.slice(1), kind: 'added' })
153 } else if (!line.startsWith('\\')) {
154 rows.push({ oldNo: oldNo++, newNo: newNo++, text: line.slice(1), kind: 'context' })
155 }
156 }
157
158 return rows
159}
160
161const INPUT_SCHEMA = {
162 type: 'object',
163 properties: {
164 title: { type: 'string', description: 'レビュー対象(例: "PR #123 ユーザー検索の追加")' },
165 phase: {
166 type: 'string',
167 enum: ['map', 'chunk', 'summary', 'finished'],
168 description: '段階。map: 全体マップ表示中 / chunk: チャンク解説中 / summary: まとめ表示・投稿確認中 / finished: 投稿済みまたは終了',
169 },
170 chunks: {
171 type: 'array',
172 description: '全チャンクの一覧と状態',
173 items: {
174 type: 'object',
175 properties: {
176 n: { type: 'number' },
177 kind: { type: 'string', description: '契約 / コア / 配線 / テスト / その他' },
178 label: { type: 'string', description: '対象ファイル・関数名' },
179 status: { type: 'string', enum: ['done', 'current', 'todo'] },
180 },
181 required: ['n', 'kind', 'label', 'status'],
182 },
183 },
184 current: { type: 'number', description: '表示中のチャンク番号。全体マップ表示時は 0' },
185 path: { type: 'string', description: '差分のファイルパス(言語判定に使う)。複数ファイルなら主たるもの' },
186 diff: {
187 type: 'string',
188 description: 'このチャンクの unified diff(@@ ハンク単位、途中で切らない)。全体マップ表示時は空文字',
189 },
190 refs: {
191 type: 'array',
192 description: '解説で参照した周辺コード',
193 items: {
194 type: 'object',
195 properties: {
196 path: { type: 'string' },
197 startLine: { type: 'number', description: 'source の1行目の行番号' },
198 source: { type: 'string', description: '参照箇所のコード(前後数行を含めて 30 行以内)' },
199 note: { type: 'string', description: '何のための参照か(例: 呼び出し元)' },
200 },
201 required: ['path', 'startLine', 'source'],
202 },
203 },
204 comments: {
205 type: 'array',
206 description: '記録済みコメント全件',
207 items: {
208 type: 'object',
209 properties: {
210 chunk: { type: 'number' },
211 location: { type: 'string', description: 'path:L42 など' },
212 text: { type: 'string' },
213 },
214 required: ['chunk', 'location', 'text'],
215 },
216 },
217 },
218 required: ['title', 'phase', 'chunks', 'current', 'path', 'diff', 'refs', 'comments'],
219}
220
221export const register: Register = on => {
222 on('session.start', async ($, e, next) => {
223 await $.command.register({
224 name: 'review-pane',
225 description: 'human-review のペインを開く',
226 })
227 const stored = await $.store.get(DIFF_MODE_STORE_KEY)
228 if (stored === 'unified' || stored === 'split') {
229 await update($, diffMode, () => stored)
230 }
231 await $.tool.register({
232 name: 'show',
233 description:
234 'human-review skill 専用。現在のチャンクの差分・参照コード・進捗・コメントをペインに色付きで表示する。' +
235 '呼ぶたびに表示内容を丸ごと置き換える。',
236 inputSchema: INPUT_SCHEMA,
237 })
238
239 return next(e)
240 })
241
242 on('command.run', { command: 'review-pane' }, async $ => {
243 await $.ui.open({ id: PANE, title: TITLE })
244
245 return { text: 'レビューペインを開きました。' }
246 })
247
248 on('tool.call', { tool: TOOL }, async ($, e) => {
249 // ツールの引数は e.input ではなく e の直下に載る(tool / tool_use_id / agentId は予約キー)
250 const { title, phase, chunks, current, path, diff, refs, comments } = e as unknown as ReviewView
251 const incoming: ReviewView = { title, phase, chunks, current, path, diff, refs, comments }
252 const previous = await read($, view)
253 await update($, view, () => incoming)
254 await update($, isBandHidden, () => false)
255 await update($, isDoneArmed, () => false)
256 await $.ui.open({ id: PANE, title: TITLE })
257 // チャンクや段階が変わったときだけ先頭に戻す(c でコメントを足しただけなら読んでいた位置を保つ)
258 if (previous?.current !== incoming.current || previous?.phase !== incoming.phase) {
259 await $.ui.scroll({ in: PANE, to: 'start' })
260 }
261
262 return { result: `#${incoming.current} をペインに表示しました。` }
263 })
264
265 // 引数(差分全文など)を会話ログに展開させず、1行の要約に差し替える
266 on('ui.render', { component: 'ToolUse', props: { tool: TOOL } }, async ($, e) => {
267 const { Text } = $.ui.resolve(e)
268 const input = e.props.input as Partial<ReviewView>
269 const phase = input.phase ?? 'chunk'
270 const chunk = input.chunks?.find(one => one.n === input.current)
271 const target =
272 phase === 'chunk' && chunk !== undefined
273 ? `#${chunk.n}/${input.chunks?.length ?? 0} ${chunk.kind}: ${chunk.label}`
274 : PHASE_LABEL[phase]
275 const state = e.props.isErrored ? ' (表示に失敗)' : e.props.isRunning ? ' …' : ''
276
277 return (
278 <Text dimColor={!e.props.isErrored} color={e.props.isErrored ? 'error' : undefined} wrap="truncate-end">
279 📝 ペインに表示: {target}
280 {state}
281 </Text>
282 )
283 })
284
285 // 完了表示は次の入力まで残し、その後は帯を消す
286 on('prompt.submit', async ($, e, next) => {
287 const current = await read($, view)
288 if (current?.phase === 'finished') {
289 await update($, isBandHidden, () => true)
290 }
291
292 return next(e)
293 })
294
295 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
296 const current = await read($, view)
297 if (e.props.hasSurvey || current === null || (await read($, isBandHidden))) {
298 return next(e)
299 }
300
301 const { Box, Button, Text } = $.ui.resolve(e)
302 const mode = await read($, diffMode)
303 const isArmed = await read($, isDoneArmed)
304 const isNavigable = current.phase === 'map' || current.phase === 'chunk'
305 const total = current.chunks.length
306 const done = current.chunks.filter(chunk => chunk.status === 'done').length
307 const filled = total === 0 ? 0 : Math.round((done / total) * Math.min(total, BAR_WIDTH))
308 const empty = Math.min(total, BAR_WIDTH) - filled
309 const chunk = current.chunks.find(one => one.n === current.current)
310
311 return (
312 <Box flexDirection="column">
313 {/* コミット範囲(「 | origin/..」以降)はペインのヘッダーで見えるので、帯では外す */}
314 <Text bold wrap="truncate-end">
315 📝 {current.title.split(' | ')[0]}
316 </Text>
317 <Text wrap="truncate-end">
318 <Text color="success">{'■'.repeat(filled)}</Text>
319 <Text dimColor>{'□'.repeat(empty)}</Text> {done}/{total}
320 {' '}
321 <Text color="suggestion">{PHASE_LABEL[current.phase] ?? PHASE_LABEL.chunk}</Text>
322 {' '}💬 {current.comments.length}
323 {/* 長いチャンク名で他の情報が切れないよう、末尾に置く */}
324 {chunk !== undefined && current.phase === 'chunk' && (
325 <Text>
326 {' '}▶ #{chunk.n} {chunk.kind}: {chunk.label}
327 </Text>
328 )}
329 </Text>
330 {/* Fragment で束ねると縦に積まれるため、ボタンは1つずつ条件を付けて横に並べる */}
331 {/* 打ったときと同じく送るので、返答中に押した分は返答が終わってから届く */}
332 <Box flexDirection="row" gap={1}>
333 {isNavigable && (
334 <Button
335 key="next"
336 label="next ▶"
337 hotkey="n"
338 variant="primary"
339 onPress={async () => {
340 await update($, isDoneArmed, () => false)
341 void $.prompt.submit({ text: 'next', asUser: true })
342 }}
343 />
344 )}
345 {isNavigable && current.current > 0 && (
346 <Button
347 key="back"
348 label="◀ back"
349 hotkey="b"
350 onPress={async () => {
351 await update($, isDoneArmed, () => false)
352 void $.prompt.submit({ text: 'back', asUser: true })
353 }}
354 />
355 )}
356 {/* done は next / back から離して押し間違いを減らす */}
357 {isNavigable && <Text dimColor>│</Text>}
358 {isNavigable && (
359 <Button
360 key="done"
361 label={isArmed ? '⚠ もう一度で終了' : '■ done'}
362 hotkey="d"
363 dimColor={!isArmed}
364 onPress={async () => {
365 if (await read($, isDoneArmed)) {
366 await update($, isDoneArmed, () => false)
367 void $.prompt.submit({ text: 'done', asUser: true })
368 return
369 }
370 await update($, isDoneArmed, () => true)
371 $.clock.after(DONE_CONFIRM_MS, () => void update($, isDoneArmed, () => false))
372 }}
373 />
374 )}
375 {isNavigable && <Text dimColor>│</Text>}
376 <Button
377 key="diff-mode"
378 label={mode === 'split' ? '⇆ split' : '☰ unified'}
379 onPress={async () => {
380 await update($, isDoneArmed, () => false)
381 const toggled: DiffMode = mode === 'split' ? 'unified' : 'split'
382 await update($, diffMode, () => toggled)
383 await $.store.set(DIFF_MODE_STORE_KEY, toggled)
384 }}
385 />
386 </Box>
387 <Text dimColor wrap="truncate-end">
388 skip N:ジャンプ c 内容:コメント map:一覧 comments:コメント一覧
389 </Text>
390 </Box>
391 )
392 })
393
394 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
395 const { Box, Text, Code } = $.ui.resolve(e)
396 const current = await read($, view)
397 const fill = { backgroundColor: PANE_BACKGROUND, minHeight: e.props.scroll.bodyRows, flexGrow: 1 } as const
398
399 if (current === null) {
400 return (
401 <Box {...fill}>
402 <Text dimColor>レビュー開始前です。/human-review で始めてください。</Text>
403 </Box>
404 )
405 }
406
407 const total = current.chunks.length
408 const isSplit = (await read($, diffMode)) === 'split' && e.props.bodyColumns >= SPLIT_MIN_COLUMNS
409 const sideColumns = Math.floor((e.props.bodyColumns - 1) / 2)
410 const gutterWidth = 7
411 const files = current.diff === '' ? [] : parseDiff(current.diff, current.path)
412
413 const drawSide = (side: Side | undefined, path: string) => (
414 <Box width={sideColumns} backgroundColor={side === undefined ? undefined : SIDE_BACKGROUND[side.kind]}>
415 <Box width={gutterWidth} flexShrink={0}>
416 {side !== undefined && (
417 <Text>
418 <Text color={SIDE_ACCENT[side.kind]}>{SIDE_BAR[side.kind]}</Text>
419 <Text color={SIDE_ACCENT[side.kind]} dimColor={side.kind === 'context'}>
420 {String(side.no).padStart(gutterWidth - 3)}
421 </Text>
422 <Text color={SIDE_ACCENT[side.kind]} bold>
423 {SIDE_SIGN[side.kind]}
424 </Text>
425 </Text>
426 )}
427 </Box>
428 {side === undefined || side.text === '' ? (
429 <Text> </Text>
430 ) : (
431 <Code source={side.text} path={path} wrap="truncate-end" />
432 )}
433 </Box>
434 )
435
436 return (
437 <Box flexDirection="column" gap={1} {...fill}>
438 <Box flexDirection="column">
439 <Text bold>{current.title}</Text>
440 {current.chunks.map(chunk => (
441 <Text
442 color={chunk.status === 'current' ? 'suggestion' : undefined}
443 bold={chunk.status === 'current'}
444 dimColor={chunk.status === 'done'}
445 wrap="truncate-end"
446 >
447 {STATUS_MARK[chunk.status]} #{chunk.n} {chunk.kind}: {chunk.label}
448 </Text>
449 ))}
450 </Box>
451
452 {files.map(file => (
453 <Box flexDirection="column">
454 <Text color="suggestion" bold wrap="truncate-end">
455 ── #{current.current}/{total} 差分: {file.path}
456 {file.renamedFrom === undefined ? '' : `(← ${file.renamedFrom})`}
457 </Text>
458 {file.hunks.length === 0 ? (
459 <Text dimColor>(内容の変更なし)</Text>
460 ) : isSplit ? (
461 toSplitRows(file.hunks).map(row =>
462 'header' in row ? (
463 <Text dimColor wrap="truncate-end">
464 {row.header}
465 </Text>
466 ) : (
467 <Box flexDirection="row">
468 {drawSide(row.left, file.path)}
469 <Text dimColor>│</Text>
470 {drawSide(row.right, file.path)}
471 </Box>
472 ),
473 )
474 ) : (
475 toUnifiedRows(file.hunks).map(row =>
476 'header' in row ? (
477 <Text dimColor wrap="truncate-end">
478 {row.header}
479 </Text>
480 ) : (
481 <Box flexDirection="row" backgroundColor={SIDE_BACKGROUND[row.kind]}>
482 <Box width={gutterWidth * 2 - 2} flexShrink={0}>
483 <Text>
484 <Text color={SIDE_ACCENT[row.kind]}>{SIDE_BAR[row.kind]}</Text>
485 <Text color={SIDE_ACCENT[row.kind]} dimColor={row.kind === 'context'}>
486 {(row.oldNo === undefined ? '' : String(row.oldNo)).padStart(gutterWidth - 3)}{' '}
487 {(row.newNo === undefined ? '' : String(row.newNo)).padStart(gutterWidth - 3)}
488 </Text>
489 <Text color={SIDE_ACCENT[row.kind]} bold>
490 {SIDE_SIGN[row.kind]}
491 </Text>
492 </Text>
493 </Box>
494 {row.text === '' ? <Text> </Text> : <Code source={row.text} path={file.path} />}
495 </Box>
496 ),
497 )
498 )}
499 </Box>
500 ))}
501
502 {current.refs.map(ref => (
503 <Box flexDirection="column">
504 <Text color="warning">
505 ── 参照: {ref.path}:{ref.startLine}
506 {ref.note === undefined ? '' : `(${ref.note})`}
507 </Text>
508 <Code source={ref.source} path={ref.path} startLine={ref.startLine} />
509 </Box>
510 ))}
511
512 {current.comments.length > 0 && (
513 <Box flexDirection="column">
514 <Text color="success" bold>
515 ── コメント({current.comments.length}件)
516 </Text>
517 {current.comments.map(comment => (
518 <Text>
519 [#{comment.chunk}] <Text dimColor>{comment.location}</Text> {comment.text}
520 </Text>
521 ))}
522 </Box>
523 )}
524 </Box>
525 )
526 })
527}
528