Live pane of long-running jobs (training, downloads, extractions): progress, ETA, stalls and finishes, read from their logs with no model calls; jobs_list /…

Claude Code mods (function-hook plugins) I find helpful. Each folder is one plugin.
Requires a Claude Code build with function-hook plugins (2.1.289 or newer). machine-guard reads macOS tools (sysctl, vm_stat, ioreg, ps).
git clone https://github.com/joeldg/claude-mods ~/Projects/claude-mods
A pane of your project's running dev servers, so you don't have to ask Claude to restart them — and a tool so Claude doesn't have to run lsof to find out what's listening.
/servers opens the Servers pane:package.json dev/start/serve/preview scripts (run with your lockfile's package manager), .claude/launch.json and Procfileclaude CLI, which also listen on localhost from the project's folder) are never listed as servers nor counted as other listeners.~/.claude/dev-servers/<project>/.dev_servers tool: this project's running servers (name, port, pid, uptime, and the log when it was started from the pane), the start commands that aren't running, and with all: true every other listener on the machine (port, process), ending with how many Claude Code sessions it left out, e.g. (7 Claude Code sessions not listed), so nothing is hidden silently. Its description tells Claude to use it instead of lsof/netstat/ps. It never starts or stops anything.Port 4000 is held by node (pid 123, up 2h, in /Users/me/other).servers: :4000 :5173.netstat -anv -p tcp (macOS) or ss -ltnp (Linux), never a bare lsof; ps and lsof -d cwd run once per new pid, one pid at a time. One open session scans per interval (15s by default) and writes ~/.claude/dev-servers/scan-cache.json for the others; a slow scan doubles the interval, up to 5 minutes.Puts files you just downloaded into your prompt with one click.
~/Downloads (top level). When a new file arrives (PDF, Markdown, images, 3MF/STL/OBJ, zip, video…), a band appears above the prompt: New in Downloads: paper.pdf, model-b.3mf · 2m ago [Attach] [Dismiss].@"/Users/you/Downloads/paper.pdf" mentions in your prompt. Dismiss hides those files./downloads lists the 10 newest files, numbered. /downloads attach 1 3 (or 2-4) adds those, and /downloads clear dismisses everything new.Settings: folder (~/Downloads), extensions, pollSeconds (5), maxAgeMinutes (120).
Sets effort per message, so you don't have to switch it by hand.
~/.claude/usage-meter/summary.json, at most every 30 s) and, once pct reaches budgetCapAt (80%), caps every turn at budgetCapEffort (high), deep asks included, so you stop hitting the 5-hour wall. A turn already at or below the cap is left alone; lowering over a warm cache waits like any other lowering and never happens mid-turn. A missing or stale summary (over 10 minutes old), or one with no percentage yet (no fresh API reading and no limit learned), is no budget information. The debug log gets one line when the cap engages and one when it releases. budgetCapAt: 0 turns it off.subagentEffort (empty by default) to run every subagent request at that effort; the budget cap applies to them too (the lower of the two). Each subagent turn's effort is decided at its first request and kept for the turn.avoidModel (a regex such as fable) to send those requests to fallbackModel instead, subagents included./route shows the last decision, the session's counts, the budget state (percent used, the cap, whether it is engaged) and the subagent effort. /route off and /route on toggle it all; /route deep and /route routine force the next turn.effort: low (routine); while the budget cap lowers it: effort: high (budget 84%).Settings: routineEffort (low), deepEffort (max), routinePattern, deepPattern, avoidModel, fallbackModel (opus), stickyTurns (2), freeSwitchTokens (30000), cacheTtlMinutes (60), budgetCapAt (80; 0 = off), budgetCapEffort (high), subagentEffort (empty = the session's own).
A Jobs pane for long-running work: training runs, downloads, extractions — and three tools so Claude follows them instead of polling.
nohup … > log & launches by itself./watch <log> [label] adds any other log file./ and /Volumes/* (the NAS).jobs: 2 running · 1 stalled. A timer Claude sets for itself — sleep 600 && echo done, a loop of sleeps, or a task described as a wait, timer, pause or delay that only polls and reports with read-only programs (rg, tail, pgrep…) — is still listed by jobs_list and shown as a dim timer row, but never toasts, never counts in the status line, does not open the pane, is judged by its exit marker alone (no ps), and leaves a minute after it ends. Anything that runs a real program is a job, however it is described./jobs opens the pane, /unwatch <label|id|done|all> removes jobs.jobs_list (every watched job's state, pid, progress, ETA, last-output age, exit code and log path), jobs_watch ({ pid?, log?, name?, quietMinutes? }: follow a process or log started elsewhere; it never starts commands) and jobs_unwatch ({ name }). The first message of each conversation says jobs are watched and names them, so Claude stops writing until … sleep loops and running ps. They need no permission prompt: they only read the mod's own list.tail, checks processes with ps (one listing, or a per-pid lookup when only pids are watched), and runs df. A probe that times out or takes over 2 s is retried at a doubling interval, up to 5 minutes, until it is fast again. The debug log names a probe's pace only once it has held for two probes in a row, and at most once per five minutes per probe, so a pace that flips with the Mac's load leaves no trail.Settings (in /config): stall minutes (10), refresh seconds (10), how long finished jobs stay (120 min; a timer leaves after a minute), auto-open (on), which disks to show.
Memory, swap and GPU on the status line, a machine_status tool for Claude, and a guard that refuses heavy local jobs when the Mac can't take them.
RAM tight 12% free · swap 7.9/8G · top python 31G · GPU 87%, and CPU 4/16 cores whenever macOS has parked the performance cores. "Free" is unused memory (vm_stat's free + inactive + speculative pages): what a new job can take without pushing anyone out. macOS's own "memory free percentage" counts active pages too, which is how a Mac can be "55% free" with the swap nearly full.sysctl calls and vm_stat), every 15 s by default; the GPU (ioreg) on every third sample, never right after a slow one. One session samples and writes ~/.claude/machine-guard/sample.json (with a lock.json while it probes); every other session shows the same numbers instead of probing too. When probes are slow or time out (10–40 s while the Mac swaps) on two samples in a row, the interval doubles, and doubles again with each further slow sample, up to 2 min; a single slow sample is a blip and changes nothing. The configured pace returns once two samples in a row are fast again. The other sessions follow the sampler's pace, so a blip stays quiet in every session.kern.sched_recommended_cores, the bitmask of CPUs the scheduler may use. When macOS's performance controller parks the performance cores (after a thermal event, or stuck until a sleep/wake or reboot), the status line shows CPU 4/16 cores, machine_status and /guard report it with the parked count, you get one toast once at least half the cores have been parked for a minute, or any parking has lasted five minutes (masks blip for seconds under GPU load), and one when they come back, and Claude gets a note when it starts heavy work so it keeps worker counts small. The guard never blocks on it.ps, the slowest probe) is taken only on demand (/guard, machine_status) or when a sample shows pressure, at most once a minute; "biggest" means the apps from a table taken in the last 5 minutes./busy.When memory is only tight (under 20% free, or kernel level 2), the job runs and Claude gets a note to start one heavy job at a time.
machine_status is a tool Claude can call (no input, allowed without asking): the sample's age, RAM free, swap, GPU, the pressure level, the biggest apps (or how to get a table), the guard's verdict and its rules. Claude is told to use it instead of ps, top, vm_stat, memory_pressure or project scripts before launching heavy work./busy 3h training a vision model reserves the Mac in every Claude session. /busy off lifts it. The reservation lives in ~/.claude/machine-guard.json, so a training script can write it too: ``bash echo '{"reason":"overnight training","until":'$(( ($(date +%s) + 8*3600) * 1000 ))'}' > ~/.claude/machine-guard.json ``/guard shows what it sees (and takes a process table when one is due). /guard pause 15m lets heavy jobs through in this session; /guard on resumes the guard.modal run, ssh), tests (pytest) and installs are never treated as heavy.overnight_|nightly_run\.sh.Watches how the other mods behave in real use, without changing them. It is listed first in CLAUDE_CODE_PLUGIN_DIRS, so the other mods' hooks run beneath it.
next.trace), with the mod's name, the event and how long it ran. Slow hooks (over 1.5 s) are recorded too. The first failure of each mod in a session raises a toast.rg, grep, pgrep or pkill exiting 1 with nothing on stderr (no match, no such process), are logged as expected (proc-expected, with why), not as failures; an exit of 2 or more, or anything on stderr, still counts. It also records model calls (the only usage the mods cost: /second-opinion, /recall ask) and file writes (folders only, never contents)./mods: a pane with one row per mod: ✓ active, ⚠ failing, ✗ not seen this session, · seen but idle. Each row shows today's counts and last activity, with Details for its recent events. It also says which mods it can't see, if any of them run above it./mods report [24h|7d|30d]: a per-mod report across all sessions, also written to ~/.claude/mods/monitor/report-latest.md for a scheduled review or Claude to read./mods failures [7d]: failures and failed subprocesses only.~/.claude/mods/monitor/<date>/<session>.jsonl, flushed every minute and at session end, with secrets masked and old days removed after 30 days.$.ui.log with wording like "failed" or "could not"): shown in Details and in /mods failures. Three in an hour mark the mod ⚠ and raise one toast. That is how effort-router's per-request hook, which runs inside the response stream where no monitor should sit, reports a failure. It also always sends the request on unchanged./secrets records there) are watched for failures and slow runs, but not counted per run.Settings: alerts (on), slowMs (1500), watchRender (on), watchCommands (on; off stops "mod-monitor" appearing beside other mods' command output), watchAppend (on), retentionDays (30), flushSeconds (60).
Keeps an eye on Modal so idle GPU containers don't burn credits — in the projects that use Modal, with one CLI run per minute for the whole machine.
.py file with import modal / from modal import … (one rg run, 5 s at most), or modal named in pyproject.toml, requirements*.txt, uv.lock or poetry.lock. The answer is remembered per project for a day. Running /modal, or any modal … command in Bash, switches it on for the session; alwaysPoll (off) watches every project.~/.claude/modal-meter/lock.json runs modal app list --json every pollSeconds (60) and writes cache.json; the other open sessions read the cache and refresh their own status line and pane from it. Once one session learns the CLI has no billing report, none tries it again for a day.app list over 2 s or a timeout doubles the interval (up to 10 minutes); a fast answer brings it back.Modal: 1 running (2 containers). Deployed apps with no containers cost nothing, so they stay off it.alertMinutes (30), repeated at most every 30 minutes./modal opens a pane of apps with state, containers and uptime. Stop asks for Confirm, then runs modal app stop. Nothing is stopped any other way.budgetToday where the Modal CLI supports billing report (1.3.3+, Team/Enterprise workspaces). Otherwise /modal says why spend isn't shown.modal or python3 -m modal. It checks PATH first rather than running a command that can only fail, never retries one that isn't there, and stays silent when Modal isn't set up.Does the "merged #219, clean up branches and start #214" round trip for you, and surfaces CI failures with their logs.
gh pr create Claude runs. It polls gh pr view every 60s.PRs: #219 ✓ · #220 CI… · #221 ✗, for every watched PR.gh pr create) or you added with /prs watch, and for any PR whose branch this worktree has checked out. PRs adopted from the repository at start stay on the status line, in /prs and in prs_status, and still get the merge ritual, but their CI results don't toast — so with seven worktree sessions of one repo a result toasts once, where it matters, not seven times. toastAdoptedCi (off) brings back toasts for every watched PR.git fetch --prune, switch to the default branch (only from the PR's own branch) and git pull --ff-only.--force, never other branches.git worktree add, such as Claude Code's .claude/worktrees/<name> sessions) it only fetches: it never switches or pulls there, because the default branch is checked out in the primary worktree and the switch could only fail ('main' is already used by worktree …). When the merged branch is the one the worktree has checked out, the toast says #N merged → this worktree's branch; remove the worktree when you're done (git worktree remove <path>) and the Tab suggestion tells Claude the branch and worktree stay until you remove them. In the primary worktree the ritual is unchanged.gh pr checks and the tail of the failed log attached, so you don't paste it.prs_status (number, title, state, branch, CI, URL, and how old the data is), instead of running gh pr view or gh pr checks itself: no API call, and it refreshes first when the data is older than a poll.Resource not accessible by personal access token), it tells you once with the fix (gh auth login --web, or grant the token "Checks: read"), keeps polling the PRs without their checks so merges are still handled, shows them as #219 CI?, and tries the checks again after 30 minutes or when you run /prs. If gh can't read PRs at all (not logged in), the status line says PRs: gh can't read them and nothing is polled until then. A GitHub rate limit pauses polling for 5 minutes; any other failure doubles the wait up to 10 minutes, back to normal on the next success. Nothing retries every minute forever; the debug log gets one line per change./prs lists watched PRs and asks gh again at once. /prs watch <n|url> and /prs forget <n|all> add and remove them.gh and git, at about one GitHub API call per open PR per minute.Settings:
pollSeconds (60)authRetryMinutes (30): how long before the checks are tried again after gh refused them over auth.attachCiLogs (on)logLines (120)deleteRemoteBranch (off): deletes the branch on GitHub too, only while it still points at the merged commit. GitHub's own "Automatically delete head branches" setting does the same job.toastAdoptedCi (off): toast the CI results of PRs adopted from the repository too, as every PR's used to; with several worktree sessions of one repo, each would toast.It never closes issues; put "Closes #N" in PR bodies for that.
Search everything you've done with coding agents, from Claude or from /recall. It replaces the broken agent-memory plugin.
/remember notes. Routine (scheduled) runs are left out unless you add routines:include to a query.grep and cat are kept but ranked low.search, expand, recap and list, which run without permission prompts. It checks them when you say "like last time" or "what did we decide", and before asking you something you already settled./goal (or the Stop hook's condition), open tasks with a count of the done ones, the questions you asked with the first line of each answer, the files touched, the commits made and PRs opened. After a compaction it goes back into Claude's context as Ledger (this session, before compaction) (about 40 lines at most), so you don't have to say "don't lose track of where we were". /recall ledger prints it any time; /clear starts a fresh one. It is written to ~/.claude/recall/ledger/<session>.json (readable only by you, secrets masked) so a reload keeps it./recall <query> opens a pane of hits grouped by session. Open shows the conversation around a hit, Attach sends it with your next message, and Copy resume command copies claude --resume <id>./recall last [n] recaps your last session in this repo: last asks, last answer, PRs, commits, open tasks and decisions. Send to Claude attaches it./recall ledger prints this session's ledger (above)./recall timeline [7d|30d|90d] [all]/recall decisions|commands|files|prs|commits|issues|urls|tasks|notes [query]/recall ask <question> answers from your history with Haiku 4.5, citing sessions. It costs a little usage and sends the matching excerpts to the model./recall stats, /recall reindex, /recall forget session <id>|project <name>|before <date> (asks you to confirm), /recall help./remember <fact>, /remember list, /remember forget <ref>.Last session here (2d ago): "…" · PR #99 · 3 open tasks [Recap].#214, ABC-12, a file name or a quoted phrase seen in past sessions, a band offers what happened then. Nothing is sent unless you click.OR gives alternatives, "quotes" an exact phrase, and -word excludes. Filters: project:name, kind:decision, since:7d, until:2026-09-30, source:codex, routines:include.~/.claude/recall/index.db, readable only by you, and never goes in a repo. The ledgers beside it are kept the same way.~/.zshrc, ~/.zprofile, ~/.bashrc and `~/.bash_profilehooks/register.tsx 846 lines1import { atom, read, update } from 'claude-code'
2import type {
3 BoxProps,
4 ButtonProps,
5 ElementConstructor,
6 EngineInterface,
7 ProcessRunResult,
8 Register,
9 TextProps,
10} from 'claude-code'
11
12import type { Disk, Job, JobState, Progress } from '../types'
13import {
14 bar,
15 doneOf,
16 etaFrom,
17 exitCodeOf,
18 formatCount,
19 formatDuration,
20 isAlive,
21 isPidAlive,
22 isTimerTask,
23 launchFromCommand,
24 matchToken,
25 outputFileFromText,
26 parseDf,
27 parseProgress,
28 resolvePath,
29} from './parse'
30
31type Engine = EngineInterface
32type Json = Record<string, unknown>
33/** The elements the pane draws with, as every surface has them. */
34type Kit = {
35 Box: ElementConstructor<BoxProps>
36 Text: ElementConstructor<TextProps>
37 Button: ElementConstructor<ButtonProps>
38}
39
40const PANE = 'job-watch'
41const TITLE = 'Jobs'
42/** The context block that tells Claude jobs are watched for it, and names the tools. */
43const BLOCK = 'jobWatch'
44/** A job that ends sooner than this was a quick command, not a long job: it leaves silently. */
45const SHORT_MS = 60_000
46/** How long a probe (`ps`, `df`, `tail`) may run before it is abandoned. */
47const PROBE_TIMEOUT_MS = 10_000
48/** A probe slower than this, or one that timed out, doubles its interval, up to BACKOFF_MAX_MS. */
49const SLOW_MS = 2_000
50const BACKOFF_MAX_MS = 300_000
51/** How often disks are re-read while `df` is quick. */
52const DF_MS = 60_000
53/** A pace is written to the debug log once it has held for two probes, and at most this often per probe. */
54const LOG_GAP_MS = 300_000
55/** How long a finished timer (a bare `sleep` of Claude's) stays listed before it is dropped. */
56const TIMER_KEEP_MS = 60_000
57
58const TOOLS = ['mcp__job-watch__jobs_list', 'mcp__job-watch__jobs_watch', 'mcp__job-watch__jobs_unwatch'] as const
59
60const LIST_DESCRIPTION = [
61 'List the long-running jobs job-watch follows: background Bash tasks, detached nohup launches, and anything added with jobs_watch.',
62 'For each: its state (running, quiet, stalled, or finished with its exit code), how long since it last wrote output, progress and ETA when its log shows them, its last log line and its log path.',
63 'Call this to follow or wait for long-running work instead of writing `until … sleep` / `while … sleep` loops or running `ps`: background Bash jobs (run_in_background: true) are picked up automatically the moment they start.',
64].join(' ')
65
66const WATCH_DESCRIPTION = [
67 'Add a process or a log file to the jobs job-watch follows, so jobs_list can report on it: `pid` (followed until it exits), `log` (a file whose growth, progress figures and last line are read), or both; `name` labels it and `quietMinutes` says after how long without output it counts as stalled.',
68 "Only needed for work started outside this session's Bash (another session, a cron job, a pid you were given): background Bash tasks (run_in_background: true) and `nohup … > log 2>&1 &` launches are picked up automatically.",
69 'It does not start commands: run those with Bash. Use it instead of `ps` or sleep loops.',
70].join(' ')
71
72const UNWATCH_DESCRIPTION =
73 'Stop following a job, by the name or id jobs_list prints; `done` removes every finished job, `all` removes them all.'
74
75const EMPTY =
76 'No jobs are being watched. Background Bash tasks (run_in_background: true) and detached `nohup … > log 2>&1 &` launches are picked up automatically once they run; jobs_watch adds any other process (by pid) or log file.'
77
78/** What the first user message carries: three short lines, so Claude asks the tools rather than polling. */
79const CONTEXT = [
80 'job-watch follows long-running work for you: background Bash tasks (run_in_background: true) and `nohup … > log &` launches are picked up automatically, with progress, ETA, stalls and finishes.',
81 'To check on or wait for a job call mcp__job-watch__jobs_list, never an `until/while … sleep` loop or `ps`.',
82 'mcp__job-watch__jobs_watch adds a pid or log file started elsewhere; mcp__job-watch__jobs_unwatch removes one.',
83].join('\n')
84
85const jobs = atom({ plugin: 'job-watch', key: 'jobs' } as const, [])
86const disks = atom({ plugin: 'job-watch', key: 'disks' } as const, [])
87
88const hashOf = (text: string): string => {
89 let hash = 0
90 for (let i = 0; i < text.length; i++) {
91 hash = (hash * 31 + text.charCodeAt(i)) | 0
92 }
93 return (hash >>> 0).toString(36)
94}
95
96const shorten = (text: string, max: number): string =>
97 text.length <= max ? text : `${text.slice(0, max - 1)}…`
98
99type Config = {
100 stallMs: number
101 pollMs: number
102 keepDoneMs: number
103 autoOpen: boolean
104 wantedDisks: string[]
105}
106
107let config: Config = { stallMs: 600_000, pollMs: 10_000, keepDoneMs: 7_200_000, autoOpen: true, wantedDisks: [] }
108let timer: { cancel: () => void } | null = null
109/** The pass over the jobs now running, shared by whoever asks for one meanwhile. */
110let inflight: Promise<void> | null = null
111let hasOpened = false
112
113/**
114 * A probe's pacing, in ticks of the poll timer: a timeout or a run slower than SLOW_MS doubles
115 * the ticks between runs (up to BACKOFF_MAX_MS), a fast run restores the base. `last` is the
116 * newest answer (null after a failure) and stands in on the ticks in between. The debug log
117 * names a pace once it has held for two probes (`heldFor`), and at most once per LOG_GAP_MS, so
118 * a pace that flips with the machine's load leaves no trail.
119 */
120type Pace = {
121 name: string
122 baseTicks: number
123 everyTicks: number
124 sinceTicks: number
125 last: ProcessRunResult | null
126 /** Consecutive probes that ended at `everyTicks`. */
127 heldFor: number
128 /** The pace the debug log last named, and when. */
129 loggedTicks: number
130 loggedAt: number | null
131}
132
133const paceOf = (name: string, baseMs: number): Pace => {
134 const baseTicks = Math.max(1, Math.round(baseMs / config.pollMs))
135 return {
136 name,
137 baseTicks,
138 everyTicks: baseTicks,
139 sinceTicks: baseTicks,
140 last: null,
141 heldFor: 0,
142 loggedTicks: baseTicks,
143 loggedAt: null,
144 }
145}
146
147let psPace = paceOf('ps', config.pollMs)
148let dfPace = paceOf('df', DF_MS)
149
150/** Counts a tick for the probe: true when it is due to run again. */
151const isDue = (pace: Pace): boolean => {
152 pace.sinceTicks += 1
153 if (pace.sinceTicks < pace.everyTicks) {
154 return false
155 }
156 pace.sinceTicks = 0
157 return true
158}
159
160/** Runs a due probe, adjusts its pace from how long it took, and logs a pace once it has settled. */
161async function probe($: Engine, pace: Pace, argv: readonly string[]): Promise<ProcessRunResult | null> {
162 const startedAt = await $.clock.now()
163 const ran = await $.process.run(argv, { timeoutMs: PROBE_TIMEOUT_MS }).catch(() => null)
164 const now = await $.clock.now()
165 const tookMs = now - startedAt
166 const isSlow = ran === null || tookMs > SLOW_MS
167 const maxTicks = Math.max(pace.baseTicks, Math.ceil(BACKOFF_MAX_MS / config.pollMs))
168 const everyTicks = isSlow ? Math.min(pace.everyTicks * 2, maxTicks) : pace.baseTicks
169 pace.heldFor = everyTicks === pace.everyTicks ? pace.heldFor + 1 : 1
170 pace.everyTicks = everyTicks
171 pace.last = ran
172 // A pace that has held for two probes is news once, and never within LOG_GAP_MS of the last line.
173 const isSettled = pace.heldFor >= 2 && everyTicks !== pace.loggedTicks
174 if (isSettled && (pace.loggedAt === null || now - pace.loggedAt >= LOG_GAP_MS)) {
175 const why = ran === null ? 'timed out' : isSlow ? `took ${formatDuration(tookMs / 1000)}` : 'is fast again'
176 $.ui.log(`job-watch: ${pace.name} ${why}: probing every ${formatDuration((everyTicks * config.pollMs) / 1000)}`, {
177 to: 'debug',
178 })
179 pace.loggedTicks = everyTicks
180 pace.loggedAt = now
181 }
182 return ran
183}
184
185function etaText(job: Job, now: number): string {
186 if (job.etaSeconds === null || job.etaAt === null) {
187 return ''
188 }
189 const left = job.etaSeconds - (now - job.etaAt) / 1000
190 return left > 0 ? `ETA ${formatDuration(left)}` : 'ETA due'
191}
192
193const progressText = (progress: Progress): string =>
194 `${progress.pct.toFixed(progress.pct < 10 ? 1 : 0)}%` +
195 (progress.total > 0 ? ` (${formatCount(progress.done)}/${formatCount(progress.total)})` : '')
196
197/** The status line's figures: the real jobs by state; a timer is not counted. */
198function summary(list: readonly Job[]): string | undefined {
199 const counted = list.filter(job => !job.isTimer)
200 const count = (state: JobState) => counted.filter(job => job.state === state).length
201 const parts = [
202 count('running') && `${count('running')} running`,
203 count('stalled') && `${count('stalled')} stalled`,
204 count('quiet') && `${count('quiet')} quiet`,
205 ].filter(Boolean)
206 return parts.length > 0 ? `jobs: ${parts.join(' · ')}` : undefined
207}
208
209/** A job as this version keeps it: fields a job stored before a reload may lack are filled in. */
210const normalize = (job: Job): Job => ({
211 ...job,
212 pid: job.pid ?? null,
213 stallMs: job.stallMs ?? null,
214 exitCode: job.exitCode ?? null,
215 isTimer: job.isTimer ?? false,
216})
217
218async function refreshDisks($: Engine) {
219 if (!isDue(dfPace)) {
220 return
221 }
222 const df = await probe($, dfPace, ['df', '-k'])
223 if (df?.exitCode === 0) {
224 const next: Disk[] = parseDf(df.stdout, config.wantedDisks)
225 await update($, disks, () => next)
226 }
227}
228
229/**
230 * The `ps` listing the live jobs are judged by: every command line when one must be matched,
231 * a per-pid lookup (cheap under load) when pids alone are followed; null when none is needed
232 * or `ps` did not answer. Between due ticks the last answer stands.
233 */
234async function processes($: Engine, list: readonly Job[]): Promise<string | null> {
235 const live = list.filter(job => job.state !== 'done')
236 const pids = live.flatMap(job => (job.pid !== null ? [String(job.pid)] : []))
237 const needsCommands = live.some(job => job.match !== null && job.pid === null)
238 if (!needsCommands && pids.length === 0) {
239 return null
240 }
241 const argv = needsCommands ? ['ps', '-axo', 'pid=,command='] : ['ps', '-o', 'pid=', '-p', pids.join(',')]
242 const ran = isDue(psPace) ? await probe($, psPace, argv) : psPace.last
243 return ran?.stdout ?? null
244}
245
246/** The log re-read once it has grown: size, last line, progress, the ETA's baseline and the exit marker. */
247async function readLog($: Engine, job: Job, now: number): Promise<Job> {
248 const stat = job.log === '' ? null : await $.fs.stat(job.log).catch(() => null)
249 if (!stat || stat.size === job.size) {
250 return job
251 }
252 const tail = await $.process.run(['tail', '-c', '8192', job.log], { timeoutMs: PROBE_TIMEOUT_MS }).catch(() => null)
253 const text = tail?.stdout ?? ''
254 const reading = parseProgress(text)
255 const restarted = reading.progress && job.progress && doneOf(reading.progress) < doneOf(job.progress)
256 const baseline =
257 reading.progress && (!job.baseline || restarted) ? { at: now, done: doneOf(reading.progress) } : job.baseline
258 return {
259 ...job,
260 size: stat.size,
261 changedAt: stat.mtimeMs,
262 lastLine: reading.lastLine || job.lastLine,
263 progress: reading.progress ?? job.progress,
264 baseline,
265 etaSeconds: reading.etaSeconds ?? etaFrom(baseline, now, reading.progress ?? job.progress),
266 etaAt: now,
267 exitCode: exitCodeOf(text),
268 }
269}
270
271/** What `ps` says of the job: by its pid, else by its command-line token; null when it cannot tell. */
272const aliveIn = (ps: string | null, job: Job): boolean | null =>
273 ps === null ? null : job.pid !== null ? isPidAlive(ps, job.pid) : job.match !== null ? isAlive(ps, job.match) : null
274
275/** Running, or quiet / stalled once the log has been silent past the job's threshold; a pid alone never stalls. */
276const quietState = (job: Job, now: number, alive: boolean | null): JobState => {
277 const quietFor = now - Math.max(job.changedAt, job.addedAt)
278 if (job.log === '' || quietFor <= (job.stallMs ?? config.stallMs)) {
279 return 'running'
280 }
281 return alive === true ? 'stalled' : 'quiet'
282}
283
284async function readJob($: Engine, job: Job, now: number, ps: string | null): Promise<Job> {
285 if (job.state === 'done') {
286 return job
287 }
288 let next = await readLog($, job, now)
289 const alive = aliveIn(ps, next)
290 const isUnseen = alive === false && !next.seenAlive && now - next.addedAt > config.pollMs * 2
291 if (alive === true && !next.seenAlive) {
292 next = { ...next, seenAlive: true }
293 }
294 if (isUnseen && next.pid === null) {
295 // `ps` never showed the token: it was a bad guess, so judge this job by its log alone.
296 next = { ...next, match: null }
297 }
298 // A pid never seen in two polls is a process that is not running, whatever it was.
299 const isGone = alive === false && (next.seenAlive || (isUnseen && next.pid !== null))
300 // A timer is silent by nature: it runs until it ends, never quiet or stalled.
301 const state: JobState =
302 isGone || next.exitCode !== null ? 'done' : next.isTimer ? 'running' : quietState(next, now, alive)
303 return state === 'done' ? { ...next, state, finishedAt: now, etaSeconds: null, etaAt: null } : { ...next, state }
304}
305
306/**
307 * Toasts a finish or a stall the tick it first shows; false for a quick command, which leaves
308 * unannounced. A timer is kept but never announced: its end is Claude's cue, not the person's.
309 */
310function announce($: Engine, was: Job, job: Job, now: number): boolean {
311 if (job.state === 'done' && was.state !== 'done') {
312 const lived = now - job.addedAt
313 if (lived < SHORT_MS) {
314 return false
315 }
316 if (!job.isTimer) {
317 $.ui.toast(`${job.label} finished after ${formatDuration(lived / 1000)}: ${shorten(job.lastLine, 80)}`, {
318 timeoutMs: 10_000,
319 })
320 }
321 }
322 if (job.state === 'stalled' && was.state !== 'stalled' && !job.isTimer) {
323 $.ui.toast(`${job.label} has written nothing for ${formatDuration((job.stallMs ?? config.stallMs) / 1000)}`, {
324 timeoutMs: 10_000,
325 })
326 }
327 return true
328}
329
330/** Whether a finished or quiet job has stayed its keepDoneMinutes (a timer, its minute) and leaves the list. */
331const isExpired = (job: Job, now: number): boolean =>
332 (job.state === 'done' &&
333 job.finishedAt !== null &&
334 now - job.finishedAt > (job.isTimer ? TIMER_KEEP_MS : config.keepDoneMs)) ||
335 (job.state === 'quiet' && now - job.changedAt > config.keepDoneMs)
336
337/** One pass: disks when due, then every job read, judged, toasted and kept or dropped. */
338async function pass($: Engine) {
339 await refreshDisks($)
340 const list = (await read($, jobs)).map(normalize)
341 if (list.length === 0) {
342 $.ui.status(undefined)
343 return
344 }
345 const now = await $.clock.now()
346 const ps = await processes($, list)
347
348 const fresh: Job[] = []
349 for (const job of list) {
350 const next = await readJob($, job, now, ps)
351 if (announce($, job, next, now) && !isExpired(next, now)) {
352 fresh.push(next)
353 }
354 }
355 await update($, jobs, () => fresh)
356 $.ui.status(summary(fresh))
357
358 // A real job a minute old opens the pane once; a timer, however long, is not news.
359 const isLong = fresh.some(job => job.state !== 'done' && !job.isTimer && now - job.addedAt >= SHORT_MS)
360 if (config.autoOpen && !hasOpened && isLong) {
361 hasOpened = true
362 void $.ui.open({ id: PANE, title: TITLE })
363 }
364}
365
366/** The pass now running, or a new one: a timer tick that lands mid-pass joins it rather than doubling it. */
367function tick($: Engine): Promise<void> {
368 if (!inflight) {
369 inflight = pass($)
370 .catch((error: unknown) => $.ui.log(`job-watch: a poll failed: ${String(error)}`, { to: 'debug' }))
371 .finally(() => {
372 inflight = null
373 })
374 }
375 return inflight
376}
377
378/** A pass that reads the jobs as they stand now: one already running is awaited first, then a fresh one runs. */
379async function tickNow($: Engine): Promise<void> {
380 if (inflight) {
381 await inflight
382 }
383 await tick($)
384}
385
386function ensureTimer($: Engine) {
387 if (!timer) {
388 timer = $.clock.every(config.pollMs, () => void tick($))
389 }
390}
391
392type NewJob = Pick<Job, 'id' | 'label' | 'log' | 'match'> & Partial<Pick<Job, 'pid' | 'stallMs' | 'isTimer'>>
393
394async function addJob($: Engine, job: NewJob) {
395 const now = await $.clock.now()
396 const added: Job = {
397 ...job,
398 pid: job.pid ?? null,
399 stallMs: job.stallMs ?? null,
400 isTimer: job.isTimer ?? false,
401 seenAlive: false,
402 addedAt: now,
403 size: -1,
404 changedAt: now,
405 lastLine: '',
406 progress: null,
407 etaSeconds: null,
408 etaAt: null,
409 baseline: null,
410 state: 'running',
411 finishedAt: null,
412 exitCode: null,
413 }
414 await update($, jobs, list =>
415 [...list.filter(one => one.id !== added.id && (added.log === '' || one.log !== added.log)), added].slice(-20),
416 )
417 ensureTimer($)
418}
419
420type Watch = { log: string | null; pid: number | null; label: string | null; stallMs: number | null }
421
422/** Registers a job the way /watch does and reads it once; the text of the refusal when the log cannot be used. */
423async function watchJob($: Engine, want: Watch): Promise<Job | string> {
424 let log = ''
425 if (want.log !== null) {
426 const resolved = resolvePath(want.log, await $.env.get('HOME'), await $.session.cwd())
427 if (!resolved || !(await $.fs.exists(resolved))) {
428 return `job-watch: ${resolved ?? want.log} does not exist.`
429 }
430 log = resolved
431 }
432 const id = log !== '' ? hashOf(log) : `pid-${want.pid}`
433 const label = shorten(want.label || (log !== '' ? log.split('/').pop() || log : `pid ${want.pid}`), 40)
434 await addJob($, { id, label, log, match: null, pid: want.pid, stallMs: want.stallMs })
435 // A fresh `ps` on a pass that sees this job, so a pid is judged now rather than from the last listing.
436 if (inflight) {
437 await inflight
438 }
439 psPace.sinceTicks = psPace.everyTicks
440 await tick($)
441 return (await read($, jobs)).find(job => job.id === id) ?? `job-watch: ${label} could not be added.`
442}
443
444/** Drops the jobs `what` names (all, done, or one by id or label); how many went and what stays. */
445async function removeJobs($: Engine, what: string): Promise<{ removed: number; kept: Job[] }> {
446 const before = await read($, jobs)
447 const kept = before.filter(job =>
448 what === 'all'
449 ? false
450 : what === 'done' || what === ''
451 ? job.state !== 'done'
452 : job.id !== what && job.label !== what,
453 )
454 await update($, jobs, () => kept)
455 $.ui.status(summary(kept))
456 return { removed: before.length - kept.length, kept }
457}
458
459/** One job as jobs_list prints it: a line of figures, then its log path and last line indented. */
460function describeJob(job: Job, now: number): string {
461 const age = formatDuration((now - Math.max(job.changedAt, job.addedAt)) / 1000)
462 const state =
463 job.state === 'done'
464 ? `finished ${formatDuration((now - (job.finishedAt ?? now)) / 1000)} ago` +
465 (job.exitCode !== null ? ` (exit ${job.exitCode})` : '')
466 : job.state === 'running'
467 ? 'running'
468 : `${job.state} (no output for ${formatDuration((job.stallMs ?? config.stallMs) / 1000)})`
469 const parts = [
470 state,
471 job.isTimer && 'timer',
472 job.pid !== null && `pid ${job.pid}`,
473 job.progress && progressText(job.progress),
474 job.state !== 'done' && etaText(job, now),
475 job.log === '' ? `no log (added ${age} ago)` : `last output ${age} ago`,
476 ].filter(Boolean)
477 const lines = [`${job.label} [${job.id}]: ${parts.join(' · ')}`]
478 if (job.log !== '') {
479 lines.push(` log ${job.log}`)
480 }
481 if (job.lastLine) {
482 lines.push(` › ${job.lastLine}`)
483 }
484 return lines.join('\n')
485}
486
487async function listTool($: Engine): Promise<string> {
488 await tickNow($)
489 const list = (await read($, jobs)).map(normalize)
490 if (list.length === 0) {
491 return EMPTY
492 }
493 const now = await $.clock.now()
494 const footer =
495 `quiet = no output for ${formatDuration(config.stallMs / 1000)} with no process to check · ` +
496 `stalled = the process is alive but has written nothing for that long · ` +
497 `finished jobs stay listed for ${formatDuration(config.keepDoneMs / 1000)}; jobs_unwatch removes one.` +
498 (list.some(job => job.isTimer)
499 ? ' · timer = a wait of yours (sleep …): listed while it runs and for a minute after it ends, never announced.'
500 : '')
501 return [...list.slice().reverse().map(job => describeJob(job, now)), '', footer].join('\n')
502}
503
504/** jobs_watch's input checked: what to watch, or the text of the refusal. */
505function watchInput(e: Json): Watch | string {
506 if (e.command !== undefined) {
507 return 'job-watch: jobs_watch does not start commands. Run it with Bash (run_in_background: true, or `nohup … > log 2>&1 &`): it is watched automatically, and jobs_list reports on it.'
508 }
509 const pid = e.pid === undefined ? null : Number(e.pid)
510 if (pid !== null && (!Number.isInteger(pid) || pid <= 0)) {
511 return 'job-watch: pid must be a positive integer.'
512 }
513 const log = typeof e.log === 'string' && e.log.trim() !== '' ? e.log.trim() : null
514 if (pid === null && log === null) {
515 return 'job-watch: jobs_watch needs a pid, a log path, or both.'
516 }
517 const quiet = e.quietMinutes === undefined ? null : Number(e.quietMinutes)
518 if (quiet !== null && !(quiet > 0)) {
519 return 'job-watch: quietMinutes must be a positive number.'
520 }
521 const label = typeof e.name === 'string' ? e.name.trim() : ''
522 return { log, pid, label: label || null, stallMs: quiet === null ? null : quiet * 60_000 }
523}
524
525/** jobs_watch's answer: where the job is read from, and what changes its state. */
526function watchedText(job: Job): string {
527 const where = [job.pid !== null && `pid ${job.pid}`, job.log !== '' && `log ${job.log}`].filter(Boolean).join(', ')
528 const quietText = `after ${formatDuration((job.stallMs ?? config.stallMs) / 1000)} without output`
529 const counts = [
530 job.log !== '' && (job.pid !== null ? `stalled ${quietText}` : `quiet ${quietText} (no process to check)`),
531 job.pid !== null && 'finished when the process exits',
532 ].filter(Boolean)
533 return `Watching ${job.label} [${job.id}]: ${where}. Call jobs_list to check on it: it counts as ${counts.join(' and as ')}.`
534}
535
536async function watchTool($: Engine, e: Json): Promise<string> {
537 const want = watchInput(e)
538 if (typeof want === 'string') {
539 return want
540 }
541 const job = await watchJob($, want)
542 if (typeof job === 'string') {
543 return job
544 }
545 // A pid the fresh listing does not show is not running: say so now rather than wait on it.
546 if (job.pid !== null && !job.seenAlive && psPace.last !== null) {
547 await update($, jobs, list => list.filter(one => one.id !== job.id))
548 return `job-watch: no process with pid ${job.pid} is running.`
549 }
550 return watchedText(job)
551}
552
553async function unwatchTool($: Engine, e: Json): Promise<string> {
554 const what = typeof e.name === 'string' ? e.name.trim() : ''
555 if (what === '') {
556 return 'job-watch: jobs_unwatch needs the name or id of a job as jobs_list prints it, or done, or all.'
557 }
558 const before = await read($, jobs)
559 if (what !== 'all' && what !== 'done' && !before.some(job => job.id === what || job.label === what)) {
560 const watched = before.map(job => `${job.label} [${job.id}]`).join(', ')
561 return `job-watch: no job named ${what}. ${before.length > 0 ? `Watched: ${watched}.` : 'No jobs are being watched.'}`
562 }
563 return `Removed ${(await removeJobs($, what)).removed} job(s).`
564}
565
566async function registerTools($: Engine): Promise<void> {
567 const tools = [
568 { name: 'jobs_list', description: LIST_DESCRIPTION, inputSchema: { type: 'object', properties: {} } },
569 {
570 name: 'jobs_watch',
571 description: WATCH_DESCRIPTION,
572 inputSchema: {
573 type: 'object',
574 properties: {
575 pid: { type: 'integer', description: 'The process to follow until it exits.' },
576 log: {
577 type: 'string',
578 description: 'A log file to read progress and the last line from (~ and relative paths are expanded).',
579 },
580 name: { type: 'string', description: 'A label for the job (default: the log file name, or the pid).' },
581 quietMinutes: {
582 type: 'number',
583 description: 'Minutes without output after which the job counts as stalled (default from settings).',
584 },
585 },
586 },
587 },
588 {
589 name: 'jobs_unwatch',
590 description: UNWATCH_DESCRIPTION,
591 inputSchema: {
592 type: 'object',
593 properties: { name: { type: 'string', description: 'The name or id jobs_list prints, or done, or all.' } },
594 required: ['name'],
595 },
596 },
597 ]
598 for (const tool of tools) {
599 // In the prompt's own tool list, so the model reaches for them instead of a sleep loop.
600 await $.tool
601 .register({ ...tool, isDeferred: false })
602 .catch((error: unknown) => $.ui.log(`job-watch: ${tool.name} did not register: ${String(error)}`, { to: 'debug' }))
603 }
604}
605
606/**
607 * A timer's pane row: dim, with when it started or ended, and the × that drops it, so the pane and
608 * jobs_list agree on what is watched. The row leaves a minute after the timer ends.
609 */
610function timerRow($: Engine, { Box, Text, Button }: Kit, job: Job, now: number) {
611 const since = formatDuration((now - (job.state === 'done' ? (job.finishedAt ?? now) : job.addedAt)) / 1000)
612 return (
613 <Box key={`job-${job.id}`} flexDirection="column">
614 <Box flexDirection="row" justifyContent="space-between">
615 <Text dimColor wrap="truncate-end">
616 {job.label}
617 </Text>
618 <Box flexDirection="row" gap={1}>
619 <Text dimColor>timer</Text>
620 <Button
621 key={`rm-${job.id}`}
622 label="×"
623 plain
624 onPress={() => update($, jobs, all => all.filter(one => one.id !== job.id))}
625 />
626 </Box>
627 </Box>
628 <Text dimColor>{job.state === 'done' ? `ended ${since} ago` : `started ${since} ago`}</Text>
629 </Box>
630 )
631}
632
633export const register: Register = (on, options) => {
634 config = {
635 stallMs: Math.max(1, Number(options.stallMinutes ?? 10)) * 60_000,
636 pollMs: Math.max(2, Number(options.pollSeconds ?? 10)) * 1000,
637 keepDoneMs: Math.max(1, Number(options.keepDoneMinutes ?? 120)) * 60_000,
638 autoOpen: options.autoOpen !== false,
639 wantedDisks: String(options.disks ?? '')
640 .split(',')
641 .map(mount => mount.trim())
642 .filter(Boolean),
643 }
644 timer = null
645 inflight = null
646 hasOpened = false
647 psPace = paceOf('ps', config.pollMs)
648 dfPace = paceOf('df', DF_MS)
649
650 on('session.start', async ($, e, next) => {
651 await $.command.register({ name: 'jobs', description: 'Open the Jobs pane (long-running jobs and disk space)' })
652 await $.command.register({
653 name: 'watch',
654 description: 'Watch a log file in the Jobs pane',
655 argumentHint: '<log path> [label]',
656 })
657 await $.command.register({
658 name: 'unwatch',
659 description: 'Stop watching a job (by label or id), or clear finished ones',
660 argumentHint: '<label|id|done|all>',
661 })
662 await registerTools($)
663 ensureTimer($)
664 void tick($)
665 return next(e)
666 })
667
668 // Once per conversation, and again after a compaction: the model learns jobs are watched for it.
669 on('prompt.context', async (_$, e, next) => {
670 const result = await next(e)
671 return { ...result, blocks: [...result.blocks.filter(block => block.name !== BLOCK), { name: BLOCK, text: CONTEXT }] }
672 })
673
674 // Picks up background Bash tasks and detached `nohup … > log &` launches once they have started.
675 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
676 const ran = await next(e)
677 if (ran.deny !== undefined || ran.isError === true) {
678 return ran
679 }
680 try {
681 const output = e.run_in_background ? outputFileFromText(ran.text) : null
682 if (output) {
683 const match = matchToken(e.command.split(/\s*(?:&&|;|\n)\s*/).pop() ?? e.command)
684 if (match !== null || e.description) {
685 // A pure wait (`sleep 600 && echo done`) is kept for jobs_list, judged by its exit marker alone.
686 const isTimer = isTimerTask(e.command, e.description)
687 await addJob($, {
688 id: output.split('/').pop()?.replace(/\.output$/, '') ?? hashOf(output),
689 label: shorten(e.description || match || 'background task', 40),
690 log: output,
691 match: isTimer ? null : match,
692 isTimer,
693 })
694 }
695 return ran
696 }
697 const launch = launchFromCommand(e.command)
698 if (launch) {
699 const home = await $.env.get('HOME')
700 const cwd = await $.session.cwd()
701 const base = launch.cwd ? (resolvePath(launch.cwd, home, cwd) ?? cwd) : cwd
702 const log = resolvePath(launch.log, home, base)
703 if (log) {
704 const match = matchToken(launch.segment)
705 const isTimer = isTimerTask(launch.segment, e.description)
706 await addJob($, {
707 id: hashOf(log),
708 label: shorten(e.description || match || log.split('/').pop() || log, 40),
709 log,
710 match: isTimer ? null : match,
711 isTimer,
712 })
713 }
714 }
715 } catch (error) {
716 $.ui.log(`job-watch: could not register a job: ${String(error)}`, { to: 'debug' })
717 }
718 return ran
719 })
720
721 // The three tools only read and edit the mod's own list of jobs: never a question for the person, though a deny in settings stands.
722 on('tool.check', { tool: [...TOOLS] }, async ($, e, next) => {
723 const verdict = await next(e)
724 return verdict.decision === 'deny'
725 ? verdict
726 : { decision: 'allow', reason: 'job-watch: reads the watched jobs; starts and stops nothing' }
727 })
728
729 on('tool.call', { tool: 'mcp__job-watch__jobs_list' }, async $ => ({ result: await listTool($) }))
730 on('tool.call', { tool: 'mcp__job-watch__jobs_watch' }, async ($, e) => ({ result: await watchTool($, e) }))
731 on('tool.call', { tool: 'mcp__job-watch__jobs_unwatch' }, async ($, e) => ({ result: await unwatchTool($, e) }))
732
733 on('command.run', { command: 'jobs' }, async $ => {
734 ensureTimer($)
735 await tick($)
736 await $.ui.open({ id: PANE, title: TITLE })
737 return { text: summary(await read($, jobs)) ?? 'No jobs are being watched.' }
738 })
739
740 on('command.run', { command: 'watch' }, async ($, e) => {
741 const [path, ...labelWords] = e.args.trim().split(/\s+/)
742 if (!path) {
743 return { text: 'Usage: /watch <log path> [label]' }
744 }
745 const job = await watchJob($, { log: path, pid: null, label: labelWords.join(' ') || null, stallMs: null })
746 if (typeof job === 'string') {
747 return { text: job }
748 }
749 await $.ui.open({ id: PANE, title: TITLE })
750 return { text: `Watching ${job.log}` }
751 })
752
753 on('command.run', { command: 'unwatch' }, async ($, e) => ({
754 text: `Removed ${(await removeJobs($, e.args.trim())).removed} job(s).`,
755 }))
756
757 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
758 const { Box, Text, Button } = $.ui.resolve(e)
759 const list = await read($, jobs)
760 const diskRows = await read($, disks)
761 const now = await $.clock.now()
762 const columns = e.viewport?.columns ?? 60
763 const barWidth = Math.max(8, Math.min(24, columns - 40))
764 const color = (state: JobState) =>
765 state === 'running' ? 'green' : state === 'stalled' ? 'red' : state === 'quiet' ? 'yellow' : 'gray'
766
767 return (
768 <Box flexDirection="column" gap={1}>
769 {list.length === 0 && (
770 <Text dimColor>
771 No jobs yet. Background commands and nohup launches that write to a log show up here; /watch adds any log
772 file.
773 </Text>
774 )}
775 {list
776 .slice()
777 .reverse()
778 .map(job => {
779 if (job.isTimer) {
780 return timerRow($, { Box, Text, Button }, job, now)
781 }
782 const age = formatDuration((now - Math.max(job.changedAt, job.addedAt)) / 1000)
783 const figures = job.progress
784 ? `${bar(job.progress.pct, barWidth)} ${job.progress.pct.toFixed(job.progress.pct < 10 ? 1 : 0)}%` +
785 (job.progress.total > 0
786 ? ` ${formatCount(job.progress.done)}/${formatCount(job.progress.total)}`
787 : '')
788 : ''
789 const eta = etaText(job, now)
790 const timing =
791 job.state === 'done'
792 ? `finished ${formatDuration((now - (job.finishedAt ?? now)) / 1000)} ago`
793 : `${eta ? `${eta} · ` : ''}log ${age} ago`
794 return (
795 <Box key={`job-${job.id}`} flexDirection="column">
796 <Box flexDirection="row" justifyContent="space-between">
797 <Text bold dimColor={job.state === 'done'} wrap="truncate-end">
798 {job.label}
799 </Text>
800 <Box flexDirection="row" gap={1}>
801 <Text color={color(job.state)}>{job.state}</Text>
802 <Button
803 key={`rm-${job.id}`}
804 label="×"
805 plain
806 onPress={() => update($, jobs, all => all.filter(one => one.id !== job.id))}
807 />
808 </Box>
809 </Box>
810 {(figures || timing) && (
811 <Text dimColor={job.state === 'done'}>
812 {figures}
813 {figures ? ' ' : ''}
814 {timing}
815 </Text>
816 )}
817 {job.lastLine && (
818 <Text dimColor wrap="truncate-end">
819 {job.lastLine}
820 </Text>
821 )}
822 </Box>
823 )
824 })}
825 {list.some(job => job.state === 'done' && !job.isTimer) && (
826 <Button
827 key="clear-done"
828 label="Clear finished"
829 onPress={() => update($, jobs, all => all.filter(job => job.state !== 'done'))}
830 />
831 )}
832 {diskRows.length > 0 && (
833 <Box flexDirection="column">
834 {diskRows.map(disk => (
835 <Text key={`disk-${disk.mount}`} dimColor color={disk.capacityPct >= 90 ? 'red' : undefined}>
836 {disk.mount === '/' ? 'This Mac' : disk.mount.replace(/^\/Volumes\//, '')}: {disk.freeGB} GB free (
837 {disk.capacityPct}% used)
838 </Text>
839 ))}
840 </Box>
841 )}
842 </Box>
843 )
844 })
845}
846hooks/parse.ts 381 lines1import type { Disk, Progress } from '../types'
2
3const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g
4/** The line Claude Code's task runner appends to a background task's .output file when it ends. */
5const EXITED = /^\[exited with code (\d+)\]$/
6
7/** The .output file a background Bash task writes to, read from the text the model got back. */
8export const outputFileFromText = (text: string | undefined): string | null =>
9 text?.match(/Output is being written to: (\S+?\.output)\b/)?.[1] ?? null
10
11const LAUNCH_NOISE = new Set(['nohup', 'nice', 'caffeinate', 'env', 'exec', 'time', 'setsid'])
12const GENERIC = new Set(['python', 'python3', 'bash', 'sh', 'zsh', 'node', 'uv', 'poetry', 'ruby'])
13const POLLERS = /^(sleep|tail|until|while|watch|wait|gh|git|ls|cat|echo|ps|pgrep)$/
14
15const unquote = (word: string): string => word.replace(/^["']|["']$/g, '')
16
17const splitWords = (segment: string): string[] => segment.match(/"[^"]*"|'[^']*'|\S+/g)?.map(unquote) ?? []
18
19/**
20 * The index of the first word that is a program: past assignments, the `skipped` words (launch
21 * wrappers, and for the timer detector the shell's keywords) and a wrapper's options (`nice -n 15`).
22 */
23const programIndex = (words: readonly string[], skipped: ReadonlySet<string>): number => {
24 let index = 0
25 while (index < words.length) {
26 const word = words[index] ?? ''
27 if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || skipped.has(word)) {
28 index += word === 'nice' && words[index + 1] === '-n' ? 3 : 1
29 continue
30 }
31 if (word.startsWith('-') && index > 0 && LAUNCH_NOISE.has(words[index - 1] ?? '')) {
32 index += 1
33 continue
34 }
35 break
36 }
37 return index
38}
39
40/**
41 * A substring that `ps -axo command=` shows while the job runs: a `-m` module, a
42 * script path, or the executable, after launch wrappers and env assignments.
43 */
44export const matchToken = (segment: string): string | null => {
45 const words = splitWords(segment.split(/\s(?:>>?|2>|&>|<)\s?/)[0] ?? '')
46 const rest = words.slice(programIndex(words, LAUNCH_NOISE))
47 const moduleAt = rest.indexOf('-m')
48 if (moduleAt >= 0 && rest[moduleAt + 1]) {
49 return rest[moduleAt + 1] ?? null
50 }
51 const script = rest.find(word => /\.(py|sh|js|mjs|ts|rb)$/.test(word))
52 if (script) {
53 return script.replace(/^\.\//, '')
54 }
55 const head = rest[0]?.split('/').pop()
56 if (!head || POLLERS.test(head)) {
57 return null
58 }
59 if (GENERIC.has(head.replace(/\d+(\.\d+)?$/, ''))) {
60 return rest[1] && !rest[1].startsWith('-') ? rest[1] : null
61 }
62 // A plain executable (`tar`, `ffmpeg`) is too common alone: keep its first literal arguments.
63 const literal: string[] = []
64 for (const word of rest.slice(0, 3)) {
65 if (/[$`]/.test(word)) {
66 break
67 }
68 literal.push(word)
69 }
70 return literal.join(' ') || null
71}
72
73/** What a pure wait is made of: a `sleep`, or a bare `timeout`. */
74const TIMER_PROGRAMS = new Set(['sleep', 'timeout'])
75/** What may dress a timer without making it a job: echoes, shell tests and the clock. */
76const TRIVIAL_PROGRAMS = new Set([
77 'echo', 'printf', 'date', 'true', 'false', ':', 'test', '[', '[[', ']', ']]', 'wait', 'exit', 'seq',
78])
79/**
80 * Programs that only read. A task described as a wait may poll a log or a process with these and
81 * report with them when it wakes (`until rg -q done log; do sleep 30; done; tail -3 log`) and still
82 * be a wait, not a job.
83 */
84const READING_PROGRAMS = new Set([
85 'cat', 'head', 'tail', 'wc', 'cut', 'tr', 'sort', 'uniq', 'grep', 'egrep', 'fgrep', 'rg', 'awk', 'jq',
86 'ls', 'stat', 'du', 'df', 'file', 'basename', 'dirname', 'readlink', 'realpath', 'pwd',
87 'pgrep', 'ps', 'top', 'sysctl', 'vm_stat', 'uptime', 'uname', 'hostname', 'ioreg', 'plutil',
88])
89const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'fi', 'while', 'until', 'do', 'done', 'in', '!', '{', '}'])
90const SKIPPED = new Set([...LAUNCH_NOISE, ...KEYWORDS])
91/** `timeout`'s options that take a value. */
92const TIMEOUT_VALUED = new Set(['-k', '-s', '--kill-after', '--signal'])
93const TIMER_WORDS = /\b(wait|timer|pause|delay)\b/i
94/** A command's words, quotes kept whole, and its control operators. */
95const TOKENS = /"[^"]*"|'[^']*'|&&|\|\||[;|&\n]|[^\s;|&"']+/g
96const OPERATOR = /^(?:&&|\|\||[;|&\n])$/
97const SUBSTITUTION = /\$\(([^()]*)\)|`([^`]*)`/g
98/** A redirection (`> log`, `2>&1`, `&>/dev/null`), whose `&` is no control operator. */
99const REDIRECTION = /\d*[<>]+&?\d*|&>>?/g
100
101const basename = (word: string): string => word.split('/').pop() || word
102
103/** The words of each simple command in `text`: split at `&&`, `||`, `;`, `|`, `&` and newlines outside quotes. */
104const simpleCommands = (text: string): string[][] => {
105 const commands: string[][] = [[]]
106 for (const token of text.match(TOKENS) ?? []) {
107 if (OPERATOR.test(token)) {
108 commands.push([])
109 } else {
110 commands[commands.length - 1]?.push(unquote(token))
111 }
112 }
113 return commands.filter(words => words.length > 0)
114}
115
116/** The command `timeout` runs, past its options and the duration; null for a bare `timeout N`. */
117const timedOut = (words: readonly string[], from: number): string | null => {
118 let at = from
119 while (words[at]?.startsWith('-')) {
120 at += TIMEOUT_VALUED.has(words[at] ?? '') ? 2 : 1
121 }
122 if (/^\d+(\.\d+)?[smhd]?$/.test(words[at] ?? '')) {
123 at += 1
124 }
125 const wrapped = words[at]
126 return wrapped ? basename(wrapped) : null
127}
128
129/**
130 * The program each simple command of `command` runs (`sleep 600 && echo done` → sleep, echo): what
131 * `$(…)` and backticks run counted too, assignments, launch wrappers (nohup, nice…) and shell keywords
132 * skipped, redirections ignored, a `for` list passed over, and the command `timeout` wraps named after it.
133 */
134export const programsOf = (command: string): string[] => {
135 const programs: string[] = []
136 const text = command
137 .replace(SUBSTITUTION, (_whole: string, inner: string | undefined, ticked: string | undefined) => {
138 programs.push(...programsOf(inner ?? ticked ?? ''))
139 return ' '
140 })
141 .replace(REDIRECTION, ' ')
142 .replace(/[()]/g, ' ')
143 for (const words of simpleCommands(text)) {
144 const index = programIndex(words, SKIPPED)
145 const head = words[index]
146 if (!head || words[0] === 'for') {
147 continue
148 }
149 const program = basename(head)
150 programs.push(program)
151 const wrapped = program === 'timeout' ? timedOut(words, index + 1) : null
152 if (wrapped) {
153 programs.push(wrapped)
154 }
155 }
156 return programs
157}
158
159/**
160 * Whether a background command is a pure wait: a `sleep` (or a bare `timeout`) dressed at most with
161 * echoes, tests and the clock; or, when described as a wait, timer, pause or delay, one that at most
162 * polls and reports with programs that only read (rg, tail, pgrep…). Such a task is tracked but never
163 * announced. Anything that runs a real program is a job, however it is described.
164 */
165export const isTimerTask = (command: string, description = ''): boolean => {
166 const programs = programsOf(command)
167 if (programs.length === 0) {
168 return false
169 }
170 const isAllowed = (program: string, mayRead: boolean) =>
171 TIMER_PROGRAMS.has(program) || TRIVIAL_PROGRAMS.has(program) || (mayRead && READING_PROGRAMS.has(program))
172 const isPureTimer =
173 programs.some(program => TIMER_PROGRAMS.has(program)) && programs.every(program => isAllowed(program, false))
174 const isDescribedWait = TIMER_WORDS.test(description) && programs.every(program => isAllowed(program, true))
175 return isPureTimer || isDescribedWait
176}
177
178export type Launch = { log: string; segment: string; cwd: string | null }
179
180/**
181 * A detached launch the command starts (`nohup … > log &`, `… >> log 2>&1 & disown`):
182 * the redirect target and the segment that writes to it, with the last `cd` before it.
183 */
184export const launchFromCommand = (command: string): Launch | null => {
185 const segments = command.split(/\s*(?:&&|;|\n|\|\|)\s*/)
186 let cwd: string | null = null
187 for (let i = 0; i < segments.length; i++) {
188 const segment = (segments[i] ?? '').trim()
189 const cd = segment.match(/^cd\s+("[^"]+"|'[^']+'|\S+)\s*$/)
190 if (cd?.[1]) {
191 cwd = cd[1].replace(/^["']|["']$/g, '')
192 continue
193 }
194 const isDetached = /^nohup\b|\bnohup\s/.test(segment) || /&\s*(disown)?\s*$/.test(segment)
195 if (!isDetached) {
196 continue
197 }
198 const target = [...segment.matchAll(/(?:^|\s)(?:\d?>>?|&>)\s*("[^"]+"|'[^']+'|[^\s&;|]+)/g)]
199 .map(found => (found[1] ?? '').replace(/^["']|["']$/g, ''))
200 .find(path => path !== '/dev/null' && !path.startsWith('&'))
201 if (target) {
202 return { log: target, segment: segment.replace(/&\s*(disown)?\s*$/, '').trim(), cwd }
203 }
204 }
205 return null
206}
207
208/** `~` and `$HOME` expanded, relative paths put under `cwd`; null when another variable is left. */
209export const resolvePath = (path: string, home: string | undefined, cwd: string): string | null => {
210 let out = path
211 if (home) {
212 out = out.replace(/^~(?=\/|$)/, home).replace(/\$\{?HOME\}?/g, home)
213 }
214 if (out.includes('$') || out.startsWith('~')) {
215 return null
216 }
217 if (!out.startsWith('/')) {
218 out = `${cwd.replace(/\/$/, '')}/${out.replace(/^\.\//, '')}`
219 }
220 return out
221}
222
223const UNITS: Record<string, number> = { '': 1, K: 1e3, M: 1e6, G: 1e9, T: 1e12 }
224
225const amount = (value: string, unit = ''): number =>
226 Number(value.replace(/,/g, '')) * (UNITS[unit.toUpperCase().replace(/I?B$/, '')] ?? 1)
227
228const clockSeconds = (text: string): number | null => {
229 if (!/^\d+(:\d+){1,2}$/.test(text)) {
230 return null
231 }
232 return text.split(':').reduce((sum, part) => sum * 60 + Number(part), 0)
233}
234
235const progressOf = (done: number, total: number): Progress | null =>
236 total > 0 && done >= 0 && done <= total * 1.001
237 ? { done, total, pct: Math.min(100, (done / total) * 100) }
238 : null
239
240export type Reading = { progress: Progress | null; etaSeconds: number | null; lastLine: string }
241
242const TQDM = /(\d{1,3}(?:\.\d+)?)%\|[^|]*\|\s*([\d.,]+)([kKMGT]?)\/([\d.,]+)([kKMGT]?)\s*\[[^<\]]*<([\d:]+|\?)/
243const COUNTED =
244 /\b(?:step|iter(?:ation)?|epoch|batch|item|file|object|asset|sample|shard|chunk|scan|mesh|video|frame)s?\b\s*[:=#]?\s*([\d,]+)\s*(?:\/|of)\s*([\d,]+)/i
245const COUNTED_AFTER =
246 /\b([\d,]+)\s*(?:\/|of)\s*([\d,]+)\s+(?:steps|iterations|epochs|batches|items|files|objects|assets|samples|shards|chunks|scans|meshes|videos|frames)\b/i
247const BRACKETED = /\[\s*([\d,]+)\s*\/\s*([\d,]+)\s*\]/
248const SIZED = /([\d.]+)\s*([KMGT])i?B?\s*(?:\/|of)\s*([\d.]+)\s*([KMGT])i?B?\b/i
249const PERCENT = /(\d{1,3}(?:\.\d+)?)\s*%/g
250
251/** Reads the newest progress figure from a log's tail, and its last line. */
252export const parseProgress = (tail: string): Reading => {
253 const lines = tail
254 .replace(ANSI, '')
255 .split(/\r\n|\r|\n/)
256 .map(line => line.trim())
257 .filter(line => line.length > 0 && !EXITED.test(line))
258 const lastLine = (lines[lines.length - 1] ?? '').slice(0, 200)
259
260 for (const line of lines.slice(-60).reverse()) {
261 const tqdm = line.match(TQDM)
262 if (tqdm) {
263 const done = amount(tqdm[2] ?? '0', tqdm[3])
264 const total = amount(tqdm[4] ?? '0', tqdm[5])
265 const progress = progressOf(done, total) ?? { done: 0, total: 0, pct: Number(tqdm[1]) }
266 return { progress, etaSeconds: clockSeconds(tqdm[6] ?? ''), lastLine }
267 }
268 const counted = line.match(COUNTED) ?? line.match(COUNTED_AFTER) ?? line.match(BRACKETED)
269 if (counted) {
270 const progress = progressOf(amount(counted[1] ?? ''), amount(counted[2] ?? ''))
271 if (progress) {
272 return { progress, etaSeconds: null, lastLine }
273 }
274 }
275 const sized = line.match(SIZED)
276 if (sized) {
277 const progress = progressOf(amount(sized[1] ?? '', sized[2]), amount(sized[3] ?? '', sized[4]))
278 if (progress) {
279 return { progress, etaSeconds: null, lastLine }
280 }
281 }
282 const percents = [...line.matchAll(PERCENT)].map(found => Number(found[1]))
283 const pct = percents.filter(value => value <= 100).pop()
284 if (pct !== undefined) {
285 return { progress: { done: 0, total: 0, pct }, etaSeconds: null, lastLine }
286 }
287 }
288 return { progress: null, etaSeconds: null, lastLine }
289}
290
291/** The exit code a background task's .output file ends with, read from its tail; null while it still runs. */
292export const exitCodeOf = (tail: string): number | null => {
293 const last = tail
294 .replace(ANSI, '')
295 .split(/\r\n|\r|\n/)
296 .map(line => line.trim())
297 .filter(line => line.length > 0)
298 .pop()
299 const found = last?.match(EXITED)
300 return found ? Number(found[1]) : null
301}
302
303/** How far along, in the reading's own unit: its count, or its percentage when it has no count. */
304export const doneOf = (progress: Progress): number => (progress.total > 0 ? progress.done : progress.pct)
305
306const totalOf = (progress: Progress): number => (progress.total > 0 ? progress.total : 100)
307
308/** Seconds left from the average rate since `baseline`, or null when it cannot be told yet. */
309export const etaFrom = (
310 baseline: { at: number; done: number } | null,
311 now: number,
312 progress: Progress | null,
313): number | null => {
314 if (!baseline || !progress || now <= baseline.at) {
315 return null
316 }
317 const perMs = (doneOf(progress) - baseline.done) / (now - baseline.at)
318 return perMs > 0 ? Math.round((totalOf(progress) - doneOf(progress)) / perMs / 1000) : null
319}
320
321/** Whether a `ps` listing of command lines (with or without a pid column) shows the job, ignoring our own probes. */
322export const isAlive = (psOutput: string, match: string): boolean =>
323 psOutput
324 .split('\n')
325 .some(line => line.includes(match) && !/^\s*(?:\d+\s+)?(ps|pgrep|tail -c)\b/.test(line))
326
327/** Whether a `ps` listing led by a pid column (`pid=,command=`, or `pid=` alone) shows the pid. */
328export const isPidAlive = (psOutput: string, pid: number): boolean =>
329 psOutput.split('\n').some(line => /^\s*(\d+)\b/.exec(line)?.[1] === String(pid))
330
331/** `df -k` rows for `/` and `/Volumes/*` (or the listed mounts), skipping Time Machine volumes. */
332export const parseDf = (output: string, wanted: readonly string[]): Disk[] => {
333 const disks: Disk[] = []
334 for (const line of output.split('\n').slice(1)) {
335 const found = line.match(/^\S+(?:\s+\S+)*?\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)%\s+(?:\d+\s+\d+\s+\d+%\s+)?(\/.*)$/)
336 if (!found) {
337 continue
338 }
339 const mount = found[5] ?? ''
340 const isWanted =
341 wanted.length > 0
342 ? wanted.includes(mount)
343 : mount === '/' || (mount.startsWith('/Volumes/') && !mount.includes('Backups of'))
344 if (isWanted && !disks.some(disk => disk.mount === mount)) {
345 disks.push({
346 mount,
347 freeGB: Math.round(Number(found[3]) / 1024 / 1024),
348 capacityPct: Number(found[4]),
349 })
350 }
351 }
352 return disks
353}
354
355export const formatDuration = (seconds: number): string => {
356 const s = Math.max(0, Math.round(seconds))
357 if (s < 90) {
358 return `${s}s`
359 }
360 const minutes = Math.round(s / 60)
361 if (minutes < 90) {
362 return `${minutes}m`
363 }
364 const hours = Math.floor(minutes / 60)
365 return hours < 48 ? `${hours}h${String(minutes % 60).padStart(2, '0')}m` : `${Math.round(hours / 24)}d`
366}
367
368export const formatCount = (value: number): string =>
369 value >= 1e9
370 ? `${(value / 1e9).toFixed(1)}G`
371 : value >= 1e6
372 ? `${(value / 1e6).toFixed(1)}M`
373 : value >= 1e4
374 ? `${(value / 1e3).toFixed(1)}k`
375 : String(Math.round(value))
376
377export const bar = (pct: number, width: number): string => {
378 const filled = Math.round((Math.max(0, Math.min(100, pct)) / 100) * width)
379 return '█'.repeat(filled) + '░'.repeat(width - filled)
380}
381types/index.d.ts 47 lines1export type JobState = 'running' | 'quiet' | 'stalled' | 'done'
2
3export type Progress = { done: number; total: number; pct: number }
4
5export type Job = {
6 id: string
7 label: string
8 /** The file the job writes to: a background task's .output file or a redirect target; '' for a job followed by pid alone. */
9 log: string
10 /** A substring of the job's command line that `ps` should show while it runs; null when unknown. */
11 match: string | null
12 /** The process to follow (jobs_watch), judged alive by its pid; null when the command line is matched instead. */
13 pid: number | null
14 /** True once `ps` has shown the job at least once. */
15 seenAlive: boolean
16 addedAt: number
17 size: number
18 changedAt: number
19 lastLine: string
20 progress: Progress | null
21 etaSeconds: number | null
22 /** When `etaSeconds` was measured; the pane counts down from there. */
23 etaAt: number | null
24 /** The first progress reading this ETA is averaged from. */
25 baseline: { at: number; done: number } | null
26 /** This job's own stall threshold (jobs_watch quietMinutes); null uses the setting. */
27 stallMs: number | null
28 state: JobState
29 finishedAt: number | null
30 /** The exit code a background task's output file ends with (`[exited with code N]`); null until then. */
31 exitCode: number | null
32 /**
33 * A pure wait of Claude's own (`sleep 600 && echo done`, a loop of sleeps, or a wait/timer/pause/delay
34 * described as one): listed for jobs_list and shown dim, judged by its exit marker alone, never toasted
35 * or counted, and dropped a minute after it ends.
36 */
37 isTimer: boolean
38}
39
40export type Disk = { mount: string; freeGB: number; capacityPct: number }
41
42declare module 'claude-code' {
43 interface PluginState {
44 'job-watch': { jobs: Job[]; disks: Disk[] }
45 }
46}
47