SLOPSHOPPER

work-panel

A right-side Claude Code panel for your task tracker: browse roadmaps, start a ready task, and clear-and-start with a handoff note when you stay in the same…

paneguardcommandprompttoolmodel
v0.1.0MITupdated 2026-10-19ilikeeatingrice/claude-code-work-panel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · work-panel
│ ┃ Work ✕ › fix the failing auth test and add an audit log call │ ┃ WORK │ ┃ ⏺ Read(src/auth.ts) │ ┃ No roadmaps here yet. ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ Talk through a design with the agent, then ⎿ Added 2 lines, removed 1 line │ ┃ type /work create <name>. ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /work │ ⎿ work-panel: Work panel open. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Work
WORK No roadmaps here yet. Talk through a design with the agent, then type /work create <name>.
README

Work Panel

A Claude Code plugin for big, long-running work: a feature that takes many tasks and many sessions.

  • Design → roadmap. Talk a feature through with the agent, then type /work create <name>. The agent writes the plan, cuts it into tasks with their dependencies, shows you a preview, and writes nothing to the tracker until you say OK.
  • Clean context, kept knowledge. Each task gets a fresh session. When the next task is in the same roadmap, the old session first writes a handoff note into the old task's journal, and the new session starts with it. Unrelated work starts clean.
  • One task, one agent. The panel offers only tasks whose prerequisites are done, and locks a task another live session is working on.

It is one plugin with three parts: a panel on the right side of the terminal, a roadmap skill the agent follows, and a small tracker script that keeps tasks as Markdown files in your repo.

Work Panel demo

Full-quality video with sound (mp4, 16:9) · 4:5 version

Install

In a Claude Code terminal session:

/plugin install work-panel --marketplace ilikeeatingrice/claude-code-work-panel

Or run it from a clone: claude --plugin-dir /path/to/claude-code-work-panel.

Python 3.10+ is needed for the tracker. No other dependencies.

Use it

  1. Design. Discuss the feature with the agent as usual.
  2. Create. /work create checkout-redesign. The agent collects every point of the discussion, writes docs/programs/checkout-redesign/PLAN.md and one brief per task, has a fresh agent check that each brief is enough on its own, then shows the preview: the points it dropped, changed or left open, every task, and what each one waits on. Reply OK (or ask for changes).
  3. Open the panel. /work shows it; it stays until you type /work again. New sessions start with it hidden. Arrow keys move, Enter opens a roadmap or picks a task.
  4. Start. Pick a ● task. In a fresh session the button is Start; it sends the first message, and the agent claims the task.
  5. Next task. When a task is done, pick the next one and press Clear and start (twice, to confirm).

What the panel shows

MarkStateCan you start it?
●Ready: every prerequisite is DoneYes
○Waiting: shows what it needs (needs .15)No
◐In progressOnly if no live session is on it
■Blocked: shows its resume conditionNo
✓Done, folded into one N done lineNo

Task briefs

A roadmap is made in one session and worked in many fresh ones, so the details of the discussion have to survive the move. The roadmap skill handles that the way plan mode does:

  • Every point is listed. PLAN.md gets a ## Discussion points list: each proposal, number, decision, rejected option and open question, labelled kept, changed, dropped or open, with kept and changed naming the task that carries it.
  • Every task gets a brief, its own plan file at docs/programs/<roadmap>/tasks/<key>.md: context, decisions in the person's words, the approach, files and code to reuse, supporting material at lasting paths (handoff packages, design pages, the source session), the points it covers, open questions and how to verify. The format is in skills/roadmap/references/brief.md.
  • A fresh agent checks each brief before the preview: given only the brief, what would it still have to ask? The answers go into the brief.
  • The start message names the brief, and the session reads it before it plans any work.

validate checks the coverage: every kept or changed point appears in its task's brief, no brief points into /tmp or a scratchpad, and every brief has its fresh-session check. Roadmaps without a points list are not checked; RM brief <id> --set <path> adds briefs to them.

Batches

Some tasks are safe to run at the same time: they touch different files and do not wait on each other. When the roadmap skill plans a roadmap, it puts those tasks in a named batch (A, B, ...) and lists the files each one expects to change. Older trackers leave both out, and the panel then draws every task on its own, as before.

The panel draws a batch as a group under its roadmap:

  ⧉ batch A · 3 ready
      ● .02 Coupon codes
      ● .03 Gift cards
      ● .04 Order emails

Pick the header (when 2 or more of its tasks can start) and press Start batch A (.02 .03 .04). It starts them all in one fresh session, which uses the overseer skill to run them in parallel: it claims every task, gives each its own worker (in its own worktree when they would share a checkout), keeps each worker to that task's planned files, and verifies and hands off each task on its own. Tasks in the batch that can't start yet are left out, and the panel says which and why. The clear and handoff rules are the same as for a single task: Start in a fresh session, Clear and start (pressed twice) after other work, with a handoff note when the old session was in the same roadmap.

While a session runs a batch, its header reads ▲ THIS SESSION · batch A with one line per task, and other sessions see all of those tasks as being worked on now.

What this session is doing

Once a session has a task, the panel shows only that task's roadmap (the rest fold into one row) and a header:

▲ THIS SESSION
TASK-001.02 · Guest checkout without an account
now: writing tests for the guest token · 2m ago

The agent keeps it current through a small focus tool the plugin gives it: it calls it when it claims or switches a task, at each milestone, and when it finishes. If an agent never calls it, the panel still follows its claims: after a tool call that marks a task In Progress, the panel switches to that task. After a plugin reload it reads the task back from the session's own live file, and when it still doesn't know (a session that claimed its task earlier), it asks the session's model once, with no tools, and checks the answer against the tracker. If the tracker stops listing the session's task (say its file no longer parses), the panel keeps the task and says so instead of forgetting it.

The task the session is on is drawn in bold teal; a task another live session holds, in plain teal.

What the button does

Your sessionButtonWhat happens
Fresh, nothing said yetStartSends the first message for the task.
Working on a task in the same roadmapClear and startThe session writes a handoff note (changes, commands, commits, decisions, findings, risk, next action), the plugin saves it on the old task with the branch and git status, runs /clear, and sends the first message with a summary of the note.
A different roadmap, or no taskClear and startPlain /clear, then the first message. No note.

The old conversation stays saved; claude --resume opens it.

Who is working on what

Each session running the plugin rewrites a small file, ~/.claude/work-panel/live/<session id>.json, every minute. A task named by a live file (written in the last 3 minutes) shows being worked on now and is locked. A stale claim can be taken over; one younger than 2 hours with no live session asks for a second press. Sessions without the plugin write no file, so the panel can't see them.

The files it keeps

Everything lives in your repo as plain text:

WORK.md                          the active roadmaps
backlog.config.yml               task id prefix, folders
backlog/tasks/task-001.02 - Coupon-codes.md
docs/programs/<roadmap>/PLAN.md  the design and the discussion points
docs/programs/<roadmap>/tasks/   one brief per task

