SLOPSHOPPER

work-queue

Shows Claude session tasks grouped by working, blocked, ready, and done

newpaneguardcommandtimer
★ 2v0.1.0MITupdated 2026-10-15bradtraversy/claude-mods/work-queue
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · work-queue
│ ┃ Tasks ✕ › fix the failing auth test and add an audit log call │ ┃ Work Queue │ ┃ ⏺ Read(src/auth.ts) │ ┃ No tasks in this session. ⎿ Read 6 lines │ ┃ The queue updates when Claude creates a ⏺ Update(src/auth.ts) │ ┃ task. ⎿ Added 2 lines, removed 1 line │ ⏺ 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-queue │ ⎿ work-queue: Work queue opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Tasks
Work Queue No tasks in this session. The queue updates when Claude creates a task.
README

Claude Code Mods

A collection of personal Claude Code mods by Brad Traversy. These mods add useful session information, interface customizations, safety demonstrations, and verification tools to Claude Code.

Every mod is a small, independent Claude Code plugin written in TypeScript. Install only the ones you want, or run all eight together.

[!IMPORTANT] Mods run inside Claude Code with your user permissions. They can see session events, start processes, access files, and make network requests. Read the source before installing any mod, including these.

What is a mod?

A mod is a Claude Code plugin with JavaScript or TypeScript event handlers. Claude Code calls those handlers when something happens, such as:

  • A session starts
  • Claude calls a tool
  • A command is submitted
  • Part of the interface is rendered
  • Context usage changes

A handler can observe the event, change it, or handle it completely. That makes mods different from normal settings hooks. A mod can draw interface elements, replace existing tool rows, register slash commands, share state between handlers, and intercept a tool call before it runs.

These mods work in:

  • Claude Code in a terminal
  • Local sessions in the Code tab of the Claude Desktop app
  • SSH sessions in the Code tab when plugins are available on the remote host

Visual elements do not appear in the VS Code chat panel, claude -p, Agent SDK sessions, or cloud sessions. Plugins are not available in WSL sessions opened through the desktop app.

Requirements

  • Claude Code 2.1.287 or newer for terminal use
  • A desktop app version that includes Claude Code 2.1.286 or newer for the Code tab
  • Git, so Claude Code can clone this marketplace
  • GitHub CLI, authenticated with gh auth login, only if you want Verification Ledger to display remote GitHub Actions runs

Check your terminal version:

claude --version

In the desktop Code tab, enter /status and check the Claude Code version.

Quick start

1. Add the marketplace

Run this in your shell:

claude plugin marketplace add bradtraversy/claude-mods

You can also enter this in a Claude Code session:

/plugin marketplace add bradtraversy/claude-mods

2. Install the mods you want

Install one mod:

claude plugin install session-hud@traversy-mods

Install all eight:

claude plugin install session-hud@traversy-mods
claude plugin install impact-map@traversy-mods
claude plugin install tool-cards@traversy-mods
claude plugin install safe-shell@traversy-mods
claude plugin install quality-console@traversy-mods
claude plugin install verification-ledger@traversy-mods
claude plugin install agent-pulse@traversy-mods
claude plugin install work-queue@traversy-mods

Inside an interactive session, the same commands start with /plugin install instead of claude plugin install.

3. Load the mods

Start a new Claude Code session. If a session was already open when you installed or updated a mod, enter:

/reload-plugins

Run /plugin and open the Installed tab to confirm that the mods are enabled.

Use the same mods in terminal and desktop

Claude Code in the terminal and local sessions in the desktop Code tab share user-scoped plugin settings. Install a mod once at user scope and it is available in both places.

For the desktop app:

  1. Open the Code tab.
  2. Start a local session.
  3. Enter /reload-plugins, or start a new session after installation.
  4. Enter /plugin and confirm the mod is listed as active.

You can also use the desktop plugin manager. Click the plus button beside the prompt, choose Plugins, and use Manage plugins to enable or disable an installed mod.

Included mods

ModWhat it doesHow to open or test it
Session HUDShows the current Git branch, context, and weekly usage with detailed session informationSwitch branches or click Details beside the context meter
Impact MapTracks touched files and opens current Git diffsSelect an edited or created file in the Impact Map
Tool CardsReplaces normal tool-use rows with compact status cardsAsk Claude to read a file or run a command
Safe ShellDemonstrates a confirmation gate for a marked Bash commandAsk Claude to run echo __SAFE_SHELL_DEMO__
Quality ConsoleValidates a local mod from inside Claude CodeEnter /mod-check <path>
Verification LedgerTracks local checks, Git state, and GitHub ActionsEnter /checks
Agent PulseShows live subagent status, activity, elapsed time, and recent transcriptsAsk Claude to use a subagent or enter /agents
Work QueueGroups session tasks by working, blocked, ready, and doneAsk Claude to create tasks or enter /work-queue

