แถบเหนือ prompt เตือน repo ที่ session นี้แตะแล้วยังไม่ commit / ยังไม่ push พร้อมปุ่ม commit และ push

One long session of building Claude Code mods on Windows 11, written up honestly: what shipped, what I tried and threw away, and why. Most mod repos only show the finished screenshot. This one also keeps the failures, because they say more about the mod API than the wins do.
Status: two weeks of daily use. Built on Claude Code 2.1.291 (2026-10-06). Still loading, with every test passing, on 2.1.306 (2026-10-21), after 12 updates and no change needed for the engine. Tested on one machine: Windows 11, Windows Terminal 1.24, Cascadia Code, a cream background (
#F2F0DA), 134 columns, fullscreen mode. The mod API is still new and may change under you. Issues welcome.
| Piece | Status | One-line lesson |
|---|---|---|
| fuel-bar | in daily use | The engine gives you context, auto-compact threshold and rate limits for free after every turn. No polling, no tokens. |
| thai-mode | in daily use | You can re-render tool rows, groups, spinner and turn duration. You cannot touch the prompt box. |
| task-band | in daily use | The engine tells a mod when an agent ends right away, but shell/monitor/workflow ends only reach it at the next tool call while Claude is busy. And there is no progress % for anything. |
| paste-peek | in daily use | The mod API can draw images only through the kitty protocol, which Windows Terminal lacks. A tiny native window beside the terminal does the job, and Claude Code already saves each pasted image to disk before you send. |
| git-band | in daily use | Two bands in AbovePrompt hide each other unless each one awaits next(e) and stacks the result. The engine has no git events, so the mod works out which repos the session touched from the tool calls. |
| Matrix intro | in daily use | A sequential intro always leaves a blank gap. Run it in parallel and stop on a file Claude writes before its first frame, or as soon as Claude puts the console in raw mode for a dialog. |
| Safe updater | in daily use | Auto-update on Windows can leave claude.exe as a 500-byte stub. Stage, verify, then rename-and-swap. |
| Right-side pane + widgets | dropped | The dock frame belongs to the engine, and Thai text breaks in the Windows Terminal grid with every font I tried. |
| project-band above the prompt | dropped | Engine notifications render between your band and the prompt, and you cannot intercept them. |
| matrix-rain as a mod | dropped | session.start fires after the first frame. Too late for a loading screen. |
| Rounded prompt box | not possible | The prompt input is not a render site. |
| Context Router, prismantis | declined | Already built in / clashes with thai-mode and adds tokens per prompt. |
TaskStop kept spinning until the session ended (fixed, see task-band).AbovePrompt bands hid each other (fixed, see git-band).git cl upload, not git push) the band showed ↑1 and a push button that could only fail. Fixed in 0.1.3.numStartups, so the intro kept raining over it, and even after the 20 s cap the dialog stayed buried under leftover rain. Fixed, see the intro section.
Two lines under the prompt:
T77 │ Opus 5.5 · medium │ ━━━━━━──── 53.7% 519.3k/1M │ 5h 26.0% (1h57m) · 7D 47.0% (3d) turn · model · effort · gauge to the auto-compact point (not to the raw window) · 5-hour and 7-day quota with time to reset.PROJECT · ✦ 24.2° night rain 39% · worked 4:32 hr, plus the latest mod toast on the right for 8 seconds.Why I built it: I was using ccusage statusline, and on a 1M-context model it showed context above 100% (147% on my screen). The engine already knows the right numbers.
How it works:
session.measure fires after every turn with context.tokens, context.window and rateLimits[] (five_hour, seven_day, each with percentUsed and resetsAt). session.usage({ breakdown: 'summary' }) adds autoCompactThreshold. Zero tokens, no process spawned.turn.step carries the current effort.PromptHint render site. If you return two lines, the engine keeps its own mode pill (⏵⏵ auto mode on) on the first line and indents the second by the pill's width. I tried drawing my own pill. The engine's pill stays anyway, so I gave up and kept theirs.ipwho.is for a rough location, then api.open-meteo.com. No keys, cached 30 min. This sends your IP to ipwho.is. Delete loadWeather if you don't want that.ui.toast can be intercepted (return { value: undefined }), so mod toasts land at the end of line 2 instead of popping over the transcript.dependencies: ["thai-mode"] in plugin.json lets fuel-bar read thai-mode's state and translate the hint itself. Two mods never fight over the same render site.Colors are hand-picked for a light cream background. On a dark theme you'll want to change the C palette in register.tsx.