Tasks use the Backlog.md file format: YAML front matter (status, labels, dependencies, parent), acceptance criteria, and a comments block that serves as the task's journal. See tracker/README.md for the format and commands (plans, tree, ready, validate, init, create, comment, status, brief).

Settings

In /config → Work Panel:

SettingDefaultMeaning
treeCommandscripts/work_tracker.py tree --jsonUse your own tracker instead of the bundled one. When this script is missing and the folder has a WORK.md, the bundled tracker is used.
startHintemptyAdded to each first message, e.g. Use the work-tracker skill.
noteAuthor@claudeAuthor written on handoff notes.

A custom tracker command must print the same JSON as python3 tracker/roadmap.py tree --json: a list of roadmaps, each with plan_id, state, parent_task_id, counts and tasks; each task with task_id, title, status, ready, waiting_on, open_children, resume_condition, last_comment_at (UTC YYYY-MM-DD HH:MM) and path. The panel draws ready; it never computes it. Two optional keys turn on batches: batch (a name, or null) and planned_files (a list of paths); a tracker that omits them gets no batches.

How it is built

  • hooks/register.tsx: the Claude Code hooks module. The panel is a pane drawn by a ui.render hook. The handoff note comes from $.model.fork over the session's own history with no tools; then $.command.run({ command: 'clear' }) and $.prompt.submit start the next session. State lives in module variables, because /clear gives the session a new id.
  • skills/roadmap/: how the agent creates a roadmap (with the preview gate), claims a task, hands off, and retires a roadmap. A project's own tracking doc (docs/work-tracking.md) takes precedence when present.
  • tracker/roadmap.py: the tracker, Python standard library only (uses PyYAML when installed).

Check with claude plugin validate . and python3 -m pytest tracker/tests.

Demo video

demo/ is a Remotion project that recreates the Claude Code terminal cell by cell. The music is original, generated by demo/audio/make_track.py at 120 BPM, and every cut, key press and caption sits on its beat grid (demo/src/beat.ts; npm run sync prints the check).

cd demo && npm install
npm run audio        # regenerate audio/track.wav (needs Python with numpy)
npm run render       # 16:9  ->  out/work-panel-demo.mp4
npm run render:4x5   # 4:5   ->  out/work-panel-demo-4x5.mp4
npm run gif

If Remotion can't download its headless Chrome, set REMOTION_CHROME to a local chrome-headless-shell binary.

License

MIT

