A pane over the session's task list that both the person and Claude edit

hooks/register.tsx 488 lines1import { atom, read, update } from 'claude-code'
2import type { BuiltinToolInputs, EngineInterface, Register } from 'claude-code'
3
4import type { Draft, FieldEdit, NewTask, Task, TaskEdit, TaskStatus } from '../types'
5
6const PANE = 'task-board'
7const tasks = atom({ plugin: 'task-board', key: 'tasks' } as const, [])
8const draft = atom({ plugin: 'task-board', key: 'draft' } as const, { edits: {}, added: [] })
9const editing = atom({ plugin: 'task-board', key: 'editing' } as const, null)
10const focusedKey = atom({ plugin: 'task-board', key: 'focusedKey' } as const, null)
11
12const statusMark: Record<TaskStatus, string> = {
13 pending: '[ ]',
14 in_progress: '[~]',
15 completed: '[x]',
16}
17
18const statusAfter: Record<TaskStatus, TaskStatus> = {
19 pending: 'in_progress',
20 in_progress: 'completed',
21 completed: 'pending',
22}
23
24type BoardRow = {
25 source: { kind: 'saved'; id: string } | { kind: 'new'; draftId: string }
26 key: string
27 label: string
28 subject: string
29 description: string
30 status: TaskStatus
31 blockedBy: string[]
32 isEdited: boolean
33}
34
35const composeRows = (saved: Task[], pending: Draft): BoardRow[] => [
36 ...saved.flatMap(task => {
37 const edit = pending.edits[task.id]
38 const status = edit?.status ?? task.status
39 if (status === 'deleted') {
40 return []
41 }
42
43 return [
44 {
45 source: { kind: 'saved', id: task.id } as const,
46 key: task.id,
47 label: `#${task.id}`,
48 subject: edit?.subject ?? task.subject,
49 description: edit?.description ?? task.description,
50 status,
51 blockedBy: task.blockedBy,
52 isEdited: edit !== undefined,
53 },
54 ]
55 }),
56 ...pending.added.map(added => ({
57 source: { kind: 'new', draftId: added.draftId } as const,
58 key: added.draftId,
59 label: 'new',
60 subject: added.subject,
61 description: added.description,
62 status: added.status,
63 blockedBy: [],
64 isEdited: true,
65 })),
66]
67
68const editRow = (pending: Draft, row: BoardRow, change: TaskEdit): Draft => {
69 const { source } = row
70 const { subject, description, status } = change
71 switch (source.kind) {
72 case 'saved':
73 return {
74 ...pending,
75 edits: { ...pending.edits, [source.id]: { ...pending.edits[source.id], ...change } },
76 }
77 case 'new':
78 return {
79 ...pending,
80 added:
81 status === 'deleted'
82 ? pending.added.filter(added => added.draftId !== source.draftId)
83 : pending.added.map(added =>
84 added.draftId === source.draftId
85 ? {
86 ...added,
87 subject: subject ?? added.subject,
88 description: description ?? added.description,
89 status: status ?? added.status,
90 }
91 : added,
92 ),
93 }
94 default: {
95 const unknown: never = source
96 throw new Error(`Unknown board row source: ${JSON.stringify(unknown)}`)
97 }
98 }
99}
100
101// TaskList leaves out description, activeForm, blocks and metadata, so the board reads the task files Claude Code writes.
102const syncTasks = async ($: EngineInterface) => {
103 const listId = (await $.env.get('CLAUDE_CODE_TASK_LIST_ID')) ?? (await $.session.id())
104 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
105 const configDir =
106 (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home === undefined ? undefined : `${home}/.claude`)
107 if (configDir === undefined) {
108 throw new Error('No CLAUDE_CONFIG_DIR, HOME or USERPROFILE to find the task list under')
109 }
110
111 const folder = `${configDir}/tasks/${listId}`
112 const entries = (await $.fs.exists(folder)) ? await $.fs.list(folder) : []
113 const saved: Task[] = await Promise.all(
114 entries
115 .filter(entry => entry.kind === 'file' && entry.name.endsWith('.json'))
116 .map(async entry => JSON.parse(await $.fs.read(`${folder}/${entry.name}`))),
117 )
118 await update($, tasks, () => saved.toSorted((a, b) => Number(a.id) - Number(b.id)))
119}
120
121const updateTask = async ($: EngineInterface, change: BuiltinToolInputs['TaskUpdate']) => {
122 const updated = await $.tool.call({ tool: 'TaskUpdate', ...change })
123 if (updated.deny !== undefined) {
124 $.ui.toast(`Task change refused: ${updated.deny}`)
125 } else if (updated.isError) {
126 $.ui.toast(`Task change failed: ${updated.text}`)
127 } else if (!updated.result.success) {
128 $.ui.toast(`Task change failed: ${updated.result.error ?? 'no reason given'}`)
129 }
130}
131
132const createTask = async ($: EngineInterface, added: NewTask) => {
133 const created = await $.tool.call({
134 tool: 'TaskCreate',
135 subject: added.subject,
136 description: added.description,
137 })
138 if (created.deny !== undefined) {
139 $.ui.toast(`Task add refused: ${created.deny}`)
140 } else if (created.isError) {
141 $.ui.toast(`Task add failed: ${created.text}`)
142 } else if (added.status !== 'pending') {
143 await updateTask($, { taskId: created.result.task.id, status: added.status })
144 }
145}
146
147// The pane's own tool calls skip this plugin's tool.call hook, so saving syncs the board itself.
148const saveDraft = async ($: EngineInterface) => {
149 const pending = await read($, draft)
150 for (const [taskId, edit] of Object.entries(pending.edits)) {
151 await updateTask($, { taskId, ...edit })
152 }
153 for (const added of pending.added) {
154 await createTask($, added)
155 }
156 await update($, draft, () => ({ edits: {}, added: [] }))
157 await syncTasks($)
158}
159
160const resetBoard = async ($: EngineInterface) => {
161 await update($, draft, () => ({ edits: {}, added: [] }))
162 await update($, editing, () => null)
163 await update($, focusedKey, () => null)
164}
165
166const editField = async ($: EngineInterface, target: FieldEdit) => {
167 await update($, editing, () => target)
168 await $.ui.focus({ requestId: PANE, key: `${target.field}-${target.key}` })
169}
170
171// The pane's own $.ui.close skips this plugin's ui.close hook, so its buttons discard here.
172const closeBoard = async ($: EngineInterface) => {
173 await resetBoard($)
174 await $.ui.close({ id: PANE })
175}
176
177export const register: Register = on => {
178 on('session.start', async ($, e, next) => {
179 await $.command.register({
180 name: 'task-board',
181 description: 'Show the task list in a pane you and Claude both edit',
182 immediate: true,
183 })
184
185 return next(e)
186 })
187
188 on('command.run', { command: 'task-board' }, async $ => {
189 await syncTasks($)
190 await $.ui.open({ id: PANE, title: 'Tasks', focus: true })
191
192 return {}
193 })
194
195 // Claude's task changes pass here and redraw the board.
196 on('tool.call', { tool: ['TaskCreate', 'TaskUpdate'] }, async ($, e, next) => {
197 const ran = await next(e)
198 await syncTasks($)
199
200 return ran
201 }).catch(($, e, next) => next(e))
202
203 // Closing the pane with Ctrl+X X or Esc discards what was not saved.
204 on('ui.close', { id: PANE }, async ($, e, next) => {
205 await resetBoard($)
206
207 return next(e)
208 }).catch(($, e, next) => next(e))
209
210 // The hotkey buttons join the ring like any Button, so the ring wraps past them.
211 on('ui.focus', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
212 const element = e.element === 'edit' ? 'new' : e.element === 'delete' ? 'close' : e.element
213 const moved = await next({ ...e, element })
214 if (moved.deny === undefined) {
215 await update($, focusedKey, () => element ?? null)
216 }
217
218 return moved
219 }).catch(($, e, next) => next(e))
220
221 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
222 if (e.surface === 'mobile') {
223 const { Text } = $.ui.resolve(e)
224
225 return <Text dimColor>The task board needs a surface with text input.</Text>
226 }
227
228 const { Box, Button, Input, Text } = $.ui.resolve(e)
229 const pending = await read($, draft)
230 const rows = composeRows(await read($, tasks), pending)
231 // While the prompt has the keyboard the board is a dimmed, read-only list.
232 const isActive = e.props.isFocused
233 const fieldEdit = isActive ? await read($, editing) : null
234 const subjectKey = fieldEdit?.field === 'subject' ? fieldEdit.key : null
235 const describedRow =
236 fieldEdit?.field === 'description' ? rows.find(row => row.key === fieldEdit.key) : undefined
237 const focused = isActive ? await read($, focusedKey) : null
238 const focusedRow = rows.find(row => `task-${row.key}` === focused)
239 const doneCount = rows.filter(row => row.status === 'completed').length
240 const unsavedCount = Object.keys(pending.edits).length + pending.added.length
241 const labelWidth = Math.max(3, ...rows.map(row => row.label.length))
242
243 return (
244 <Box flexDirection="column" paddingX={1}>
245 <Box columnGap={2} marginBottom={1}>
246 <Text bold dimColor={!isActive}>
247 Tasks
248 </Text>
249 <Text dimColor>
250 {rows.length - doneCount} open · {doneCount} done
251 </Text>
252 {unsavedCount > 0 && (
253 <Text color="warning" dimColor={!isActive}>
254 {unsavedCount} unsaved
255 </Text>
256 )}
257 </Box>
258 {/* Above the list, so a new row does not shift the focus ring off this field. */}
259 {isActive && (
260 <Box marginBottom={1}>
261 <Input
262 key="new"
263 label="+ "
264 placeholder="New task"
265 value=""
266 autoFocus={fieldEdit === null ? true : undefined}
267 submitLabel="add"
268 onSubmit={async subject => {
269 if (subject.trim() !== '') {
270 const added: NewTask = {
271 draftId: `new-${crypto.randomUUID()}`,
272 subject: subject.trim(),
273 description: '',
274 status: 'pending',
275 }
276 await update($, draft, current => ({
277 ...current,
278 added: [...current.added, added],
279 }))
280 }
281 }}
282 />
283 </Box>
284 )}
285 {rows.length === 0 && <Text dimColor>No tasks yet.</Text>}
286 {rows.map(row =>
287 isActive && row.key !== subjectKey ? (
288 <Button
289 key={`task-${row.key}`}
290 plain
291 onPress={() =>
292 update($, draft, current =>
293 editRow(current, row, { status: statusAfter[row.status] }),
294 )
295 }
296 >
297 <Text dimColor>{`${statusMark[row.status]} ${row.label.padEnd(labelWidth)} `}</Text>
298 <Text
299 bold={row.status === 'in_progress'}
300 italic={row.isEdited}
301 dimColor={row.status === 'completed'}
302 strikethrough={row.status === 'completed'}
303 >
304 {row.subject}
305 </Text>
306 {row.blockedBy.length > 0 && (
307 <Text color="warning">
308 {` blocked by ${row.blockedBy.map(id => `#${id}`).join(', ')}`}
309 </Text>
310 )}
311 </Button>
312 ) : (
313 <Box key={`row-${row.key}`} columnGap={1}>
314 <Text dimColor>{statusMark[row.status]}</Text>
315 <Box width={labelWidth} flexShrink={0}>
316 <Text dimColor>{row.label}</Text>
317 </Box>
318 {row.key === subjectKey ? (
319 <>
320 <Box flexGrow={1} flexShrink={1} minWidth={0}>
321 <Input
322 key={`subject-${row.key}`}
323 value={row.subject}
324 autoFocus
325 submitLabel="keep"
326 onSubmit={async subject => {
327 await update($, draft, current => editRow(current, row, { subject }))
328 await update($, editing, () => null)
329 }}
330 />
331 </Box>
332 <Box flexShrink={0} marginLeft={2}>
333 <Button
334 key={`cancel-${row.key}`}
335 plain
336 dimColor
337 label="cancel"
338 onPress={() => update($, editing, () => null)}
339 />
340 </Box>
341 </>
342 ) : (
343 <Text dimColor strikethrough={row.status === 'completed'}>
344 {row.subject}
345 {row.blockedBy.length > 0 &&
346 ` blocked by ${row.blockedBy.map(id => `#${id}`).join(', ')}`}
347 </Text>
348 )}
349 </Box>
350 ),
351 )}
352 {/* Below the list, since a description can run to a paragraph. */}
353 {describedRow !== undefined ? (
354 <Box marginTop={1}>
355 <Box flexGrow={1} flexShrink={1} minWidth={0}>
356 <Input
357 key={`description-${describedRow.key}`}
358 label={`${describedRow.label} `}
359 placeholder="Description"
360 value={describedRow.description}
361 autoFocus
362 submitLabel="keep"
363 onSubmit={async description => {
364 await update($, draft, current => editRow(current, describedRow, { description }))
365 await update($, editing, () => null)
366 }}
367 />
368 </Box>
369 <Box flexShrink={0} marginLeft={2}>
370 <Button
371 key={`cancel-${describedRow.key}`}
372 plain
373 dimColor
374 label="cancel"
375 onPress={() => update($, editing, () => null)}
376 />
377 </Box>
378 </Box>
379 ) : (
380 focusedRow !== undefined &&
381 focusedRow.description !== '' && (
382 <Box marginTop={1}>
383 <Text dimColor>{focusedRow.description}</Text>
384 </Box>
385 )
386 )}
387 {!isActive && (
388 <Box marginTop={1}>
389 <Text dimColor>Ctrl+X Tab to edit</Text>
390 </Box>
391 )}
392 {isActive && (
393 <>
394 <Box marginTop={1} flexDirection="column" alignItems="flex-start">
395 <Button
396 key="save"
397 variant="primary"
398 label="save"
399 onPress={async () => {
400 await saveDraft($)
401 await closeBoard($)
402 }}
403 />
404 <Button
405 key="fill"
406 label="prompt"
407 dimColor={rows.length === 0}
408 onPress={async () => {
409 await saveDraft($)
410 const saved = await read($, tasks)
411 await closeBoard($)
412 if (saved.length === 0) {
413 $.ui.toast('No tasks to put in the prompt.')
414 return
415 }
416 const filled = await $.prompt.fill({
417 mode: 'insert',
418 text: [
419 'User updated tasks:',
420 ...saved.map(
421 task =>
422 `#${task.id} [${task.status}] ${task.subject}` +
423 (task.blockedBy.length > 0
424 ? ` (blocked by ${task.blockedBy.map(id => `#${id}`).join(', ')})`
425 : ''),
426 ),
427 ].join('\n'),
428 })
429 if (!filled.isFilled) {
430 $.ui.toast(`Prompt fill refused: ${filled.refusal ?? 'no reason given'}`)
431 }
432 }}
433 />
434 <Button
435 key="close"
436 role="dismiss"
437 label={unsavedCount > 0 ? 'discard' : 'close'}
438 onPress={() => closeBoard($)}
439 />
440 </Box>
441 <Box columnGap={2} marginTop={1}>
442 <Button
443 key="edit"
444 plain
445 hotkey="e"
446 label="edit"
447 dimColor={focusedRow === undefined}
448 onPress={async () => {
449 if (focusedRow !== undefined) {
450 await editField($, { key: focusedRow.key, field: 'subject' })
451 }
452 }}
453 />
454 <Button
455 key="describe"
456 plain
457 hotkey="i"
458 label="describe"
459 dimColor={focusedRow === undefined}
460 onPress={async () => {
461 if (focusedRow !== undefined) {
462 await editField($, { key: focusedRow.key, field: 'description' })
463 }
464 }}
465 />
466 <Button
467 key="delete"
468 plain
469 hotkey="d"
470 label="delete"
471 dimColor={focusedRow === undefined}
472 onPress={async () => {
473 if (focusedRow !== undefined) {
474 await update($, draft, current =>
475 editRow(current, focusedRow, { status: 'deleted' }),
476 )
477 }
478 }}
479 />
480 </Box>
481 <Text dimColor>Enter cycles status · Esc back to prompt</Text>
482 </>
483 )}
484 </Box>
485 )
486 })
487}
488types/index.d.ts 40 lines1export type TaskStatus = 'pending' | 'in_progress' | 'completed'
2
3export type Task = {
4 id: string
5 subject: string
6 description: string
7 activeForm?: string
8 status: TaskStatus
9 owner?: string
10 metadata?: Record<string, unknown>
11 blocks: string[]
12 blockedBy: string[]
13}
14
15// The fields the person changed on a saved task, in TaskUpdate's own terms.
16export type TaskEdit = {
17 subject?: string
18 description?: string
19 status?: TaskStatus | 'deleted'
20}
21
22// A task added in the pane that has no id until the draft is saved.
23export type NewTask = { draftId: string; subject: string; description: string; status: TaskStatus }
24
25export type Draft = { edits: Record<string, TaskEdit>; added: NewTask[] }
26
27// The row field an Input in the pane is editing.
28export type FieldEdit = { key: string; field: 'subject' | 'description' }
29
30declare module 'claude-code' {
31 interface PluginState {
32 'task-board': {
33 tasks: Task[]
34 draft: Draft
35 editing: FieldEdit | null
36 focusedKey: string | null
37 }
38 }
39}
40