Session HUD

Session HUD draws a compact band above the prompt with:

  • The current Git branch
  • Current context usage
  • A visual progress bar
  • Overall weekly account usage

Working branches appear in green. main and master appear in yellow as a reminder that you are on the default branch. Detached HEAD states are also yellow, and folders outside a Git repository say so directly. Session HUD checks every five seconds, so it also catches branch changes made in the built-in terminal or another terminal. Branches changed by a Claude Bash tool refresh immediately.

The compact Week label shows overall seven-day account usage. Click Details beside it to open Session Details. The pane shows:

  • Five-hour account usage with its reset time
  • Weekly account usage with its reset time
  • Session cost when Claude Code reports one
  • A color-coded meter for your personal context target

Claude Code also counts the current context and shows:

  • Clean progress bars for messages, system content, tool schemas, memory, skills, and agents
  • Messages as one conversation total
  • Loaded MCP tokens grouped by server, with tool details available from a server picker
  • Free space and the automatic compaction buffer

The full breakdown runs only when you click Details or press Refresh. It does not poll in the background. Claude Code provides a reliable total for Messages, but it does not provide a reliable token count for every individual message.

The context percentage uses a configurable personal target. It does not change Claude's actual context window or automatic compaction behavior.

Change the context target

Open Session Details and select Change beside the current target. Enter a value such as 200k, 300k, 750k, or 1m, then press Enter to save it. You can also open Claude Code's /config menu and change Context target there.

The setting is saved with the plugin and applies to future sessions. The default is 300k, and accepted values range from 10k through 10m.

The meter is green below 70 percent, yellow from 70 through 89 percent, and red at 90 percent or higher. Its visual fill stops at 100 percent, but the numeric percentage can go higher.

Test Session HUD

  1. Install and load session-hud.
  2. Send a prompt so Claude Code records session usage.
  3. Look directly above the prompt box.
  4. Confirm that the current branch, context, and weekly usage appear.
  5. Switch branches in the built-in terminal and confirm that the label updates within five seconds.
  6. Confirm that the Week label shows your weekly percentage.
  7. Click Details beside the progress bar.
  8. Confirm that Session Details shows five-hour usage, weekly usage, session cost, context categories, and any connected MCP tool schemas.
  9. Select Change, enter another context target, and confirm that the percentage updates after the mod reloads.

Source: session-hud/hooks/register.tsx

Impact Map

Impact Map opens a pane that records the most recent files Claude touched during the current session.

It labels each file as:

  • READ when Claude uses the Read tool
  • EDITED when Claude uses the Edit tool
  • CREATED when Claude uses the Write tool

The pane keeps the 14 most recent unique file paths. Reading or changing the same file again moves it to the newest position.

Edited and created files are clickable. Selecting one opens a Diff pane with Claude Code's native unified-diff highlighting. Tracked files use the current working-tree diff against HEAD. Untracked files are shown as newly added files.

The Diff pane reflects the file's current Git state, not a private history of only Claude's edits. If you or another tool changed the same file, those changes appear too. Read-only files are not clickable because they have no change to display.

Test Impact Map

  1. Install and load impact-map.
  2. Ask Claude to read two files and edit one of them.
  3. Watch the Impact Map pane update.
  4. Select the edited file and confirm that its highlighted diff opens in a new pane tab.
  5. If the Impact Map pane is closed, enter /impact-map to reopen it.

Claude Code has one docked pane area. If Verification Ledger is also open, the two panes appear as tabs in that area rather than side by side.

Source: impact-map/hooks/register.tsx

Tool Cards

Tool Cards replaces Claude Code's standard tool-use row with a bordered card that emphasizes the current state, tool name, and target.

Possible states are:

  • RUNNING
  • DONE
  • FAILED
  • STOPPED

For file tools, the card displays the file path. For Bash, it displays the command. It also handles tools that expose a path or pattern field.

Test Tool Cards

  1. Install and load tool-cards.
  2. Ask Claude to read a file.
  3. Watch the card change from RUNNING to DONE.
  4. Ask Claude to run a command that fails if you want to see the FAILED state.

The green DONE label is part of this mod. Disable Tool Cards from /plugin to return to Claude Code's normal tool rows.

Source: tool-cards/hooks/register.tsx

Safe Shell

Safe Shell is a harmless demonstration of a tool.check handler. It shows how a mod can stop before a Bash command runs and ask the user to approve or cancel it.

This version looks only for the marker:

__SAFE_SHELL_DEMO__

It does not attempt to identify real dangerous commands. That limited behavior is intentional, so the demo cannot accidentally become a false promise of shell security.