Rewrites, with a built-in dictionary (no model calls):
ToolUse): Read → อ่านไฟล์, Bash → รันคำสั่ง, and MCP tools as service · Thai verbToolResult): "read 120 lines (40–159 of 300)", "added 4 · removed 1 lines", with the diff still drawn by the engine's Code componentToolGroup): กำลังเขียน 1 ไฟล์ · แก้ 1 ไฟล์ · รัน 1 คำสั่ง…requesting / thinking / responding / tool-input / tool-use)ctrl+b hint/thai toggles it, and the choice persists in $.store.
Things I learned:
Edit gets folded into a ToolGroup, so your nice single-row rendering mostly shows up only in ctrl+o.
A framed band above the prompt (AbovePrompt) titled "งานเบื้องหลัง" (background work). Each running subagent, Workflow, background shell and Monitor gets one chip with its own gauge, 3 per page:
What the API gives you (build 2.1.292):
agent.spawn answers with an agentId. Its end is turn.complete carrying that agentId, and it arrives immediately. Workflow agents come through agent.spawn too, with e.workflow.runId.backgroundTaskId. Monitor and Workflow results carry taskId (Workflow also runId and workflowName).prompt.submit with origin.kind === 'task-notification', with <task-id> and <status> in the text. When Claude is idle that is instant. While a turn runs it waits for the next tool-call boundary (I measured 4.3 s late).await next(e).Things that bit me:
Box takes borderStyle but has no border title. Laying a position: "absolute" title over the border line shifted the whole screen sideways and left it garbled until a resize forced a full redraw. The frame is now three plain Text rows sized to bodyColumns (the engine draws [-] at the far right of the band).TaskStop now ends its chip right away (marked ✗) instead of spinning until the stop notice arrives. The band also renders what other mods put in AbovePrompt first, see git-band below.A one-line band above the prompt, shown only while Claude is idle, listing every repo this session touched that still has work to save:
git ค้าง my-app ●3 [ commit ] │ notes ↑1 [ push ]
●3 = three changed files, ↑1 = one commit not on the remote yet.git push from the mod itself, no tokens. It shows ⠹ กำลัง push, then ✓ push แล้ว for 5 seconds. On failure it shows a short reason (needs pull / login / network) and a [ ให้ Claude แก้ ] button that hands the full git error to Claude.logic.ts and register.tsx if you want them in English.How it decides which repos to watch:
Edit / Write / NotebookEdit.cd, Set-Location, pushd or git -C inside a Bash or PowerShell command.git rev-parse --show-toplevel and cached. The band refreshes on turn.complete for the main agent only, so a subagent finishing doesn't make it flicker.Things that bit me:
AbovePrompt handler returns its own element without calling next(e), every band from another mod disappears. Await next(e) and put the result above or below yours. task-band was fixed for the same reason.git push can pick the wrong one and fail with 403. If the repo has no credential.username set, the mod adds -c credential.username=<owner from the remote URL> for that one push.↑N: the mod counts commits not on any remote (rev-list HEAD --not --remotes) and pushes with -u.gerrit.host is set or the remote is on googlesource.com, the mod ignores ↑N and shows no push button, only ●. A plain push there goes nowhere useful.<git dir>/git-band-skip.txt (mtime in ms, a tab, the path). The band stops counting a listed file until the file changes again, so a skipped file can't hide new edits.
Windows only. Claude Code shows a pasted image as [Image #1] and nothing else, so you can't tell whether you attached the right screenshot until Claude answers. paste-peek opens a small strip in the bottom-right corner of your Windows Terminal window with a thumbnail of every [Image #N] in your draft:
[Image #2] from the draft and #2 leaves the strip. Send the message and the strip closes.Alt+V pastes and for files dragged onto the terminal.Why a separate window: the mod API has an Image element, but the engine draws it only through the kitty graphics protocol, which Windows Terminal doesn't speak, so you just get the alt text. I also tried a Raster of half-block characters (▀, two pixels per cell). It works everywhere, but a 6-row thumbnail is about 21×12 pixels, which is too blurry to tell screenshots apart.
How it works:
$.prompt.read()) every 250 ms and writes the list of [Image #N] numbers to a small state file in %TEMP%.peek.exe (C#, WinForms, about 475 lines in native/peek.cs). The exe watches the state file with a FileSystemWatcher and closes itself when the file goes empty, which the mod does on submit.%TEMP%\claude\<project-slug>\<session-id>\images\<N>.<ext> as soon as you paste or drop it, before you send. This is undocumented and may change in a future version. Claude Code skips this when transcript saving is off (for example a session started from inside another Claude session, which shows a "Transcript saving is off" notice), and the strip then says "no preview". My first build read the clipboard instead, and a dragged file then showed whatever image was last copied.EVENT_SYSTEM_FOREGROUND and location changes. No polling.Measured on my laptop: about 24 MB private memory and 0% CPU while the strip is open, nothing at all while there are no images, and the strip appears in about 0.2 s.
No binary in this repo. On first use the mod compiles native/peek.cs with the C# compiler that ships with Windows (%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe, .NET Framework 4.x) into %LOCALAPPDATA%\paste-peek\. That takes about a second, once.
Options (/config): label language (en / th), theme (dark / light), and the distance from the window's bottom and right edges. The default bottom distance clears a two-line footer. Raise it if the strip covers your prompt.
Tested end to end in a fresh session: first-use compile, dark theme, English labels, a pasted image showing in the strip. Not handled yet: more than one terminal tab in the same window (the strip follows the window, not the tab), and terminals other than Windows Terminal.

Katakana rain in ink-on-cream with the folder name decoding in the middle, shown while Claude Code loads (about 4.7 s on this laptop). It is not a mod. It is a tiny C# exe started by the launcher.
The path there was three failures:
claude. However long the intro runs, you still get a blank or log-only screen between the intro ending and Claude's first frame.session.start fires after Claude has drawn its first screen. The rain lands on top of Claude, and in fullscreen mode Ctrl+L does not clear it.What works:
claude-launcher.cmd does start "" /b matrix-intro.exe and then call claude at the same moment. The rain shows within ~0.7 s.numStartups in <CLAUDE_CONFIG_DIR>\.claude.json every 120 ms. Claude bumps it 0.4–0.7 s before drawing its first frame, which is the "ready" signal. Hard cap: 20 s.cls, but only if the intro actually ran (it drops a marker file).-p, --version, --help and subcommands. CLAUDE_MATRIX_INTRO=0 disables it.Dialogs before the first frame (fixed 2026-10-26). The "Accessing workspace" trust dialog (and any other prompt Claude shows before its first screen) comes before the numStartups bump. The old intro rained right over it, and when it stopped, the dialog stayed hidden: Claude repaints only the cells that change, so the leftover rain never went away. What fixed it:
0x208 here) the moment it shows anything that takes keys: a dialog or the prompt. The intro checks this every frame and stops on the change.SetConsoleWindowInfo). Claude treats that as a resize and repaints the whole screen, so whatever it already drew comes back clean.WINDOW_BUFFER_SIZE_EVENT into the input buffer with WriteConsoleInput. Claude ignores it. Only a real size change triggers the repaint.Batch trap: claude installed by npm is claude.cmd. If you write claude %* instead of call claude %* in a .cmd, nothing after that line ever runs.
Half-width katakana take exactly one cell in Windows Terminal with Cascadia Code, so the columns line up.
Build it with the C# compiler that ships with Windows:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /nologo /optimize+ /codepage:65001 windows\matrix-intro.cs
On this machine, Claude Code's own auto-update repeatedly left node_modules\@anthropic-ai\claude-code\bin\claude.exe as a ~500-byte stub ("This version of claude.exe is not compatible…"), or failed with "claude.exe in use" while another session was open. Its warning also showed up in the middle of the screen:

