A live todo pane for the session: the agent keeps it current through a tool, you read and tick it without asking.

A Claude Code mod that puts the session's todo list in a side pane. The agent keeps the list current through a tool it is told to use, so you can see what is done, what is in progress and what is left without asking.
about under the title saying what the list is for (cut to 80 characters with an ellipsis, so it stays a line). Each row shows a status glyph, the item text and an optional note; items are numbered straight through the pane. A small mark after the text says who does the item: an orange ✱ for the agent, a yellow ♟ for you (items you add with /todo add, and steps the agent marks as yours because only you can take them: approve, decide, run something it may not). Click the glyph to cycle an item pending → in progress → done. While the pane holds the keyboard (click once into it), each row ends in a ⧉; a click on it puts the item's text on the clipboard, its note on a second line. The icons are absent while the pane is unfocused, because on the desktop the first click on an unfocused pane only focuses it. Every in-progress item is repeated in a now: block, and a legend closes the pane.[>] TODO: 3. <current item> (+1), or [ ] TODO: 4. <first pending item> when nothing is in progress, the number being the item's number in the pane (so /todo done 3 needs no lookup), then at the right the done/total count, an "Open Pane" button and a ▸. The glyph is the shown item's own toggle: click it to cycle the item pending → in progress → done, as in the pane. The ▸ and the item text unfold the band: the whole board is drawn under the row as the pane draws it, glyph clicks and all, and a board taller than half the screen scrolls in the engine's window (the wheel, or the arrow keys while the band is focused). ▾ folds it again, and the fold is remembered for the session. When the item in progress finishes, the band shows it ticked for a moment before moving on to the next.auto (the default: the band while the pane is closed, and the pane opens on its own at the first items), both (the band always, the pane as in auto), band (the band always, the pane only when you open it with the band's button or /todo) and pane (no band, the pane as in auto). An empty board shows nothing in any layout, and a pane you close stays closed for the session in every layout. Pick one in the ⚙ settings row, with /todo layout auto|both|band|pane (/todo layout alone cycles through them), or in the /config row. The earlier "Band" setting's values still work: off is pane, closed is auto, always is both.[ ] TODO YOU: 5. <item>, the status box in its usual colour and the label in yours, and the pane lists it first in the block under the lists, with the note. A toast names it too, once per item, unless "notify" is off: the ⚙ settings row, /todo notify on|off, or the /config row. Changes you make yourself (a click, a /todo command) never poke you./todo add, /todo start, /todo done, /todo remove, /todo clear or /todo drop leaves a one-line session-todo: note in the conversation that the model reads on its next step, without a prompt from you and without the note showing as typed. The system prompt tells it such a note needs no reply, only to count when it changes the next step.done/total count: done, in progress and blocked take their share in colour, the rest is dim, and any status with at least one item keeps at least one cell./todo command for your own edits: /todo (show), /todo add [@list] <text>, /todo start <n>, /todo done <n>, /todo remove <n>, /todo about <list> [text], /todo clear [list], /todo drop <list>, /todo focus <list>, /todo theme <name>, /todo layout [auto|both|band|pane], /todo compact [on|off], /todo notify [on|off], and for shared boards /todo share <name> [as <label>], /todo join <name> [as <label>], /todo leave, /todo boards, /todo forget <name>./todo name <name>, /todo share [name] [as <label>] (no name shares under the board's own), and in each session that does part of the work /todo join plan as backend. Every session reads it back every two seconds and applies its own changes over what the others wrote, so the plan, the progress and the ticks all land in one place. Items show @label for the session that created them or last moved them. /todo leave returns a session to its own board, kept untouched meanwhile; /todo boards lists the shared ones with their last change; /todo forget <name> deletes one nobody follows. Every stored board, shared or a session's own, carries the time of its last write, and a session start drops the ones untouched for 30 days. /clear leaves a shared board rather than emptying it. The agent is told that other sessions write there too, so it adds and updates rather than rewriting lists it did not create. Boards are shared through the plugin store on one machine; two sessions changing the same board in the same instant can lose one change./todo compact on|off, or the /config row drops it.classic (the terminal's green, yellow, red), cyberpunk (neon green and purple), and the standard palettes dracula, nord, solarized, gruvbox, monokai, catppuccin, tokyo-night, one-dark. Pick one with the ⚙ button at the top of the pane, /todo theme <name>, or in /config under the plugin's "Theme" row; the choice is stored in your user settings.mcp__ccd_turn__update_plan) now lands in the pane's main list too: a plan given in full replaces the list, an item keeping its id, owner and note when its text is still there; a step advanced, done or started by position moves the same item here. The agent is told to keep using the app's list and to call the todo tool for what that list cannot say: a second list, an item that is yours, a blocked step with its note, an about line. A shared board is left alone by the mirror, since its main list may be another session's.session-todo: note at its second such call, asking the agent to write the plan now (with the todo tool, or with the app's own list where there is one) and keep it current. A single edit needs no list, so one call earns no note; subagents' calls do not count.todo tool the agent calls (mcp__session-todo__todo): write a named list, add, update, remove, read (every list), clear, drop, focus, describe (the about line). A system-prompt section tells the agent to write the plan before any task that takes more than one tool call, also when it does every step itself and you only watch, keep the step it works on in progress (one at a time preferred, several allowed), mark items done as it goes, and keep follow-ups such as "open the PR" or "report to Jira" in a second list so the main plan stays focused.Several lists, two flat levels (list, item), item ids unique across lists. The board lives in the session's plugin state (survives hot reloads and context compaction) and is mirrored to the plugin store under the session id, so claude --resume brings it back; a session that followed a shared board follows it again on resume. /clear empties it.
From a terminal session of Claude Code:
/plugin install session-todo --marketplace jepperip/claude-session-todo
Answer y to add the marketplace, then pick the user scope. A mod installed at the user scope also loads in the sessions the Claude desktop app starts.
For a terminal session: claude --plugin-dir <path-to-this-folder>.
For the desktop app, which takes no flags, name the folder in ~/.claude/settings.json:
{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "C:\\code\\claude-session-todo" } }
An interactive session watches the folder and reloads the mod when a file changes.
.claude-plugin/plugin.json manifest
.claude-plugin/marketplace.json makes this repository installable as a marketplace
hooks/hooks.json names the hooks module
hooks/register.tsx the mod: tool, command, pane, status line, prompt section, mirror of the app's task list
types/index.d.ts the state contract (what the pane draws from)
types/host-tools.d.ts the desktop app's task-list tool, typed so the mirror's hook checks
claude plugin validate . checks the manifest and module. The engine writes this build's API declarations to .claude-plugin/types/ on every load (gitignored), so tsc -p . type-checks the module after the mod has loaded once.
Early access API: Claude Code's function-hook plugin API moves between releases, so a newer engine may need small changes here. Written against Claude Code 2.1.293.
Works in a terminal and in the Claude desktop app. In Claude Code for VS Code (extension 2.1.292 at the time of writing) the mod loads and the todo tool, the prompt section and /todo work, but the extension's webview does not draw plugin panes or bands yet, so there is no pane, band or settings row there; /todo prints the board as text instead. Nothing here has to change for that: the engine already treats VS Code as a drawing surface, and the pane appears once an extension release draws it.
hooks/register.tsx 1542 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { SharedBoard, TodoBoard, TodoItem, TodoList, TodoStatus } from '../types'
5
6const PANE = 'session-todo'
7const TOOL = 'mcp__session-todo__todo'
8/** The desktop app's own task list, which the app tells the model to keep in place of any other; its calls are mirrored into the main list here. */
9const APP_PLAN_TOOL = 'mcp__ccd_turn__update_plan'
10const COMMAND = 'todo'
11const DEFAULT_LIST = 'main'
12const EMPTY: TodoBoard = { lists: [], nextId: 1 }
13
14const board = atom({ plugin: 'session-todo', key: 'board' } as const, EMPTY)
15const settingsOpen = atom({ plugin: 'session-todo', key: 'settingsOpen' } as const, false)
16const justDone = atom({ plugin: 'session-todo', key: 'justDone' } as const, null)
17const paneAutoOpened = atom({ plugin: 'session-todo', key: 'paneAutoOpened' } as const, false)
18const shared = atom({ plugin: 'session-todo', key: 'shared' } as const, null)
19const bandOpen = atom({ plugin: 'session-todo', key: 'bandOpen' } as const, false)
20const THEME_FIELD = 'theme'
21
22/** How often a session following a shared board reads it back from the store for other sessions' writes. */
23const POLL_MS = 2000
24/** The longest label a session signs a shared board with. */
25const LABEL_MAX = 20
26/** How long a stored board may go without a write before a session start prunes it. */
27const KEEP_MS = 30 * 24 * 60 * 60 * 1000
28/** How long the toast about an item waiting on the person stays; longer than the default, since it is the one thing not to miss. */
29const TOAST_MS = 8000
30
31const STATUSES: readonly TodoStatus[] = ['pending', 'in_progress', 'done', 'blocked']
32
33// The empty box holds a figure space (U+2007), as wide as a digit, so it lines up with [x] where a
34// proportional font would draw a plain space narrower.
35const GLYPH: Record<TodoStatus, string> = {
36 pending: '[ ]',
37 in_progress: '[>]',
38 done: '[x]',
39 blocked: '[!]',
40}
41
42/** Follows the text of an item the agent does itself, so the person's own steps stand out by its absence. */
43const AGENT_MARK = '✱'
44/** Follows the text of an item the person does. */
45const USER_MARK = '♟'
46/** The marks' own colours, muted so they read as badges rather than status: orange for the agent, yellow for the person. */
47const AGENT_MARK_COLOR = '#c97b4a'
48const USER_MARK_COLOR = '#d4b24c'
49
50/** The copy button at the end of each row while the pane holds the keyboard; a press puts the item's text and note on the clipboard. */
51const COPY_MARK = '⧉'
52const COPY_COLOR = '#777777'
53
54const LEGEND = `${GLYPH.pending} pending ${GLYPH.in_progress} in progress ${GLYPH.done} done ${GLYPH.blocked} blocked ${AGENT_MARK} Claude's ${USER_MARK} yours · click a glyph to cycle, ${COPY_MARK} to copy`
55
56/** The speech bubble and the figure under it, drawn at the bottom of the pane on Fridays. */
57const FRIDAY_BUBBLE = ['╭──────────────────────╮', '│ have a nice weekend! │', '╰─┬────────────────────╯']
58const FRIDAY_GUY = [' ╯', ' \\o/🍺', ' |', ' / \\']
59
60const FRIDAY = 5
61
62/** Whether the given moment falls on a Friday where this module runs. */
63function isFriday(epochMs: number): boolean {
64 return new Date(epochMs).getDay() === FRIDAY
65}
66
67/** What a theme paints: the colour of each status, the accents, and the bar's two glyphs. */
68type Theme = {
69 /** Per status: the bar segment and, for in progress and blocked, the item text. Pending and done text keep the surface's colours. */
70 status: Record<TodoStatus, string | undefined>
71 /** The active list's title; undefined keeps the surface's text colour. */
72 title: string | undefined
73 /** The percentage and the `now:` lines. */
74 accent: string | undefined
75 barFill: string
76 barRest: string
77 /** How many glyphs fit where one plain cell would: under 1 for glyphs the desktop draws wider than a cell. */
78 barScale?: number
79}
80
81const THEMES: Record<string, Theme> = {
82 classic: {
83 status: { done: 'green', in_progress: 'yellow', blocked: 'red', pending: undefined },
84 title: undefined,
85 accent: undefined,
86 barFill: '█',
87 barRest: '░',
88 },
89 cyberpunk: {
90 status: { done: '#39ff14', in_progress: '#c77dff', blocked: '#ff2975', pending: '#5a3d7a' },
91 title: '#c77dff',
92 accent: '#39ff14',
93 barFill: '▰',
94 barRest: '▱',
95 barScale: 0.55,
96 },
97 dracula: {
98 status: { done: '#50fa7b', in_progress: '#f1fa8c', blocked: '#ff5555', pending: '#6272a4' },
99 title: '#bd93f9',
100 accent: '#ff79c6',
101 barFill: '█',
102 barRest: '░',
103 },
104 nord: {
105 status: { done: '#a3be8c', in_progress: '#ebcb8b', blocked: '#bf616a', pending: '#4c566a' },
106 title: '#88c0d0',
107 accent: '#81a1c1',
108 barFill: '█',
109 barRest: '░',
110 },
111 solarized: {
112 status: { done: '#859900', in_progress: '#b58900', blocked: '#dc322f', pending: '#586e75' },
113 title: '#268bd2',
114 accent: '#2aa198',
115 barFill: '█',
116 barRest: '░',
117 },
118 gruvbox: {
119 status: { done: '#b8bb26', in_progress: '#fabd2f', blocked: '#fb4934', pending: '#665c54' },
120 title: '#fe8019',
121 accent: '#83a598',
122 barFill: '█',
123 barRest: '░',
124 },
125 monokai: {
126 status: { done: '#a6e22e', in_progress: '#e6db74', blocked: '#f92672', pending: '#75715e' },
127 title: '#ae81ff',
128 accent: '#66d9ef',
129 barFill: '█',
130 barRest: '░',
131 },
132 catppuccin: {
133 status: { done: '#a6e3a1', in_progress: '#f9e2af', blocked: '#f38ba8', pending: '#585b70' },
134 title: '#cba6f7',
135 accent: '#89b4fa',
136 barFill: '█',
137 barRest: '░',
138 },
139 'tokyo-night': {
140 status: { done: '#9ece6a', in_progress: '#e0af68', blocked: '#f7768e', pending: '#565f89' },
141 title: '#bb9af7',
142 accent: '#7aa2f7',
143 barFill: '█',
144 barRest: '░',
145 },
146 'one-dark': {
147 status: { done: '#98c379', in_progress: '#e5c07b', blocked: '#e06c75', pending: '#5c6370' },
148 title: '#c678dd',
149 accent: '#61afef',
150 barFill: '█',
151 barRest: '░',
152 },
153}
154const DEFAULT_THEME = 'classic'
155const THEME_NAMES = Object.keys(THEMES)
156
157function themeName(name: unknown): string {
158 return typeof name === 'string' && THEMES[name] ? name : DEFAULT_THEME
159}
160
161/** The bar's segments left to right: what is finished, what is moving, what is stuck, what is left. */
162const BAR_ORDER: readonly TodoStatus[] = ['done', 'in_progress', 'blocked', 'pending']
163
164type BarSegment = { status: TodoStatus; cells: number }
165
166/** Splits `width` cells between the statuses in proportion, rounding on the running total so the cells always add up. */
167function barSegments(items: readonly TodoItem[], width: number): BarSegment[] {
168 const total = items.length
169 if (total === 0) return [{ status: 'pending', cells: width }]
170 const counts = BAR_ORDER.map(status => ({ status, count: items.filter(item => item.status === status).length }))
171 const present = counts.filter(one => one.count > 0)
172 // Every status that has an item gets at least one cell, so a lone blocked item still shows on a
173 // short bar; the rest of the width is shared in proportion, the largest remainders rounding up.
174 // With more statuses than cells (a bar under four cells) the floor cannot hold and the shares
175 // fall back to plain proportion.
176 const floor = present.length <= width ? 1 : 0
177 const spare = width - floor * present.length
178 const shares = present.map(one => {
179 const exact = (one.count / total) * spare
180 return { status: one.status, cells: floor + Math.floor(exact), remainder: exact - Math.floor(exact) }
181 })
182 let left = width - shares.reduce((sum, one) => sum + one.cells, 0)
183 for (const share of [...shares].sort((a, b) => b.remainder - a.remainder)) {
184 if (left === 0) break
185 share.cells += 1
186 left -= 1
187 }
188 return shares.map(({ status, cells }) => ({ status, cells }))
189}
190
191/** The longest `about` line a list may carry: one short sentence, never a paragraph. */
192const ABOUT_MAX = 80
193
194type TodoToolInput = {
195 action: 'write' | 'add' | 'update' | 'remove' | 'read' | 'clear' | 'drop' | 'focus' | 'describe' | 'join' | 'leave'
196 list?: string
197 title?: string
198 about?: string
199 items?: Array<{ id?: string; text: string; status?: TodoStatus; note?: string; owner?: TodoOwner }>
200 id?: string
201 text?: string
202 status?: TodoStatus
203 note?: string
204 owner?: TodoOwner
205 board?: string
206 label?: string
207}
208
209/** The tool actions that change a board, as opposed to joining or leaving one. */
210type TodoBoardInput = TodoToolInput & { action: Exclude<TodoToolInput['action'], 'join' | 'leave'> }
211
212type TodoOwner = NonNullable<TodoItem['owner']>
213
214const TOOL_DESCRIPTION = [
215 'The todo lists the user watches in the Todo side pane. They are their view of the plan and of your progress, so keep them current without being asked, also when you do every step yourself.',
216 `Where the host has a task list of its own (${APP_PLAN_TOOL}), every call to it is mirrored into the main list here, so that list needs no second write; call this tool for what the host's list cannot say: a second list, an item the person owns, a blocked step with its note, an about line.`,
217 'Lists are named (default "main"); items are addressed by id, unique across lists.',
218 '- write: replace one list with its steps (list, title, items, optional about). Do this before the first edit, command or search of any task that takes more than one tool call or spans more than one turn; only a single edit or a question answered from memory needs no list. The first list written becomes the active one, drawn first; focus switches it.',
219 '- board (with write): a short name for the whole board, letters, digits, _ and -, such as the ticket or the feature (DAN-1234, release-notes). Give it with the first write of a plan: the pane shares the board under that name with one click. Lists are many, so the board\'s name is its own.',
220 `- about (optional, one line of at most ${ABOUT_MAX} characters; a longer one is cut with an ellipsis): one short sentence under the title saying what the list is for or what done looks like, so the user still knows a day later. Not a summary of the items. Set it with write and leave it; describe changes it later.`,
221 '- add / update / remove: one item. Mark the step you begin in_progress (prefer one at a time, several when work really runs in parallel), done the moment it finishes, blocked with a note when it waits on the user.',
222 '- owner: who does the item, "agent" (you; the default) or "user". Mark a step "user" when only the person can take it: approve, decide, click, run something you may not. The pane marks your own items so theirs stand out.',
223 '- read: every list as the pane shows it, with ids. Call it after a context compaction.',
224 '- clear: empty one list (list) or all. drop: remove a list. focus: make a list the active one. describe: set or clear a list\'s about (list, about).',
225 'Use a second list, e.g. "followup", for things to do after the main work (open the PR, report a finding to Jira), so the main list stays focused.',
226 'Keep item text short and imperative, one line each. Before reporting a task finished, leave its list true: every item done, items that fell away removed.',
227 '- join (board, optional label): follow a board shared by another session instead of this session\'s own; leave: back to this session\'s own board. The person usually does this with /todo share and /todo join; call join only when they ask for it.',
228 'On a shared board (the result says so) other sessions write too: add your items with add or write a list of your own, report progress with update, and never write a list you did not create, since write replaces its items.',
229].join('\n')
230
231const TOOL_SCHEMA = {
232 type: 'object',
233 properties: {
234 action: { type: 'string', enum: ['write', 'add', 'update', 'remove', 'read', 'clear', 'drop', 'focus', 'describe', 'join', 'leave'] },
235 board: { type: 'string', description: 'With write: a short name for the whole board (letters, digits, _ and -), the name it is shared under. With join: the shared board to follow.' },
236 label: { type: 'string', description: `What this session signs its changes on the shared board with (join); at most ${LABEL_MAX} characters.` },
237 list: {
238 type: 'string',
239 description: 'The list name (write, add, clear, drop, focus, describe). Defaults to the active list, or "main".',
240 },
241 title: { type: 'string', description: 'A heading for the list (write only); defaults to the name.' },
242 about: {
243 type: 'string',
244 description: `One short line under the title saying what the list is for (write, describe). Optional; at most ${ABOUT_MAX} characters, a longer one is cut. Empty clears it.`,
245 },
246 items: {
247 type: 'array',
248 description: 'The whole list (write only). Reuse an existing id to keep an item in place.',
249 items: {
250 type: 'object',
251 properties: {
252 id: { type: 'string' },
253 text: { type: 'string' },
254 status: { type: 'string', enum: STATUSES },
255 note: { type: 'string' },
256 owner: { type: 'string', enum: ['agent', 'user'] },
257 },
258 required: ['text'],
259 },
260 },
261 id: { type: 'string', description: 'The item (update, remove).' },
262 text: { type: 'string', description: 'The item text (add, update).' },
263 status: { type: 'string', enum: STATUSES, description: 'The new status (add, update).' },
264 note: { type: 'string', description: 'A short note on the item, e.g. why it is blocked (add, update). Empty removes it.' },
265 owner: { type: 'string', enum: ['agent', 'user'], description: 'Who does the item (add, update): agent (default) or user.' },
266 },
267 required: ['action'],
268}
269
270const PROMPT_SECTION = {
271 id: 'session-todo:instructions',
272 scope: 'session',
273 text: [
274 '# Session todo pane',
275 `The person watches a live todo pane driven by the \`${TOOL}\` tool. It is how they follow your progress while you work, also when every step is yours and they take none, so a list is wanted whenever the work is more than a moment's.`,
276 '',
277 '- Before the first edit, command or search of any task that takes more than one tool call, or that spans more than one turn, write the list (action write): the steps as you see them, one short imperative line each. One write is cheap; work the person could not follow is not. Skip it only for a single edit or a question answered from what you already know.',
278 '- Give the board a short name with that first write (board: the ticket or the feature, letters, digits, _ and -). The pane shares the board under it with one click, so other sessions can join the plan.',
279 '- Caught mid-task without a list? Write it now, with the finished steps already marked done.',
280 '- Mark the step you begin in_progress (one at a time; several only when work really runs in parallel), done the moment it finishes, blocked with a note when it waits on the person.',
281 '- Add and remove items as the work changes. Keep follow-ups (open the PR, report to Jira, update docs) in a second list so the main plan stays focused.',
282 '- A list may carry an optional about: one short sentence on what it is for, set when the list is written and then left alone.',
283 '- Before reporting a task finished, leave its list true: every item done, items that fell away removed. A stale list is worse than none.',
284 '- After a context compaction, call read to recover the lists.',
285 `- Where the host has a task list of its own (${APP_PLAN_TOOL}), keep using it: every call to it is mirrored into the main list here. Call the todo tool for what that list cannot say: a second list, an item the person owns, a blocked step with its note, an about line.`,
286 '- A shared board (the person joined one with /todo share or /todo join; every tool result then says so) is written by other sessions too: add your items with add or in a list of your own, report progress with update, and never write a list you did not create, since write replaces its items.',
287 '- When the person changes the board themselves (a click in the pane, a /todo command), a short "session-todo:" note tells you so. It needs no reply; take it into account when it changes your next step, for instance an item of yours they marked done or one they added.',
288 ].join('\n'),
289} as const
290
291/** The tools whose calls are work the person would want to follow: an edit, a file written, a command run. */
292const WORK_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash', 'PowerShell'])
293
294/** The work call of a turn at which an empty board earns a note: one edit needs no list, a second says the task has steps. */
295const NUDGE_AT = 2
296
297const NUDGE = `session-todo: the Todo pane is empty while you edit and run commands. Write the plan now, with the ${TOOL} tool (action write, the finished steps already marked done) or with the host's own task list where it has one, and keep it current as you go.`
298
299/** The work calls of the main loop's current turn, and whether the turn has had its note. */
300let workCalls = 0
301let nudged = false
302
303/** The words a note to the model uses for a status the person set. */
304const STATUS_WORD: Record<TodoStatus, string> = { pending: 'pending again', in_progress: 'in progress', done: 'done', blocked: 'blocked' }
305
306/**
307 * Tells the model what the person just did to the board: a user-role row they do not see typed,
308 * read on the model's next step, so a tick in the pane reaches the agent without a prompt.
309 */
310async function tell($: EngineInterface, what: string): Promise<void> {
311 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: `session-todo: the person ${what}` }] } })
312}
313
314function isValidName(name: string): boolean {
315 return /^[a-z0-9][a-z0-9_-]{0,31}$/i.test(name)
316}
317
318function listNamed(todo: TodoBoard, name: string): TodoList | undefined {
319 return todo.lists.find(list => list.name.toLowerCase() === name.toLowerCase())
320}
321
322function targetList(todo: TodoBoard, name: string | undefined): TodoList | undefined {
323 if (name) return listNamed(todo, name)
324 if (todo.active) return listNamed(todo, todo.active)
325 return todo.lists[0]
326}
327
328function allItems(todo: TodoBoard): TodoItem[] {
329 return todo.lists.flatMap(list => list.items)
330}
331
332/** Every item in the order the pane numbers them: the active list first, then creation order. */
333function drawnItems(todo: TodoBoard): TodoItem[] {
334 return drawn(todo).flatMap(list => list.items)
335}
336
337function itemById(todo: TodoBoard, id: string | undefined): TodoItem | undefined {
338 return id ? allItems(todo).find(item => item.id === id) : undefined
339}
340
341/**
342 * The items the person has to act on now: every blocked one (the agent marks a step blocked when
343 * it waits on them), and their own that are up: in progress, or next when nothing is in progress.
344 */
345function waitingOnYou(todo: TodoBoard): TodoItem[] {
346 const items = drawnItems(todo)
347 const waiting = items.filter(item => item.status === 'blocked' || (item.owner === 'user' && item.status === 'in_progress'))
348 if (!items.some(item => item.status === 'in_progress')) {
349 const next = items.find(item => item.status === 'pending')
350 if (next?.owner === 'user') waiting.push(next)
351 }
352 return waiting
353}
354
355/** Whether a toast names an item that starts waiting on the person; set from the plugin's options on load. */
356let notifies = true
357
358/**
359 * Toasts the person when an item starts waiting on them between two states of the board, once
360 * per item, unless turned off. The band and the pane show the item in their colour either way.
361 */
362function pokeFor($: EngineInterface, before: TodoBoard, after: TodoBoard): void {
363 if (!notifies) return
364 const was = new Set(waitingOnYou(before).map(item => item.id))
365 const fresh = waitingOnYou(after).filter(item => !was.has(item.id))
366 const first = fresh[0]
367 if (!first) return
368 $.ui.toast(`${USER_MARK} needs you: ${first.text}${fresh.length > 1 ? ` (+${fresh.length - 1})` : ''}`, { timeoutMs: TOAST_MS })
369}
370
371/** Lists in the order the pane draws them: the active one first, then creation order. */
372function drawn(todo: TodoBoard): TodoList[] {
373 const active = todo.active ? listNamed(todo, todo.active) : undefined
374 if (!active) return todo.lists
375 return [active, ...todo.lists.filter(list => list !== active)]
376}
377
378function nextStatus(status: TodoStatus): TodoStatus {
379 if (status === 'pending') return 'in_progress'
380 if (status === 'in_progress') return 'done'
381 return 'pending'
382}
383
384function mapItem(todo: TodoBoard, id: string, change: (item: TodoItem) => TodoItem): TodoBoard {
385 return {
386 ...todo,
387 lists: todo.lists.map(list => ({
388 ...list,
389 items: list.items.map(item => (item.id === id ? change(item) : item)),
390 })),
391 }
392}
393
394function render(todo: TodoBoard, following?: SharedBoard | null): string {
395 const lines: string[] = following
396 ? [`Shared board "${following.name}" (this session signs as "${following.label}"): other sessions write here too; add and update, never write over their lists.`]
397 : todo.name
398 ? [`Board "${todo.name}" (shareable under that name)`]
399 : []
400 if (todo.lists.length === 0) return [...lines, 'Todo: no lists'].join('\n')
401 let n = 0
402 for (const list of drawn(todo)) {
403 const done = list.items.filter(item => item.status === 'done').length
404 const marker = list.name === todo.active ? ' (active)' : ''
405 lines.push(`${list.title} [${list.name}]${marker} ${done}/${list.items.length} done`)
406 if (list.about) lines.push(` ${list.about}`)
407 if (list.items.length === 0) lines.push(' (empty)')
408 for (const item of list.items) {
409 n++
410 const glyph = GLYPH[item.status].replace(' ', ' ')
411 const owner = item.owner === 'user' ? ' [yours]' : ''
412 const by = item.by ? ` @${item.by}` : ''
413 lines.push(` ${glyph} ${n}. ${item.text} (${item.id})${owner}${by}${item.note ? ` — ${item.note}` : ''}`)
414 }
415 }
416 return lines.join('\n')
417}
418
419function storeKey(sessionId: string): string {
420 return `board:${sessionId}`
421}
422
423/** Where a session records the shared board it follows, so a resume follows it again. */
424function followKey(sessionId: string): string {
425 return `follow:${sessionId}`
426}
427
428const SHARED_PREFIX = 'shared:'
429
430function sharedKey(name: string): string {
431 return `${SHARED_PREFIX}${name}`
432}
433
434/** The follow record as stored, with a label filled in where an older record has none. */
435function asFollow(value: unknown, sessionId: string): SharedBoard | undefined {
436 const held = value as Partial<SharedBoard> | undefined
437 if (!held || typeof held.name !== 'string' || !isValidName(held.name)) return undefined
438 return { name: held.name, label: labelOf(typeof held.label === 'string' ? held.label : undefined, sessionId) }
439}
440
441function asBoard(value: unknown): TodoBoard | undefined {
442 const held = value as TodoBoard | undefined
443 return held && Array.isArray(held.lists) ? held : undefined
444}
445
446async function loadShared($: EngineInterface, name: string): Promise<TodoBoard | undefined> {
447 return asBoard(await $.store.get(sharedKey(name)))
448}
449
450function stamped(todo: TodoBoard, now: number): TodoBoard {
451 return { ...todo, updatedAt: now }
452}
453
454function ago(ms: number): string {
455 const days = Math.floor(ms / (24 * 60 * 60 * 1000))
456 return days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days} days ago`
457}
458
459const MIRROR_PREFIX = 'board:'
460
461/**
462 * Drops the boards nobody has written for KEEP_MS: other sessions' mirrors (with the shared
463 * board they followed) and shared boards. This session's own mirror and the board it follows
464 * are stamped instead; a board from before the stamps gets one now, so it ages from here.
465 */
466async function prune($: EngineInterface, sessionId: string, followed: string | undefined): Promise<void> {
467 const now = await $.clock.now()
468 const kept = new Set([storeKey(sessionId), ...(followed ? [sharedKey(followed)] : [])])
469 for (const key of await $.store.keys()) {
470 const isMirror = key.startsWith(MIRROR_PREFIX)
471 if (!isMirror && !key.startsWith(SHARED_PREFIX)) continue
472 const held = asBoard(await $.store.get(key))
473 if (!held) continue
474 if (kept.has(key) || held.updatedAt === undefined) {
475 await $.store.set(key, stamped(held, now))
476 continue
477 }
478 if (now - held.updatedAt <= KEEP_MS) continue
479 await $.store.delete(key)
480 if (isMirror) await $.store.delete(followKey(key.slice(MIRROR_PREFIX.length)))
481 }
482}
483
484/** Signs the items this session created or moved on a shared board, so every session sees who did what. */
485function signed(next: TodoBoard, base: TodoBoard, label: string): TodoBoard {
486 const was = new Map(allItems(base).map(item => [item.id, item]))
487 return {
488 ...next,
489 lists: next.lists.map(list => ({
490 ...list,
491 items: list.items.map(item => {
492 const before = was.get(item.id)
493 return before && before.status === item.status ? item : { ...item, by: label }
494 }),
495 })),
496 }
497}
498
499/** The label a session signs a shared board with: the one given, else the start of its id. */
500function labelOf(given: string | undefined, sessionId: string): string {
501 const label = (given ?? '').trim().replace(/\s+/g, ' ')
502 return (label || sessionId.slice(0, 6)).slice(0, LABEL_MAX)
503}
504
505/** `<name> [as <label>]`, as /todo share and /todo join take it. */
506function nameAndLabel(words: string[]): { name: string | undefined; label: string | undefined } {
507 // `as` at the front is the label's keyword too: `/todo share as backend` shares under the board's own name.
508 const at = words.indexOf('as')
509 return { name: at === 0 ? undefined : words[0], label: at >= 0 ? words.slice(at + 1).join(' ') : undefined }
510}
511
512/** The poll of the shared board; a hot reload cancels it, and session.start arms it again. */
513let polling: Timer | undefined
514
515/** Reads the shared board back from the store and redraws when another session changed it. */
516async function pull($: EngineInterface, name: string): Promise<void> {
517 const fresh = await loadShared($, name)
518 if (!fresh) return
519 const held = await read($, board)
520 if (JSON.stringify(fresh) === JSON.stringify(held)) return
521 await update($, board, () => fresh)
522 pokeFor($, held, fresh)
523}
524
525async function follow($: EngineInterface, following: SharedBoard, todo: TodoBoard): Promise<void> {
526 await $.store.set(followKey(await $.session.id()), following)
527 await update($, shared, () => following)
528 await update($, board, () => todo)
529 polling?.cancel()
530 polling = $.clock.every(POLL_MS, () => void pull($, following.name))
531}
532
533/** Back to this session's own board, left as it was when the shared one was joined. */
534async function unfollow($: EngineInterface): Promise<void> {
535 polling?.cancel()
536 polling = undefined
537 const sessionId = await $.session.id()
538 await $.store.delete(followKey(sessionId))
539 await update($, shared, () => null)
540 const own = asBoard(await $.store.get(storeKey(sessionId))) ?? EMPTY
541 await update($, board, () => own)
542}
543
544type Joined = { todo: TodoBoard; following: SharedBoard }
545
546async function joinBoard($: EngineInterface, name: string | undefined, label: string | undefined): Promise<Joined | string> {
547 if (!name || !isValidName(name)) return `board names are letters, digits, _ and -: ${name ?? '(none)'}`
548 const todo = await loadShared($, name)
549 if (!todo) return `no shared board named ${name}; /todo share ${name} creates it from a session's own board`
550 const following = { name, label: labelOf(label, await $.session.id()) }
551 await follow($, following, todo)
552 await openPane($)
553 return { todo, following }
554}
555
556/** Publishes this session's own board, under the given name or the board's own, and follows it. */
557async function shareBoard($: EngineInterface, given: string | undefined, label: string | undefined): Promise<Joined | string> {
558 const current = await read($, shared)
559 if (current) return `this session already follows the shared board ${current.name}; /todo leave first`
560 const own = await read($, board)
561 const name = given ?? own.name
562 if (!name) return 'the board has no name yet: /todo share <name>, or /todo name <name> first'
563 if (!isValidName(name)) return `board names are letters, digits, _ and -: ${name}`
564 if (await loadShared($, name)) return `a shared board named ${name} exists; /todo join ${name} follows it`
565 const todo = stamped({ ...own, name }, await $.clock.now())
566 await $.store.set(sharedKey(name), todo)
567 const following = { name, label: labelOf(label, await $.session.id()) }
568 await follow($, following, todo)
569 await openPane($)
570 return { todo, following }
571}
572
573async function leaveBoard($: EngineInterface): Promise<string> {
574 const following = await read($, shared)
575 if (!following) return 'This session follows no shared board.'
576 await unfollow($)
577 return `Left the shared board ${following.name}; back to this session's own board.`
578}
579
580async function sharedBoards($: EngineInterface): Promise<string> {
581 const keys = (await $.store.keys()).filter(key => key.startsWith(SHARED_PREFIX))
582 if (keys.length === 0) return "No shared boards. /todo share <name> shares this session's board."
583 const following = await read($, shared)
584 const now = await $.clock.now()
585 const lines: string[] = []
586 for (const key of keys) {
587 const name = key.slice(SHARED_PREFIX.length)
588 const held = asBoard(await $.store.get(key)) ?? EMPTY
589 const items = allItems(held)
590 const done = items.filter(item => item.status === 'done').length
591 const changed = held.updatedAt === undefined ? '' : `, last change ${ago(now - held.updatedAt)}`
592 lines.push(`${name}${following?.name === name ? ' (following)' : ''}: ${done}/${items.length} done${changed}`)
593 }
594 return [...lines, `Boards with no change for ${KEEP_MS / (24 * 60 * 60 * 1000)} days are dropped when a session starts; /todo forget <name> drops one now.`].join('\n')
595}
596
597async function forgetBoard($: EngineInterface, name: string | undefined): Promise<string> {
598 if (!name) return 'Usage: /todo forget <name>'
599 if ((await read($, shared))?.name === name) return `This session follows ${name}; /todo leave first.`
600 if (!(await loadShared($, name))) return `No shared board named ${name}.`
601 await $.store.delete(sharedKey(name))
602 return `Forgot the shared board ${name}. A session still following it keeps what it holds and writes it back on its next change.`
603}
604
605async function isPaneShown($: EngineInterface): Promise<boolean> {
606 return (await $.ui.panes()).some(pane => pane.id === PANE && pane.isShown)
607}
608
609async function isPaneFocused($: EngineInterface): Promise<boolean> {
610 return (await $.ui.panes()).some(pane => pane.id === PANE && pane.isFocused)
611}
612
613/** How often the pane's focus is read back, since no event says when a click gives it the keyboard. */
614const FOCUS_POLL_MS = 300
615let focusWatch: Timer | undefined
616let wasFocused = false
617
618/**
619 * Redraws the pane when it gains or loses the keyboard. On the desktop a click on an unfocused
620 * pane only focuses it, so the copy buttons are drawn only while a click would reach them.
621 */
622function watchFocus($: EngineInterface): void {
623 focusWatch?.cancel()
624 focusWatch = $.clock.every(FOCUS_POLL_MS, () => {
625 void isPaneFocused($).then(focused => {
626 if (focused === wasFocused) return
627 wasFocused = focused
628 redraw($)
629 })
630 })
631}
632
633/** The band above the prompt depends on whether the pane is on screen, which no state read tracks. */
634function redraw($: EngineInterface): void {
635 $.ui.invalidate('ui.render')
636}
637
638/** How long the band shows an item that just finished before moving on to the next one. */
639const JUST_DONE_MS = 2000
640
641/**
642 * Applies a change and persists the board: the session's own in its store slot, or the shared
643 * one, re-read from the store first so that what other sessions wrote since the last poll is
644 * kept under the change. Resolves to the change's refusal when it gives one. A change the
645 * person made themselves (a command, a click) never pokes them about what it put up next.
646 */
647async function commit($: EngineInterface, change: (todo: TodoBoard) => TodoBoard | string, byPerson = false): Promise<TodoBoard | string> {
648 const following = await read($, shared)
649 const held = await read($, board)
650 const base = following ? ((await loadShared($, following.name)) ?? held) : held
651 const changed = change(base)
652 if (typeof changed === 'string') return changed
653 if (changed === base) {
654 if (base !== held) await update($, board, () => base)
655 return base
656 }
657 const todo = stamped(following ? signed(changed, base, following.label) : changed, await $.clock.now())
658 await update($, board, () => todo)
659 await $.store.set(following ? sharedKey(following.name) : storeKey(await $.session.id()), todo)
660
661 const before = allItems(held)
662 const finished = allItems(todo).find(item => {
663 const was = before.find(one => one.id === item.id)
664 return was?.status === 'in_progress' && item.status === 'done'
665 })
666 if (finished) {
667 await update($, justDone, () => ({ id: finished.id, text: finished.text }))
668 $.clock.after(JUST_DONE_MS, () => void update($, justDone, held => (held?.id === finished.id ? null : held)))
669 }
670 if (!byPerson) pokeFor($, held, todo)
671 return todo
672}
673
674/**
675 * Writes one of the plugin's options through its own /config row. The row's key carries the
676 * plugin's loaded name, which differs by how it was loaded (`session-todo`, `session-todo@inline`,
677 * `session-todo@<marketplace>`), so the row is found by its field rather than spelled out.
678 * Resolves to the reason when the write did not happen.
679 */
680async function setOption($: EngineInterface, field: string, value: string | boolean): Promise<string | undefined> {
681 // The rows are cached across a hot reload of this plugin, so a field the manifest gained since
682 // the session started is missing from them until the cache is dropped.
683 const isOwn = (key: string) => key === `session-todo.${field}` || /^session-todo@[^.]+\.(.+)$/.exec(key)?.[1] === field
684 let rows = await $.config.list()
685 if (!rows.some(one => isOwn(one.key))) {
686 $.ui.invalidate('config.describe')
687 rows = await $.config.list()
688 }
689 const row = rows.find(one => isOwn(one.key))
690 if (!row) return `no "${field}" row in /config for this plugin (rows: ${rows.length}); a restart of Claude Code lists it`
691 try {
692 const set = await $.config.set({ key: row.key, value })
693 return set.deny
694 } catch (error) {
695 return error instanceof Error ? error.message : String(error)
696 }
697}
698
699function setTheme($: EngineInterface, name: string): Promise<string | undefined> {
700 return setOption($, THEME_FIELD, name)
701}
702
703/** Opens the pane because the person asked: a command, a button on the band. */
704async function openPane($: EngineInterface): Promise<void> {
705 // A pane that is placed but hidden (another pane in front of it) is opened again too.
706 if (!(await isPaneShown($))) await $.ui.open({ id: PANE, title: 'Todo' })
707 await update($, paneAutoOpened, () => true)
708 redraw($)
709}
710
711/**
712 * Opens the pane on the agent's behalf, once per session at most: the first write brings it up,
713 * and after that a pane the person closed stays closed, with the band standing in for it. In the
714 * band-only layout the pane opens only when the person asks for it.
715 */
716async function autoOpenPane($: EngineInterface): Promise<void> {
717 if (layout === 'band') return
718 if (await read($, paneAutoOpened)) return
719 await openPane($)
720}
721
722/** The arguments of the desktop app's task-list tool: a whole plan, or a step change by position. */
723type AppPlanInput = {
724 items?: Array<{ content?: unknown; status?: unknown }>
725 advance?: unknown
726 done?: unknown
727 start?: unknown
728}
729
730const APP_STATUS: Record<string, TodoStatus> = { pending: 'pending', in_progress: 'in_progress', completed: 'done' }
731
732/**
733 * Applies a call of the app's own task list to the main list: a plan given in full replaces the
734 * list, an item keeping its id (and so its owner and note) when the same text is still there;
735 * `done` and `start` name items by their position in that list, and `advance` finishes the step
736 * in progress and starts the next one still pending. Resolves to the board unchanged when the
737 * call changes nothing it can mirror.
738 */
739function applyAppPlan(todo: TodoBoard, input: AppPlanInput): TodoBoard | string {
740 if (Array.isArray(input.items)) {
741 const existing = listNamed(todo, DEFAULT_LIST)
742 const spare = [...(existing?.items ?? [])]
743 const items: NonNullable<TodoToolInput['items']> = []
744 for (const given of input.items) {
745 if (typeof given?.content !== 'string' || !given.content) continue
746 const kept = spare.findIndex(item => item.text === given.content)
747 const id = kept === -1 ? undefined : spare.splice(kept, 1)[0]?.id
748 const status = typeof given.status === 'string' ? APP_STATUS[given.status] : undefined
749 const item: NonNullable<TodoToolInput['items']>[number] = { text: given.content, status: status ?? 'pending' }
750 if (id) item.id = id
751 items.push(item)
752 }
753 const write: TodoBoardInput = { action: 'write', list: DEFAULT_LIST, items }
754 if (!existing) write.title = 'Plan'
755 return applyTool(todo, write)
756 }
757 const list = listNamed(todo, DEFAULT_LIST)
758 if (!list) return todo
759 const at = (position: unknown) => (typeof position === 'number' ? list.items[position - 1] : undefined)
760 let changed = todo
761 const set = (item: TodoItem | undefined, status: TodoStatus) => {
762 if (item && item.status !== status) changed = mapItem(changed, item.id, one => ({ ...one, status }))
763 }
764 if (input.advance === true) {
765 const current = list.items.filter(item => item.status === 'in_progress')
766 for (const item of current) set(item, 'done')
767 const after = current.length > 0 ? Math.max(...current.map(item => list.items.indexOf(item))) + 1 : 0
768 set(list.items.slice(after).find(item => item.status === 'pending') ?? list.items.find(item => item.status === 'pending'), 'in_progress')
769 }
770 if (Array.isArray(input.done)) for (const position of input.done) set(at(position), 'done')
771 set(at(input.start), 'in_progress')
772 return changed
773}
774
775function applyTool(todo: TodoBoard, input: TodoBoardInput): TodoBoard | string {
776 switch (input.action) {
777 case 'read':
778 return todo
779 case 'write': {
780 const name = input.list ?? todo.active ?? DEFAULT_LIST
781 if (!isValidName(name)) return `list names are letters, digits, _ and -: ${name}`
782 if (input.board !== undefined && !isValidName(input.board)) return `board names are letters, digits, _ and -: ${input.board}`
783 const boardName = input.board ?? todo.name
784 const existing = listNamed(todo, name)
785 const others = todo.lists.filter(list => list !== existing)
786 const taken = new Set(others.flatMap(list => list.items.map(item => item.id)))
787 let nextId = todo.nextId
788 const items: TodoItem[] = []
789 for (const given of input.items ?? []) {
790 if (!given.text) return 'every item needs a text'
791 let id = given.id
792 if (!id || taken.has(id)) {
793 do id = `t${nextId++}`
794 while (taken.has(id))
795 }
796 taken.add(id)
797 // An id reused from the list being rewritten keeps that item in place: what the call
798 // leaves out (owner, note, signature) carries over rather than resetting.
799 const kept = existing?.items.find(item => item.id === id)
800 const item: TodoItem = { id, text: given.text, status: given.status ?? 'pending', owner: given.owner ?? kept?.owner ?? 'agent' }
801 const note = given.note ?? kept?.note
802 if (note) item.note = note
803 if (kept?.by) item.by = kept.by
804 items.push(item)
805 }
806 const about = aboutOf(input.about, existing?.about)
807 const list: TodoList = { name: existing?.name ?? name, title: input.title ?? existing?.title ?? name, items }
808 if (about) list.about = about
809 const lists = existing ? todo.lists.map(one => (one === existing ? list : one)) : [...todo.lists, list]
810 const written: TodoBoard = { lists, active: todo.active ?? list.name, nextId }
811 if (boardName) written.name = boardName
812 return written
813 }
814 case 'add': {
815 if (!input.text) return 'add needs a text'
816 let target = targetList(todo, input.list)
817 let lists = todo.lists
818 if (!target) {
819 const name = input.list ?? DEFAULT_LIST
820 if (!isValidName(name)) return `list names are letters, digits, _ and -: ${name}`
821 target = { name, title: name, items: [] }
822 lists = [...lists, target]
823 }
824 // A written list may hold an id of the generated form (t5) that nextId has not passed yet.
825 const taken = new Set(allItems(todo).map(item => item.id))
826 let nextId = todo.nextId
827 let id: string
828 do id = `t${nextId++}`
829 while (taken.has(id))
830 const item: TodoItem = { id, text: input.text, status: input.status ?? 'pending', owner: input.owner ?? 'agent' }
831 if (input.note) item.note = input.note
832 const added = target
833 return {
834 ...todo,
835 lists: lists.map(list => (list === added ? { ...list, items: [...list.items, item] } : list)),
836 active: todo.active ?? added.name,
837 nextId,
838 }
839 }
840 case 'update': {
841 const target = itemById(todo, input.id)
842 if (!target) return `no item with id ${input.id ?? '(none)'}`
843 return mapItem(todo, target.id, item => {
844 const changed: TodoItem = { ...item }
845 if (input.text) changed.text = input.text
846 if (input.status) changed.status = input.status
847 if (input.owner) changed.owner = input.owner
848 if (input.note !== undefined) {
849 if (input.note) changed.note = input.note
850 else delete changed.note
851 }
852 return changed
853 })
854 }
855 case 'remove': {
856 const target = itemById(todo, input.id)
857 if (!target) return `no item with id ${input.id ?? '(none)'}`
858 return {
859 ...todo,
860 lists: todo.lists.map(list => ({ ...list, items: list.items.filter(item => item !== target) })),
861 }
862 }
863 case 'clear': {
864 if (!input.list) return { ...todo, lists: todo.lists.map(list => ({ ...list, items: [] })) }
865 const target = listNamed(todo, input.list)
866 if (!target) return `no list named ${input.list}`
867 return { ...todo, lists: todo.lists.map(list => (list === target ? { ...list, items: [] } : list)) }
868 }
869 case 'drop': {
870 const target = input.list ? listNamed(todo, input.list) : undefined
871 if (!target) return `no list named ${input.list ?? '(none)'}`
872 const lists = todo.lists.filter(list => list !== target)
873 return { ...todo, lists, active: todo.active === target.name ? lists[0]?.name : todo.active }
874 }
875 case 'focus': {
876 const target = input.list ? listNamed(todo, input.list) : undefined
877 if (!target) return `no list named ${input.list ?? '(none)'}`
878 return { ...todo, active: target.name }
879 }
880 case 'describe': {
881 const target = targetList(todo, input.list)
882 if (!target) return `no list named ${input.list ?? '(none)'}`
883 const about = aboutOf(input.about, undefined)
884 return {
885 ...todo,
886 lists: todo.lists.map(list => {
887 if (list !== target) return list
888 const changed: TodoList = { ...list }
889 if (about) changed.about = about
890 else delete changed.about
891 return changed
892 }),
893 }
894 }
895 default:
896 return `unknown action ${String((input as { action?: unknown }).action)}`
897 }
898}
899
900/** The `about` a call leaves on a list: the given one trimmed, or the current one when none is given. */
901function aboutOf(given: string | undefined, current: string | undefined): string | undefined {
902 if (given === undefined) return current
903 return given.trim().replace(/\s+/g, ' ') || undefined
904}
905
906/**
907 * Cuts an `about` past the cap at a word boundary, with an ellipsis, and says so: the field is
908 * optional, so a long one must never fail the call that carries it.
909 */
910function fitAbout(about: string | undefined): { about: string | undefined; note?: string } {
911 if (about === undefined) return { about }
912 const whole = about.trim().replace(/\s+/g, ' ')
913 if (whole.length <= ABOUT_MAX) return { about: whole }
914 const room = whole.slice(0, ABOUT_MAX - 1)
915 const atWord = room.lastIndexOf(' ')
916 const cut = `${(atWord > ABOUT_MAX / 2 ? room.slice(0, atWord) : room).trimEnd()}…`
917 return { about: cut, note: `about was ${whole.length} characters and is cut to ${ABOUT_MAX}: "${cut}"` }
918}
919
920/** An item's number in the pane: counted across lists in drawn order, as the rows and the band show it. */
921function numberOf(todo: TodoBoard, item: TodoItem): number {
922 return drawn(todo).flatMap(list => list.items).findIndex(one => one.id === item.id) + 1
923}
924
925/** An item by its number in the pane (counted across lists in drawn order) or by id. */
926function byNumber(todo: TodoBoard, arg: string): TodoItem | undefined {
927 const items = drawnItems(todo)
928 const n = /^[0-9]+$/.test(arg) ? Number(arg) : Number.NaN
929 if (Number.isInteger(n) && n >= 1 && n <= items.length) return items[n - 1]
930 return items.find(item => item.id === arg)
931}
932
933/**
934 * What shows where: `auto` (the band while the pane is closed; the pane opens on its own at the
935 * first items), `both` (the band always, the pane as in auto), `band` (the band always, the pane
936 * only when asked for), `pane` (no band, the pane as in auto).
937 */
938type Layout = 'auto' | 'both' | 'band' | 'pane'
939const LAYOUTS: readonly Layout[] = ['auto', 'both', 'band', 'pane']
940const LAYOUT_LABELS: Record<Layout, string> = { auto: 'auto', both: 'band and pane', band: 'band only', pane: 'pane only' }
941/** The band setting the layout replaced: its modes, and the switch it was before that, map onto layouts. */
942const OLD_BAND: Record<string, Layout> = { off: 'pane', closed: 'auto', always: 'both' }
943
944function layoutOf(value: unknown, oldBand?: unknown): Layout {
945 if (typeof value === 'string' && (LAYOUTS as readonly string[]).includes(value)) return value as Layout
946 if (oldBand === false) return 'pane'
947 if (typeof oldBand === 'string' && oldBand in OLD_BAND) return OLD_BAND[oldBand] as Layout
948 return 'auto'
949}
950
951/** The layout in force; set from the plugin's options on load. */
952let layout: Layout = 'auto'
953
954type BoardElements = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
955/** `canCopy`: whether to draw the copy button on each row; only while the site holds the keyboard, since a click on an unfocused pane only focuses it. */
956type BoardDrawing = { theme: Theme; isCompact: boolean; bodyColumns: number; canCopy: boolean }
957
958/**
959 * The lists with their items, and the block under them (the items needing the person, the ones
960 * in progress), as both the pane and the unfolded band draw them. A glyph click cycles the item.
961 */
962function drawBoard($: EngineInterface, ui: BoardElements, todo: TodoBoard, { theme, isCompact, bodyColumns, canCopy }: BoardDrawing) {
963 const { Box, Text, Button } = ui
964 const lists = drawn(todo)
965 const current = lists.flatMap(list => list.items).filter(item => item.status === 'in_progress')
966 const waiting = waitingOnYou(todo)
967 // The bar sits in the title row, so it stays short: a sixth of the width, between 8 and 18 cells.
968 const barWidth = Math.max(4, Math.round(Math.min(18, Math.max(8, Math.round(bodyColumns / 6))) * (theme.barScale ?? 1)))
969 const toggle = (item: TodoItem) => () => {
970 const status = nextStatus(item.status)
971 void commit($, todo => mapItem(todo, item.id, one => ({ ...one, status })), true).then(outcome => {
972 if (typeof outcome !== 'string') void tell($, `marked "${item.text}" (${item.id}) ${STATUS_WORD[status]} in the pane.`)
973 })
974 }
975
976 let n = 0
977 return [
978 ...(lists.length === 0
979 ? [
980 <Text key="empty" dimColor wrap="wrap">
981 Nothing planned yet. The agent fills this in as work is planned; /todo add adds your own.
982 </Text>,
983 ]
984 : []),
985 ...lists.map((list, index) => {
986 const done = list.items.filter(item => item.status === 'done').length
987 return (
988 <Box key={`list:${list.name}`} flexDirection="column" marginTop={index === 0 ? 0 : 1}>
989 <Box flexDirection="row" justifyContent="space-between" gap={2}>
990 <Text bold color={theme.title} wrap="wrap">
991 {list.title}
992 </Text>
993 <Box flexDirection="row" gap={1} flexShrink={0}>
994 <Box flexDirection="row">
995 {barSegments(list.items, barWidth)
996 .filter(segment => segment.cells > 0)
997 .map(segment => (
998 <Text
999 key={`bar:${list.name}:${segment.status}`}
1000 color={theme.status[segment.status]}
1001 dimColor={segment.status === 'pending' && !theme.status.pending}
1002 >
1003 {(segment.status === 'pending' ? theme.barRest : theme.barFill).repeat(segment.cells)}
1004 </Text>
1005 ))}
1006 </Box>
1007 <Text bold={done === list.items.length && done > 0} dimColor={done !== list.items.length && !theme.accent} color={theme.accent}>
1008 {list.items.length === 0 ? 'empty' : `${done}/${list.items.length}`}
1009 </Text>
1010 </Box>
1011 </Box>
1012 <Box marginBottom={list.items.length === 0 ? 0 : 1}>
1013 {list.about && (
1014 <Text dimColor italic wrap="wrap">
1015 {list.about}
1016 </Text>
1017 )}
1018 </Box>
1019 {list.items.map((item, index) => {
1020 n++
1021 return (
1022 <Box key={`row:${item.id}`} flexDirection="column" marginTop={index === 0 || isCompact ? 0 : 1}>
1023 <Box flexDirection="row" gap={1}>
1024 <Button plain key={`toggle:${item.id}`} label={GLYPH[item.status]} dimColor={item.status === 'done'} onPress={toggle(item)} />
1025 <Text
1026 wrap="wrap"
1027 bold={item.status === 'in_progress'}
1028 dimColor={item.status === 'done'}
1029 strikethrough={item.status === 'done'}
1030 color={item.status === 'done' || item.status === 'pending' ? undefined : theme.status[item.status]}
1031 >
1032 {`${n}. ${item.text}`}
1033 </Text>
1034 <Text color={item.owner === 'user' ? USER_MARK_COLOR : AGENT_MARK_COLOR} dimColor={item.status === 'done'}>
1035 {item.owner === 'user' ? USER_MARK : AGENT_MARK}
1036 </Text>
1037 {item.by && <Text dimColor>{`@${item.by}`}</Text>}
1038 {canCopy && (
1039 <Button
1040 plain
1041 key={`copy:${item.id}`}
1042 onPress={press => {
1043 const text = item.note ? `${item.text}\r\n${item.note}` : item.text
1044 void $.ui
1045 .copy({ text, surface: press.surface })
1046 .then(copied => $.ui.toast(copied.isCopied ? 'Copied to clipboard' : `Could not copy: ${copied.reason}`))
1047 }}
1048 >
1049 <Text color={COPY_COLOR}>{COPY_MARK}</Text>
1050 </Button>
1051 )}
1052 </Box>
1053 {item.note && (
1054 <Box paddingLeft={4}>
1055 <Text dimColor wrap="wrap">
1056 {item.note}
1057 </Text>
1058 </Box>
1059 )}
1060 </Box>
1061 )
1062 })}
1063 </Box>
1064 )
1065 }),
1066 ...(waiting.length > 0 || current.length > 0
1067 ? [
1068 <Box key="now" flexDirection="column" marginTop={1}>
1069 {waiting.map(item => (
1070 <Text key={`you:${item.id}`} bold color={USER_MARK_COLOR} wrap="wrap">
1071 {`${USER_MARK} needs you: ${item.text}${item.note ? ` — ${item.note}` : ''}`}
1072 </Text>
1073 ))}
1074 {current
1075 .filter(item => !waiting.includes(item))
1076 .map(item => (
1077 <Text key={`now:${item.id}`} dimColor={!theme.accent} color={theme.accent} wrap="wrap">
1078 {`now: ${item.text}`}
1079 </Text>
1080 ))}
1081 </Box>,
1082 ]
1083 : []),
1084 ]
1085}
1086
1087const USAGE = `Usage: /todo [add [@list] <text> | start <n> | done <n> | remove <n> | about <list> [text] | clear [list] | drop <list> | focus <list> | name <name> | share [name] [as <label>] | join <name> [as <label>] | leave | boards | forget <name> | theme <${THEME_NAMES.join('|')}> | layout [${LAYOUTS.join('|')}] | compact [on|off] | notify [on|off]]`
1088
1089export const register: Register = (on, options) => {
1090 const themeKey = themeName(options.theme)
1091 const isCompact = options.compact === true
1092 layout = layoutOf(options.layout, (options as Record<string, unknown>).band)
1093 notifies = options.notify !== false
1094 const theme = THEMES[themeKey] as Theme
1095
1096 on('session.start', async ($, e, next) => {
1097 await $.tool.register({
1098 name: 'todo',
1099 description: TOOL_DESCRIPTION,
1100 inputSchema: TOOL_SCHEMA,
1101 isDeferred: false,
1102 })
1103 await $.command.register({
1104 name: COMMAND,
1105 description: 'The session todo pane: /todo, add [@list] <text>, start <n>, done <n>, remove <n>, about <list> [text], clear [list], drop <list>, focus <list>, name <name>, share [name], join <name>, leave, boards, forget <name>, theme <name>, layout [auto|both|band|pane], compact [on|off], notify [on|off]',
1106 argumentHint: '[add [@list] <text> | start <n> | done <n> | remove <n> | about <list> [text] | clear [list] | drop <list> | focus <list> | name <name> | share [name] [as <label>] | join <name> [as <label>] | leave | boards | forget <name> | theme <name> | layout [auto|both|band|pane] | compact [on|off] | notify [on|off]]',
1107 })
1108
1109 const sessionId = await $.session.id()
1110 const following = asFollow(await $.store.get(followKey(sessionId)), sessionId)
1111 const saved = following ? await loadShared($, following.name) : asBoard(await $.store.get(storeKey(sessionId)))
1112 if (following) await follow($, following, saved ?? EMPTY)
1113 else if (saved) await update($, board, () => saved)
1114 await prune($, sessionId, following?.name)
1115 watchFocus($)
1116
1117 // The pane opens on its own only when there is something to show: a restored board with
1118 // items. Otherwise the first write (the agent's or /todo add) opens it.
1119 if (saved && allItems(saved).length > 0) void autoOpenPane($)
1120 return next(e)
1121 })
1122
1123 on('session.end', async ($, e, next) => {
1124 // /clear empties this session's board and never a shared one: the session leaves it instead.
1125 if (e.reason === 'clear') {
1126 if (await read($, shared)) await unfollow($)
1127 await update($, board, () => EMPTY)
1128 // The mirror goes too, so a session.start under the same id does not bring the board back.
1129 await $.store.delete(storeKey(await $.session.id()))
1130 }
1131 return next(e)
1132 })
1133
1134 on('ui.close', { id: PANE }, async ($, e, next) => {
1135 const closed = await next(e)
1136 if (e.origin.kind !== 'unload') redraw($)
1137 return closed
1138 })
1139
1140 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1141 if (layout === 'pane' || e.props.hasSurvey) return next(e)
1142 const todo = await read($, board)
1143 const items = drawnItems(todo)
1144 if (items.length === 0 || (layout === 'auto' && (await isPaneShown($)))) return next(e)
1145
1146 const { Box, Text, Button } = $.ui.resolve(e)
1147 const done = items.filter(item => item.status === 'done').length
1148 const current = items.filter(item => item.status === 'in_progress')
1149 // With nothing in progress the band names the next pending item, so a freshly added item
1150 // shows up at once; with nothing pending either, it says so.
1151 const upcoming = current.length === 0 ? items.find(item => item.status === 'pending') : undefined
1152 // Every item is named with its number in the pane, so `/todo done <n>` needs no lookup.
1153 const named = (item: TodoItem) => `${numberOf(todo, item)}. ${item.text}`
1154 const now =
1155 current[0]
1156 ? `TODO: ${named(current[0])}${current.length > 1 ? ` (+${current.length - 1})` : ''}`
1157 : upcoming
1158 ? `TODO: ${named(upcoming)}`
1159 : 'TODO: nothing left'
1160
1161 const isIdle = current.length === 0 && upcoming === undefined
1162 // An item that just went from in progress to done holds the band for a moment, ticked, before
1163 // the next item takes its place.
1164 const finished = await read($, justDone)
1165 // Otherwise an item waiting on the person takes the band over everything else, in their colour.
1166 const waiting = waitingOnYou(todo)
1167 const you = finished ? undefined : waiting[0]
1168 const glyph = finished ? GLYPH.done : you ? GLYPH[you.status] : current.length > 0 ? GLYPH.in_progress : GLYPH.pending
1169 const glyphColor = finished
1170 ? theme.status.done
1171 : you
1172 ? you.status === 'pending'
1173 ? undefined
1174 : theme.status[you.status]
1175 : current.length > 0
1176 ? theme.status.in_progress
1177 : undefined
1178 const finishedItem = finished ? itemById(todo, finished.id) : undefined
1179 const label = finished
1180 ? `DONE: ${finishedItem ? named(finishedItem) : finished.text}`
1181 : you
1182 ? `${named(you)}${waiting.length > 1 ? ` (+${waiting.length - 1})` : ''}`
1183 : now
1184 // The ▸ unfolds the whole board under the row, as the pane draws it; the engine scrolls a
1185 // tall one in its window. The fold is remembered for the session.
1186 const isOpen = await read($, bandOpen)
1187 const fold = () => void update($, bandOpen, open => !open)
1188 // The glyph is the shown item's own toggle, as in the pane: a click cycles its status.
1189 const shown = finishedItem ?? you ?? current[0] ?? upcoming
1190 const cycle = (item: TodoItem) => () => {
1191 const status = nextStatus(item.status)
1192 void commit($, todo => mapItem(todo, item.id, one => ({ ...one, status })), true).then(outcome => {
1193 if (typeof outcome !== 'string') void tell($, `marked "${item.text}" (${item.id}) ${STATUS_WORD[status]} on the band.`)
1194 })
1195 }
1196 return (
1197 <Box flexDirection="column">
1198 <Box flexDirection="row" justifyContent="space-between" gap={2}>
1199 <Box flexDirection="row" gap={1} minWidth={0} flexShrink={1} overflow="hidden">
1200 {/* The desktop draws a button's text in its own style, so the coloured moments (thetypes/index.d.ts 61 lines1export type TodoStatus = 'pending' | 'in_progress' | 'done' | 'blocked'
2
3export type TodoItem = {
4 /** Unique across every list, so an item is addressed by id alone. */
5 id: string
6 text: string
7 status: TodoStatus
8 /** A short note on why it is blocked, or what was decided. */
9 note?: string
10 /** Who does it: the agent (the default for items it writes) or the person (items they add, or steps only they can take). */
11 owner?: 'agent' | 'user'
12 /** On a shared board: the label of the session that created the item or last changed its status. */
13 by?: string
14}
15
16/** A board several sessions read and write through the plugin store, and what this session signs its changes with. */
17export type SharedBoard = {
18 name: string
19 label: string
20}
21
22export type TodoList = {
23 /** What the tool and /todo address the list by. */
24 name: string
25 title: string
26 /** One short line under the title saying what the list is for; optional, at most ABOUT_MAX characters. */
27 about?: string
28 items: TodoItem[]
29}
30
31export type TodoBoard = {
32 /** A short name for the whole board, given by the agent with the plan; the shared board's name when the person shares it. */
33 name?: string
34 /** In creation order; the active list is drawn first whatever its position. */
35 lists: TodoList[]
36 /** The name of the list the agent is working in, drawn first with a bold title. */
37 active?: string
38 /** Feeds the next item id, so ids stay unique after removals. */
39 nextId: number
40 /** When the board was last written to the store, in epoch milliseconds; a board untouched for long is pruned. */
41 updatedAt?: number
42}
43
44declare module 'claude-code' {
45 interface PluginState {
46 'session-todo': {
47 board: TodoBoard
48 /** Whether the pane's settings row (the theme selector) is unfolded. */
49 settingsOpen: boolean
50 /** The item that just went from in progress to done, shown on the band for a moment; null otherwise. */
51 justDone: { id: string; text: string } | null
52 /** Whether the pane has already opened on its own this session; it does so once at most. */
53 paneAutoOpened: boolean
54 /** The shared board this session follows instead of its own, or null. */
55 shared: SharedBoard | null
56 /** Whether the band above the prompt is unfolded to show the whole board under its row. */
57 bandOpen: boolean
58 }
59 }
60}
61