Test Safe Shell

  1. Install and load safe-shell.
  2. Ask Claude to run this exact command:
   echo __SAFE_SHELL_DEMO__
  1. Claude Code should show a confirmation prompt from Safe Shell before the command runs.
  2. Choose whether to continue or cancel.
  3. Run a normal command such as git status and confirm that Safe Shell does not interfere.

Source: safe-shell/hooks/register.ts

Quality Console

Quality Console adds a /mod-check command that runs Claude Code's official static validator against a local mod directory.

Use it from a Claude Code session:

/mod-check /absolute/path/to/a-mod

If you omit the path, it validates the current working directory:

/mod-check

The command displays PASS, FAIL, or ERROR followed by the validator output. Validation checks the manifest, hook events, matchers, API calls, imports, and statically detectable capabilities. It does not execute the mod.

Test Quality Console

  1. Install and load quality-console.
  2. Clone this repository if you do not already have a local mod to check.
  3. Enter /mod-check with the absolute path to one of the mod directories.
  4. Confirm that the result starts with PASS.

Example:

/mod-check /path/to/claude-mods/session-hud

Source: quality-console/hooks/register.ts

Verification Ledger

Verification Ledger opens a Checks pane that combines three kinds of evidence:

  • Local verification commands run by Claude through the Bash tool
  • Current Git branch, commit, working-tree state, and upstream state
  • GitHub Actions runs for the current commit

Open it with:

/checks

The pane does not open automatically, so it does not compete with Impact Map until you ask for it. When both panes are open, Claude Code places them in tabs within the same docked pane area.

Recognized local commands

The ledger recognizes common commands in these categories:

  • Verify: npm run verify, pnpm verify, yarn verify, bun verify, and ./scripts/verify
  • Tests: package test scripts, Vitest, Jest, Pytest, cargo test, and go test
  • Lint: package lint scripts, ESLint, Biome, Ruff, golangci-lint, and Cargo Clippy
  • Typecheck: package typecheck scripts, tsc --noEmit, Mypy, and Pyright
  • Build: package build scripts, cargo build, and go build

The command must be run by Claude through its Bash tool. A command run manually in a separate terminal is not a Claude Code event, so the mod cannot observe it.

Pass, fail, and stale results

Verification Ledger stores the latest result in each category for the current session.

  • PASS means the recognized command completed successfully.
  • FAIL means it returned an error.
  • STALE means files, the current commit, or the recorded session revision changed after the check ran.

Local results reset when the mod reloads or a new session starts. The ledger is a live session display, not a permanent audit database.

GitHub Actions support

Remote checks require the GitHub CLI:

gh --version
gh auth status

If needed, authenticate it:

gh auth login

While the Checks pane is open, the mod runs this read-only query for the current commit every 15 seconds:

gh run list --commit <commit-sha> --limit 8 --json name,status,conclusion,url,headSha,workflowName

The pane displays workflow links and the states RUNNING, PASS, FAIL, or SKIPPED. It also shows a toast when a previously running workflow passes or fails.

If gh is missing, not authenticated, or the repository is not hosted on GitHub, the remote section reports that GitHub CI is unavailable. Local checks and Git state still work.

Change the polling interval

Open verification-ledger/hooks/config.ts:

export const CI_POLL_INTERVAL_MS = 15_000
export const MAX_CI_RUNS = 8

Change the values to control how often the open pane refreshes and how many workflow runs it displays.

Test Verification Ledger

  1. Install and load verification-ledger in a Git repository.
  2. Enter /checks.
  3. Ask Claude to run the project's test command.
  4. Confirm that Tests appears with PASS or FAIL.
  5. Ask Claude to edit a file.
  6. Reopen or refresh /checks and confirm that the earlier result is STALE.
  7. Push a commit with GitHub Actions configured.
  8. Leave the pane open and watch the workflow move from RUNNING to its final state.

Source: verification-ledger/hooks/register.tsx

Agent Pulse

Agent Pulse opens an Agents pane when the first subagent starts in the current session. It gives each agent a compact card with:

  • Current status
  • Agent name or task description
  • Elapsed time since the mod first observed it
  • Current tool while one is running
  • Most recent tool after it finishes

The pane does not open when a session has no subagents. It also does not take keyboard focus when it opens automatically. Enter /agents whenever you want to open it manually or bring it back after closing it.

Select View on an agent card to replace the list with a compact detail view. The detail view shows the agent type, status, elapsed time, parent agent when present, and up to eight recent transcript messages. Select Back to return to the full list.

Agent Pulse keeps finished agents in the pane for the rest of the current session, even when Claude Code no longer includes them in its live agent list. The history resets when the mod reloads or a new session starts.

Possible states are:

  • PENDING before work begins
  • RUNNING while the agent is working
  • WAITING when it is waiting on another action
  • IDLE when a teammate is available for more work
  • COMPLETED after a successful result
  • FAILED after an error or refusal
  • KILLED after an interrupted run

