工具呼叫收成一行淡色摘要(Edit、Write、Bash 與錯誤訊息照常顯示),計畫清單顯示在 prompt 上方;/clean 切換

個人使用的 Claude Code mod marketplace。這裡只放通用的程式碼,網址、token 這類私人設定由每台電腦各自設定,不進版控。
| mod | 用途 |
|---|---|
clean-view | 工具呼叫收成一行淡色摘要(Edit、Write、Bash 與錯誤訊息照常顯示),計畫清單顯示在輸入框上方;/clean 切換 |
next-steps | 回合結束後建議下一步(繁體中文版,fork 自 anthropics/claude-plugins-community,Apache 2.0) |
gitlab-sync | 分支跟遠端的同步狀態與還開著的張數(GitLab 的 Task、Issue 分開計數);GitLab 與 GitHub 上自己的 issue/MR(PR)有新動態時通知,/gitlab、/github 查看 |
agent-supervisor | 監控子代理、回報的任務與依賴、可能的阻塞與下一步建議;/supervisor 開關面板,說明見 agent-supervisor/README.md |
clone 到固定的資料夾,再把那個資料夾加成 marketplace。這樣 Claude Code 會直接讀資料夾裡的程式,git pull 之後執行 /reload-plugins 就是新版:
git clone <這個 repo 的網址> ~/.claude/mods-marketplaces/my-mods
claude plugin marketplace add ~/.claude/mods-marketplaces/my-mods
claude plugin install clean-view@my-mods
claude plugin install next-steps@my-mods
claude plugin install gitlab-sync@my-mods
claude plugin install agent-supervisor@my-mods
| 項目 | 設定方式 | 沒設定時 | |
|---|---|---|---|
| GitLab 網址 | 在 Claude Code 執行 /plugin configure gitlab-sync,填入 gitlabUrl(例如 https://gitlab.example.com,不含 /api/v4);也可以執行 `echo '{"gitlabUrl":"https://gitlab.example.com"}' \ | claude plugin configure gitlab-sync@my-mods --values-stdin` | 不檢查 GitLab |
| GitLab token | 環境變數 GITLAB_TOKEN;或存進 macOS 鑰匙圈:security add-generic-password -U -a "$USER" -s gitlab-token -w。環境變數優先,是空的或被拒絕(401)時改讀鑰匙圈 | 同步狀態列顯示「GitLab 通知暫停」(在 GitHub repo 裡不顯示:只顯示目前 repo 所屬平台的新動態與通知暫停) | |
| GitHub | gh auth login,token 跟 gh CLI 共用 | 不檢查 GitHub | |
| 同步狀態列 | mod 把這一列(含 ANSI 顏色)寫到 ~/.claude/gitlab-sync/statusline/<session id>.txt,每分鐘重寫一次;在自己的 statusline 腳本用輸入的 session_id 找檔、檔案 3 分鐘內有更新才印。閒置時 statusline 不會重跑,settings.json 的 statusLine 要加 "refreshInterval": 10(秒) | 看不到同步狀態列(/gitlab、/github 照常) |
設定值存在這台電腦的 Claude Code 設定裡,不在這個 repo。
改完任一個 mod:
claude plugin test <mod 資料夾>
claude plugin validate <mod 資料夾>
bash scripts/check-contracts.sh # 改過任何 types/index.d.ts 後執行
可能有好幾個 Claude Code session 同時在改這裡的檔案,動手前先看 git status。
scripts/tui-sim/ 會在背景的虛擬終端機裡跑一個暫時的 Claude Code,可以送按鍵、滑鼠事件,擷取畫面時連反白都讀得到。用來實測點擊範圍、狀態列、停靠位置這類 claude plugin test 測不到的地方,用法見 scripts/tui-sim/README.md。
scripts/git-hooks/pre-push 會在 git push 前掃描要送出去的 commit:新增的行、檔名、作者與提交者、commit 訊息。找到私有網段 IP,或私人關鍵字清單裡的字,就擋下推送。每個 clone 要做兩件事:
git config core.hooksPath scripts/git-hooks
# 這台電腦的私人關鍵字清單:一行一個延伸正規表示式,不分大小寫,# 開頭是註解
$EDITOR ~/.config/git/private-patterns
git push --no-verify。clean-view 與 gitlab-sync 採用根目錄的 MIT License。next-steps(Apache 2.0)是 fork,依它資料夾裡的 LICENSE。
hooks/register.tsx 827 lines1// Clean View:工具呼叫收成一行淡色摘要(Edit、Write、Bash 與錯誤訊息照常顯示),Claude 回報的計畫清單顯示在 prompt 上方;/clean 切換
2import { atom, read, update } from 'claude-code'
3import type { Color, EngineInterface, Register, RenderNode, ThemeKey, Timer } from 'claude-code'
4
5import type { CombinedBoxMode, PlanStatus, PlanStep, TurnClock } from '../types'
6
7const PLAN_TOOL_NAME = 'update_plan'
8// 外掛註冊的工具,模型看到的全名固定是 mcp__<plugin>__<name>;寫成字串常值,matcher 才讀得出來。
9// where-am-i/hooks/register.tsx 也用這個名稱略過計畫工具,改名要兩邊一起改
10const PLAN_TOOL = 'mcp__clean-view__update_plan'
11const MAX_GROUP_LINES = 5
12// 這幾個工具照 Claude Code 原本的樣子畫,看得到 diff、指令與輸出。
13// 唯讀的 Bash(ls、cat、grep…)會被 Claude Code 折進 ToolGroup,那裡照樣一行摘要
14const FULL_VIEW_TOOLS: readonly string[] = ['Edit', 'Write', 'Bash']
15const MAX_ERROR_LINES = 4
16
17// 計畫清單的排版
18const BAR_WIDTH = 12
19const BAR_COLUMNS = BAR_WIDTH + 2 // 進度條後面空兩格再接狀態字
20// 影片 1:53~1:56 的進行中(影片寫 Working)條是一顆彗星:頭最亮,後面四格一格比一格淡,融進灰色底
21const COMET_FADE = [1, 0.7, 0.45, 0.25, 0.1]
22// 影片的主色:橘、粉紅、紫、藍。彗星顏色隨時間在這幾個顏色之間來回變化
23const ORANGE = '#f79a4f'
24const PINK = '#ec4f8f'
25const ACCENT_COLORS = [ORANGE, PINK, '#b45ce6', '#6f7df2']
26const TITLE_MARK = '✳ '
27const PLAN_FINISHED_TITLE = '全部完成'
28const TITLE_COLOR = ORANGE
29const ELAPSED_COLUMNS = 10 // 「1小時05分」寬 9,再空一格
30const COMET_COLOR_HALF_PERIOD_FRAMES = 15 // 從橘變到藍約 3 秒
31const MARK_COLUMNS = 4 // 「 ✓ 」
32const STATUS_COLUMNS = 7 // 「進行中」寬 6,再空一格
33const MIN_TITLE_COLUMNS = 12
34const BOX_CHROME_COLUMNS = 4 // 外框左右各一格線、一格內距
35const BOX_BORDER_ROWS = 2
36// gitlab-sync 那一段的 key(gitlab-sync/hooks/register.tsx 的 BAND_KEY),改名要一起改。那一段固定在 band 最下面、
37// 緊貼輸入框;合併框要讓出它的列數,不然計畫一長整排就超過 maxRows,最下面的同步狀態會被收成「n more」
38const GITLAB_BAND_KEY = 'gitlab-band'
39const GITLAB_FRAMED_ROWS = 3
40const COMBINED_BOX_FRAME = { paddingX: 1, borderStyle: 'round', borderColor: 'suggestion' } as const
41// 拿掉框時的左右內距:框線一格加內距一格的位置,文字留在同一欄
42const UNFRAMED_PADDING_X = 2
43const PLAN_HEADER_ROWS = 2 // 整體進度列與「計畫:」標題列
44const PERCENT_COLUMNS = 5 // 「 100%」
45const MIN_OVERALL_BAR_WIDTH = 6
46// 影片 1:53~1:56:整體長條填滿的那段有一道較亮的光,約兩格寬,往右掃到填滿處尾端後停一下再從頭來。
47// 影片約 0.4 秒一格,長條一長要掃很久,依使用者要求加快成每拍(0.2 秒)一格
48const OVERALL_SHIMMER_WIDTH = 2
49const OVERALL_SHIMMER_PAUSE_CELLS = 4
50const OVERALL_SHIMMER_LIGHTEN = 0.35
51const MIN_STEP_ROWS = 3
52const MAX_STEP_ROWS = 7
53// 有彗星或亮光要動時每 0.2 秒一拍;只剩標題列的經過秒數要更新時,每秒一拍就夠
54const ANIMATION_MS = 200
55const CLOCK_ONLY_MS = 1000
56
57// ▆ 只佔格子下方四分之三:Ghostty 自己畫方塊字元並填滿整格高度,用滿格的方塊上下列會黏在一起,
58// ▆ 上方留空,列與列之間才分得開。完成的步驟是綠漸層,進行中的步驟是彗星(見 stepBar)
59const BAR_CELL = '▆'
60const DONE_GRADIENT = { from: '#2c9a52', to: '#9ee6b4' }
61// 整體長條已完成那段的填色:左邊橘、填滿處的尾端粉紅
62const OVERALL_FILL_GRADIENT = { from: ORANGE, to: PINK }
63// 「進行中」狀態字與整體百分比的顏色
64const WORKING_COLOR = PINK
65// 空的部分是灰色底;暫停時彗星停住、改成淺灰
66const PAUSED_COLOR = '#8a8a94'
67const TRACK_COLOR = '#4a4a52'
68
69// 狀態由 host 保存,熱重載後仍在;每個 session 預設開啟
70const isEnabled = atom({ plugin: 'clean-view', key: 'isEnabled' } as const, true)
71const plan = atom({ plugin: 'clean-view', key: 'plan' } as const, [] as PlanStep[])
72// 只有 band 讀它,所以動畫只會讓 band 重畫;用 $.ui.invalidate 會連 transcript 每一列都重跑
73const tick = atom({ plugin: 'clean-view', key: 'tick' } as const, 0)
74// 一次工作的起訖時間(含背景子代理跑的時間,見 turn.start):動畫計時器看它判斷工作是否進行中,標題列用它算經過秒數;
75// 合併框要不要顯示看 combinedBox,跟它無關
76const turnClock = atom({ plugin: 'clean-view', key: 'turnClock' } as const, null as TurnClock | null)
77// where-am-i 讀這個值決定要不要讓出位置(where-am-i/hooks/register.tsx 的 cleanViewCombinedBox),改名要兩邊一起改
78const combinedBox = atom({ plugin: 'clean-view', key: 'combinedBox' } as const, 'hidden' as CombinedBoxMode)
79// where-am-i 擁有的摘要,合併框讀來顯示目標、目前、等你
80const whereAmIRecap = { plugin: 'where-am-i', key: 'recap' } as const
81const whereAmILive = { plugin: 'where-am-i', key: 'live' } as const
82// next-steps 的建議清單是否顯示中。清單由外層的 next-steps 接在合併框下面、閒置時才出現;整排超過 maxRows 時
83// Claude Code 會把最下面收成「n more」,最先藏起來的就是那些選項,所以清單顯示中合併框要先讓出它的列數
84const nextStepsActive = { plugin: 'next-steps', key: 'active' } as const
85// 清單最多佔的列數:框 2 列、「next:」1 列、最多 3 個建議、dismiss 1 列(next-steps/hooks/register.tsx 的 FRAME_ROWS、
86// MAX_SUGGESTIONS),那邊改了這裡要跟著改
87const NEXT_STEPS_LIST_ROWS = 7
88
89// 看畫面的人讀的語言;計畫工具的說明、主對話的計畫指示與子代理的語言要求共用,換語言只改這裡
90const READER_LANGUAGE = 'Traditional Chinese (Taiwan usage)'
91
92const PLAN_SCHEMA = {
93 type: 'object',
94 properties: {
95 steps: {
96 type: 'array',
97 description: 'The whole plan, in order. It replaces the previous list.',
98 items: {
99 type: 'object',
100 properties: {
101 title: { type: 'string', description: `A short phrase in ${READER_LANGUAGE}; keep code identifiers, commands and paths as they are.` },
102 status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
103 },
104 required: ['title', 'status'],
105 },
106 },
107 },
108 required: ['steps'],
109}
110
111const PLAN_TOOL_DESCRIPTION =
112 'Show the person a checklist of your plan above their prompt; they see it instead of your tool calls. ' +
113 'Send the whole list every time: it replaces the previous one. Keep exactly one step in_progress while you work. ' +
114 `Step titles are short phrases (about 20 CJK characters at most) in ${READER_LANGUAGE}, keeping code identifiers, commands and paths as they are.`
115
116// 這個環境的主對話沒有 TodoWrite/TaskCreate,計畫清單只能靠模型主動回報,所以要在 system prompt 交代。
117// 最後一行的語言要求:工具呼叫收成一行後,畫面上最顯眼的是工具之間的進度說明,
118// 而查對話紀錄發現英文幾乎都出在這裡(思考是英文或剛收到英文的系統提醒時特別容易)
119const PLAN_INSTRUCTIONS = [
120 '# Plan checklist',
121 `The person uses Clean View: each tool call shows as one short line, and a checklist from the ${PLAN_TOOL} tool shows above the prompt.`,
122 `For a task of three or more steps, call ${PLAN_TOOL} before starting, the first step in_progress and the rest pending.`,
123 'Call it again as each step finishes, moving in_progress to the next one, and mark every step completed when the work is done.',
124 'Skip it for questions you answer directly and for tasks of one or two steps.',
125 `Write the step titles in ${READER_LANGUAGE}.`,
126 `Write the progress notes between tool calls, and any status update you give in reply to a system reminder, in ${READER_LANGUAGE} even when your thinking or the reminder is in English; keep code identifiers, commands and paths as they are.`,
127].join('\n')
128
129// 每則送出的訊息都附這一則提醒:放在 system prompt 與 CLAUDE.md 的語言規則在很長的 session 裡會被大量英文資料
130// (型別定義、文件、工具輸出、英文的系統提醒)蓋過,連最後的回覆都漂成英文(2026-10-08、10-13 都發生過)。
131// 附在最新的這則訊息上,每一輪都在離回覆最近的位置
132const LANGUAGE_REMINDER =
133 `Reply in ${READER_LANGUAGE}: the final answer, the progress notes between tool calls, and any status update after a system reminder, ` +
134 'even when what you read is in English. Keep code identifiers, commands and paths as they are.'
135
136// 附在每個子代理任務尾端的語言要求;內容固定,同一句不論附幾次都一樣
137const SUBAGENT_LANGUAGE_NOTE = [
138 '# Language',
139 `The person watches this run on screen and reads ${READER_LANGUAGE}.`,
140 `Write your progress notes between tool calls, the description you give each tool call, and your final report in ${READER_LANGUAGE}.`,
141 'Keep code identifiers, commands, file names and paths as they are.',
142 'If the task above explicitly asks for another language or an exact output format, follow the task.',
143].join('\n')
144
145// 畫面上的步驟狀態:in_progress 依回合是否進行中分成 running 與 paused(例如 Esc 中斷後)
146type StepDisplay = 'completed' | 'running' | 'paused' | 'pending'
147
148type RowStyle = {
149 mark: string
150 markColor?: Color
151 isMarkDim: boolean
152 isTextBold: boolean
153 isTextDim: boolean
154 label: string
155 labelColor?: Color
156 isLabelBold: boolean
157}
158
159const ROW_STYLE: Record<StepDisplay, RowStyle> = {
160 completed: { mark: '✓', markColor: 'success', isMarkDim: false, isTextBold: false, isTextDim: true, label: '完成', isLabelBold: false },
161 running: { mark: '▸', isMarkDim: false, isTextBold: true, isTextDim: false, label: '進行中', labelColor: WORKING_COLOR, isLabelBold: true },
162 paused: { mark: '▸', isMarkDim: true, isTextBold: false, isTextDim: false, label: '暫停', isLabelBold: false },
163 pending: { mark: '○', isMarkDim: true, isTextBold: false, isTextDim: true, label: '—', isLabelBold: false },
164}
165
166type PlanRow = { text: string; display: StepDisplay }
167type RecapSummary = { goal: string; now: string; waiting: string }
168
169// 模組重新載入時 engine 會丟掉舊的 timer,這個變數也跟著重來
170let animation: { timer: Timer; intervalMs: number } | undefined
171
172// 使用者自己送出 prompt 的來源(按 Enter、Remote Control、SDK);子代理的回報(2.1.299 是 peer)、背景工作的通知都不是
173const USER_PROMPT_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
174// 還算在跑的子代理;teammate 等訊息時是 idle,不算
175const ACTIVE_AGENT_STATUSES: readonly string[] = ['pending', 'running', 'waiting']
176// 最近一次 classic.Stop/classic.SubagentStop 回報的背景工作裡,有沒有還沒跑完的 workflow。workflow 的子代理不會出現在
177// $.agent.list(),只有這裡看得到;workflow 跑完會送通知開一個主回合,那一回合結束前的 classic.Stop 就會更新成 false。
178// 背景的 shell、monitor 不算:dev server 這種一直不會結束,算進去計時就停不下來
179let isWorkflowRunning = false
180
181function noteBackgroundTasks(tasks: readonly { type: string }[] | undefined) {
182 if (tasks !== undefined) isWorkflowRunning = tasks.some(task => task.type === 'workflow')
183}
184// 下一個主回合是不是使用者自己送出的 prompt 開的:prompt.submit 記下,主回合開始時用掉;
185// 主回合結束時也清掉,回合中送進去的 prompt 不會開新回合,不能留給之後的回合
186let isUserPromptPending = false
187
188// 子代理或 workflow 還有沒跑完的
189async function isAgentWorkRunning($: EngineInterface) {
190 if (isWorkflowRunning) return true
191 try {
192 return (await $.agent.list()).some(agent => ACTIVE_AGENT_STATUSES.includes(agent.status))
193 } catch {
194 return false // 列不出子代理的 surface 就當作沒有
195 }
196}
197
198// 計畫、開關或回合狀態變動後都呼叫這裡:決定合併框的顯示模式,以及計時器要不要跑、跑多快
199async function refreshPlanBand($: EngineInterface) {
200 const [enabled, steps, clock, currentMode] = await Promise.all([read($, isEnabled), read($, plan), read($, turnClock), read($, combinedBox)])
201 const mode = combinedBoxMode(enabled, steps)
202 // 沒變就不寫:寫入會讓讀它的 band(含 where-am-i)重畫
203 if (mode !== currentMode) await update($, combinedBox, () => mode)
204 const isWorkRunning = clock !== null && clock.endedAt === null
205 syncAnimation($, enabled && isWorkRunning ? animationIntervalMs(steps) : null)
206}
207
208function syncAnimation($: EngineInterface, intervalMs: number | null) {
209 if (animation?.intervalMs === intervalMs) return
210 stopAnimation()
211 if (intervalMs === null) return
212 animation = { intervalMs, timer: $.clock.every(intervalMs, () => void update($, tick, frame => frame + 1).catch(() => {})) }
213}
214
215function stopAnimation() {
216 animation?.timer.cancel()
217 animation = undefined
218}
219
220// 回合中有計畫才需要計時器:有進行中的步驟(彗星)或整體長條有亮光可掃時每 0.2 秒一拍,
221// 只剩標題列的經過秒數要更新時每秒一拍;沒有計畫就不跑
222export function animationIntervalMs(steps: readonly PlanStep[]): number | null {
223 if (steps.length === 0) return null
224 const hasComet = steps.some(step => step.status === 'in_progress')
225 const hasShimmer = countCompleted(steps) > 0 && !isPlanFinished(steps)
226 return hasComet || hasShimmer ? ANIMATION_MS : CLOCK_ONLY_MS
227}
228
229// next-steps 沒裝時讀不到,當作沒有清單
230async function isNextStepsOffering($: EngineInterface): Promise<boolean> {
231 const { value } = await $.state.get(nextStepsActive).catch(() => ({ value: undefined }))
232 return value === true
233}
234
235// where-am-i 沒裝或還沒有摘要時回傳 null,合併框就只畫計畫
236async function readRecapSummary($: EngineInterface): Promise<RecapSummary | null> {
237 const { value: recap } = await $.state.get(whereAmIRecap)
238 if (!recap) return null
239 const { value: live } = await $.state.get(whereAmILive)
240 return { goal: recap.goal, now: live || recap.now, waiting: recap.waiting }
241}
242
243export const register: Register = on => {
244 on('session.start', async ($, e, next) => {
245 const started = await next(e)
246 // 名稱已被 Claude Code 佔用時會被拒絕,不影響其他功能
247 await $.command
248 .register({ name: 'clean', description: '切換 Clean View:收起工具呼叫細節,只看計畫清單' })
249 .catch(() => {})
250 await $.tool.register({ name: PLAN_TOOL_NAME, description: PLAN_TOOL_DESCRIPTION, inputSchema: PLAN_SCHEMA })
251 await refreshPlanBand($) // 熱重載也會走到這裡,回合中重載時把動畫接回來
252 return started
253 })
254
255 on('command.run', { command: 'clean' }, async $ => {
256 const enabled = await update($, isEnabled, value => !value)
257 await refreshPlanBand($)
258 return { text: enabled ? 'Clean View 已開啟:工具呼叫收成一行摘要,Edit、Write、Bash 與錯誤訊息照常顯示。' : 'Clean View 已關閉:恢復完整顯示。' }
259 })
260
261 // 內容固定的 session 區段,不會讓 prompt cache 每次失效;沒有這個工具的請求(例如部分 subagent)不加
262 on('prompt.compose', async ($, e, next) => {
263 const composed = await next(e)
264 if (!e.tools.includes(PLAN_TOOL)) return composed
265 return { sections: [...composed.sections, { id: 'clean-view:plan', text: PLAN_INSTRUCTIONS, scope: 'session' }] }
266 })
267
268 // 子代理的 system prompt 由 agent 定義自己組成,不經過 prompt.compose,所以語言要求只能附在交給它的任務尾端。
269 // workflow 啟動的 agent 內容不能改寫(改了會被忽略並記一行失敗),原樣放行
270 on('agent.spawn', async ($, e, next) => {
271 if (e.workflow) return next(e)
272 return next({ ...e, prompt: withSubagentLanguageNote(e.prompt) })
273 })
274
275 // 自己回答,不呼叫 next:這個工具沒有實際執行的東西,也就不會跳權限確認
276 on('tool.call', { tool: PLAN_TOOL }, async ($, e) => {
277 if (e.agentId) return { result: '略過:只有主對話會更新計畫。' }
278 const steps = parseSteps((e as { steps?: unknown }).steps)
279 if (steps === null) return { deny: 'steps 必須是 { title, status } 的陣列,status 只能是 pending、in_progress 或 completed。' }
280 await update($, plan, () => steps)
281 await refreshPlanBand($)
282 return { result: `已顯示計畫:完成 ${countCompleted(steps)}/${steps.length} 步。` }
283 })
284
285 // 上一份計畫已全部完成才清掉;還沒做完的留著,Claude 可能下一輪接著做。
286 // prompt 被擋下也無妨:做完的計畫在閒置時本來就不顯示
287 on('prompt.submit', async ($, e, next) => {
288 isUserPromptPending = USER_PROMPT_ORIGINS.includes(e.origin?.kind)
289 await update($, plan, current => (isPlanFinished(current) ? [] : current))
290 await refreshPlanBand($)
291 return next({ ...e, context: [...(e.context ?? []), LANGUAGE_REMINDER] })
292 })
293
294 // 經過時間算的是一整次工作:從使用者送出 prompt,到主迴圈的回合結束而且子代理、workflow 都跑完,使用者要看完整跑完花多久。
295 // 派出背景子代理或 workflow 後主迴圈的回合就結束了,跑完會再開一個回合處理回報或通知,這些都接著算。
296 // 只有使用者自己送出 prompt、而且沒有子代理或 workflow 在跑時才從 0 重新算;它們在跑時使用者插話也接著算。
297 // 2.1.299 起子代理開始跑也會發 turn.start(帶 agentId,型別還沒寫),不能從那裡重新計時
298 on('turn.start', async ($, e, next) => {
299 if (!(e as { agentId?: string }).agentId) {
300 const isUserPrompt = isUserPromptPending
301 isUserPromptPending = false
302 const startedAt = await $.clock.now()
303 const isNewWork = isUserPrompt && !(await isAgentWorkRunning($))
304 await update($, turnClock, clock => (clock !== null && clock.endedAt === null && !isNewWork ? clock : { startedAt, endedAt: null }))
305 await refreshPlanBand($)
306 }
307 return next(e)
308 })
309
310 // 中斷(reason 為 aborted)也會發 turn.complete;子代理或 workflow 還在跑就不停,等它們回報或通知的回合結束再停
311 on('turn.complete', async ($, e, next) => {
312 if (!e.agentId) {
313 isUserPromptPending = false
314 if (!(await isAgentWorkRunning($))) {
315 const endedAt = await $.clock.now()
316 await update($, turnClock, clock => (clock ? { ...clock, endedAt } : clock))
317 }
318 await refreshPlanBand($)
319 }
320 return next(e)
321 })
322
323 // 主迴圈停下前(約在 turn.complete 前 0.1 秒)與每個子代理停下時都會回報還在跑的背景工作,只讀不改
324 on('classic.Stop', async ($, e, next) => {
325 noteBackgroundTasks(e.background_tasks)
326 return next(e)
327 })
328
329 on('classic.SubagentStop', async ($, e, next) => {
330 noteBackgroundTasks(e.background_tasks)
331 return next(e)
332 })
333
334 on('session.end', async ($, e, next) => {
335 stopAnimation()
336 if (e.reason === 'clear') {
337 await update($, plan, () => [])
338 await refreshPlanBand($)
339 }
340 return next(e)
341 })
342
343 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
344 if (!(await read($, isEnabled)) || FULL_VIEW_TOOLS.includes(e.props.tool)) return next(e)
345 const { Box, Text } = $.ui.resolve(e)
346 if (e.props.tool === PLAN_TOOL) return <Box />
347 return (
348 <Box flexDirection="column">
349 {toolLines(e.props).map(line => (
350 <Text color={line.color} dimColor={line.color === undefined} wrap="truncate-end">
351 {line.text}
352 </Text>
353 ))}
354 </Box>
355 )
356 })
357
358 // 錯誤內容由上面 ToolUse 那一列接在摘要下面:群組裡的呼叫沒有 ToolResult,兩邊才畫得一致
359 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
360 if (!(await read($, isEnabled)) || FULL_VIEW_TOOLS.includes(e.props.tool)) return next(e)
361 const { Box } = $.ui.resolve(e)
362 return <Box />
363 })
364
365 // 連續的讀檔、搜尋會被折成一組;照樣一個動作一行(出錯的下面接錯誤內容),太多時只留最後幾個
366 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
367 if (!(await read($, isEnabled))) return next(e)
368 const { Box, Text } = $.ui.resolve(e)
369 const calls = e.props.calls.filter(call => call.tool !== PLAN_TOOL)
370 const shown = calls.slice(-MAX_GROUP_LINES)
371 const hiddenCount = calls.length - shown.length
372 return (
373 <Box flexDirection="column">
374 {hiddenCount > 0 && <Text dimColor>{` · 前面還有 ${hiddenCount} 個動作`}</Text>}
375 {shown.flatMap(toolLines).map(line => (
376 <Text color={line.color} dimColor={line.color === undefined} wrap="truncate-end">
377 {line.text}
378 </Text>
379 ))}
380 </Box>
381 )
382 })
383
384 // 計畫顯示時畫合併框:where-am-i 的目標、目前、等你加上計畫清單(下一步跟計畫重複所以不放)
385 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
386 const rest = await next(e) // 其他 mod 與 Claude Code 自己畫的內容保留在下面
387 const mode = await read($, combinedBox)
388 if (e.props.hasSurvey || !isCombinedBoxShown(mode)) return rest
389
390 const { Box, Text } = $.ui.resolve(e)
391 const innerColumns = e.props.bodyColumns - BOX_CHROME_COLUMNS
392 const [summary, clock, steps, frame, isNextStepsShown] = await Promise.all([
393 readRecapSummary($),
394 read($, turnClock),
395 read($, plan),
396 read($, tick),
397 isNextStepsOffering($),
398 ])
399 const title = titleRow(summary?.goal ?? '', steps, await elapsedLabel($, clock), innerColumns)
400 const rowsAbove = rowsAbovePlan(title, summary)
401 const gitlabRows = rowsOfGitlabLine(rest)
402 const maxRows = e.props.maxRows - (isNextStepsShown ? NEXT_STEPS_LIST_ROWS : 0)
403 const viewFor = (rows: number) => planView(steps, { frame, isWorking: e.props.isWorking, columns: innerColumns, rows })
404 // 先照有框排:讓出 gitlab-sync 那一段的列數。計畫列數有下限,視窗太矮時還是放不下,就把合併框與 gitlab-sync 那一段的框
405 // 一起拿掉(使用者選的「放不下先拿掉框」),省下 4 列;拿掉框時改用兩格內距,文字留在同一欄、可用寬度不變
406 const framedView = viewFor(maxRows - BOX_BORDER_ROWS - rowsAbove - gitlabRows)
407 const isFramed = combinedBoxRows(rowsAbove, framedView.rows.length, true) + gitlabRows <= maxRows
408 const view = isFramed ? framedView : viewFor(maxRows - rowsAbove - Math.min(gitlabRows, 1))
409 const below = isFramed ? rest : replaceKeyed(rest, GITLAB_BAND_KEY, withoutFrame)
410 return (
411 <Box flexDirection="column">
412 <Box flexDirection="column" {...(isFramed ? COMBINED_BOX_FRAME : { paddingX: UNFRAMED_PADDING_X })}>
413 {/* 標題列(照影片):左邊是目標,右邊是這個回合經過的時間 */}
414 {title && (
415 <Box flexDirection="row" justifyContent="space-between">
416 <Text bold color={TITLE_COLOR} wrap="truncate-end">
417 {title.text}
418 </Text>
419 {title.elapsed !== null && <Text dimColor>{title.elapsed}</Text>}
420 </Box>
421 )}
422 {summary?.now && (
423 <Text wrap="truncate-end">
424 <Text dimColor>{' 目前:'}</Text>
425 <Text>{summary.now}</Text>
426 </Text>
427 )}
428 {/* 整體進度列:進度條跟各步驟的進度條從同一欄開始,一路延伸到框的右邊 */}
429 <Box flexDirection="row">
430 <Box width={view.titleColumns}>
431 <Text dimColor wrap="truncate-end">{` ${view.overall.label}`}</Text>
432 </Box>
433 <Box width={view.overall.cells.length + 1}>
434 <Text>
435 {colorRuns(view.overall.cells).map(run => (
436 <Text color={run.color}>{BAR_CELL.repeat(run.count)}</Text>
437 ))}
438 </Text>
439 </Box>
440 <Text bold color={view.overall.isFinished ? 'success' : WORKING_COLOR}>
441 {view.overall.percent}
442 </Text>
443 </Box>
444 {/* 標籤跟「目前」「等你」一樣縮排;完成幾步看上面的「步驟 x/y」,這裡不重複 */}
445 <Text dimColor>{' 計畫:'}</Text>
446 {view.rows.map(row => (
447 <Box flexDirection="row">
448 <Box width={view.titleColumns}>
449 <Text wrap="truncate-end">
450 <Text color={row.style.markColor} dimColor={row.style.isMarkDim}>{` ${row.style.mark} `}</Text>
451 <Text bold={row.style.isTextBold} dimColor={row.style.isTextDim}>
452 {row.text}
453 </Text>
454 </Text>
455 </Box>
456 <Box width={BAR_COLUMNS}>
457 <Text>
458 {colorRuns(row.cells).map(run => (
459 <Text color={run.color}>{BAR_CELL.repeat(run.count)}</Text>
460 ))}
461 </Text>
462 </Box>
463 {view.isStatusShown && (
464 <Text bold={row.style.isLabelBold} color={row.style.labelColor} dimColor={row.style.labelColor === undefined}>
465 {row.style.label}
466 </Text>
467 )}
468 </Box>
469 ))}
470 {summary?.waiting && <Text color="yellow" wrap="truncate-end">{` 等你:${summary.waiting}`}</Text>}
471 </Box>
472 {below}
473 </Box>
474 )
475 })
476}
477
478// 已經附過(例如上層子代理把整段任務轉交下去)就不再重複
479function withSubagentLanguageNote(prompt: string) {
480 if (prompt.includes(SUBAGENT_LANGUAGE_NOTE)) return prompt
481 return `${prompt.trimEnd()}\n\n${SUBAGENT_LANGUAGE_NOTE}`
482}
483
484// 做完的計畫閒置時也留著,使用者要看最後停在幾秒;下一個 prompt 送出時才清掉(見 prompt.submit)
485export function combinedBoxMode(enabled: boolean, steps: readonly PlanStep[]): CombinedBoxMode {
486 return !enabled || steps.length === 0 ? 'hidden' : 'always'
487}
488
489export function isCombinedBoxShown(mode: CombinedBoxMode) {
490 return mode === 'always'
491}
492
493// 計畫區塊上方、框線以外的列數:標題列、目前、等你;跟 JSX 裡畫哪些列要一致
494function rowsAbovePlan(title: TitleRow | null, summary: RecapSummary | null) {
495 return (title ? 1 : 0) + (summary?.now ? 1 : 0) + (summary?.waiting ? 1 : 0)
496}
497
498// 串接在裡面的 gitlab-sync 那一段佔幾列:有框 3 列、沒框 1 列、沒有這一段 0 列
499export function rowsOfGitlabLine(rest: RenderNode): number {
500 const line = findKeyed(rest, GITLAB_BAND_KEY)
501 if (line === null) return 0
502 const props = (line as { props?: Record<string, unknown> }).props
503 return props?.borderStyle !== undefined ? GITLAB_FRAMED_ROWS : 1
504}
505
506// 合併框整個佔幾列:框線、計畫上方的標題列與目前、等你、整體進度與「計畫:」、計畫各列
507export function combinedBoxRows(rowsAbove: number, planRowCount: number, isFramed: boolean): number {
508 return (isFramed ? BOX_BORDER_ROWS : 0) + rowsAbove + PLAN_HEADER_ROWS + planRowCount
509}
510
511// 拿掉 gitlab-sync 那一段的框,改用兩格內距讓文字留在同一欄(框的屬性見 gitlab-sync 的 BAND_FRAME;next-steps 也有同樣的做法)
512function withoutFrame(node: RenderNode): RenderNode {
513 if (typeof node !== 'object' || node === null || !('props' in node) || node.props === undefined) return node
514 const { borderStyle: _style, borderColor: _color, ...props } = node.props as Record<string, string | number | boolean>
515 return { ...node, props: { ...props, paddingX: UNFRAMED_PADDING_X } } as RenderNode
516}
517
518// 把 tree 裡 key 為 key 的元素換成 replace 的結果;找不到就原樣回傳。tree 是 next(e) 給的唯讀資料,沿路的節點都換成新的物件
519function replaceKeyed(node: RenderNode, key: string, replace: (found: RenderNode) => RenderNode): RenderNode {
520 if (typeof node !== 'object' || node === null) return node
521 if ('props' in node && (node.props as Record<string, unknown> | undefined)?.key === key) return replace(node)
522 if (!('children' in node) || !Array.isArray(node.children)) return node
523 const children = node.children as RenderNode[]
524 const replaced = children.map(child => replaceKeyed(child, key, replace))
525 return replaced.every((child, index) => child === children[index]) ? node : ({ ...node, children: replaced } as RenderNode)
526}
527
528function findKeyed(node: RenderNode, key: string): RenderNode | null {
529 if (typeof node !== 'object' || node === null) return null
530 if ('props' in node && (node.props as Record<string, unknown> | undefined)?.key === key) return node
531 const children = 'children' in node && Array.isArray(node.children) ? (node.children as RenderNode[]) : []
532 for (const child of children) {
533 const found = findKeyed(child, key)
534 if (found !== null) return found
535 }
536 return null
537}
538
539// 工作還沒跑完就算到現在(只有這時才需要讀時鐘),跑完了就停在結束那一刻;還沒有工作就不顯示
540async function elapsedLabel($: EngineInterface, clock: TurnClock | null) {
541 if (!clock) return null
542 const end = clock.endedAt ?? (await $.clock.now())
543 return formatElapsed(end - clock.startedAt)
544}
545
546type TitleRow = { text: string; elapsed: string | null }
547
548// 標題列:左邊「✳ 目標」,where-am-i 還沒有摘要時改用目前步驟的標題,計畫全部做完(沒有目前步驟)時寫「全部完成」;
549// 右邊是經過時間。兩邊都沒有就不畫
550export function titleRow(goal: string, steps: readonly PlanStep[], elapsed: string | null, innerColumns: number): TitleRow | null {
551 const subject = goal || (steps[currentStepIndex(steps)]?.title ?? (isPlanFinished(steps) ? PLAN_FINISHED_TITLE : ''))
552 const fitted = fitToWidth(subject, innerColumns - displayWidth(TITLE_MARK) - ELAPSED_COLUMNS)
553 const text = fitted ? TITLE_MARK + fitted : ''
554 if (!text && elapsed === null) return null
555 return { text, elapsed }
556}
557
558export function formatElapsed(ms: number): string {
559 const totalSeconds = Math.max(0, Math.floor(ms / 1000))
560 const hours = Math.floor(totalSeconds / 3600)
561 const minutes = Math.floor((totalSeconds % 3600) / 60)
562 const seconds = totalSeconds % 60
563 if (hours > 0) return `${hours}小時${String(minutes).padStart(2, '0')}分`
564 if (minutes > 0) return `${minutes}分${String(seconds).padStart(2, '0')}秒`
565 return `${seconds}秒`
566}
567
568// 超過寬度時依顯示寬度截斷,補「…」;中文一個字算兩格
569export function fitToWidth(text: string, maxColumns: number): string {
570 if (maxColumns <= 0) return ''
571 if (displayWidth(text) <= maxColumns) return text
572 let kept = ''
573 let width = 0
574 for (const char of text) {
575 if (width + charWidth(char) > maxColumns - 1) break
576 kept += char
577 width += charWidth(char)
578 }
579 return `${kept}…`
580}
581
582type PlanViewOptions = { frame: number; isWorking: boolean; columns: number; rows: number }
583
584// 合併框裡計畫區塊要畫的一切:進度字樣、欄寬、要不要顯示狀態字,以及每一列的樣式與方格顏色
585export function planView(steps: readonly PlanStep[], options: PlanViewOptions) {
586 const stepRows = Math.min(MAX_STEP_ROWS, Math.max(MIN_STEP_ROWS, options.rows - PLAN_HEADER_ROWS))
587 const rows = planRows(steps, stepRows, options.isWorking)
588 const layout = planLayout(rows, options.columns)
589 // 標籤欄也要放得下整體進度列的「 步驟 x/y」,不然標籤會換行、多出一列
590 const titleColumns = Math.max(layout.titleColumns, displayWidth(` ${overallLabel(steps)}`) + 1)
591 return {
592 ...layout,
593 titleColumns,
594 overall: overallProgress(steps, {
595 barWidth: Math.max(MIN_OVERALL_BAR_WIDTH, options.columns - titleColumns - PERCENT_COLUMNS),
596 frame: options.frame,
597 isAnimated: options.isWorking, // 閒置時計時器已停,亮光停在半路很怪,乾脆不畫
598 }),
599 rows: rows.map(row => ({ ...row, style: ROW_STYLE[row.display], cells: stepBar(row.display, options.frame) })),
600 }
601}
602
603// 影片的整體進度列:步驟 x/y(影片寫 Step x of y)、一條長進度條、百分比。x 是進行中的那一步,沒有進行中時是第一個還沒完成的步驟。
604// 百分比只算已完成的步驟(步驟內部沒有進度可量);全部完成時整條變綠
605type OverallBarOptions = { barWidth: number; frame: number; isAnimated: boolean }
606
607export function overallProgress(steps: readonly PlanStep[], options: OverallBarOptions) {
608 const { barWidth } = options
609 const completedCount = countCompleted(steps)
610 const ratio = steps.length === 0 ? 0 : completedCount / steps.length
611 const filledCells = Math.round(ratio * barWidth)
612 const isFinished = isPlanFinished(steps)
613 const positions = Array.from({ length: barWidth }, (_, index) => index)
614 if (isFinished) {
615 const cells = positions.map(index => gradientAt(DONE_GRADIENT, index, barWidth))
616 return { label: overallLabel(steps), percent: '100%', cells, isFinished }
617 }
618 // 漸層只鋪在已填滿的那段,左邊橘、填滿處的尾端粉紅,跟影片一樣;再疊上掃過的亮光
619 const isShimmer = options.isAnimated ? shimmerBand(options.frame, filledCells) : () => false
620 const cells = positions.map(index => {
621 if (index >= filledCells) return TRACK_COLOR
622 const color = gradientAt(OVERALL_FILL_GRADIENT, index, filledCells)
623 return isShimmer(index) ? lighten(color, OVERALL_SHIMMER_LIGHTEN) : color
624 })
625 return { label: overallLabel(steps), percent: `${Math.round(ratio * 100)}%`, cells, isFinished }
626}
627
628export function overallLabel(steps: readonly PlanStep[]) {
629 const current = currentStepIndex(steps)
630 return `步驟 ${(current >= 0 ? current : steps.length - 1) + 1}/${steps.length}`
631}
632
633// 目前的步驟:進行中的那一步,沒有的話是第一個還沒完成的步驟;全部完成時是 -1
634function currentStepIndex(steps: readonly PlanStep[]) {
635 const runningIndex = steps.findIndex(step => step.status === 'in_progress')
636 return runningIndex >= 0 ? runningIndex : steps.findIndex(step => step.status !== 'completed')
637}
638
639// 連續同色的格子合併成一段,少畫很多元素(整體長條在寬螢幕上可能有一百多格)
640export function colorRuns(cells: readonly string[]): { color: string; count: number }[] {
641 const runs: { color: string; count: number }[] = []
642 for (const color of cells) {
643 const last = runs[runs.length - 1]
644 if (last?.color === color) last.count += 1
645 else runs.push({ color, count: 1 })
646 }
647 return runs
648}
649
650function shimmerBand(frame: number, filledCells: number) {
651 const head = frame % (filledCells + OVERALL_SHIMMER_PAUSE_CELLS)
652 return (index: number) => index <= head && index > head - OVERALL_SHIMMER_WIDTH
653}
654
655// band 的高度有限,還要跟其他 mod 共用:超過列數時先把已完成的收成一列,還放不下就把後段收成「還有 N 項」
656export function planRows(steps: readonly PlanStep[], maxRows: number, isWorking: boolean): PlanRow[] {
657 const rows = steps.map(step => ({ text: step.title, display: displayOf(step.status, isWorking) }))
658 if (rows.length <= maxRows) return rows
659
660 const completedCount = countCompleted(steps)
661 const folded: PlanRow[] = completedCount > 0 ? [{ text: `已完成 ${completedCount} 項`, display: 'completed' }] : []
662 const compact = [...folded, ...rows.filter(row => row.display !== 'completed')]
663 if (compact.length <= maxRows) return compact
664
665 const kept = compact.slice(0, maxRows - 1)
666 return [...kept, { text: `還有 ${compact.length - kept.length} 項`, display: 'pending' }]
667}
668
669function displayOf(status: PlanStatus, isWorking: boolean): StepDisplay {
670 if (status === 'in_progress') return isWorking ? 'running' : 'paused'
671 return status
672}
673
674// 標題欄寬取最長的標題,讓進度條對齊成一欄;太窄時先拿掉狀態字,再縮標題,進度條維持原寬
675export function planLayout(rows: readonly PlanRow[], columns: number) {
676 const longest = Math.max(0, ...rows.map(row => displayWidth(row.text)))
677 const wantedTitleColumns = MARK_COLUMNS + longest + 2
678 const roomWithStatus = columns - BAR_COLUMNS - STATUS_COLUMNS
679 if (roomWithStatus >= MIN_TITLE_COLUMNS) {
680 return { titleColumns: Math.min(wantedTitleColumns, roomWithStatus), isStatusShown: true }
681 }
682 const roomWithoutStatus = columns - BAR_COLUMNS
683 return { titleColumns: Math.max(MIN_TITLE_COLUMNS, Math.min(wantedTitleColumns, roomWithoutStatus)), isStatusShown: false }
684}
685
686// 每一格的顏色,由左到右:完成是綠漸層,未開始只有灰色底;進行中是一顆彗星從左往右走,
687// 尾巴也離開右邊後再從左邊進來,frame 每拍加一。暫停時停在左邊、整顆看得見的位置並改成淺灰,
688// 不沿用最後一拍的位置:那一拍可能剛好出界,看起來就跟未開始一樣
689const PAUSED_HEAD = COMET_FADE.length - 1
690
691export function stepBar(display: StepDisplay, frame: number): string[] {
692 const positions = Array.from({ length: BAR_WIDTH }, (_, index) => index)
693 if (display === 'completed') return positions.map(index => gradientAt(DONE_GRADIENT, index))
694 if (display === 'pending') return positions.map(() => TRACK_COLOR)
695 const head = display === 'paused' ? PAUSED_HEAD : frame % (BAR_WIDTH + COMET_FADE.length)
696 const headColor = display === 'running' ? cometColor(frame) : PAUSED_COLOR
697 return positions.map(index => {
698 const intensity = COMET_FADE[head - index]
699 return intensity === undefined ? TRACK_COLOR : mixColor(TRACK_COLOR, headColor, intensity)
700 })
701}
702
703// 彗星此刻的顏色:沿著 ACCENT_COLORS 來回走,一個來回是兩個半週期
704export function cometColor(frame: number): string {
705 const phase = frame % (COMET_COLOR_HALF_PERIOD_FRAMES * 2)
706 const progress = (phase <= COMET_COLOR_HALF_PERIOD_FRAMES ? phase : COMET_COLOR_HALF_PERIOD_FRAMES * 2 - phase) / COMET_COLOR_HALF_PERIOD_FRAMES
707 return paletteAt(ACCENT_COLORS, progress)
708}
709
710// 沿著一串顏色取色:progress 0 是第一個、1 是最後一個,中間在相鄰兩色之間內插
711function paletteAt(colors: readonly string[], progress: number) {
712 const position = progress * (colors.length - 1)
713 const lower = Math.min(Math.floor(position), colors.length - 2)
714 return mixColor(colors[lower]!, colors[lower + 1]!, position - lower)
715}
716
717function gradientAt(gradient: { from: string; to: string }, index: number, length = BAR_WIDTH) {
718 return mixColor(gradient.from, gradient.to, length > 1 ? index / (length - 1) : 0)
719}
720
721// 兩個顏色之間取比例:0 是 from、1 是 to
722function mixColor(from: string, to: string, ratio: number) {
723 const target = hexChannels(to)
724 const mixed = hexChannels(from).map((channel, i) => Math.round(channel + (target[i]! - channel) * ratio))
725 return `#${mixed.map(channel => channel.toString(16).padStart(2, '0')).join('')}`
726}
727
728function hexChannels(hex: string) {
729 return [1, 3, 5].map(start => parseInt(hex.slice(start, start + 2), 16))
730}
731
732function lighten(hex: string, ratio: number) {
733 return mixColor(hex, '#ffffff', ratio)
734}
735
736// 東亞寬字元、全形符號與 emoji 在終端機佔兩格;範圍用 \u 跳脫,避免存檔時字元被正規化成別的碼位
737const WIDE_CHAR = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F300}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u
738
739function charWidth(char: string) {
740 return WIDE_CHAR.test(char) ? 2 : 1
741}
742
743function displayWidth(text: string) {
744 let width = 0
745 for (const char of text) width += charWidth(char)
746 return width
747}
748
749type ToolCallView = { tool: string; input: unknown; isRunning: boolean; isErrored: boolean; isInterrupted: boolean; output?: unknown }
750type ToolLine = { text: string; color?: ThemeKey }
751
752// 一個工具呼叫在畫面上的所有列:一行摘要,出錯時下面接錯誤內容
753export function toolLines(call: ToolCallView): ToolLine[] {
754 const errors = errorLines(call)
755 const indented = errors.map((line, index) => ({ text: `${index === 0 ? ' ⎿ ' : ' '}${line}`, color: 'error' as const }))
756 return [toolLine(call), ...indented]
757}
758
759export function toolLine(call: ToolCallView): ToolLine {
760 const label = ` · ${describe(call.tool, call.input)}`
761 if (call.isInterrupted) return { text: `${label}(已中斷)`, color: 'warning' }
762 if (call.isErrored) return { text: `${label}(失敗)`, color: 'error' }
763 if (call.isRunning) return { text: `${label} …` }
764 return { text: label }
765}
766
767// 出錯時 output 是模型讀到的文字。中斷不算錯誤內容,摘要已標「(已中斷)」。
768// Bash 失敗是「Exit code N」後面接整段輸出,錯誤多半在最後,所以太長時留第一行與最後幾行
769export function errorLines(call: ToolCallView): string[] {
770 if (!call.isErrored || call.isInterrupted || typeof call.output !== 'string') return []
771 const text = call.output
772 .replace(/<\/?tool_use_error>/g, '')
773 .replace(/\x1b\[[0-9;]*m/g, '') // Python traceback 之類的輸出夾帶的 ANSI 色碼
774 const lines = text.split('\n').filter(line => line.trim() !== '')
775 if (lines.length <= MAX_ERROR_LINES) return lines
776 const tail = lines.slice(-(MAX_ERROR_LINES - 2))
777 return [lines[0]!, `…(省略 ${lines.length - 1 - tail.length} 行)`, ...tail]
778}
779
780// 一句話說出 Claude 在做什麼,取代原本的工具名稱與參數;where-am-i 的 describe 用同一套用字
781export function describe(tool: string, input: unknown): string {
782 const args = (typeof input === 'object' && input !== null ? input : {}) as Record<string, unknown>
783 const text = (key: string) => (typeof args[key] === 'string' ? (args[key] as string) : '')
784 const file = (path: string) => path.split('/').slice(-2).join('/')
785 if (tool === 'Bash') return `執行:${text('description') || text('command').slice(0, 80)}`
786 if (tool === 'Read') return `讀取 ${file(text('file_path'))}`
787 if (tool === 'Write') return `寫入 ${file(text('file_path'))}`
788 if (tool === 'Edit') return `編輯 ${file(text('file_path'))}`
789 if (tool === 'NotebookEdit') return `編輯 ${file(text('notebook_path'))}`
790 if (tool === 'Grep' || tool === 'Glob') return `搜尋 "${text('pattern').slice(0, 40)}"`
791 if (tool === 'WebSearch') return `搜尋網路「${text('query').slice(0, 40)}」`
792 if (tool === 'WebFetch') return `讀取網頁 ${hostOf(text('url'))}`
793 if (tool === 'Agent') return `委派 agent:${text('description')}`
794 if (tool === 'Skill') return `使用 skill:${text('skill')}`
795 if (tool === 'AskUserQuestion') return '詢問你問題'
796 if (tool === 'ToolSearch') return '載入工具'
797 if (tool.startsWith('mcp__')) return `使用 ${tool.split('__').slice(1).join(' ')}`
798 return `使用 ${tool}`
799}
800
801function hostOf(url: string) {
802 const match = /^[a-z]+:\/\/([^/?#]+)/i.exec(url)
803 return match?.[1] ?? url.slice(0, 40)
804}
805
806const PLAN_STATUSES: readonly string[] = ['pending', 'in_progress', 'completed'] satisfies PlanStatus[]
807
808export function parseSteps(value: unknown): PlanStep[] | null {
809 if (!Array.isArray(value)) return null
810 const steps = value.flatMap(item => (isPlanStep(item) ? [{ title: item.title.trim(), status: item.status }] : []))
811 return steps.length === value.length ? steps : null
812}
813
814function isPlanStep(item: unknown): item is PlanStep {
815 if (typeof item !== 'object' || item === null) return false
816 const { title, status } = item as Record<string, unknown>
817 return typeof title === 'string' && typeof status === 'string' && PLAN_STATUSES.includes(status)
818}
819
820function countCompleted(steps: readonly PlanStep[]) {
821 return steps.filter(step => step.status === 'completed').length
822}
823
824function isPlanFinished(steps: readonly PlanStep[]) {
825 return steps.length > 0 && countCompleted(steps) === steps.length
826}
827types/index.d.ts 27 lines1export type PlanStatus = 'pending' | 'in_progress' | 'completed'
2
3export type PlanStep = { title: string; status: PlanStatus }
4
5// 合併框何時顯示:hidden 不顯示(沒有計畫或 /clean 關掉)、always 一直顯示(計畫做完了也留著,看最後停在幾秒,下一個 prompt 送出時清掉)
6export type CombinedBoxMode = 'hidden' | 'always'
7
8// 目前(或最近一次)工作的起訖時間:從使用者送出 prompt,到主迴圈的回合結束而且子代理都跑完;endedAt 是 null 表示還在跑
9export type TurnClock = { startedAt: number; endedAt: number | null }
10
11declare module 'claude-code' {
12 interface PluginState {
13 // where-am-i/types/index.d.ts 也宣告了同樣的形狀,改這裡要一起改;../scripts/check-contracts.sh 會抓出不一致
14 'clean-view': {
15 isEnabled: boolean
16 plan: PlanStep[]
17 tick: number
18 turnClock: TurnClock | null
19 combinedBox: CombinedBoxMode
20 }
21 // where-am-i 擁有,這裡只讀來放進合併框;形狀要跟它自己的合約一致
22 'where-am-i': { recap: { goal: string; now: string; waiting: string; next: string } | null; live: string }
23 // next-steps 擁有(next-steps/types/index.d.ts),這裡只讀來讓出它建議清單的列數
24 'next-steps': { active: boolean }
25 }
26}
27