windows/claude-update-safe.ps1:
npm view @anthropic-ai/claude-code version.--version.claude.exe.old-<timestamp> (Windows allows renaming a running exe, not overwriting it), then moves the new one in. Open sessions keep running the old file. New sessions get the new one..old-* files on the next run, and logs to %LOCALAPPDATA%\claude-update-safe\claude-update.log.Set "env": { "DISABLE_AUTOUPDATER": "1" } in settings.json so the built-in updater stops fighting it. matrix-intro.exe launches the script hidden at every start if it sits in the same folder.
This only applies to the global npm install. The native installer manages its own versioned folders.
Right-side pane with widgets (project name, a 3-tab reminder list, weather, other open sessions). Inspired by paneline and flightdeck. It worked technically (Pane render site with fullscreen: true), but:
เ ปิด). I tried Noto Sans Thai, Leelawadee, Tahoma, Tlwg Mono and Tlwg Typo. None fixed it. This is a WT grid limit, not a font problem.viewport.columns in PromptHint is the transcript width, not the full window./pane.project-band above the prompt (AbovePrompt, one line: project · weather · time worked). It looked good until Claude Code showed its own notice (Auto-update failed …). Engine notices render between AbovePrompt and the prompt, and they are standing warnings, not ui.toast, so a mod can't catch them. I merged the band into fuel-bar's second line instead.
matrix-rain as a mod. See the intro section: session.start is too late.
Rounded prompt box. I mocked it in a browser first. That was a mistake, because the prompt input is not one of the render sites, so a mod can't change it. A custom theme can recolor the border (promptBorder) but not reshape it.
CLAUDE.md from parent folders, and @path imports work.ToolUse, ToolGroup and TurnDuration (the same sites as thai-mode), and its diagramHints adds about 190 tokens to every prompt.The HUD in one popular mod's demo video (LIFE / LEVEL / XP bars across the top) is rendered with Revideo in its demo/ folder. The README says as much: "Nothing in it is captured". It isn't something the mod draws in your terminal. Before you promise someone a feature you saw in a GIF, grep the mod's hooks/ folder.
Mockups in a browser lie about fonts, colors and cell widths. What I used instead:
wt -w new <file.cmd>. Start-Process with arguments quotes the whole command line and fails with 0x80070002.CASCADIA_HOSTING_WINDOW_CLASS. Capture it with PrintWindow(hwnd, dc, 2) after SetProcessDPIAware(). That works even when the window is behind another one. CopyFromScreen only sees what's visible.SendInput + KEYEVENTF_UNICODE. SendKeys follows the active keyboard layout: with Thai active, /exit arrives as /59.claude plugin marketplace add <path-to-clone>\mods
claude plugin install fuel-bar@field-notes-mods --scope user
claude plugin install thai-mode@field-notes-mods --scope user
claude plugin install task-band@field-notes-mods --scope user
claude plugin install paste-peek@field-notes-mods --scope user
claude plugin install git-band@field-notes-mods --scope user
Plugins are read from that folder in place: edit a file, then run /reload-plugins. claude plugin test <folder> runs the tests (fuel-bar 7, thai-mode 5, task-band 14, paste-peek 4, git-band 11).
For the intro: compile windows/matrix-intro.cs, then put matrix-intro.exe, claude-update-safe.ps1 and claude-launcher.cmd in one folder on your PATH.
บันทึกการทำ mod ให้ Claude Code บน Windows ในหนึ่งวัน ทั้งชิ้นที่ใช้จริงและชิ้นที่ลองแล้วทิ้ง
ผ่านไปสองสัปดาห์ (2026-10-21): ใช้ทุกวันตั้งแต่ Claude Code 2.1.291 ถึง 2.1.306 (อัปเดต 12 ครั้ง) ไม่ต้องแก้ mod เพราะ engine เปลี่ยนเลย บั๊กที่เจอมาจากการใช้งานจริงทั้งหมด: task-band ค้างเมื่อหยุดงานด้วย TaskStop · แถบ AbovePrompt สองตัวบังกัน · git-band ขึ้นปุ่ม push ใน repo แบบ Gerrit · git-band เตือนไม่หยุดเรื่องไฟล์ที่ Claude ตั้งใจไม่ commit ทุกข้อแก้แ
hooks/register.tsx 280 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { RepoState } from '../types'
5import { C, cellWidth, commandDirs, commitPrompt, fit, fixPushPrompt, githubAccount, isGerrit, isPending, isSkipped, norm, parentDir, parseSkip, parseStatus, shortReason, SKIP_FILE } from './logic'
6
7const repos = atom({ plugin: 'git-band', key: 'repos' } as const, [] as RepoState[])
8const roots = atom({ plugin: 'git-band', key: 'roots' } as const, [] as string[])
9const edited = atom({ plugin: 'git-band', key: 'edited' } as const, [] as string[])
10const busy = atom({ plugin: 'git-band', key: 'busy' } as const, false)
11
12const LEAD = 'git ค้าง '
13const rootOf = new Map<string, string | null>()
14const gerritOf = new Map<string, boolean>()
15const gitDirs = new Map<string, string | undefined>()
16let refreshing: Promise<void> | null = null
17
18async function git($: EngineInterface, root: string, args: string[], timeoutMs = 15000) {
19 return $.process.run(['git', '-C', root, ...args], { timeoutMs })
20}
21
22async function findRoot($: EngineInterface, dir: string): Promise<string | null> {
23 const key = norm(dir)
24 if (rootOf.has(key)) return rootOf.get(key) ?? null
25 let root: string | null = null
26 try {
27 const r = await $.process.run(['git', '-C', dir, 'rev-parse', '--show-toplevel'], { timeoutMs: 5000 })
28 if (r.exitCode === 0) root = r.stdout.trim() || null
29 } catch {
30 root = null
31 }
32 rootOf.set(key, root)
33 return root
34}
35
36async function addDir($: EngineInterface, dir: string) {
37 const root = await findRoot($, dir)
38 if (!root) return
39 await update($, roots, list => (list.some(r => norm(r) === norm(root)) ? list : [...list, root]))
40}
41
42async function gitDirOf($: EngineInterface, root: string): Promise<string | undefined> {
43 const key = norm(root)
44 if (gitDirs.has(key)) return gitDirs.get(key)
45 let dir: string | undefined
46 try {
47 const r = await git($, root, ['rev-parse', '--absolute-git-dir'])
48 if (r.exitCode === 0) dir = r.stdout.trim() || undefined
49 } catch {
50 dir = undefined
51 }
52 gitDirs.set(key, dir)
53 return dir
54}
55
56async function gerrit($: EngineInterface, root: string): Promise<boolean> {
57 const key = norm(root)
58 const known = gerritOf.get(key)
59 if (known !== undefined) return known
60 let yes = false
61 try {
62 const host = await git($, root, ['config', '--get', 'gerrit.host'])
63 const url = await git($, root, ['remote', 'get-url', 'origin'])
64 yes = isGerrit(host.stdout, url.stdout)
65 } catch {
66 yes = false
67 }
68 gerritOf.set(key, yes)
69 return yes
70}
71
72async function scan($: EngineInterface, root: string, prev: RepoState | undefined, mineAbs: string[]): Promise<RepoState | null> {
73 let st
74 try {
75 const r = await git($, root, ['status', '--porcelain=v1', '-b', '-uall'])
76 if (r.exitCode !== 0) return null
77 st = parseStatus(r.stdout)
78 } catch {
79 return null
80 }
81 let ahead = st.ahead
82 if (!st.upstream) {
83 try {
84 const remotes = await git($, root, ['remote'])
85 if (remotes.stdout.trim()) {
86 const c = await git($, root, ['rev-list', '--count', 'HEAD', '--not', '--remotes'])
87 ahead = c.exitCode === 0 ? Number(c.stdout.trim()) || 0 : 0
88 } else ahead = 0
89 } catch {
90 ahead = 0
91 }
92 }
93 if (ahead > 0 && (await gerrit($, root))) ahead = 0
94 const base = norm(root)
95 const gitDir = await gitDirOf($, root)
96 const skip = gitDir ? parseSkip(await $.fs.read(`${gitDir}/${SKIP_FILE}`).catch(() => '')) : new Map<string, number>()
97 const files: string[] = []
98 for (const f of st.files) {
99 const stat = skip.size ? await $.fs.stat(`${root}/${f}`).catch(() => undefined) : undefined
100 if (!isSkipped(skip, f, stat?.mtimeMs)) files.push(f)
101 }
102 const mine = files.filter(f => mineAbs.includes(`${base}/${norm(f)}`))
103 const name = root.replace(/\\/g, '/').split('/').filter(Boolean).pop() ?? root
104 const keep = prev?.phase === 'fail' || prev?.phase === 'pushing' || prev?.phase === 'done' ? prev : undefined
105 return {
106 root,
107 name,
108 branch: st.branch,
109 gitDir,
110 dirty: files.length,
111 files,
112 mine,
113 ahead,
114 phase: keep?.phase,
115 reason: keep?.reason,
116 error: keep?.error,
117 }
118}
119
120async function refresh($: EngineInterface) {
121 if (refreshing) return refreshing
122 refreshing = (async () => {
123 const [list, prev, mineAbs] = await Promise.all([read($, roots), read($, repos), read($, edited)])
124 const out: RepoState[] = []
125 for (const root of list ?? []) {
126 const s = await scan($, root, (prev ?? []).find(p => p.root === root), mineAbs ?? [])
127 if (s) out.push(s)
128 }
129 await update($, repos, () => out)
130 })()
131 try {
132 await refreshing
133 } finally {
134 refreshing = null
135 }
136}
137
138async function setPhase($: EngineInterface, root: string, patch: Partial<RepoState>) {
139 await update($, repos, list => list.map(r => (r.root === root ? { ...r, ...patch } : r)))
140}
141
142async function push($: EngineInterface, r: RepoState) {
143 await setPhase($, r.root, { phase: 'pushing', reason: undefined, error: undefined })
144 let args = ['push']
145 try {
146 let remote: string | undefined
147 const up = await git($, r.root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])
148 if (up.exitCode !== 0) {
149 const remotes = (await git($, r.root, ['remote'])).stdout.split(/\r?\n/).filter(Boolean)
150 remote = remotes.includes('origin') ? 'origin' : remotes[0]
151 if (!remote) {
152 await setPhase($, r.root, { phase: 'fail', reason: 'ไม่มี remote', error: 'repo นี้ยังไม่มี remote ให้ push' })
153 return
154 }
155 args = ['push', '-u', remote, r.branch]
156 } else {
157 remote = up.stdout.trim().split('/')[0]
158 }
159 const pinned = await git($, r.root, ['config', 'credential.username'])
160 if (!pinned.stdout.trim() && remote) {
161 const url = await git($, r.root, ['remote', 'get-url', '--push', remote])
162 const account = githubAccount(url.stdout)
163 if (account) args = ['-c', `credential.username=${account}`, ...args]
164 }
165 const res = await git($, r.root, args, 120000)
166 if (res.exitCode === 0) {
167 await setPhase($, r.root, { phase: 'done' })
168 $.clock.after(5000, async () => {
169 await setPhase($, r.root, { phase: undefined })
170 await refresh($)
171 })
172 } else {
173 await setPhase($, r.root, { phase: 'fail', reason: shortReason(res.stderr), error: res.stderr })
174 }
175 } catch (err) {
176 await setPhase($, r.root, { phase: 'fail', reason: 'git ไม่ตอบ', error: String(err) })
177 }
178}
179
180async function commit($: EngineInterface, r: RepoState) {
181 await setPhase($, r.root, { phase: 'queued' })
182 await $.prompt.submit({ text: commitPrompt(r) })
183}
184
185async function askFix($: EngineInterface, r: RepoState) {
186 await setPhase($, r.root, { phase: undefined, reason: undefined })
187 await $.prompt.submit({ text: fixPushPrompt(r) })
188}
189
190export const register: Register = on => {
191 on('session.start', async ($, e, next) => {
192 const started = await next(e)
193 await update($, busy, () => false)
194 await addDir($, await $.session.cwd())
195 await refresh($)
196 return started
197 })
198
199 on('tool.call', async ($, e, next) => {
200 const result = await next(e)
201 if (e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit') {
202 const file = 'file_path' in e ? (e.file_path as string) : 'notebook_path' in e ? (e.notebook_path as string) : ''
203 if (file) {
204 await update($, edited, list => (list.includes(norm(file)) ? list : [...list, norm(file)]))
205 await addDir($, parentDir(file))
206 }
207 } else if (e.tool === 'Bash' || e.tool === 'PowerShell') {
208 const command = 'command' in e ? (e.command as string) : ''
209 for (const d of commandDirs(command)) await addDir($, d)
210 }
211 return result
212 }).catch(($, e, next) => next(e))
213
214 on('turn.start', async ($, e, next) => {
215 await update($, busy, () => true)
216 return next(e)
217 })
218
219 on('turn.complete', async ($, e, next) => {
220 const done = await next(e)
221 if (e.agentId === undefined) {
222 await update($, repos, list => list.map(r => (r.phase === 'queued' ? { ...r, phase: undefined } : r)))
223 await refresh($)
224 await update($, busy, () => false)
225 }
226 return done
227 })
228
229 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
230 const [list, isBusy] = await Promise.all([read($, repos), read($, busy)])
231 const pending = (list ?? []).filter(isPending)
232 if (e.props.hasSurvey || isBusy || pending.length === 0) return next(e)
233
234 const below = await next(e)
235 const { Box, Button, Text } = $.ui.resolve(e)
236 const { shown, hidden } = fit(pending, e.props.bodyColumns - 1, cellWidth(LEAD) + 1)
237
238 return (
239 <Box flexDirection="column">
240 <Text color={C.faint}>{'╌'.repeat(Math.max(0, e.props.bodyColumns - 1))}</Text>
241 <Box flexDirection="row">
242 <Text color={C.dim}> {LEAD}</Text>
243 {shown.map((r, i) => (
244 <Box key={r.root} flexDirection="row">
245 {i > 0 ? <Text color={C.faint}> │ </Text> : null}
246 <Text color={C.fg}>{r.name} </Text>
247 {r.phase === 'pushing' ? (
248 <Text color={C.blue}>⠹ กำลัง push</Text>
249 ) : r.phase === 'done' ? (
250 <Text color={C.green}>✓ push แล้ว</Text>
251 ) : r.phase === 'fail' ? (
252 <Box flexDirection="row">
253 <Text color={C.red}>✗ push ไม่ผ่าน {r.reason ?? ''} </Text>
254 <Button key={`fix:${r.root}`} label="ให้ Claude แก้" onPress={() => askFix($, r)} />
255 </Box>
256 ) : (
257 <Box flexDirection="row">
258 {r.dirty > 0 ? <Text color={C.amber}>●{r.dirty} </Text> : null}
259 {r.ahead > 0 ? <Text color={C.amber}>↑{r.ahead} </Text> : null}
260 {r.phase === 'queued' ? (
261 <Text color={C.dim}>◷ รอ Claude commit</Text>
262 ) : (
263 <Box flexDirection="row">
264 {r.dirty > 0 ? <Button key={`commit:${r.root}`} label="commit" onPress={() => commit($, r)} /> : null}
265 {r.dirty > 0 && r.ahead > 0 ? <Text> </Text> : null}
266 {r.ahead > 0 ? <Button key={`push:${r.root}`} label="push" onPress={() => push($, r)} /> : null}
267 </Box>
268 )}
269 </Box>
270 )}
271 </Box>
272 ))}
273 {hidden > 0 ? <Text color={C.dim}> │ +{hidden}</Text> : null}
274 </Box>
275 {below}
276 </Box>
277 )
278 })
279}
280hooks/logic.ts 178 lines1import type { RepoState } from '../types'
2
3export const C = {
4 fg: '#2d2a24',
5 dim: '#6b675e',
6 faint: '#b9b5a3',
7 green: '#3f8a3a',
8 amber: '#a06c00',
9 red: '#b8322b',
10 blue: '#2f5fd0',
11}
12
13const THAI_ZERO = /[ัิ-ฺ็-๎]/u
14
15export function cellWidth(s: string): number {
16 let n = 0
17 for (const ch of s) if (!THAI_ZERO.test(ch)) n++
18 return n
19}
20
21export function norm(p: string): string {
22 let s = p.replace(/\\/g, '/').replace(/\/+$/, '')
23 const msys = s.match(/^\/([a-zA-Z])\/(.*)$/)
24 if (msys) s = `${msys[1]}:/${msys[2]}`
25 return s.toLowerCase()
26}
27
28export function parentDir(p: string): string {
29 const s = p.replace(/\\/g, '/').replace(/\/+$/, '')
30 const i = s.lastIndexOf('/')
31 return i > 0 ? s.slice(0, i) : s
32}
33
34export type Status = {
35 branch: string
36 upstream?: string
37 ahead: number
38 files: string[]
39}
40
41export function parseStatus(out: string): Status {
42 const lines = out.split(/\r?\n/).filter(l => l.length > 0)
43 let branch = ''
44 let upstream: string | undefined
45 let ahead = 0
46 const files: string[] = []
47 for (const l of lines) {
48 if (l.startsWith('## ')) {
49 const head = l.slice(3)
50 const m = head.match(/^(.+?)(?:\.\.\.(\S+))?(?: \[(.*)\])?$/)
51 branch = m?.[1] ?? head
52 if (branch.startsWith('No commits yet on ')) branch = branch.slice(18)
53 upstream = m?.[2]
54 const a = (m?.[3] ?? '').match(/ahead (\d+)/)
55 ahead = a ? Number(a[1]) : 0
56 continue
57 }
58 let f = l.slice(3)
59 const arrow = f.indexOf(' -> ')
60 if (arrow >= 0) f = f.slice(arrow + 4)
61 if (f.startsWith('"') && f.endsWith('"')) f = f.slice(1, -1)
62 files.push(f)
63 }
64 return { branch, upstream, ahead, files }
65}
66
67const CD = /(?:^|[;&|(]\s*)(?:cd|Set-Location|pushd|sl)\s+(?:-LiteralPath\s+|-Path\s+|\/d\s+)?("[^"]+"|'[^']+'|[^\s;&|)]+)/gi
68const GIT_C = /\bgit\s+-C\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/gi
69
70function unquote(s: string): string {
71 return s.replace(/^["']|["']$/g, '')
72}
73
74export function commandDirs(command: string): string[] {
75 const out: string[] = []
76 for (const m of command.matchAll(CD)) out.push(unquote(m[1] ?? ''))
77 for (const m of command.matchAll(GIT_C)) out.push(unquote(m[1] ?? ''))
78 return out.filter(d => /^([a-zA-Z]:[\\/]|\/[a-zA-Z]\/)/.test(d))
79}
80
81export function shortReason(stderr: string): string {
82 const lines = stderr.split(/\r?\n/).map(l => l.trim()).filter(Boolean)
83 const hit =
84 lines.find(l => /rejected|non-fast-forward|fetch first/i.test(l)) ??
85 lines.find(l => /^(fatal|error|remote):/i.test(l)) ??
86 lines[lines.length - 1] ??
87 'ไม่ทราบสาเหตุ'
88 if (/fetch first|non-fast-forward|rejected/i.test(hit)) return 'ต้อง pull ก่อน'
89 if (/could not read|authentication|permission denied|403/i.test(hit)) return 'สิทธิ์/login ไม่ผ่าน'
90 if (/could not resolve host|unable to access/i.test(hit)) return 'ต่อเน็ตไม่ได้'
91 return hit.replace(/^(fatal|error|remote):\s*/i, '').slice(0, 40)
92}
93
94export function isPending(r: RepoState): boolean {
95 return r.dirty > 0 || r.ahead > 0 || r.phase !== undefined
96}
97
98export const SKIP_FILE = 'git-band-skip.txt'
99
100export function parseSkip(text: string): Map<string, number> {
101 const out = new Map<string, number>()
102 for (const line of text.split(/\r?\n/)) {
103 const m = line.match(/^(\d+)\t(.+)$/)
104 if (m) out.set(norm(m[2]!.trim()), Number(m[1]))
105 }
106 return out
107}
108
109export function isSkipped(skip: Map<string, number>, file: string, mtimeMs: number | undefined): boolean {
110 const at = skip.get(norm(file))
111 return at !== undefined && mtimeMs !== undefined && Math.floor(mtimeMs) === at
112}
113
114export function chipWidth(r: RepoState): number {
115 let n = cellWidth(r.name) + 1
116 if (r.phase === 'pushing') return n + cellWidth('⠹ กำลัง push')
117 if (r.phase === 'done') return n + cellWidth('✓ push แล้ว')
118 if (r.phase === 'fail') return n + cellWidth(`✗ push ไม่ผ่าน ${r.reason ?? ''} `) + cellWidth('[ ให้ Claude แก้ ]')
119 if (r.dirty > 0) n += cellWidth(`●${r.dirty}`) + 1
120 if (r.ahead > 0) n += cellWidth(`↑${r.ahead}`) + 1
121 if (r.phase === 'queued') return n + cellWidth('◷ รอ Claude commit')
122 if (r.dirty > 0) n += cellWidth('[ commit ]') + 1
123 if (r.ahead > 0) n += cellWidth('[ push ]')
124 return n
125}
126
127export function fit(list: RepoState[], columns: number, lead: number): { shown: RepoState[]; hidden: number } {
128 const shown: RepoState[] = []
129 let used = lead
130 for (let i = 0; i < list.length; i++) {
131 const r = list[i]!
132 const w = chipWidth(r) + (shown.length > 0 ? 3 : 0)
133 const rest = list.length - i - 1
134 const tail = rest > 0 ? cellWidth(` │ +${rest}`) : 0
135 if (used + w + tail > columns && shown.length > 0) return { shown, hidden: list.length - shown.length }
136 shown.push(r)
137 used += w
138 }
139 return { shown, hidden: 0 }
140}
141
142export function commitPrompt(r: RepoState): string {
143 const mine = r.mine
144 const others = r.files.filter(f => !mine.includes(f))
145 const lines = [
146 `[git-band] founder กดปุ่ม commit เอง = ต้องการให้ commit งานที่ค้างทั้งหมดใน repo ${r.root} (branch ${r.branch}) แม้บางไฟล์จะมาจาก session อื่น`,
147 ]
148 if (mine.length > 0) lines.push(`ไฟล์ที่ session นี้แก้: ${mine.join(', ')}`)
149 if (others.length > 0) lines.push(`${mine.length > 0 ? 'ไฟล์อื่นที่ค้าง' : 'ไฟล์ที่ค้าง'} (งานจาก session อื่นหรือแก้มือ): ${others.join(', ')}`)
150 lines.push(
151 'ทำ: อ่าน git diff ก่อน · แยกเป็นหลาย commit ตามเรื่องของงาน (งานของ session นี้เป็น commit แยก) · เขียนข้อความ commit ให้ตรงงาน · ใช้ git identity ที่ตั้งไว้ใน repo',
152 'ข้ามเฉพาะไฟล์ที่มีค่าลับ ไฟล์ชั่วคราว/ขยะ หรือโค้ดที่เห็นชัดว่าเสียครึ่งทาง แล้วบอก founder ว่าข้ามไฟล์ไหนเพราะอะไร · อย่าปฏิเสธเพียงเพราะไม่ใช่งานของ session นี้',
153 `ไฟล์ที่ข้าม (ยังไม่ลบ) ให้จดลง ${r.gitDir ?? '<git dir>'}/${SKIP_FILE} บรรทัดละไฟล์: <mtime ms>, tab, <path ตาม git status> · mtime ms = [DateTimeOffset]::new((Get-Item <file>).LastWriteTimeUtc).ToUnixTimeMilliseconds() · band จะไม่นับไฟล์นั้นจนกว่าไฟล์จะถูกแก้อีก`,
154 'ยังไม่ต้อง push',
155 )
156 return lines.join('\n')
157}
158
159export function githubAccount(url: string): string | null {
160 const m = url.trim().match(/^https:\/\/([^@/]+@)?github\.com\/([^/]+)\//i)
161 if (!m || m[1]) return null
162 return m[2] ?? null
163}
164
165export function isGerrit(gerritHost: string, url: string): boolean {
166 if (/^true$/i.test(gerritHost.trim())) return true
167 return /^(https?|sso|rpc):\/\/[^/]*googlesource\.com\//i.test(url.trim())
168}
169
170export function fixPushPrompt(r: RepoState): string {
171 return [
172 `[git-band] git push ใน repo ${r.root} (branch ${r.branch}) ไม่ผ่าน`,
173 'ข้อความจาก git:',
174 (r.error ?? '').slice(0, 1500),
175 'แก้ให้ push ได้ (เช่น pull --rebase ถ้าปลอดภัย) · ถ้าต้องตัดสินใจอะไรที่เสี่ยงให้ถามก่อน',
176 ].join('\n')
177}
178types/index.d.ts 22 lines1export type RepoPhase = 'queued' | 'pushing' | 'done' | 'fail'
2
3export type RepoState = {
4 root: string
5 name: string
6 branch: string
7 gitDir?: string
8 dirty: number
9 files: string[]
10 mine: string[]
11 ahead: number
12 phase?: RepoPhase
13 reason?: string
14 error?: string
15}
16
17declare module 'claude-code' {
18 interface PluginState {
19 'git-band': { repos: RepoState[]; roots: string[]; edited: string[]; busy: boolean }
20 }
21}
22