SLOPSHOPPER

task-band

Framed band above the prompt: running subagents, workflows, background shells and monitors, each with its own gauge; ctrl+x tab then arrows to page

bandguardprompttimeragents
A shopper browsing a rack in a slop shop
README

Claude Code mods: field notes from day one (Windows · Thai)

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.

PieceStatusOne-line lesson
fuel-barin daily useThe engine gives you context, auto-compact threshold and rate limits for free after every turn. No polling, no tokens.
thai-modein daily useYou can re-render tool rows, groups, spinner and turn duration. You cannot touch the prompt box.
task-bandin daily useThe 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-peekin daily useThe 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-bandin daily useTwo 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 introin daily useA 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 updaterin daily useAuto-update on Windows can leave claude.exe as a 500-byte stub. Stage, verify, then rename-and-swap.
Right-side pane + widgetsdroppedThe dock frame belongs to the engine, and Thai text breaks in the Windows Terminal grid with every font I tried.
project-band above the promptdroppedEngine notifications render between your band and the prompt, and you cannot intercept them.
matrix-rain as a moddroppedsession.start fires after the first frame. Too late for a loading screen.
Rounded prompt boxnot possibleThe prompt input is not a render site.
Context Router, prismantisdeclinedAlready built in / clashes with thai-mode and adds tokens per prompt.

Two weeks later (2026-10-21)

  • Engine updates: Claude Code went from 2.1.291 to 2.1.306 in 12 updates. None of the mods needed a change for that. Every fix below came from using them, not from the API moving.
  • Safe updater: all 12 updates went through it. Once (2026-10-07) the staged download was the 500-byte stub. The script refused it and left the working exe in place, which is the case it was written for.
  • Bugs found in daily use:
  • task-band: a task stopped with TaskStop kept spinning until the session ended (fixed, see task-band).
  • task-band and git-band: two AbovePrompt bands hid each other (fixed, see git-band).
  • git-band: in a Gerrit repo (changes go up with git cl upload, not git push) the band showed ↑1 and a push button that could only fail. Fixed in 0.1.3.
  • git-band: files Claude deliberately left out of a commit (scratch files, secrets) kept the band nagging forever. Fixed in 0.1.3.
  • No bugs turned up in fuel-bar, thai-mode or paste-peek.
  • Matrix intro (2026-10-26, Claude Code 2.1.310): the rain hid the folder-trust dialog. That dialog shows before Claude bumps 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.

fuel-bar: context + quota footer

fuel-bar

Two lines under the prompt:

  1. 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.
  2. 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.
  • It draws into the 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.
  • On narrow terminals it drops, in order: the hint text, the reset times, the 5h/7D block, then wraps to two lines. The token count always stays.
  • Weather: 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.

thai-mode: Claude Code in Thai

thai-mode

Rewrites, with a built-in dictionary (no model calls):

  • tool rows (ToolUse): Read → อ่านไฟล์, Bash → รันคำสั่ง, and MCP tools as service · Thai verb
  • results (ToolResult): "read 120 lines (40–159 of 300)", "added 4 · removed 1 lines", with the diff still drawn by the engine's Code component
  • collapsed groups (ToolGroup): กำลังเขียน 1 ไฟล์ · แก้ 1 ไฟล์ · รัน 1 คำสั่ง…
  • the spinner word by real phase (requesting / thinking / responding / tool-input / tool-use)
  • turn duration and the ctrl+b hint

/thai toggles it, and the choice persists in $.store.

Things I learned:

  • In this version even a single Edit gets folded into a ToolGroup, so your nice single-row rendering mostly shows up only in ctrl+o.
  • Command output and diffs stay as they are. Translating those would be lying about what ran.

task-band: background work above the prompt