Agent Pulse uses only Claude Code's agent, session, clock, command, and interface APIs. It does not call a model, start a process, read project files, make a network request, or save agent transcripts outside the current session.

Claude Code may deny transcript access for an agent running in another process, a remote workflow agent, or an agent whose saved transcript is no longer available. The card still shows any status and activity that Claude Code reports, and the detail view explains when its transcript cannot be read.

Test Agent Pulse

  1. Install and load agent-pulse.
  2. Enter /agents and confirm that the empty state says there are no subagents in the session.
  3. Ask Claude to use an Explore subagent to inspect a small part of the current project.
  4. Confirm that the Agents pane opens without taking focus.
  5. Watch the card update with the agent status, elapsed time, and current or last tool.
  6. Select View and confirm that the recent prompt, response, and tool names appear.
  7. Select Back to return to the agent list.
  8. Repeat the same check in a terminal session and a local session in the desktop Code tab.

Source: agent-pulse/hooks/register.tsx

Work Queue

Work Queue opens a Tasks pane when Claude creates the first task in the current session. It turns Claude's task state into four focused groups:

  • Working for tasks in progress
  • Blocked for pending tasks with unfinished dependencies
  • Ready for pending tasks that can start
  • Done for completed tasks

Each row shows the task subject, owner when one is assigned, and how long it has been in its current state. Select View to see the full description, owner, creation and update times, tasks that block it, and tasks that depend on it. Dependencies are clickable, so you can move through the work graph without leaving the pane.

The pane does not open in an empty session and does not take keyboard focus when it opens automatically. Enter /work-queue to open it manually or bring it back after closing it.

Work Queue observes TaskCreate, TaskUpdate, TaskList, and TaskGet tool calls. It also observes Claude Code's task-created and task-completed lifecycle events, which catches task activity that did not pass through those tools. It never creates, updates, completes, or deletes a task itself.

Task history lives only in memory for the current session. Reloading the mod or starting a new session clears the pane. The mod does not call a model, start a process, read project files, make a network request, or persist task data.

Claude Code does not deliver classic task lifecycle events to user-installed plugins when an organization manages the installation. Normal task tool calls still appear, but a task created in another process may be missing if it produces only a lifecycle event.

Test Work Queue

  1. Install and load work-queue.
  2. Enter /work-queue and confirm that the empty state says there are no tasks in the session.
  3. Ask Claude to create a three-step task plan where the interface task depends on the API task.
  4. Ask Claude to start the API task.
  5. Confirm that the pane shows one task under Working, the dependent task under Blocked, and the remaining task under Ready.
  6. Select View on the blocked task and confirm that the API task appears under Blocked by.
  7. Complete the API task and confirm that it moves to Done while the dependent task moves to Ready.
  8. Repeat the check in a terminal session and a local session in the desktop Code tab.

Source: work-queue/hooks/register.tsx

How the mods work together

The mods have separate responsibilities, so their interface elements do not duplicate each other:

  • Session HUD owns the band above the prompt.
  • Tool Cards owns tool-use rows in the transcript.
  • Impact Map owns a file-activity pane.
  • Verification Ledger owns a checks pane.
  • Agent Pulse owns a live subagent pane.
  • Work Queue owns a task-state pane.
  • Quality Console owns /mod-check.
  • Safe Shell owns only its marked-command confirmation.

Impact Map, Verification Ledger, Agent Pulse, and Work Queue share Claude Code's single docked pane area as separate tabs. Agent Pulse shows who is working, while Work Queue shows what work exists and what is blocked. All other mods use different interface regions or event types.

Develop locally from scratch

You do not need Node.js, a bundler, or a dependency installation. Claude Code loads TypeScript mod files directly and supplies the test runner.

1. Clone the repository

git clone https://github.com/bradtraversy/claude-mods.git
cd claude-mods

2. Validate the marketplace and every mod

claude plugin validate .
claude plugin validate ./session-hud
claude plugin validate ./impact-map
claude plugin validate ./tool-cards
claude plugin validate ./safe-shell
claude plugin validate ./quality-console
claude plugin validate ./verification-ledger
claude plugin validate ./agent-pulse
claude plugin validate ./work-queue

Validation reads the mod without executing it. Review the reported hooks: and calls: lines to see what it handles and which Claude Code APIs it uses.

3. Run the automated tests

claude plugin test ./session-hud
claude plugin test ./impact-map
claude plugin test ./tool-cards
claude plugin test ./safe-shell
claude plugin test ./quality-console
claude plugin test ./verification-ledger
claude plugin test ./agent-pulse
claude plugin test ./work-queue

The interface tests mount each visual mod on simulated terminal and desktop surfaces.

4. Load one mod for a development session

claude --plugin-dir ./session-hud

Claude Code watches a directory loaded with --plugin-dir and reloads the hooks module after changes. Run /plugin to confirm that the mod loaded.