Source 2 files
hooks/register.tsx 1026 lines
1import type { Register } from 'claude-code'
2
3import type { TreePlan, TreeTask, LiveEntry } from '../types'
4
5// The Work panel: browse the roadmaps of the task tracker in the folder this
6// session runs in, start a task whose prerequisites are done, and on "Clear
7// and start" in the same roadmap have this session write its handoff note
8// first. The tracker is read through one command (`treeCommand`, JSON on
9// stdout; the shape is in ../types/index.d.ts and the README).
10//
11// State lives in module variables, not $.state: /clear gives the process a new
12// session id and $.state belongs to the old one, while the module keeps going.
13
14const PANE = 'work-panel'
15const LIVE_FRESH_MS = 3 * 60_000
16const CLAIM_GUARD_MS = 2 * 60 * 60_000
17const TEAL = '#6fb7b9'
18const AMBER = '#e0a85a'
19
20let root = ''
21let treeArgv: string[] = []
22let startHint = ''
23let noteAuthor = '@claude'
24let liveDir = ''
25let isEnabled = false
26let sessionId = ''
27
28let plans: TreePlan[] = []
29let loadError: string | undefined
30let live = new Map<string, LiveEntry>()
31const expanded = new Set<string>()
32let selected: string | undefined
33let armed: string | undefined
34let busy: string | undefined
35let problem: string | undefined
36let sessionTask: { id: string; plan: string } | undefined
37// When this session runs a batch (several tasks the plan marked safe to run at
38// the same time), all of its task ids; `sessionTask` stays the first of them,
39// so the code that only knows one task keeps working.
40let sessionBatch: { plan: string; name: string; ids: string[] } | undefined
41// The batch picked in the list (the way `selected` is the picked task).
42let selectedBatch: { plan: string; name: string } | undefined
43// This session's task when the tracker does not list it (a task file that no
44// longer parses, say): kept and shown with a warning instead of forgotten.
45let missingTask: string | undefined
46let showOthers = false
47let nowText: string | undefined
48let nowAt = 0
49let isTurnRunning = false
50let isFresh = true
51let heartbeat: { cancel: () => void } | undefined
52
53// ---------- data ----------
54
55async function refresh($: any) {
56  if (!isEnabled) await resolveTracker($)
57  if (!isEnabled) {
58    plans = []
59    $.ui.invalidate('ui.render')
60    return
61  }
62  try {
63    let out = await $.process.run(treeArgv, { cwd: root, timeoutMs: 20_000 })
64    const bundled = bundledArgv($)
65    if (out.exitCode !== 0 && treeArgv.join(' ') !== bundled.join(' ') && (await $.fs.exists(`${root}/WORK.md`))) {
66      // The configured tracker failed (an older copy without `tree`, say);
67      // the bundled one reads the same files.
68      const retry = await $.process.run(bundled, { cwd: root, timeoutMs: 20_000 })
69      if (retry.exitCode === 0) {
70        treeArgv = bundled
71        out = retry
72      }
73    }
74    if (out.exitCode !== 0) {
75      loadError = (out.stderr || out.stdout || 'tree failed').trim().split('\n').slice(-1)[0]
76    } else {
77      plans = JSON.parse(out.stdout) as TreePlan[]
78      loadError = undefined
79    }
80  } catch (err) {
81    loadError = String((err as Error)?.message ?? err)
82  }
83  live = await readLive($)
84  if (missingTask && !sessionTask) {
85    const found = findTask(missingTask)
86    if (found) {
87      sessionTask = { id: missingTask, plan: found.plan.plan_id }
88      expanded.add(found.plan.plan_id)
89      missingTask = undefined
90    }
91  }
92  try {
93    isFresh = (await $.session.messages()).length === 0
94  } catch {
95    isFresh = false
96  }
97  $.ui.invalidate('ui.render')
98}
99
100async function readLive($: any): Promise<Map<string, LiveEntry>> {
101  const map = new Map<string, LiveEntry>()
102  try {
103    if (!(await $.fs.exists(liveDir))) return map
104    const now = await $.clock.now()
105    for (const entry of await $.fs.list(liveDir)) {
106      if (!entry.name.endsWith('.json')) continue
107      try {
108        const value = JSON.parse(await $.fs.read(`${liveDir}/${entry.name}`)) as LiveEntry
109        if (value.sessionId !== sessionId && now - value.at > 24 * 60 * 60_000) {
110          // a session that ended a day ago: drop its file
111          await $.process.run(['rm', '-f', `${liveDir}/${entry.name}`])
112          continue
113        }
114        // Every task of another session's batch counts as being worked on.
115        const ids = value.tasks?.length ? value.tasks : value.task ? [value.task] : []
116        if (!ids.length || value.sessionId === sessionId) continue
117        if (now - value.at > LIVE_FRESH_MS) continue
118        for (const id of ids) map.set(id, value)
119      } catch {
120        // a half-written file from another session: skip it this round
121      }
122    }
123  } catch {
124    // no live folder yet
125  }
126  return map
127}
128
129async function beat($: any) {
130  if (!isEnabled || !sessionId) return
131  const value: LiveEntry = {
132    sessionId,
133    task: sessionTask?.id ?? missingTask ?? null,
134    tasks: sessionBatch ? sessionBatch.ids : sessionTask ? [sessionTask.id] : missingTask ? [missingTask] : [],
135    now: nowText ?? null,
136    nowAt,
137    cwd: root,
138    at: await $.clock.now(),
139  }
140  await $.fs.write(`${liveDir}/${sessionId}.json`, JSON.stringify(value))
141}
142
143// After a reload the module starts blank: take this session's task back from
144// its own live file, which outlives the module.
145async function restoreFromLive($: any) {
146  try {
147    const path = `${liveDir}/${sessionId}.json`
148    if (!(await $.fs.exists(path))) return
149    const saved = JSON.parse(await $.fs.read(path)) as LiveEntry
150    if (!saved.task) return
151    nowText = saved.now ?? undefined
152    nowAt = saved.nowAt ?? 0
153    const found = findTask(saved.task)
154    if (!found) {
155      missingTask = saved.task
156      return
157    }
158    sessionTask = { id: saved.task, plan: found.plan.plan_id }
159    if (saved.tasks && saved.tasks.length > 1) sessionBatch = batchFrom(saved.tasks)
160    expanded.add(found.plan.plan_id)
161    nowText = saved.now ?? undefined
162    nowAt = saved.nowAt ?? 0
163  } catch {
164    // no saved state
165  }
166}
167
168// When the panel does not know this session's task but the conversation has
169// history, ask the session's own model once (no tools, cached prefix).
170let askedModel = false
171async function askModelForTask($: any) {
172  if (sessionTask || missingTask || isFresh || askedModel || !plans.length) return
173  askedModel = true
174  const example = plans.find(plan => plan.tasks.length)?.tasks[0]?.task_id ?? 'TASK-001.01'
175  try {
176    const reply = await $.model.fork({
177      prompt: `Which tracked task is this session working on right now (task ids look like ${example})? Reply with exactly one line: the task id, a space, a vertical bar, a space, then what you are doing now in under 8 words. If this session is not working on a tracked task, reply NONE.`,
178    })
179    if (!reply.isAnswered || !reply.text) return
180    const line = reply.text.trim().split('\n')[0] ?? ''
181    const match = line.match(/\b([A-Za-z][A-Za-z0-9]*-\d+(?:\.\d+)*)\b\s*\|?\s*(.*)$/)
182    if (!match) return
183    const id = match[1]!.toUpperCase()
184    const found = findTask(id)
185    if (!found || found.task.status === 'Done' || found.task.completed) return
186    sessionTask = { id, plan: found.plan.plan_id }
187    expanded.add(found.plan.plan_id)
188    showOthers = false
189    nowText = (match[2] ?? '').trim().slice(0, 80) || undefined
190    nowAt = await $.clock.now()
191    await beat($)
192    $.ui.invalidate('ui.render')
193  } catch {
194    // the question is a convenience; the panel works without it
195  }
196}
197
198function findTask(id: string): { plan: TreePlan; task: TreeTask } | undefined {
199  for (const plan of plans) {
200    const task = plan.tasks.find(one => one.task_id === id)
201    if (task) return { plan, task }
202  }
203  return undefined
204}
205
206// A batch from task ids: the ids that exist, in the plan of the first one,
207// need to be 2 or more. The name is the tasks' shared `batch`, else 'batch'.
208function batchFrom(ids: string[]): { plan: string; name: string; ids: string[] } | undefined {
209  const found = [...new Set(ids)].map(findTask).filter((one): one is { plan: TreePlan; task: TreeTask } => one !== undefined)
210  const planId = found[0]?.plan.plan_id
211  const same = found.filter(one => one.plan.plan_id === planId)
212  if (!planId || same.length < 2) return undefined
213  const names = new Set(same.map(one => one.task.batch || ''))
214  const only = names.size === 1 ? [...names][0] : ''
215  return { plan: planId, name: only || 'batch', ids: same.map(one => one.task.task_id) }
216}
217
218// The open tasks of one batch in a plan, split into what a press would start
219// and what it would leave out (with the reason).
220function batchState(members: TreeTask[], now: number) {
221  const ready: TreeTask[] = []
222  const guards: { task: TreeTask; guard: string }[] = []
223  const left: { task: TreeTask; why: string }[] = []
224  for (const task of members) {
225    const s = startability(task, now)
226    if (s.canStart) {
227      ready.push(task)
228      if (s.guard) guards.push({ task, guard: s.guard })
229    } else {
230      left.push({ task, why: s.why ?? 'not ready' })
231    }
232  }
233  return { ready, guards, left }
234}
235
236function openBatchMembers(plan: TreePlan, name: string): TreeTask[] {
237  return plan.tasks.filter(task => task.batch === name && task.status !== 'Done' && !task.completed)
238}
239
240function lastCommentMs(task: TreeTask): number | undefined {
241  if (!task.last_comment_at) return undefined
242  const ms = Date.parse(`${task.last_comment_at.trim().replace(' ', 'T')}Z`)
243  return Number.isNaN(ms) ? undefined : ms
244}
245
246// Can this task be started from the panel, and does it need a second press?
247function startability(task: TreeTask, now: number): { canStart: boolean; why?: string; guard?: string } {
248  if (task.completed || task.status === 'Done') return { canStart: false, why: 'done' }
249  if (sessionTask?.id === task.task_id || sessionBatch?.ids.includes(task.task_id)) return { canStart: false, why: 'this session' }
250  if (task.status === 'Blocked') return { canStart: false, why: task.resume_condition ? `blocked · ${task.resume_condition}` : 'blocked' }
251  if (task.status === 'In Progress') {
252    const holder = live.get(task.task_id)
253    if (holder) return { canStart: false, why: 'being worked on now' }
254    const last = lastCommentMs(task)
255    const age = last === undefined ? undefined : now - last
256    const ago = age === undefined ? 'claimed' : `claimed ${agoText(age)} ago`
257    if (age !== undefined && age < CLAIM_GUARD_MS) return { canStart: true, why: `${ago} · no live session`, guard: `${ago}, no live session seen` }
258    return { canStart: true, why: `${ago} · nobody on it now` }
259  }
260  if (task.status === 'To Do' && task.ready) return { canStart: true }
261  if (task.status === 'To Do') {
262    const waits = [...task.waiting_on, ...task.open_children].map(shortId)
263    return { canStart: false, why: waits.length ? `needs ${waits.join(', ')}` : 'not ready' }
264  }
265  return { canStart: false, why: task.status.toLowerCase() }
266}
267
268function agoText(ms: number): string {
269  const min = Math.round(ms / 60_000)
270  if (min < 60) return `${min}m`
271  const h = Math.round(min / 60)
272  if (h < 48) return `${h}h`
273  return `${Math.round(h / 24)}d`
274}
275
276function nowLine(text: string, ageMs: number): string {
277  const ago = ageMs < 60_000 ? 'just now' : `${agoText(ageMs)} ago`
278  return text === 'done' ? `finished ${ago}` : `now: ${text} · ${ago}`
279}
280
281function shortId(id: string): string {
282  const dot = id.indexOf('.')
283  return dot === -1 ? id : id.slice(dot)
284}
285
286type Case = 'start' | 'same' | 'other'
287
288function caseFor(plan: TreePlan): Case {
289  if (isFresh && !sessionTask) return 'start'
290  if (sessionTask && sessionTask.plan === plan.plan_id) return 'same'
291  return 'other'
292}
293
294// ---------- the start flow ----------
295
296const NOTE_PROMPT = `Write the handoff note for the task this session worked on, for the next session that continues the same roadmap. Use exactly this shape, replacing every placeholder with exact facts from this session (write "None" where nothing applies). Reply with the note only, no preamble.
297
298session end
299  Changes: <exact files and behavior changed>
300  Commands/results: \`<exact command>\`: <trimmed actual result>
301  Commits or dirty state: <SHA(s), or the exact git status>
302  Decisions: <decisions made and why>
303  Findings: <facts discovered, including failed attempts>
304  Residual risk: <known unverified behavior, or None>
305  Next action: <the next concrete action or None>`
306
307async function appendComment($: any, path: string, entry: string) {
308  const text: string = await $.fs.read(path)
309  const end = '<!-- COMMENTS:END -->'
310  const at = text.lastIndexOf(end)
311  if (at === -1) throw new Error('task file has no comments block')
312  const now = new Date(await $.clock.now())
313  const iso = now.toISOString().replace(/\.\d+Z$/, 'Z')
314  const created = `${iso.slice(0, 10)} ${iso.slice(11, 16)}`
315  const body = entry.trim().split('\n')
316  const record = `author: ${noteAuthor}\ncreated: ${created}\n---\n${iso}: ${body[0]}\n${body.slice(1).join('\n')}\n---\n`
317  const before = text.slice(0, at)
318  await $.fs.write(path, `${before}${before.endsWith('\n') ? '' : '\n'}${record}${text.slice(at)}`)
319}
320
321async function gitFacts($: any): Promise<string> {
322  try {
323    const branch = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root })
324    const status = await $.process.run(['git', 'status', '--short'], { cwd: root })
325    const lines = status.stdout.trim().split('\n').filter(Boolean)
326    const shown = lines.slice(0, 15).map((line: string) => `    ${line}`).join('\n')
327    return `  Branch (read by the work panel): ${branch.stdout.trim()}\n  git status --short (${lines.length} lines):\n${shown || '    clean'}${lines.length > 15 ? '\n    …' : ''}`
328  } catch {
329    return '  Branch: (could not read git)'
330  }
331}
332
333type Note = { from: string; text: string }
334
335const takeoverLine = (task: TreeTask) =>
336  `${task.task_id} is already In Progress${task.assignees.length ? ` (assignee ${task.assignees.join(', ')})` : ''}, but no live session is working on it. Read its latest comment first, take over the claim, and record the takeover in its journal.`
337
338function noteLines(note: Note): string[] {
339  return [
340    '',
341    `This continues the same roadmap. The previous session just handed off ${note.from}; its full note is the latest comment on ${note.from}. Read it before you start. The note:`,
342    '',
343    note.text.trim(),
344  ]
345}
346
347// A task brief is the task's own plan file; a fresh session reads it first.
348const briefLine = (tasks: TreeTask[]): string[] => {
349  const given = tasks.filter(task => task.brief)
350  if (!given.length) return []
351  const list = given.map(task => (tasks.length > 1 ? `${shortId(task.task_id)}: ${task.brief}` : task.brief)).join('; ')
352  return [`Read the task brief${given.length > 1 ? 's' : ''} and the files ${given.length > 1 ? 'they mark' : 'it marks'} must read before planning any work — ${list}`]
353}
354
355function firstMessage(plan: TreePlan, task: TreeTask, note?: Note): string {
356  const lines = [
357    `Start ${task.task_id} (${task.title}). Roadmap: ${plan.plan_id} (${plan.parent_task_id}).${startHint ? ` ${startHint}` : ''}`,
358    ...briefLine([task]),
359  ]
360  if (task.status === 'In Progress') lines.push(takeoverLine(task))
361  if (note) lines.push(...noteLines(note))
362  return lines.join('\n')
363}
364
365function batchMessage(plan: TreePlan, name: string, members: TreeTask[], note?: Note): string {
366  const list = members.map(task => `${task.task_id} (${task.title})`).join(', ')
367  const lines = [
368    `Start batch ${name} of roadmap ${plan.plan_id} (${plan.parent_task_id}): ${list}.`,
369    `The plan marked these tasks safe to run at the same time. Use the overseer skill to run them in parallel: claim every task first, give each task its own worker (in its own worktree when they would share a checkout), keep each worker to that task's planned files, then verify and hand off each task on its own.${startHint ? ` ${startHint}` : ''}`,
370  ]
371  for (const task of members) {
372    if (task.status === 'In Progress') lines.push(takeoverLine(task))
373  }
374  const files = members.filter(task => task.planned_files?.length)
375  if (files.length) {
376    lines.push(`Planned files — ${files.map(task => `${shortId(task.task_id)}: ${task.planned_files!.join(', ')}`).join('; ')}`)
377  }
378  lines.push(...briefLine(members))
379  if (note) lines.push(...noteLines(note))
380  return lines.join('\n')
381}
382
383// The shared first half of a start: when the session is in the same roadmap,
384// its model writes the handoff note (saved on the task it was on); then
385// /clear, unless the session is fresh. Returns the note, if one was written.
386async function handOff($: any, which: Case): Promise<Note | undefined> {
387  let note: Note | undefined
388  if (which === 'same' && sessionTask) {
389    const from = findTask(sessionTask.id)
390    busy = `writing the handoff note on ${sessionTask.id}…`
391    $.ui.invalidate('ui.render')
392    const reply = await $.model.fork({ prompt: NOTE_PROMPT })
393    if (!reply.isAnswered || !reply.text?.trim()) {
394      throw new Error(`the note could not be written (${reply.reason ?? 'empty reply'}); nothing was cleared`)
395    }
396    const text = `${reply.text.trim()}\n${await gitFacts($)}`
397    if (from) await appendComment($, from.task.path, text)
398    note = { from: sessionTask.id, text }
399  }
400  if (which !== 'start') {
401    busy = 'clearing…'
402    $.ui.invalidate('ui.render')
403    await $.command.run({ command: 'clear' })
404    sessionId = await $.session.id()
405  }
406  return note
407}
408
409// Hand off, clear, take the task(s) as this session's, and send the first
410// message. `batchName` is set when `ids` is a batch.
411async function launch(
412  $: any,
413  plan: TreePlan,
414  which: Case,
415  ids: string[],
416  batchName: string | undefined,
417  message: (note?: Note) => string,
418) {
419  problem = undefined
420  armed = undefined
421  try {
422    const note = await handOff($, which)
423    sessionTask = { id: ids[0]!, plan: plan.plan_id }
424    sessionBatch = batchName ? { plan: plan.plan_id, name: batchName, ids } : undefined
425    missingTask = undefined
426    nowText = batchName ? 'starting batch' : 'starting'
427    nowAt = await $.clock.now()
428    expanded.add(plan.plan_id)
429    showOthers = false
430    selected = undefined
431    selectedBatch = undefined
432    busy = undefined
433    isFresh = false
434    await beat($)
435    $.ui.invalidate('ui.render')
436    await $.prompt.submit({ text: message(note) })
437  } catch (err) {
438    busy = undefined
439    problem = String((err as Error)?.message ?? err)
440    $.ui.invalidate('ui.render')
441  }
442}
443
444async function start($: any, planId: string, taskId: string) {
445  const found = findTask(taskId)
446  if (!found || found.plan.plan_id !== planId) return
447  const { plan, task } = found
448  await launch($, plan, caseFor(plan), [task.task_id], undefined, note => firstMessage(plan, task, note))
449}
450
451async function startBatch($: any, planId: string, name: string) {
452  problem = undefined
453  armed = undefined
454  // The list may have moved since the press that armed this: read it again.
455  await refresh($)
456  const plan = plans.find(one => one.plan_id === planId)
457  const members = plan ? batchState(openBatchMembers(plan, name), await $.clock.now()).ready : []
458  if (!plan || members.length < 2) {
459    problem = `Batch ${name} no longer has 2 tasks ready to start; nothing was cleared.`
460    $.ui.invalidate('ui.render')
461    return
462  }
463  await launch($, plan, caseFor(plan), members.map(task => task.task_id), name, note => batchMessage(plan, name, members, note))
464}
465
466// ---------- hooks ----------
467
468// About 30% of the terminal, 56-96 columns; remembered for opens at startup.
469function paneColumns(terminalColumns: number | undefined): number {
470  return Math.min(96, Math.max(56, Math.round((terminalColumns ?? 190) * 0.3)))
471}
472
473async function openPane($: any, terminalColumns?: number) {
474  const stored = await $.store.get('columns')
475  const columns = terminalColumns ? paneColumns(terminalColumns) : typeof stored === 'number' ? stored : paneColumns(undefined)
476  await $.store.set('columns', columns)
477  return $.ui.open({ id: PANE, title: 'Work', columns, focus: true })
478}
479
480// The command's first word: a script path relative to the session folder
481// (a .py one runs with that folder's .venv python, else python3), or a
482// program on PATH.
483async function resolveTree($: any, command: string): Promise<string[] | undefined> {
484  const words = command.trim().split(/\s+/).filter(Boolean)
485  const first = words[0]
486  if (!first) return undefined
487  const isPath = first.includes('/')
488  if (isPath && !(await $.fs.exists(`${root}/${first}`))) return undefined
489  if (first.endsWith('.py')) {
490    const venv = `${root}/.venv/bin/python`
491    return [(await $.fs.exists(venv)) ? venv : 'python3', ...words]
492  }
493  return words
494}
495
496let treeCommand = ''
497
498const FOCUS_TOOL = 'mcp__work-panel__focus'
499const FOCUS_SPEC = {
500  name: 'focus',
501  description:
502    "Tell the Work Panel (the task list beside this conversation) which tracked task this session is working on and what you are doing right now. Call it when you claim or switch to a task, at each milestone (a new step, tests running, waiting on the person), and with done: true when the task is finished. Keep `now` to a short phrase, e.g. 'writing tests for coupon rules'. When you run a batch of tasks together, pass every task id in task_ids. It only updates the panel; it changes no files.",
503  inputSchema: {
504    type: 'object',
505    properties: {
506      task_id: { type: 'string', description: 'The tracked task id, e.g. TASK-001.02' },
507      task_ids: {
508        type: 'array',
509        items: { type: 'string' },
510        description: 'Every task id this session is working on, when it runs a batch',
511      },
512      now: { type: 'string', description: 'What you are doing right now, a short phrase (under 60 characters)' },
513      done: { type: 'boolean', description: 'True when the task is finished' },
514    },
515    required: ['task_id', 'now'],
516  },
517}
518
519function bundledArgv($: any): string[] {
520  return ['python3', `${$.plugin.root}/tracker/roadmap.py`, 'tree', '--json']
521}
522
523// The configured tracker command when its script is here; otherwise the
524// bundled tracker once the folder has a WORK.md registry.
525async function resolveTracker($: any) {
526  const argv = await resolveTree($, treeCommand)
527  if (argv) {
528    treeArgv = argv
529  } else if (await $.fs.exists(`${root}/WORK.md`)) {
530    treeArgv = bundledArgv($)
531  } else {
532    isEnabled = false
533    return
534  }
535  isEnabled = true
536}
537
538function createPrompt(name: string): string {
539  return [
540    `Create a roadmap named "${name}" from the design we discussed in this conversation.`,
541    'Follow the "Create a roadmap from a design" steps of the roadmap skill (work-panel:roadmap):',
542    'write the PLAN.md, cut the slices, show me the dry-run preview, and wait for my OK before anything is written.',
543  ].join(' ')
544}
545
546export const register: Register = (on, options) => {
547  const settings = options as { treeCommand?: string; startHint?: string; noteAuthor?: string }
548  on('session.start', async ($, e, next) => {
549    const started = await next(e)
550    root = e.cwd
551    treeCommand = settings.treeCommand || 'scripts/work_tracker.py tree --json'
552    startHint = settings.startHint || 'Use the roadmap skill (work-panel:roadmap).'
553    noteAuthor = settings.noteAuthor || '@claude'
554    const home = (await $.process.run(['printenv', 'HOME'])).stdout.trim()
555    liveDir = `${home}/.claude/work-panel/live`
556    sessionId = await $.session.id()
557    await $.command.register({
558      name: 'work',
559      description: 'Show or hide the Work panel; /work create <name> turns the design discussed here into a roadmap',
560      argumentHint: '[create <name>]',
561    })
562    await $.tool.register(FOCUS_SPEC)
563    await refresh($)
564    await restoreFromLive($)
565    $.ui.invalidate('ui.render')
566    await beat($)
567    heartbeat?.cancel()
568    heartbeat = $.clock.every(60_000, () => {
569      void beat($).then(() => (isTurnRunning ? undefined : refresh($)))
570    })
571    return started
572  })
573
574  on('session.end', async ($, e, next) => {
575    // The process goes on after /clear under a new id; free the old id's entry.
576    if (isEnabled && e.sessionId) {
577      try {
578        await $.fs.write(`${liveDir}/${e.sessionId}.json`, JSON.stringify({ sessionId: e.sessionId, task: null, cwd: root, at: 0 }))
579      } catch {
580        // nothing to free
581      }
582    }
583    if (e.reason === 'clear') {
584      sessionTask = undefined
585      sessionBatch = undefined
586      missingTask = undefined
587      nowText = undefined
588      askedModel = false
589      isFresh = true
590    }
591    return next(e)
592  })
593
594  on('command.run', { command: 'work' }, async ($, e) => {
595    const args = (e.args ?? '').trim()
596    if (/^create\b/i.test(args)) {
597      const name = args.replace(/^create\b/i, '').trim()
598      if (!name) return { text: 'Usage: /work create <roadmap name>' }
599      if (isTurnRunning) return { text: 'Work panel: wait for the current turn to finish, then /work create again.' }
600      $.clock.after(50, () => void $.prompt.submit({ text: createPrompt(name) }))
601      return { text: `Work panel: asked the agent to draft the roadmap "${name}". It will show a preview first.` }
602    }
603    const panes = await $.ui.panes()
604    // A pane opened unasked waits undrawn below 144 columns: only one the
605    // person can see is closed; otherwise /work opens it for real.
606    if (panes.some(pane => pane.id === PANE && pane.isPlaced && pane.isShown)) {
607      await $.ui.close({ id: PANE })
608      return { text: 'Work panel hidden.' }
609    }
610    await refresh($)
611    void askModelForTask($)
612    const opened = await openPane($, e.presentation?.columns)
613    return { text: opened.isPlaced ? 'Work panel open.' : 'Work panel waits for a wider terminal.' }
614  })
615
616  on('prompt.submit', async ($, e, next) => {
617    isTurnRunning = true
618    isFresh = false
619    return next(e)
620  }).catch(($, e, next) => next(e))
621
622  // The agent reports its task and what it is doing now; the panel shows it.
623  on('tool.call', { tool: FOCUS_TOOL }, async ($, e) => {
624    const input = e as unknown as { task_id?: string; task_ids?: unknown; now?: string; done?: boolean }
625    const id = String(input.task_id ?? '').trim().toUpperCase()
626    const given = Array.isArray(input.task_ids)
627      ? input.task_ids.map(one => String(one).trim().toUpperCase()).filter(Boolean)
628      : []
629    let found = findTask(id)
630    if (!found || given.some(one => !findTask(one))) {
631      await refresh($)
632      found = findTask(id)
633    }
634    if (!found) return { result: `Work Panel: no task ${id} in this folder's tracker; nothing changed.` }
635    const batch = given.length ? batchFrom([id, ...given]) : undefined
636    // A single task of the current batch keeps the batch and only moves the
637    // now text; any other task replaces the batch.
638    const keeps = !batch && sessionBatch?.ids.includes(id) === true
639    const sameBatch = batch !== undefined && sessionBatch?.ids.join() === batch.ids.join()
640    if (!keeps && (batch ? !sameBatch : sessionTask?.id !== id)) {
641      expanded.add(found.plan.plan_id)
642      showOthers = false
643      selected = undefined
644      selectedBatch = undefined
645      armed = undefined
646    }
647    if (!keeps) {
648      sessionTask = { id, plan: found.plan.plan_id }
649      sessionBatch = batch
650    }
651    missingTask = undefined
652    // One member finishing is not the batch finishing: name which one.
653    const doneText = keeps ? `${shortId(id)} done` : 'done'
654    nowText = input.done ? doneText : String(input.now ?? '').trim().slice(0, 80) || undefined
655    nowAt = await $.clock.now()
656    await beat($)
657    $.ui.invalidate('ui.render')
658    const where = sessionBatch ? `batch ${sessionBatch.name} (${sessionBatch.ids.join(', ')})` : id
659    return { result: `Work Panel shows this session on ${where}${nowText ? ` (now: ${nowText})` : ''}.` }
660  }).catch(() => ({ result: 'Work Panel could not update; carry on with the task.' }))
661
662  // This session's task follows its claims as they happen: after a tool call
663  // that names a task and looks like a status change, the tracker is re-read,
664  // and a named task that has just become In Progress is this session's task.
665  on('tool.call', async ($, e, next) => {
666    const result = await next(e)
667    if (!isEnabled || e.tool === FOCUS_TOOL) return result
668    const fields = e as unknown as Record<string, unknown>
669    const text = [fields.command, fields.file_path, fields.new_string, fields.content]
670      .filter(v => typeof v === 'string')
671      .join(' ')
672    if (!/in progress|status|tasks\//i.test(text)) return result
673    const named = new Set<string>()
674    for (const match of text.matchAll(/\b([a-z][a-z0-9]*)-(\d+(?:\.\d+)*)\b/gi)) {
675      named.add(`${match[1]!.toUpperCase()}-${match[2]}`)
676    }
677    const before = [...named].filter(id => {
678      const found = findTask(id)
679      return found !== undefined && found.task.status !== 'In Progress'
680    })
681    if (!before.length) return result
682    await refresh($)
683    for (const id of before) {
684      const found = findTask(id)
685      // A claim inside this session's own batch is the batch working, not a switch.
686      if (sessionBatch?.ids.includes(id)) continue
687      if (found && found.task.status === 'In Progress' && sessionTask?.id !== id) {
688        sessionTask = { id, plan: found.plan.plan_id }
689        sessionBatch = undefined
690        missingTask = undefined
691        expanded.add(found.plan.plan_id)
692        showOthers = false
693        selected = undefined
694        selectedBatch = undefined
695        armed = undefined
696        await beat($)
697        $.ui.invalidate('ui.render')
698      }
699    }
700    return result
701  }).catch(($, e, next) => next(e))
702
703  on('turn.complete', async ($, e, next) => {
704    const done = await next(e)
705    isTurnRunning = false
706    if (isEnabled) void refresh($).then(() => askModelForTask($))
707    return done
708  })
709
710  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
711    const { Box, Text, Button } = $.ui.resolve(e)
712    // The pane's own body width (viewport.columns is the whole conversation's).
713    const width = Math.max(30, (e.props?.bodyColumns ?? 58) - 1)
714    const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, Math.max(1, n - 1))}…` : s)
715    const now = Date.now()
716
717    if (!isEnabled) {
718      return (
719        <Box flexDirection="column" gap={1}>
720          <Text bold>WORK</Text>
721          <Text dimColor wrap="wrap">No roadmaps here yet.</Text>
722          <Text wrap="wrap">{'Talk through a design with the agent, then type /work create <name>.'}</Text>
723        </Box>
724      )
725    }
726    if (loadError && !plans.length) {
727      return (
728        <Box flexDirection="column">
729          <Text color="error">Could not read the tracker</Text>
730          <Text dimColor wrap="wrap">{loadError}</Text>
731          <Button plain dimColor onPress={() => void refresh($)}>Retry</Button>
732        </Box>
733      )
734    }
735
736    const current = sessionTask ? findTask(sessionTask.id) : undefined
737    const lostId = current ? undefined : (sessionTask?.id ?? missingTask)
738    const active = plans.filter(plan => plan.state === 'Active')
739    const pickedRow = selected ? findTask(selected) : undefined
740
741    // A session with a task sees its own roadmap; the rest fold into one row.
742    const focus = sessionTask ? active.find(plan => plan.plan_id === sessionTask?.plan) : undefined
743    const others = focus ? active.length - 1 : 0
744    const shown = focus && !showOthers ? [focus] : active
745
746    const rows: any[] = []
747    for (const plan of shown) {
748      const isOpen = expanded.has(plan.plan_id)
749      const isSame = sessionTask?.plan === plan.plan_id
750      const meta = `${plan.counts.done}/${plan.counts.total} · ${plan.counts.ready} ready`
751      const name = `${plan.parent_task_id.replace(/^[A-Za-z]+-/, '')} ${plan.plan_id}`
752      rows.push(
753        <Box key={`p-${plan.plan_id}`} flexDirection="row" justifyContent="space-between">
754          <Button
755            key={`plan-${plan.plan_id}`}
756            plain
757            label={`${isOpen ? '▾' : '▸'} ${cut(name, width - meta.length - 4)}`}
758            onPress={() => {
759              if (isOpen) expanded.delete(plan.plan_id)
760              else expanded.add(plan.plan_id)
761              $.ui.invalidate('ui.render')
762            }}
763          />
764          <Text color={isSame ? TEAL : undefined} dimColor={!isSame}>{isSame ? 'this roadmap' : meta}</Text>
765        </Box>,
766      )
767      if (!isOpen) continue
768      const open = plan.tasks.filter(task => task.status !== 'Done' && !task.completed)
769      const doneCount = plan.tasks.length - open.length
770      const order = (task: TreeTask) => {
771        const s = startability(task, now)
772        if (task.status === 'In Progress') return s.canStart ? 1 : 0
773        if (s.canStart) return 1
774        if (task.status === 'Blocked') return 3
775        return 2
776      }
777      const sorted = [...open].sort((a, b) => order(a) - order(b))
778      // One task's row (and its why line); batch members sit two columns deeper.
779      const pushTask = (task: TreeTask, indent: number) => {
780        const s = startability(task, now)
781        const mark =
782          task.status === 'In Progress' ? '◐' : task.status === 'Blocked' ? '■' : s.canStart ? '●' : '○'
783        const isPicked = selected === task.task_id
784        // A task someone is on right now is drawn in teal; this session's own, bold.
785        const isMine = s.why === 'this session'
786        const working = isMine || s.why === 'being worked on now'
787        const label = `${' '.repeat(indent)}${isPicked ? '▶' : mark} ${shortId(task.task_id).padEnd(4)} ${cut(task.title, width - 10 - indent)}`
788        rows.push(
789          s.canStart ? (
790            <Button
791              key={`t-${task.task_id}`}
792              plain
793              dimColor={!isPicked && task.status === 'In Progress'}
794              label={label}
795              onPress={() => {
796                selected = task.task_id
797                selectedBatch = undefined
798                armed = undefined
799                problem = undefined
800                $.ui.invalidate('ui.render')
801              }}
802            />
803          ) : (
804            <Text
805              key={`t-${task.task_id}`}
806              dimColor={!working}
807              bold={isMine}
808              color={working ? TEAL : task.status === 'Blocked' ? AMBER : undefined}
809              wrap="truncate-end"
810            >
811              {label}
812            </Text>
813          ),
814        )
815        if (s.why) {
816          rows.push(
817            <Text key={`w-${task.task_id}`} dimColor={!isMine} color={working ? TEAL : undefined} wrap="truncate-end">
818              {`${' '.repeat(indent + 7)}${cut(s.why, width - 8 - indent)}`}
819            </Text>,
820          )
821        }
822      }
823      // A batch is drawn at the place of its best-sorted member: a header, then
824      // its members. Tasks without a batch are drawn as they always were.
825      const drawn = new Set<string>()
826      for (const task of sorted) {
827        const bname = task.batch || undefined
828        if (!bname) {
829          pushTask(task, 2)
830          continue
831        }
832        if (drawn.has(bname)) continue
833        drawn.add(bname)
834        const members = sorted.filter(one => one.batch === bname)
835        const ready = batchState(members, now).ready.length
836        const isMineBatch = sessionBatch?.plan === plan.plan_id && sessionBatch.name === bname
837        const isPickedBatch = selectedBatch?.plan === plan.plan_id && selectedBatch.name === bname
838        const header = isMineBatch
839          ? `  ⧉ batch ${bname} · this session`
840          : `  ${isPickedBatch ? '▶' : '⧉'} batch ${bname} · ${ready} ready`
841        rows.push(
842          !isMineBatch && ready >= 2 ? (
843            <Button
844              key={`b-${plan.plan_id}-${bname}`}
845              plain
846              label={cut(header, width)}
847              onPress={() => {
848                selectedBatch = { plan: plan.plan_id, name: bname }
849                selected = undefined
850                armed = undefined
851                problem = undefined
852                $.ui.invalidate('ui.render')
853              }}
854            />
855          ) : (
856            <Text
857              key={`b-${plan.plan_id}-${bname}`}
858              dimColor={!isMineBatch}
859              color={isMineBatch ? TEAL : undefined}
860              wrap="truncate-end"
861            >
862              {cut(header, width)}
863            </Text>
864          ),
865        )
866        for (const member of members) pushTask(member, 4)
867      }
868      if (doneCount) rows.push(<Text key={`d-${plan.plan_id}`} dimColor>{`  ✓ ${doneCount} done`}</Text>)
869    }
870    if (others > 0) {
871      rows.push(
872        <Button
873          key="others"
874          plain
875          dimColor
876          label={showOthers ? '▴ only this roadmap' : `▸ ${others} other roadmap${others === 1 ? '' : 's'}`}
877          onPress={() => {
878            showOthers = !showOthers
879            $.ui.invalidate('ui.render')
880          }}
881        />,
882      )
883    }
884
885    const hintFor = (which: Case) =>
886      which === 'same'
887        ? `Same roadmap: a handoff note goes on ${sessionTask?.id} first.`
888        : which === 'other'
889          ? 'No handoff note: different roadmap or no task here.'
890          : 'Fresh session: nothing to clear.'
891
892    // The picked batch counts only while 2 of its members can still start.
893    const pickedBatchPlan = selectedBatch ? plans.find(plan => plan.plan_id === selectedBatch?.plan) : undefined
894    const pickedBatchState =
895      pickedBatchPlan && selectedBatch ? batchState(openBatchMembers(pickedBatchPlan, selectedBatch.name), now) : undefined
896
897    let action: any = null
898    if (busy) {
899      action = <Text color={TEAL}>{busy}</Text>
900    } else if (pickedBatchPlan && selectedBatch && pickedBatchState && pickedBatchState.ready.length >= 2) {
901      const bplan = pickedBatchPlan
902      const bname = selectedBatch.name
903      const { ready, guards, left } = pickedBatchState
904      const which = caseFor(bplan)
905      const ids = ready.map(task => shortId(task.task_id)).join(' ')
906      const verb = which === 'start' ? 'Start' : 'Clear and start'
907      const needsConfirm = which !== 'start' || guards.length > 0
908      const key = `batch:${bplan.plan_id}:${bname}`
909      const isArmed = armed === key
910      action = (
911        <Box flexDirection="column">
912          {guards.map(one => (
913            <Text key={`g-${one.task.task_id}`} color={AMBER} wrap="wrap">{`Careful: ${shortId(one.task.task_id)} ${one.guard}.`}</Text>
914          ))}
915          <Button
916            key="go-batch"
917            variant="primary"
918            autoFocus
919            label={isArmed ? `Press again: ${verb.toLowerCase()} batch ${bname} (${ids})` : `${verb} batch ${bname} (${ids})`}
920            onPress={() => {
921              if (isTurnRunning) {
922                problem = 'Wait for the current turn to finish.'
923                $.ui.invalidate('ui.render')
924                return
925              }
926              if (needsConfirm && !isArmed) {
927                armed = key
928                $.ui.invalidate('ui.render')
929                return
930              }
931              const planId = bplan.plan_id
932              $.clock.after(50, () => void startBatch($, planId, bname))
933            }}
934          />
935          <Text dimColor wrap="wrap">{hintFor(which)}</Text>
936          {left.length ? (
937            <Text dimColor wrap="wrap">{`Leaves out ${left.map(one => `${shortId(one.task.task_id)} (${one.why})`).join(', ')}`}</Text>
938          ) : null}
939          <Text dimColor wrap="wrap">Runs in one session; overseer runs them in parallel.</Text>
940        </Box>
941      )
942    } else if (pickedRow) {
943      const which = caseFor(pickedRow.plan)
944      const s = startability(pickedRow.task, now)
945      const id = shortId(pickedRow.task.task_id)
946      const verb = which === 'start' ? 'Start' : 'Clear and start'
947      const needsConfirm = which !== 'start' || Boolean(s.guard)
948      const isArmed = armed === pickedRow.task.task_id
949      const hint = hintFor(which)
950      action = (
951        <Box flexDirection="column">
952          {s.guard ? <Text color={AMBER} wrap="wrap">{`Careful: ${s.guard}.`}</Text> : null}
953          <Button
954            key="go"
955            variant="primary"
956            autoFocus
957            label={isArmed ? `Press again: ${verb.toLowerCase()} ${id}` : `${verb} ${pickedRow.task.task_id}`}
958            onPress={() => {
959              if (isTurnRunning) {
960                problem = 'Wait for the current turn to finish.'
961                $.ui.invalidate('ui.render')
962                return
963              }
964              if (needsConfirm && !isArmed) {
965                armed = pickedRow.task.task_id
966                $.ui.invalidate('ui.render')
967                return
968              }
969              const planId = pickedRow.plan.plan_id
970              const taskId = pickedRow.task.task_id
971              $.clock.after(50, () => void start($, planId, taskId))
972            }}
973          />
974          <Text dimColor wrap="wrap">{hint}</Text>
975        </Box>
976      )
977    } else {
978      action = <Text dimColor>Pick a ● task to start it.</Text>
979    }
980
981    return (
982      <Box flexDirection="column" gap={1}>
983        <Box flexDirection="row" justifyContent="space-between">
984          <Text bold>WORK</Text>
985          <Text dimColor>{`${active.length} roadmap${active.length === 1 ? '' : 's'} · /work hides`}</Text>
986        </Box>
987        {current ? (
988          <Box flexDirection="column">
989            <Text color={AMBER}>
990              {sessionBatch && sessionBatch.ids.length >= 2
991                ? `▲ THIS SESSION · batch ${sessionBatch.name}`
992                : current.task.status === 'Done' || current.task.completed
993                  ? '▲ THIS SESSION · done'
994                  : '▲ THIS SESSION'}
995            </Text>
996            {sessionBatch && sessionBatch.ids.length >= 2 ? (
997              sessionBatch.ids.map(id => {
998                const member = findTask(id)?.task
999                const isDone = member?.status === 'Done' || member?.completed
1000                return <Text key={`m-${id}`}>{cut(`${isDone ? '✓' : '◐'} ${shortId(id)} ${member?.title ?? "(not in the tracker's list)"}`, width)}</Text>
1001              })
1002            ) : (
1003              <Text>{cut(`${current.task.task_id} · ${current.task.title}`, width)}</Text>
1004            )}
1005            {nowText ? <Text dimColor>{cut(nowLine(nowText, now - nowAt), width)}</Text> : null}
1006          </Box>
1007        ) : lostId ? (
1008          <Box flexDirection="column">
1009            <Text color={AMBER}>▲ THIS SESSION</Text>
1010            <Text>{cut(`${lostId} · not in the tracker's list`, width)}</Text>
1011            <Text color="warning" wrap="wrap">
1012              Its task file may not parse. Run the tracker's validate command to see why.
1013            </Text>
1014          </Box>
1015        ) : null}
1016        <Box flexDirection="column">{rows}</Box>
1017        <Box flexDirection="column">
1018          {action}
1019          {problem ? <Text color="error" wrap="wrap">{problem}</Text> : null}
1020          {loadError ? <Text color="warning" wrap="wrap">{`Tracker: ${loadError}`}</Text> : null}
1021        </Box>
1022      </Box>
1023    )
1024  })
1025}
1026
types/index.d.ts 53 lines
1// Shapes the Work panel reads: the tracker command's JSON (treeCommand) and
2// the per-session live files under ~/.claude/work-panel/live/.
3
4export type TreeTask = {
5  task_id: string
6  title: string
7  status: string
8  priority: string | null
9  ordinal: number
10  assignees: string[]
11  labels: string[]
12  parent_task_id: string | null
13  dependencies: string[]
14  ready: boolean
15  waiting_on: string[]
16  open_children: string[]
17  resume_condition: string | null
18  last_comment_at: string | null
19  completed: boolean
20  path: string
21  // Optional: older trackers omit both. A named group of tasks in one plan that
22  // the plan marked safe to run at the same time, and the files a task expects
23  // to change. Missing means null / [].
24  batch?: string | null
25  planned_files?: string[]
26  // Optional: the task's plan file (a task brief) and its spec key. Older
27  // trackers omit both.
28  brief?: string | null
29  key?: string | null
30}
31
32export type TreePlan = {
33  plan_id: string
34  priority: number
35  state: string
36  path: string
37  parent_task_id: string
38  parent_title: string | null
39  counts: { total: number; done: number; ready: number; in_progress: number; blocked: number; waiting: number }
40  tasks: TreeTask[]
41}
42
43export type LiveEntry = {
44  sessionId: string
45  // The first task id; `tasks` lists every task when the session runs a batch.
46  task: string | null
47  tasks?: string[]
48  now?: string | null
49  nowAt?: number
50  cwd: string
51  at: number
52}
53