task-band

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:

  • Workflow: agents finished / agents started (1/2) plus elapsed time.
  • Single agent: an estimated ~62% once this agent type has finished at least 3 times (average kept in $.store), otherwise a sweeping line plus elapsed time.
  • Shell / Monitor: sweeping line plus elapsed time. Nothing reports real progress.
  • Running chips come first, finished ones (✓ / ✗) after them, and finished chips stay until the turn ends. Within each group chips keep the order you started them in.
  • When a task starts or ends, the band jumps to its page for 3 seconds. Ctrl+X then Tab focuses the band, ← / → page, Esc goes back to the prompt.

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.
  • Background Bash/PowerShell results carry backgroundTaskId. Monitor and Workflow results carry taskId (Workflow also runId and workflowName).
  • Their end arrives as 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).
  • Results of tool calls sent in parallel come back in any order. To keep chips in the order you started them, take the order key when the hook is entered, before 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).
  • Windows Terminal gives Thai above/below marks zero cells, the same as the engine does. Don't pad widths to "fix" the mis-spaced look. It only misaligns the frame.
  • Engine notices still render between the band and the prompt (the reason project-band was dropped). Here it matters less, because the band is only there while something runs.
  • 0.2.2: a task stopped with 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.

git-band: uncommitted and unpushed work above the prompt

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.
  • [ commit ] sends Claude a prompt to read the diff, split it into commits by topic and skip secrets or junk files, then tell you what it skipped. It does not push.
  • [ push ] runs 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.
  • Labels are in Thai. Change the strings in logic.ts and register.tsx if you want them in English.

How it decides which repos to watch:

  • The session's starting folder.
  • The folder of every file Claude writes with Edit / Write / NotebookEdit.
  • Any absolute path in cd, Set-Location, pushd or git -C inside a Bash or PowerShell command.
  • Each folder is resolved once with 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:

  • Bands hide each other. If a mod's 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.
  • Which GitHub account pushes. With several accounts in Git Credential Manager, a plain 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.
  • A repo with no upstream still shows ↑N: the mod counts commits not on any remote (rev-list HEAD --not --remotes) and pushes with -u.
  • 0.1.3, Gerrit repos: if 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.
  • 0.1.3, files left out on purpose: the commit prompt asks Claude to list each file it skipped in <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.

paste-peek: see the image you just pasted (Windows)