You can load multiple development directories by repeating the flag:

claude \
  --plugin-dir ./session-hud \
  --plugin-dir ./impact-map \
  --plugin-dir ./tool-cards

5. Use the local checkout in terminal and desktop

Register the clone itself as a local marketplace:

claude plugin marketplace add /absolute/path/to/claude-mods

Then install any mod from traversy-mods. A marketplace added from a local directory reads these relative plugin directories in place, so edits appear after a new session starts or after /reload-plugins.

This is the easiest development setup for sharing the exact same working directory between terminal sessions and local desktop Code sessions.

Anatomy of each mod

Every directory follows the same basic structure:

mod-name/
├── .claude-plugin/
│   ├── plugin.json
│   └── types/
│       ├── .gitignore
│       └── tsconfig.json
├── hooks/
│   ├── hooks.json
│   ├── config.ts       # only when the mod has user-editable settings
│   └── register.tsx    # register.ts when JSX is not needed
├── tests/
│   └── mod-name.test.ts
└── tsconfig.json

plugin.json

The plugin manifest provides the mod name, version, description, and author.

hooks.json

This file points Claude Code to the TypeScript module that registers the event handlers.

register.ts or register.tsx

The module imports the Register type from claude-code and exports a register function:

import type { Register } from 'claude-code'

export const register: Register = on => {
  on('session.start', ($, event, next) => {
    return next(event)
  })
}

The Register type comes from declarations generated by Claude Code in .claude-plugin/types/. Those declarations also provide types for $, event, and next, which removes the red lines a

