A pane pinned near the prompt listing the files each turn changed, with added and deleted line counts; collapsible, one per session.

作者:LazyJerry
最後更新:2026-10-15
Claude Code mod(以 plugin 形式載入的 hook 模組)收藏。每個子資料夾是一個獨立的 mod。
| Mod | 用途 |
|---|---|
| changed-files | 列出本 session 每一輪改到的檔案與增刪行數 |
追蹤 Edit、Write、NotebookEdit 與 Bash 造成的檔案變更,依輪次整理成清單,並累計 +新增 −刪除 行數。Bash 的變更用執行前後的 git diff --numstat 與未追蹤檔案比對,所以需要在 git repo 內才能計到 Bash 造成的變更;比對的 repo 以 session 開始時的工作目錄解析一次,之後 cd 到別的 repo 不會跟著換。
面板在 session 第一次記到變更時才自動打開,沒改檔的 session 不會出現;關掉後要再看就輸入 /changed-files。
| 環境 | 顯示方式 |
|---|---|
| 終端機(fullscreen) | 輸入框旁的「變更檔案」面板(x 收合/展開),每輪結束追加一行摘要 |
| VS Code 擴充套件 2.1.299 以上 | 輸入框上方的「變更檔案」面板(外框與標題列由擴充套件繪製,mod 無法隱藏),加上 /changed-files 的文字輸出 |
| VS Code 擴充套件 2.1.296 以下 | 只有 /changed-files 的文字輸出;面板、狀態列、對話摘要與 toast 都不會顯示 |
VS Code 的版本分界來自實測:2.1.296 的擴充套件 bundle 沒有 Pane/AbovePrompt 的渲染程式,2.1.299 才有。兩個人裝同一份 mod、一個有面板一個只有文字,先比擴充套件版本。
前置條件:已安裝 Claude Code,且 claude 指令可用。
一行指令:遠端下載並安裝(建議)
不用先 clone,下載 repo 壓縮檔到暫存目錄後執行 install.sh,裝完刪掉暫存目錄(需要 curl、tar、jq):
tmp="$(mktemp -d)" && curl -fsSL https://github.com/lazyjerry/claude-mods/archive/refs/heads/main.tar.gz | tar -xz -C "$tmp" && bash "$tmp/claude-mods-main/install.sh" && rm -rf "$tmp"
不加參數會出現互動選單;要跳過選單,在 install.sh 後面加 --all 或 mod 名稱(例如 changed-files)。結果與方式三相同:mod 複製到 ~/.claude/mods,路徑補進 ~/.claude/settings.json。
不支援 curl …/install.sh | bash:腳本從自己所在的資料夾偵測 mod,只下載腳本本身會找不到任何 mod。
以下三種方式適合要自己保留原始碼、或要改 mod 的情況。
方式一:啟動時指定資料夾(單次,適合試用)
claude --plugin-dir /path/to/claude-mods/changed-files
方式二:用環境變數永久載入(終端機與 VS Code 都適用)
在 ~/.claude/settings.json 加入 env,路徑指向本資料夾下的 changed-files:
{
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-mods/changed-files"
}
}
已有 env 區塊就只加這一個鍵。要同時載入多個 mod,路徑用冒號分隔(未實測,依 PATH 慣例推定)。
方式三:複製到 ~/.claude/mods
mkdir -p ~/.claude/mods
cp -R /path/to/claude-mods/changed-files ~/.claude/mods/
再用方式二指向 ~/.claude/mods/changed-files。這樣原始碼與實際載入的版本分開,改動前請先確認要改哪一份。
上面兩步可以用 install.sh 一次完成,它會複製選定的 mod 並把 CLAUDE_CODE_PLUGIN_DIRS 補進 ~/.claude/settings.json(需要 jq):
bash install.sh # 互動選單,挑要裝的 mod
bash install.sh changed-files # 直接指定 mod 名稱,可多個
bash install.sh --all # 全部安裝
bash install.sh --list # 只列出可安裝的 mod
重跑是安全的:已安裝的副本先搬到 ~/.claude/mods/.bak/<時間戳>/ 再覆蓋,settings.json 改動前留 settings.json.bak-<時間戳>,路徑已存在就不重複加。--mods-dir、--settings 可改目的地與設定檔位置,--no-validate 略過安裝後的 claude plugin validate。
/changed-files。看到「變更檔案面板已打開。」代表指令已註冊;輸入框打到 /changed-files 卻顯示 No matching commands,代表 mod 還沒載入。/changed-files 看清單。claude plugin validate /path/to/claude-mods/changed-files
claude plugin test /path/to/claude-mods/changed-files
驗證預期有一則 author 缺漏的警告,不影響載入。測試預期全部通過。
| 現象 | 處理 |
|---|---|
輸入框顯示 No matching commands | 確認 CLAUDE_CODE_PLUGIN_DIRS 路徑存在,並新開對話 |
| VS Code 沒有面板 | 擴充套件 2.1.296 以下沒有這個顯示位置,更新到 2.1.299 以上並新開對話;或改用 /changed-files |
VS Code 版本夠新仍沒有面板,log 有 session.start: raised (surface none, not interactive) 與 ui.open: no-surface | 兩個可能,依序查:(1) claudeCode.useTerminal 為 true,Claude 跑在終端機裡沒有 webview,使用者層級與工作區檔(.code-workspace)兩處都要拿掉;(2) 帳號層級的伺服器端 feature flag 未開,jq '.cachedGrowthBookFeatures.tengu_melodic_ember' ~/.claude.json 為 false 時內建 binary 不宣告 ui_surface_v1,webview 不會 attach。第 (2) 種本機沒有正規方式打開,只能用 /changed-files 文字輸出或終端機版 |
| 面板一直沒出現 | 面板在第一次記到變更時才開;還沒改檔或變更不在判定範圍內(見「Bash 的變更沒計入」)就不會開 |
| 想確認 VS Code 有沒有載入 | 命令面板執行 Claude: Show Logs,Output 選「Claude VSCode」,篩選 changed-files,應看到 plugin.register: changed-files ... admitted |
| Bash 的變更沒計入 | 確認 session 開始時的工作目錄在 git repo 內,且改到的檔案在同一個 repo;用 Bash 改其他 repo 或非 repo 的檔案不會計入 |
移除 settings.json 的 CLAUDE_CODE_PLUGIN_DIRS(或只拿掉這個路徑),刪除複製過去的資料夾,新開對話即可。
changed-files/
├── .claude-plugin/plugin.json # mod 名稱、版本與型別契約位置
├── hooks/
│ ├── hooks.json # 指向 register.tsx
│ ├── register.tsx # 事件 hook 與畫面
│ └── lib.ts # 行數計算與 git 快照比對
├── tests/changed-files.test.ts
├── tsconfig.json
└── types/index.d.ts # 狀態值的型別契約
.claude-plugin/types/ 由引擎在載入時自動產生(API 型別),不放進這個資料夾,也不用手動建立。
hooks/register.tsx 263 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { ChangedFile, ChangedTurn } from '../types'
5import {
6 countLines,
7 countPatch,
8 diffSnapshots,
9 mergeFile,
10 parseNumstat,
11 parseZeroList,
12 relativeTo,
13 snippet,
14 sumFiles,
15} from './lib'
16import type { Counts, Snapshot } from './lib'
17
18const PANE = 'changed-files'
19const TITLE = '變更檔案'
20const KEEP_TURNS = 30
21const PROMPT_CHARS = 48
22const MAX_ROWS = 16
23
24const turns = atom({ plugin: 'changed-files', key: 'turns' } as const, [])
25const current = atom({ plugin: 'changed-files', key: 'current' } as const, null)
26const isExpanded = atom({ plugin: 'changed-files', key: 'isExpanded' } as const, true)
27const hasAutoOpened = atom({ plugin: 'changed-files', key: 'hasAutoOpened' } as const, false)
28
29type Engine = EngineInterface
30
31// Module-level: a hot reload starts these over, and each is re-read lazily.
32let root: string | undefined
33// undefined: not checked yet; null: the session's cwd is not inside a git repo
34let gitRoot: string | null | undefined
35
36const projectRoot = async ($: Engine): Promise<string> => {
37 root ??= await $.session.root().catch(() => '')
38 return root
39}
40
41const repoRoot = async ($: Engine): Promise<string | null> => {
42 if (gitRoot !== undefined) return gitRoot
43 const ran = await $.process.run(['git', 'rev-parse', '--show-toplevel']).catch(() => undefined)
44 gitRoot = ran !== undefined && ran.exitCode === 0 ? ran.stdout.trim() : null
45 return gitRoot
46}
47
48/** The working tree against HEAD: tracked files' numstat and the untracked paths. */
49const snapshot = async ($: Engine): Promise<Snapshot | undefined> => {
50 const cwd = await repoRoot($)
51 if (cwd === null) return undefined
52 const [numstat, others] = await Promise.all([
53 $.process.run(['git', 'diff', '--numstat', '-z', 'HEAD', '--'], { cwd, timeoutMs: 10_000 }),
54 $.process.run(['git', 'ls-files', '--others', '--exclude-standard', '-z'], { cwd, timeoutMs: 10_000 }),
55 ]).catch(() => [undefined, undefined])
56 if (numstat === undefined || others === undefined) return undefined
57 return {
58 tracked: numstat.exitCode === 0 ? parseNumstat(numstat.stdout) : new Map(),
59 untracked: others.exitCode === 0 ? new Set(parseZeroList(others.stdout)) : new Set(),
60 }
61}
62
63/** Files a turn changed in the session's list, under the current turn (or an unnamed one). */
64const record = async ($: Engine, path: string, counts: Counts): Promise<void> => {
65 if (counts.added === 0 && counts.deleted === 0) return
66 const file: ChangedFile = { path: relativeTo(await projectRoot($), path), ...counts }
67 const now = await read($, current)
68 await update($, turns, list => {
69 const last = list[list.length - 1]
70 const id = now?.id ?? last?.id ?? 'session'
71 const prompt = now?.prompt ?? last?.prompt ?? '(沒有提示)'
72 if (last !== undefined && last.id === id) {
73 const turn: ChangedTurn = { ...last, files: mergeFile(last.files, file) }
74 return [...list.slice(0, -1), turn]
75 }
76 return [...list, { id, prompt, files: [file] }].slice(-KEEP_TURNS)
77 })
78 $.ui.status(await summary($))
79 await openOnFirstChange($)
80}
81
82/** 面板只在 session 第一次記到變更時自動開;之後由 /changed-files 開,關掉就不再自動冒出來。 */
83const openOnFirstChange = async ($: Engine): Promise<void> => {
84 if (await read($, hasAutoOpened)) return
85 await update($, hasAutoOpened, () => true)
86 await $.ui.open({ id: PANE, title: TITLE, rows: MAX_ROWS }).catch(() => undefined)
87}
88
89/** 沒有畫面板的 surface(如 VS Code 未開放面板時)改看狀態列與指令輸出的文字版。 */
90const summary = async ($: Engine): Promise<string | undefined> => {
91 const files = (await read($, turns)).flatMap(turn => turn.files)
92 if (files.length === 0) return undefined
93 const total = sumFiles(files)
94 const paths = new Set(files.map(file => file.path)).size
95
96 return `${TITLE} ${paths} 檔 +${total.added} −${total.deleted}${total.isApprox ? ' ~' : ''}`
97}
98
99const listText = async ($: Engine): Promise<string> => {
100 const list = await read($, turns)
101 if (list.length === 0) return '這個 session 還沒有改到檔案。'
102 const head = (await summary($)) ?? TITLE
103 const rows = [...list].reverse().flatMap((turn, i) => [
104 `#${list.length - i} ${turn.prompt}`,
105 ...turn.files.map(file => ` +${file.added} −${file.deleted} ${file.path}${file.isApprox ? ' ~' : ''}`),
106 ])
107
108 return [head, ...rows].join('\n')
109}
110
111export const register: Register = on => {
112 on('session.start', async ($, e, next) => {
113 root = undefined
114 gitRoot = undefined
115 await $.command.register({
116 name: 'changed-files',
117 description: '打開本 session 的變更檔案面板(每輪的檔案與增刪行數)',
118 })
119
120 return next(e)
121 })
122
123 on('command.run', { command: 'changed-files' }, async $ => {
124 await $.ui.open({ id: PANE, title: TITLE, focus: true, rows: MAX_ROWS })
125
126 return { text: `變更檔案面板已打開。\n${await listText($)}` }
127 })
128
129 on('turn.start', async ($, e, next) => {
130 await update($, current, () => ({ id: e.turnId, prompt: snippet(e.text, PROMPT_CHARS) }))
131
132 return next(e)
133 })
134
135 // 每輪結束,這輪有改到檔案才在對話裡追加一行摘要(不改動模型的回答)
136 on('turn.complete', async ($, e, next) => {
137 const ran = await next(e)
138 const turn = (await read($, turns)).find(one => one.id === e.turnId)
139 if (turn !== undefined && turn.files.length > 0) {
140 const { added, deleted } = sumFiles(turn.files)
141 $.ui.log(`${TITLE}(本輪)${turn.files.length} 檔 +${added} −${deleted}`) }
142
143 return ran
144 })
145
146 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
147 const ran = await next(e)
148 if (ran.deny === undefined && ran.isError === undefined && ran.result.staged !== true) {
149 await record($, e.file_path, countPatch(ran.result.structuredPatch))
150 }
151
152 return ran
153 })
154
155 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
156 const ran = await next(e)
157 if (ran.deny === undefined && ran.isError === undefined && ran.result.staged !== true) {
158 const { structuredPatch, originalFile, content } = ran.result
159 const counts: Counts =
160 structuredPatch.length > 0
161 ? countPatch(structuredPatch)
162 : {
163 added: countLines(content),
164 deleted: originalFile === null ? 0 : countLines(originalFile),
165 isApprox: originalFile !== null && originalFile !== content,
166 }
167 await record($, e.file_path, counts)
168 }
169
170 return ran
171 })
172
173 on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
174 const ran = await next(e)
175 if (ran.deny === undefined && ran.isError === undefined && ran.result.error === undefined) {
176 const { edit_mode, new_source, old_source } = ran.result
177 await record($, e.notebook_path, {
178 added: edit_mode === 'delete' ? 0 : countLines(new_source),
179 deleted: countLines(old_source ?? ''),
180 isApprox: true,
181 })
182 }
183
184 return ran
185 })
186
187 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
188 const before = await snapshot($)
189 const ran = await next(e)
190 if (before === undefined || ran.deny !== undefined) return ran
191 const after = await snapshot($)
192 if (after === undefined) return ran
193 const cwd = (await repoRoot($)) ?? ''
194 const { changed, created } = diffSnapshots(before, after)
195 for (const [path, counts] of changed) {
196 await record($, `${cwd}/${path}`, { ...counts, isApprox: false })
197 }
198 for (const path of created) {
199 const text = await $.fs.read(`${cwd}/${path}`).catch(() => undefined)
200 await record($, `${cwd}/${path}`, {
201 added: text === undefined ? 0 : countLines(text),
202 deleted: 0,
203 isApprox: text === undefined,
204 })
205 }
206
207 return ran
208 })
209
210 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
211 const { Box, Text, Button } = $.ui.resolve(e)
212 const list = await read($, turns)
213 const expanded = await read($, isExpanded)
214 const allFiles = list.flatMap(turn => turn.files)
215 const total = sumFiles(allFiles)
216 const paths = new Set(allFiles.map(file => file.path)).size
217 const width = Math.max(20, e.props.bodyColumns)
218
219 const toggle = () => {
220 void update($, isExpanded, was => !was)
221 void $.ui.open({ id: PANE, title: TITLE, rows: expanded ? 1 : MAX_ROWS }).catch(() => undefined)
222 }
223
224 return (
225 <Box flexDirection="column" width={width}>
226 <Box flexDirection="row" gap={1}>
227 <Text>
228 {paths} 檔 +{total.added} −{total.deleted}
229 {total.isApprox ? ' ~' : ''}
230 </Text>
231 <Button
232 key="toggle"
233 hotkey="x"
234 plain
235 dimColor
236 label={expanded ? '[收合]' : '[展開]'}
237 onPress={toggle}
238 />
239 </Box>
240 {expanded && list.length === 0 && <Text dimColor>這個 session 還沒有改到檔案。</Text>}
241 {expanded &&
242 [...list].reverse().map((turn, i) => (
243 <Box flexDirection="column">
244 <Text dimColor wrap="truncate-end">
245 #{list.length - i} {turn.prompt}
246 </Text>
247 {turn.files.map(file => (
248 <Box flexDirection="row" gap={1}>
249 <Text color="green">{`+${file.added}`.padStart(5)}</Text>
250 <Text color="red">{`−${file.deleted}`.padStart(5)}</Text>
251 <Text wrap="truncate-start">
252 {file.path}
253 {file.isApprox ? ' ~' : ''}
254 </Text>
255 </Box>
256 ))}
257 </Box>
258 ))}
259 </Box>
260 )
261 })
262}
263hooks/lib.ts 102 lines1import type { ChangedFile } from '../types'
2
3export type Counts = { added: number; deleted: number; isApprox: boolean }
4export type Numstat = { added: number; deleted: number }
5export type Snapshot = { tracked: Map<string, Numstat>; untracked: Set<string> }
6
7type Patch = readonly { lines: readonly string[] }[]
8
9/** Counts the `+` and `-` lines of a structured patch (Edit / Write results). */
10export const countPatch = (patch: Patch): Counts => {
11 let added = 0
12 let deleted = 0
13 for (const hunk of patch) {
14 for (const line of hunk.lines) {
15 if (line.startsWith('+')) added += 1
16 else if (line.startsWith('-')) deleted += 1
17 }
18 }
19 return { added, deleted, isApprox: false }
20}
21
22/** Lines of a text: none for '', a trailing newline adds no line. */
23export const countLines = (text: string): number => {
24 if (text === '') return 0
25 const body = text.endsWith('\n') ? text.slice(0, -1) : text
26 return body.split('\n').length
27}
28
29/** `git diff --numstat -z`: "added\tdeleted\tpath\0" per file; binary files read `-`. */
30export const parseNumstat = (stdout: string): Map<string, Numstat> => {
31 const map = new Map<string, Numstat>()
32 for (const row of stdout.split('\0')) {
33 if (row === '') continue
34 const [a, d, ...rest] = row.split('\t')
35 const path = rest.join('\t')
36 if (path === '' || a === undefined || d === undefined) continue
37 map.set(path, { added: a === '-' ? 0 : Number(a), deleted: d === '-' ? 0 : Number(d) })
38 }
39 return map
40}
41
42/** `git ls-files -z`: paths separated by NUL. */
43export const parseZeroList = (stdout: string): string[] =>
44 stdout.split('\0').filter(path => path !== '')
45
46/**
47 * What a Bash command changed, from two snapshots against HEAD: a tracked
48 * file's counts grew, or an untracked file appeared. A count that shrank
49 * (a commit, a revert) is clamped to 0 and dropped.
50 */
51export const diffSnapshots = (
52 before: Snapshot,
53 after: Snapshot,
54): { changed: Map<string, Numstat>; created: string[] } => {
55 const changed = new Map<string, Numstat>()
56 for (const [path, now] of after.tracked) {
57 const was = before.tracked.get(path) ?? { added: 0, deleted: 0 }
58 const added = Math.max(0, now.added - was.added)
59 const deleted = Math.max(0, now.deleted - was.deleted)
60 if (added > 0 || deleted > 0) changed.set(path, { added, deleted })
61 }
62 const created = [...after.untracked].filter(path => !before.untracked.has(path))
63 return { changed, created }
64}
65
66/** The path as shown: relative to `root` when inside it. */
67export const relativeTo = (root: string, path: string): string => {
68 const base = root.endsWith('/') ? root : `${root}/`
69 return path.startsWith(base) ? path.slice(base.length) : path
70}
71
72/** The first line of a prompt, cut to `max` characters. */
73export const snippet = (text: string, max: number): string => {
74 const line = text.split('\n').find(one => one.trim() !== '') ?? ''
75 const chars = [...line.trim()]
76 return chars.length > max ? `${chars.slice(0, max).join('')}…` : chars.join('')
77}
78
79/** Adds one change to a turn's list, summing into an existing row of the same path. */
80export const mergeFile = (files: readonly ChangedFile[], one: ChangedFile): ChangedFile[] => {
81 const index = files.findIndex(file => file.path === one.path)
82 if (index < 0) return [...files, one]
83 const was = files[index]!
84 const merged: ChangedFile = {
85 path: was.path,
86 added: was.added + one.added,
87 deleted: was.deleted + one.deleted,
88 isApprox: was.isApprox || one.isApprox,
89 }
90 return [...files.slice(0, index), merged, ...files.slice(index + 1)]
91}
92
93export const sumFiles = (files: readonly ChangedFile[]): Counts =>
94 files.reduce<Counts>(
95 (sum, file) => ({
96 added: sum.added + file.added,
97 deleted: sum.deleted + file.deleted,
98 isApprox: sum.isApprox || file.isApprox,
99 }),
100 { added: 0, deleted: 0, isApprox: false },
101 )
102types/index.d.ts 28 lines1export type ChangedFile = {
2 path: string
3 added: number
4 deleted: number
5 /** True when the counts were estimated (no patch available) rather than read off a diff. */
6 isApprox: boolean
7}
8
9export type ChangedTurn = {
10 id: string
11 prompt: string
12 files: ChangedFile[]
13}
14
15export type CurrentTurn = { id: string; prompt: string }
16
17declare module 'claude-code' {
18 interface PluginState {
19 'changed-files': {
20 turns: ChangedTurn[]
21 current: CurrentTurn | null
22 isExpanded: boolean
23 /** True once the pane auto-opened for this session's first change. */
24 hasAutoOpened: boolean
25 }
26 }
27}
28