paste-peek

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:

  • Click a thumbnail to enlarge it, click again to shrink. The strip never takes focus, so you keep typing.
  • Delete [Image #2] from the draft and #2 leaves the strip. Send the message and the strip closes.
  • Works for Alt+V pastes and for files dragged onto the terminal.
  • Stays with its own terminal window: it follows moves, hides when you switch to another app or minimize, and comes back when you return.

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:

  • The mod reads the draft ($.prompt.read()) every 250 ms and writes the list of [Image #N] numbers to a small state file in %TEMP%.
  • On the first image it starts 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.
  • Where the pictures come from: Claude Code writes every attached image to %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.
  • The exe ties itself to the Windows Terminal window that was in front when you pasted, and listens for 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.

Matrix boot intro

matrix-intro

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:

  1. Intro first, then claude. However long the intro runs, you still get a blank or log-only screen between the intro ending and Claude's first frame.
  2. Intro as a mod. 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.
  3. Intro in PowerShell. pwsh takes ~0.9 s to start and ~1.5 s to set up, so the first second is blank anyway.

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.
  • The exe polls 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.
  • Claude's fullscreen mode uses the alternate screen, so the rain on the main screen is hidden behind it. After Claude exits, the launcher runs cls, but only if the intro actually ran (it drops a marker file).
  • The intro is skipped for -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:

  • Watch the console input mode as well. While Claude loads, stdin is in line mode. Claude switches it off (mode 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.
  • On stop, clear the screen, wait 400 ms, then narrow the console by one column and widen it back (SetConsoleWindowInfo). Claude treats that as a resize and repaints the whole screen, so whatever it already drew comes back clean.
  • Tried and failed: writing a fake 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

Safe updater for the npm install

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:

engine notice

windows/claude-update-safe.ps1:

  1. Takes a global mutex, so two launches don't race.
  2. Compares the installed version with npm view @anthropic-ai/claude-code version.
  3. Installs the new version into a staging folder, picks the real binary (≥10 MB), and checks --version.
  4. Renames the live exe to 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.
  5. Cleans up old .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.

Tried and dropped

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:

  • The dock frame and its colors belong to the engine and follow the Claude Code theme, not yours.
  • Thai text in Windows Terminal is mis-spaced: combining vowels and tone marks get their own cell (เ ปิด). 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.
  • While the dock is open, viewport.columns in PromptHint is the transcript width, not the full window.
  • Below 144 columns the pane doesn't open by itself. On a 134-column window you have to open it once with /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.

Considered and declined

  • Context Router (load different context per folder). Claude Code already does this: it loads CLAUDE.md from parent folders, and @path imports work.
  • prismantis. Its default theme is dark. It also re-renders ToolUse, ToolGroup and TurnDuration (the same sites as thai-mode), and its diagramHints adds about 190 tokens to every prompt.

A warning about mod screenshots

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.

Testing on the real terminal (Windows)

Mockups in a browser lie about fonts, colors and cell widths. What I used instead:

  • Launch a fresh window with wt -w new <file.cmd>. Start-Process with arguments quotes the whole command line and fails with 0x80070002.
  • Find the window by class 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.
  • Type with SendInput + KEYEVENTF_UNICODE. SendKeys follows the active keyboard layout: with Thai active, /exit arrives as /59.

Install

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 ทุกข้อแก้แ

Source 3 files
hooks/register.tsx 234 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { BandJump, BandTask, TaskStatus } from '../types'
5import { average, C, cellWidth, chipSegs, clampPage, clearFinished, insertOrdered, navLabel, pageOf, paginate, parseNotifications, pushSample, segWidth, statusOf, stoppedTaskId, viewOrder, frameTop, frameBottom, rowPad } from './logic'
6
7const tasks = atom({ plugin: 'task-band', key: 'tasks' } as const, [] as BandTask[])
8const page = atom({ plugin: 'task-band', key: 'page' } as const, 0)
9const jump = atom({ plugin: 'task-band', key: 'jump' } as const, null as BandJump | null)
10const tick = atom({ plugin: 'task-band', key: 'tick' } as const, 0)
11
12const JUMP_MS = 3000
13const FRAME = 4
14let pageCount = 1
15let seq = 0
16type Durations = Record<string, number[]>
17
18async function now($: EngineInterface): Promise<number> {
19  return $.clock.now()
20}
21
22async function entryOrder($: EngineInterface): Promise<number> {
23  const s = ++seq % 1000
24  return (await now($)) + s / 1000
25}
26
27async function flash($: EngineInterface, id: string) {
28  const until = (await now($)) + JUMP_MS
29  await update($, jump, () => ({ id, until }))
30  $.clock.after(JUMP_MS + 50, async () => {
31    const j = await read($, jump)
32    if (j && j.until <= (await now($))) await update($, jump, () => null)
33  })
34}
35
36async function addTask($: EngineInterface, t: BandTask) {
37  await update($, tasks, list => insertOrdered(list ?? [], t))
38  await flash($, t.id)
39}
40
41async function finish($: EngineInterface, match: (t: BandTask) => boolean, status: TaskStatus) {
42  const at = await now($)
43  let hit: BandTask | undefined
44  await update($, tasks, list =>
45    (list ?? []).map(t => {
46      if (t.status !== 'running' || !match(t)) return t
47      hit = { ...t, status, endedAt: at }
48      return hit
49    }),
50  )
51  if (!hit) return
52  await flash($, hit.id)
53  if (hit.kind === 'agent' && status === 'done' && hit.agentType) {
54    const all = ((await $.store.get('durations')) as Durations | undefined) ?? {}
55    all[hit.agentType] = pushSample(all[hit.agentType], at - hit.startedAt)
56    await $.store.set('durations', all)
57  }
58}
59
60async function estimateFor($: EngineInterface, agentType: string): Promise<number | undefined> {
61  const all = (await $.store.get('durations')) as Durations | undefined
62  return average(all?.[agentType])
63}
64
65async function onTick($: EngineInterface) {
66  const list = await read($, tasks)
67  if (list && list.some(t => t.status === 'running')) await update($, tick, n => (n + 1) % 1_000_000)
68}
69
70export const register: Register = on => {
71  on('session.start', async ($, e, next) => {
72    $.clock.every(1000, () => onTick($))
73    return next(e)
74  })
75
76  on('agent.spawn', async ($, e, next) => {
77    const order = await entryOrder($)
78    const r = await next(e)
79    const agentId = (r as { agentId?: string }).agentId
80    if (!agentId) return r
81    const at = await now($)
82    if (e.workflow) {
83      const runId = e.workflow.runId
84      const list = (await read($, tasks)) ?? []
85      if (!list.some(t => t.runId === runId)) {
86        await addTask($, { id: `run:${runId}`, kind: 'wf', label: 'workflow', startedAt: at, order, status: 'running', runId, members: [], finished: [] })
87      }
88      await update($, tasks, l => (l ?? []).map(t => (t.runId === runId ? { ...t, members: [...(t.members ?? []), agentId] } : t)))
89      return r
90    }
91    const agentType = e.subagentType || 'general-purpose'
92    await addTask($, { id: agentId, kind: 'agent', label: e.description || agentType, agentType, startedAt: at, order, status: 'running', estMs: await estimateFor($, agentType) })
93    return r
94  })
95
96  on('tool.call', async ($, e, next) => {
97    const bg = e.tool === 'Bash' || e.tool === 'PowerShell' || e.tool === 'Monitor' || e.tool === 'Workflow'
98    const order = bg && !e.agentId ? await entryOrder($) : undefined
99    const r = await next(e)
100    if (e.agentId || !('result' in r) || !r.result) return r
101    const res = r.result as Record<string, unknown>
102    const at = await now($)
103    if (e.tool === 'Bash' || e.tool === 'PowerShell') {
104      const bgId = res.backgroundTaskId
105      if (typeof bgId === 'string') {
106        const label = (e.description as string | undefined) || String(e.command).split('\n')[0] || e.tool
107        await addTask($, { id: bgId, taskId: bgId, kind: 'sh', label, startedAt: at, order, status: 'running' })
108      }
109    } else if (e.tool === 'Monitor') {
110      const id = res.taskId
111      if (typeof id === 'string') await addTask($, { id, taskId: id, kind: 'mon', label: String(e.description || 'monitor'), startedAt: at, order, status: 'running' })
112    } else if (e.tool === 'TaskStop') {
113      const id = stoppedTaskId(e as unknown as Record<string, unknown>)
114      if (id) await finish($, t => t.taskId === id || t.id === id, statusOf('stopped'))
115    } else if (e.tool === 'Workflow') {
116      const id = res.taskId
117      const runId = typeof res.runId === 'string' ? res.runId : undefined
118      const label = typeof res.workflowName === 'string' ? res.workflowName : 'workflow'
119      if (typeof id !== 'string') return r
120      const list = (await read($, tasks)) ?? []
121      if (runId && list.some(t => t.runId === runId)) {
122        await update($, tasks, l => (l ?? []).map(t => (t.runId === runId ? { ...t, taskId: id, label } : t)))
123      } else {
124        await addTask($, { id, taskId: id, kind: 'wf', label, startedAt: at, order, status: 'running', runId, members: [], finished: [] })
125      }
126    }
127    return r
128  })
129
130  on('turn.complete', async ($, e, next) => {
131    const r = await next(e)
132    const agentId = e.agentId
133    if (!agentId) {
134      await update($, tasks, l => clearFinished(l ?? []))
135      return r
136    }
137    const list = (await read($, tasks)) ?? []
138    const wf = list.find(t => t.status === 'running' && t.members?.includes(agentId) && !t.finished?.includes(agentId))
139    if (wf) {
140      await update($, tasks, l => (l ?? []).map(t => (t.id === wf.id ? { ...t, finished: [...(t.finished ?? []), agentId] } : t)))
141      return r
142    }
143    if (list.some(t => t.id === agentId && t.status === 'running')) {
144      const info = (await $.agent.list().catch(() => [])).find(a => a.id === agentId)
145      if (info && (info.status === 'idle' || info.status === 'waiting')) return r
146      await finish($, t => t.id === agentId, statusOf(info?.status))
147    }
148    return r
149  })
150
151  on('prompt.submit', async ($, e, next) => {
152    if (e.origin?.kind === 'task-notification') {
153      for (const n of parseNotifications(e.text)) {
154        const status = statusOf(n.status)
155        await finish($, t => t.taskId === n.id || t.id === n.id, status)
156      }
157    }
158    return next(e)
159  })
160
161  on('ui.focus', async ($, e, next) => {
162    if (e.component !== 'AbovePrompt' || e.plugin !== 'task-band' || e.origin.kind !== 'person') return next(e)
163    if (e.element === 'prev' || e.element === 'next') {
164      const step = e.element === 'next' ? 1 : -1
165      await update($, jump, () => null)
166      await update($, page, p => clampPage(p + step, pageCount))
167      return {}
168    }
169    return next(e)
170  })
171
172  on('ui.scroll', async ($, e, next) => {
173    if (e.component !== 'AbovePrompt' || e.by === 0) return next(e)
174    const list = (await read($, tasks)) ?? []
175    if (list.length === 0) return next(e)
176    await update($, jump, () => null)
177    await update($, page, p => clampPage(p + (e.by > 0 ? 1 : -1), pageCount))
178    return {}
179  })
180
181  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
182    const list = viewOrder((await read($, tasks)) ?? [])
183    if (e.props.hasSurvey || list.length === 0) return next(e)
184    const above = await next(e)
185    const [t, p, j, at] = await Promise.all([read($, tick), read($, page), read($, jump), now($)])
186    const chips = list.map(task => chipSegs(task, at, t))
187    const pages = paginate(chips.map(segWidth), e.props.bodyColumns - 1 - FRAME)
188    pageCount = pages.length
189    const jumpIndex = j && j.until > at ? list.findIndex(x => x.id === j.id) : -1
190    const shown = jumpIndex >= 0 ? pageOf(pages, jumpIndex) : clampPage(p, pages.length)
191    const [from, to] = pages[shown] ?? [0, 0]
192    const { Box, Button, Text } = $.ui.resolve(e)
193    const many = pages.length > 1
194
195    const W = e.props.bodyColumns - 1
196    const nav = many ? `‹ ${navLabel(from + 1, to, list.length)} ›  ` : ''
197    const visible = chips.slice(from, to)
198    const used = cellWidth(nav) + visible.reduce((n, segs, i) => n + segWidth(segs) + (i > 0 ? 3 : 0), 0)
199
200    return (
201      <Box flexDirection="column">
202        {above}
203        <Text color={C.faint}>{frameTop(W)}</Text>
204        <Box flexDirection="row">
205          <Text color={C.faint}>│ </Text>
206          {many ? <Button key="prev" label="‹" plain dimColor onPress={() => undefined} /> : null}
207          {many ? <Text> </Text> : null}
208          {many ? <Button key="pos" label={navLabel(from + 1, to, list.length)} plain autoFocus onPress={() => undefined} /> : null}
209          {many ? <Text> </Text> : null}
210          {many ? <Button key="next" label="›" plain dimColor onPress={() => undefined} /> : null}
211          {many ? <Text>  </Text> : null}
212          {visible.map((segs, i) => {
213            const task = list[from + i]
214            const isJump = jumpIndex === from + i
215            return (
216              <Box key={task?.id ?? `c${i}`} flexDirection="row">
217                {i > 0 ? <Text color={C.faint}> │ </Text> : null}
218                {segs.map((s, k) => (
219                  <Text key={`s${k}`} color={s.color} backgroundColor={isJump ? C.hl : undefined} bold={s.bold}>
220                    {s.text}
221                  </Text>
222                ))}
223              </Box>
224            )
225          })}
226          <Text>{rowPad(W, used)}</Text>
227          <Text color={C.faint}> │</Text>
228        </Box>
229        <Text color={C.faint}>{frameBottom(W)}</Text>
230      </Box>
231    )
232  })
233}
234
hooks/logic.ts 192 lines
1import type { BandTask, TaskStatus } from '../types'
2
3export const C = {
4  fg: '#2d2a24',
5  dim: '#6b675e',
6  faint: '#b9b5a3',
7  green: '#3f8a3a',
8  red: '#b8322b',
9  hl: '#e6e2bf',
10}
11
12export type Seg = { text: string; color?: string; bg?: string; bold?: boolean }
13
14export const GAUGE = 8
15export const LABEL_MAX = 18
16export const MIN_SAMPLES = 3
17export const EST_CAP = 95
18const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
19const SEP = ' │ '
20const THAI_ZERO = /[ัิ-ฺ็-๎]/u
21
22export function cellWidth(s: string): number {
23  let n = 0
24  for (const ch of s) if (!THAI_ZERO.test(ch)) n++
25  return n
26}
27
28export function fitCells(s: string, max: number): string {
29  if (cellWidth(s) <= max) return s
30  let out = ''
31  for (const ch of s) {
32    if (cellWidth(out + ch) > max - 1) break
33    out += ch
34  }
35  return `${out}…`
36}
37
38export function clock(ms: number): string {
39  const s = Math.max(0, Math.floor(ms / 1000))
40  const h = Math.floor(s / 3600)
41  const m = Math.floor((s % 3600) / 60)
42  const sec = String(s % 60).padStart(2, '0')
43  return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`
44}
45
46export function average(samples: number[] | undefined): number | undefined {
47  if (!samples || samples.length < MIN_SAMPLES) return undefined
48  return samples.reduce((a, b) => a + b, 0) / samples.length
49}
50
51export function pushSample(samples: number[] | undefined, ms: number): number[] {
52  return [...(samples ?? []), ms].slice(-10)
53}
54
55export function estimate(elapsed: number, estMs: number | undefined): number | undefined {
56  if (!estMs || estMs <= 0) return undefined
57  return Math.min(EST_CAP, Math.round((elapsed / estMs) * 100))
58}
59
60function bar(fill: number, color: string): Seg[] {
61  const n = Math.max(0, Math.min(GAUGE, Math.round(fill * GAUGE)))
62  return [{ text: '━'.repeat(n), color }, { text: '─'.repeat(GAUGE - n), color: C.faint }]
63}
64
65function sweep(tick: number): Seg[] {
66  const pos = tick % (GAUGE - 1)
67  return [
68    { text: '─'.repeat(pos), color: C.faint },
69    { text: '━━', color: C.fg },
70    { text: '─'.repeat(GAUGE - 2 - pos), color: C.faint },
71  ]
72}
73
74export function chipSegs(t: BandTask, now: number, tick: number): Seg[] {
75  const elapsed = (t.endedAt ?? now) - t.startedAt
76  const head: Seg[] =
77    t.status === 'done'
78      ? [{ text: '✓ ', color: C.green }]
79      : t.status === 'fail'
80        ? [{ text: '✗ ', color: C.red }]
81        : [{ text: `${SPIN[tick % SPIN.length]} `, color: C.fg }]
82  head.push({ text: `${t.kind} `, color: C.dim }, { text: `${fitCells(t.label, LABEL_MAX)} `, color: C.fg })
83
84  const total = t.members?.length ?? 0
85  const done = t.finished?.length ?? 0
86  const count = t.kind === 'wf' && total > 0 ? `${t.status === 'done' ? total : done}/${total}` : undefined
87
88  if (t.status === 'done') {
89    return [...head, ...bar(1, C.green), { text: ` ${count ?? '100%'}`, color: C.green }]
90  }
91  if (t.status === 'fail') {
92    const fill = total > 0 ? done / total : (estimate(elapsed, t.estMs) ?? 50) / 100
93    return [...head, ...bar(fill, C.red), { text: ' fail', color: C.red }, { text: ` ${clock(elapsed)}`, color: C.dim }]
94  }
95  if (count) {
96    return [...head, ...bar(done / total, C.fg), { text: ` ${count}`, color: C.fg }, { text: ` ${clock(elapsed)}`, color: C.dim }]
97  }
98  const pct = t.kind === 'agent' ? estimate(elapsed, t.estMs) : undefined
99  if (pct !== undefined) {
100    return [...head, ...bar(pct / 100, C.fg), { text: ` ~${pct}%`, color: C.dim }, { text: ` ${clock(elapsed)}`, color: C.dim }]
101  }
102  return [...head, ...sweep(tick), { text: ` ${clock(elapsed)}`, color: C.dim }]
103}
104
105export function segWidth(segs: Seg[]): number {
106  return segs.reduce((n, s) => n + cellWidth(s.text), 0)
107}
108
109export const MAX_PER_PAGE = 3
110
111export function navLabel(first: number, last: number, total: number): string {
112  return first === last ? `${first}/${total}` : `${first}-${last}/${total}`
113}
114
115export function navWidth(total: number): number {
116  return cellWidth(`‹ ${navLabel(total, total, total)} ›  `) + 2
117}
118
119export function paginate(widths: number[], columns: number): Array<[number, number]> {
120  const room = columns - navWidth(widths.length) - 1
121  const pages: Array<[number, number]> = []
122  let i = 0
123  while (i < widths.length) {
124    let used = widths[i] ?? 0
125    let j = i + 1
126    while (j < widths.length && j - i < MAX_PER_PAGE && used + SEP.length + (widths[j] ?? 0) <= room) {
127      used += SEP.length + (widths[j] ?? 0)
128      j++
129    }
130    pages.push([i, j])
131    i = j
132  }
133  return pages
134}
135
136export function pageOf(pages: Array<[number, number]>, index: number): number {
137  const p = pages.findIndex(([a, b]) => index >= a && index < b)
138  return p < 0 ? 0 : p
139}
140
141export function clampPage(page: number, count: number): number {
142  return Math.max(0, Math.min(page, count - 1))
143}
144
145export function parseNotifications(text: string): Array<{ id: string; status: string }> {
146  const out: Array<{ id: string; status: string }> = []
147  const blocks = text.match(/<task-notification>[\s\S]*?<\/task-notification>/g) ?? []
148  for (const b of blocks) {
149    const id = b.match(/<task-id>([^<]+)<\/task-id>/)?.[1]?.trim()
150    const status = b.match(/<status>([^<]+)<\/status>/)?.[1]?.trim()
151    if (id && status) out.push({ id, status })
152  }
153  return out
154}
155
156export function stoppedTaskId(input: Record<string, unknown>): string | undefined {
157  const id = input.task_id ?? input.shell_id
158  return typeof id === 'string' && id.trim() ? id.trim() : undefined
159}
160
161export function statusOf(word: string | undefined): TaskStatus {
162  if (word === 'failed' || word === 'killed' || word === 'error' || word === 'stopped') return 'fail'
163  return 'done'
164}
165
166export function insertOrdered(list: BandTask[], t: BandTask): BandTask[] {
167  return [...list.filter(x => x.id !== t.id), t].sort((a, b) => (a.order ?? a.startedAt) - (b.order ?? b.startedAt))
168}
169
170export function viewOrder(list: BandTask[]): BandTask[] {
171  return [...list.filter(t => t.status === 'running'), ...list.filter(t => t.status !== 'running')]
172}
173
174export function clearFinished(tasks: BandTask[]): BandTask[] {
175  return tasks.filter(t => t.status === 'running')
176}
177
178export const TITLE = 'งานเบื้องหลัง'
179
180export function frameTop(width: number): string {
181  const head = `┌─ ${TITLE} `
182  return head + '─'.repeat(Math.max(0, width - cellWidth(head) - 1)) + '┐'
183}
184
185export function frameBottom(width: number): string {
186  return '└' + '─'.repeat(Math.max(0, width - 2)) + '┘'
187}
188
189export function rowPad(width: number, used: number): string {
190  return ' '.repeat(Math.max(0, width - 4 - used))
191}
192
types/index.d.ts 32 lines
1export type TaskKind = 'agent' | 'wf' | 'sh' | 'mon'
2export type TaskStatus = 'running' | 'done' | 'fail'
3
4export type BandTask = {
5  id: string
6  kind: TaskKind
7  label: string
8  startedAt: number
9  status: TaskStatus
10  endedAt?: number
11  order?: number
12  taskId?: string
13  agentType?: string
14  estMs?: number
15  runId?: string
16  members?: string[]
17  finished?: string[]
18}
19
20export type BandJump = { id: string; until: number }
21
22declare module 'claude-code' {
23  interface PluginState {
24    'task-band': {
25      tasks: BandTask[]
26      page: number
27      jump: BandJump | null
28      tick: number
29    }
30  }
31}
32