Source 1 files
hooks/register.tsx 534 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3const PANE = 'work-queue'
4const CLOCK_INTERVAL_MS = 5_000
5
6type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'deleted'
7type TaskGroup = 'Working' | 'Blocked' | 'Ready' | 'Done'
8
9type WorkTask = {
10  id: string
11  subject: string
12  description: string
13  activeForm: string
14  status: TaskStatus
15  owner: string
16  blockedBy: string[]
17  blocks: string[]
18  createdAt: number
19  updatedAt: number
20  statusChangedAt: number
21}
22
23type TaskListItem = {
24  id: string
25  subject: string
26  status: Exclude<TaskStatus, 'deleted'>
27  owner?: string
28  blockedBy: string[]
29}
30
31type TaskDetail = {
32  id: string
33  subject: string
34  description: string
35  status: Exclude<TaskStatus, 'deleted'>
36  blocks: string[]
37  blockedBy: string[]
38}
39
40const tasks = new Map<string, WorkTask>()
41let selectedTaskId = ''
42let currentTime = 0
43let didAutoOpen = false
44let clockTimer: Timer | null = null
45
46function unique(values: string[]): string[] {
47  return [...new Set(values)]
48}
49
50function resetState(): void {
51  tasks.clear()
52  selectedTaskId = ''
53  currentTime = 0
54  didAutoOpen = false
55  clockTimer?.cancel()
56  clockTimer = null
57}
58
59function ensureTask(id: string, now: number, subject = `Task ${id}`): WorkTask {
60  const existing = tasks.get(id)
61  if (existing) return existing
62
63  const task: WorkTask = {
64    id,
65    subject,
66    description: '',
67    activeForm: '',
68    status: 'pending',
69    owner: '',
70    blockedBy: [],
71    blocks: [],
72    createdAt: now,
73    updatedAt: now,
74    statusChangedAt: now,
75  }
76  tasks.set(id, task)
77  return task
78}
79
80function setStatus(task: WorkTask, status: TaskStatus, now: number): void {
81  if (task.status === status) return
82  task.status = status
83  task.statusChangedAt = now
84  task.updatedAt = now
85}
86
87function isBlocked(task: WorkTask): boolean {
88  if (task.status !== 'pending') return false
89  return task.blockedBy.some(id => tasks.get(id)?.status !== 'completed')
90}
91
92function taskGroup(task: WorkTask): TaskGroup {
93  if (task.status === 'completed') return 'Done'
94  if (task.status === 'in_progress') return 'Working'
95  if (isBlocked(task)) return 'Blocked'
96  return 'Ready'
97}
98
99function groupColor(group: TaskGroup): 'success' | 'warning' | 'accent' | 'inactive' {
100  if (group === 'Working') return 'success'
101  if (group === 'Blocked') return 'warning'
102  if (group === 'Ready') return 'accent'
103  return 'inactive'
104}
105
106function durationLabel(milliseconds: number): string {
107  const seconds = Math.max(0, Math.floor(milliseconds / 1_000))
108  if (seconds < 60) return `${seconds}s`
109
110  const minutes = Math.floor(seconds / 60)
111  if (minutes < 60) return `${minutes}m`
112
113  const hours = Math.floor(minutes / 60)
114  return `${hours}h ${minutes % 60}m`
115}
116
117function taskAge(task: WorkTask): string {
118  if (task.status === 'in_progress') {
119    return durationLabel(currentTime - task.statusChangedAt)
120  }
121  if (task.status === 'completed') {
122    return `${durationLabel(currentTime - task.updatedAt)} ago`
123  }
124  return durationLabel(currentTime - task.createdAt)
125}
126
127function taskMeta(task: WorkTask, group: TaskGroup): string {
128  const parts = task.owner ? [task.owner] : []
129  if (group === 'Blocked') {
130    const count = task.blockedBy.length
131    parts.push(`${count} blocker${count === 1 ? '' : 's'}`)
132  }
133  return parts.join('  ') || 'Unassigned'
134}
135
136function taskReference(id: string): WorkTask {
137  return tasks.get(id) ?? {
138    id,
139    subject: `Task ${id}`,
140    description: '',
141    activeForm: '',
142    status: 'pending',
143    owner: '',
144    blockedBy: [],
145    blocks: [],
146    createdAt: currentTime,
147    updatedAt: currentTime,
148    statusChangedAt: currentTime,
149  }
150}
151
152function taskCreateResult(value: unknown): { id: string; subject: string } | null {
153  if (!value || typeof value !== 'object' || !('task' in value)) return null
154  const task = value.task
155  if (!task || typeof task !== 'object') return null
156  if (!('id' in task) || typeof task.id !== 'string') return null
157  if (!('subject' in task) || typeof task.subject !== 'string') return null
158  return { id: task.id, subject: task.subject }
159}
160
161function taskUpdateSucceeded(value: unknown): boolean {
162  return Boolean(value && typeof value === 'object' && 'success' in value && value.success === true)
163}
164
165function taskListResult(value: unknown): TaskListItem[] | null {
166  if (!value || typeof value !== 'object' || !('tasks' in value) || !Array.isArray(value.tasks)) {
167    return null
168  }
169
170  const items: TaskListItem[] = []
171  for (const item of value.tasks) {
172    if (!item || typeof item !== 'object') continue
173    if (!('id' in item) || typeof item.id !== 'string') continue
174    if (!('subject' in item) || typeof item.subject !== 'string') continue
175    if (!('status' in item) || (
176      item.status !== 'pending'
177      && item.status !== 'in_progress'
178      && item.status !== 'completed'
179    )) continue
180
181    items.push({
182      id: item.id,
183      subject: item.subject,
184      status: item.status,
185      owner: 'owner' in item && typeof item.owner === 'string' ? item.owner : undefined,
186      blockedBy: 'blockedBy' in item && Array.isArray(item.blockedBy)
187        ? item.blockedBy.filter((id: unknown): id is string => typeof id === 'string')
188        : [],
189    })
190  }
191  return items
192}
193
194function taskDetailResult(value: unknown): TaskDetail | null {
195  if (!value || typeof value !== 'object' || !('task' in value)) return null
196  const task = value.task
197  if (!task || typeof task !== 'object') return null
198  if (!('id' in task) || typeof task.id !== 'string') return null
199  if (!('subject' in task) || typeof task.subject !== 'string') return null
200  if (!('description' in task) || typeof task.description !== 'string') return null
201  if (!('status' in task) || (
202    task.status !== 'pending'
203    && task.status !== 'in_progress'
204    && task.status !== 'completed'
205  )) return null
206
207  return {
208    id: task.id,
209    subject: task.subject,
210    description: task.description,
211    status: task.status,
212    blocks: 'blocks' in task && Array.isArray(task.blocks)
213      ? task.blocks.filter(id => typeof id === 'string')
214      : [],
215    blockedBy: 'blockedBy' in task && Array.isArray(task.blockedBy)
216      ? task.blockedBy.filter(id => typeof id === 'string')
217      : [],
218  }
219}
220
221function maybeOpen($: EngineInterface): void {
222  if (didAutoOpen || tasks.size === 0) return
223  didAutoOpen = true
224  void $.ui.open({ id: PANE, title: 'Tasks', columns: 58 })
225}
226
227function changed($: EngineInterface): void {
228  maybeOpen($)
229  $.ui.invalidate('ui.render')
230}
231
232async function tickOpenPane($: EngineInterface): Promise<void> {
233  try {
234    const pane = (await $.ui.panes()).find(item => item.id === PANE)
235    if (!pane?.isPlaced || !pane.isShown) return
236    currentTime = await $.clock.now()
237    $.ui.invalidate('ui.render')
238  } catch {
239    // A display refresh should never affect Claude's work.
240  }
241}
242
243export const register: Register = on => {
244  on('session.start', async ($, event, next) => {
245    resetState()
246    await $.command.register({
247      name: 'work-queue',
248      description: 'Open the current Claude task queue',
249    })
250    clockTimer = $.clock.every(CLOCK_INTERVAL_MS, () => {
251      void tickOpenPane($)
252    })
253    return next(event)
254  })
255
256  on('session.end', ($, event, next) => {
257    clockTimer?.cancel()
258    clockTimer = null
259    return next(event)
260  })
261
262  on('command.run', { command: 'work-queue' }, async $ => {
263    await $.ui.open({
264      id: PANE,
265      title: 'Tasks',
266      focus: true,
267      closeOnEscape: true,
268      columns: 58,
269    })
270    currentTime = await $.clock.now()
271    $.ui.invalidate('ui.render')
272    return { text: 'Work queue opened.' }
273  }).catch(() => ({ text: 'Work Queue could not open the task pane.' }))
274
275  on('classic.TaskCreated', async ($, event, next) => {
276    const result = await next(event)
277    const now = await $.clock.now()
278    currentTime = now
279    const task = ensureTask(event.task_id, now, event.task_subject)
280    task.subject = event.task_subject
281    task.description = event.task_description ?? task.description
282    task.owner = event.teammate_name ?? task.owner
283    task.updatedAt = now
284    changed($)
285    return result
286  }).catch(($, event, next) => next(event))
287
288  on('classic.TaskCompleted', async ($, event, next) => {
289    const result = await next(event)
290    const now = await $.clock.now()
291    currentTime = now
292    const task = ensureTask(event.task_id, now, event.task_subject)
293    task.subject = event.task_subject
294    task.description = event.task_description ?? task.description
295    task.owner = event.teammate_name ?? task.owner
296    setStatus(task, 'completed', now)
297    changed($)
298    return result
299  }).catch(($, event, next) => next(event))
300
301  on('tool.call', async ($, event, next) => {
302    const result = await next(event)
303    if (result.isError || result.deny) return result
304
305    const now = await $.clock.now()
306    currentTime = now
307
308    if (event.tool === 'TaskCreate') {
309      const created = taskCreateResult(result.result)
310      if (!created) return result
311
312      const task = ensureTask(created.id, now, created.subject)
313      task.subject = event.subject || created.subject
314      task.description = event.description
315      task.activeForm = event.activeForm ?? ''
316      task.updatedAt = now
317      changed($)
318    }
319
320    if (event.tool === 'TaskUpdate') {
321      if (!taskUpdateSucceeded(result.result)) return result
322
323      const task = ensureTask(event.taskId, now)
324      if (event.subject !== undefined) task.subject = event.subject
325      if (event.description !== undefined) task.description = event.description
326      if (event.activeForm !== undefined) task.activeForm = event.activeForm
327      if (event.owner !== undefined) task.owner = event.owner
328      if (event.addBlockedBy) {
329        task.blockedBy = unique([...task.blockedBy, ...event.addBlockedBy])
330        for (const blockerId of event.addBlockedBy) {
331          const blocker = ensureTask(blockerId, now)
332          blocker.blocks = unique([...blocker.blocks, task.id])
333        }
334      }
335      if (event.addBlocks) {
336        task.blocks = unique([...task.blocks, ...event.addBlocks])
337        for (const blockedId of event.addBlocks) {
338          const blocked = ensureTask(blockedId, now)
339          blocked.blockedBy = unique([...blocked.blockedBy, task.id])
340        }
341      }
342      task.updatedAt = now
343      if (event.status) setStatus(task, event.status, now)
344      changed($)
345    }
346
347    if (event.tool === 'TaskList') {
348      const listed = taskListResult(result.result)
349      if (!listed) return result
350
351      for (const item of listed) {
352        const task = ensureTask(item.id, now, item.subject)
353        const before = JSON.stringify([task.subject, task.owner, task.blockedBy, task.status])
354        task.subject = item.subject
355        task.owner = item.owner ?? ''
356        task.blockedBy = item.blockedBy
357        setStatus(task, item.status, now)
358        if (before !== JSON.stringify([task.subject, task.owner, task.blockedBy, task.status])) {
359          task.updatedAt = now
360        }
361      }
362      changed($)
363    }
364
365    if (event.tool === 'TaskGet') {
366      const detail = taskDetailResult(result.result)
367      if (!detail) return result
368
369      const task = ensureTask(detail.id, now, detail.subject)
370      const before = JSON.stringify([
371        task.subject,
372        task.description,
373        task.blocks,
374        task.blockedBy,
375        task.status,
376      ])
377      task.subject = detail.subject
378      task.description = detail.description
379      task.blocks = detail.blocks
380      task.blockedBy = detail.blockedBy
381      setStatus(task, detail.status, now)
382      if (before !== JSON.stringify([
383        task.subject,
384        task.description,
385        task.blocks,
386        task.blockedBy,
387        task.status,
388      ])) task.updatedAt = now
389      changed($)
390    }
391
392    return result
393  }).catch(($, event, next) => next(event))
394
395  on('ui.render', { component: 'Pane', requestId: PANE }, ($, event) => {
396    const { Box, Button, Text } = $.ui.resolve(event)
397    const selected = selectedTaskId ? tasks.get(selectedTaskId) : undefined
398
399    if (selected && selected.status !== 'deleted') {
400      const group = taskGroup(selected)
401      const blockedBy = selected.blockedBy.map(taskReference)
402      const blocks = selected.blocks.map(taskReference)
403
404      return (
405        <Box flexDirection="column" gap={1}>
406          <Button
407            key="work-back"
408            label="Back"
409            plain
410            onPress={() => {
411              selectedTaskId = ''
412              $.ui.invalidate('ui.render')
413            }}
414          />
415
416          <Box flexDirection="column">
417            <Box justifyContent="space-between" width="100%">
418              <Text bold wrap="wrap">{selected.subject}</Text>
419              <Text color={groupColor(group)}>{group}</Text>
420            </Box>
421            {selected.description && <Text dimColor wrap="wrap">{selected.description}</Text>}
422          </Box>
423
424          <Box flexDirection="column">
425            <Text dimColor>Owner: {selected.owner || 'Unassigned'}</Text>
426            <Text dimColor>Created {durationLabel(currentTime - selected.createdAt)} ago</Text>
427            <Text dimColor>Updated {durationLabel(currentTime - selected.updatedAt)} ago</Text>
428          </Box>
429
430          {blockedBy.length > 0 && (
431            <Box flexDirection="column">
432              <Text bold>Blocked by</Text>
433              {blockedBy.map(task => (
434                <Button
435                  key={`dependency:${task.id}`}
436                  plain
437                  dimColor
438                  onPress={() => {
439                    selectedTaskId = task.id
440                    $.ui.invalidate('ui.render')
441                  }}
442                >
443                  {task.subject}
444                </Button>
445              ))}
446            </Box>
447          )}
448
449          {blocks.length > 0 && (
450            <Box flexDirection="column">
451              <Text bold>Blocks</Text>
452              {blocks.map(task => (
453                <Button
454                  key={`dependent:${task.id}`}
455                  plain
456                  dimColor
457                  onPress={() => {
458                    selectedTaskId = task.id
459                    $.ui.invalidate('ui.render')
460                  }}
461                >
462                  {task.subject}
463                </Button>
464              ))}
465            </Box>
466          )}
467        </Box>
468      )
469    }
470
471    const visibleTasks = [...tasks.values()].filter(task => task.status !== 'deleted')
472    const openCount = visibleTasks.filter(task => task.status !== 'completed').length
473    const doneCount = visibleTasks.length - openCount
474    const groups: TaskGroup[] = ['Working', 'Blocked', 'Ready', 'Done']
475
476    return (
477      <Box flexDirection="column" gap={1}>
478        <Box justifyContent="space-between" width="100%">
479          <Text bold>Work Queue</Text>
480          {visibleTasks.length > 0 && <Text dimColor>{openCount} open  {doneCount} done</Text>}
481        </Box>
482
483        {visibleTasks.length === 0 ? (
484          <Box flexDirection="column">
485            <Text dimColor>No tasks in this session.</Text>
486            <Text dimColor>The queue updates when Claude creates a task.</Text>
487          </Box>
488        ) : groups.map(group => {
489          const groupTasks = visibleTasks
490            .filter(task => taskGroup(task) === group)
491            .sort((left, right) => left.createdAt - right.createdAt)
492          if (groupTasks.length === 0) return null
493
494          return (
495            <Box key={`group:${group}`} flexDirection="column">
496              <Box gap={1}>
497                <Text color={groupColor(group)}>●</Text>
498                <Text bold>{group}</Text>
499                <Text dimColor>{groupTasks.length}</Text>
500              </Box>
501
502              <Box flexDirection="column" marginLeft={2}>
503                {groupTasks.map(task => (
504                  <Box key={`task:${task.id}`} flexDirection="column" marginBottom={1}>
505                    <Box justifyContent="space-between" alignItems="center" width="100%">
506                      <Text wrap="truncate">{task.subject}</Text>
507                      <Button
508                        key={`task-view:${task.id}`}
509                        label="View"
510                        plain
511                        dimColor
512                        onPress={() => {
513                          selectedTaskId = task.id
514                          $.ui.invalidate('ui.render')
515                        }}
516                      />
517                    </Box>
518                    <Box justifyContent="space-between" width="100%">
519                      <Text dimColor wrap="truncate">
520                        {taskMeta(task, group)}
521                      </Text>
522                      <Text dimColor>{taskAge(task)}</Text>
523                    </Box>
524                  </Box>
525                ))}
526              </Box>
527            </Box>
528          )
529        })}
530      </Box>
531    )
532  })
533}
534