Painel lateral de post-its: crie, conclua e consulte os concluídos

Um mod para o Claude Code: painel lateral de post-its no terminal.

Enquanto os agentes trabalham na conversa, o painel ao lado guarda a tarefa atual, com uma subtarefa por frente, e as próximas que vêm depois.
(✎)) e removíveis ((✕)).Numa sessão do Claude Code no terminal:
/plugin install post-its --marketplace DiogoGRS/claude-post-its
Responda y para adicionar o marketplace e escolha o escopo de usuário. O mod fica ativo na hora e em toda sessão seguinte.
/postits abre ou fecha o painel.Esc devolve o teclado ao prompt.Quem decide a largura da lateral é o Claude Code: 45% do terminal (até 90 colunas), ou a largura que você arrastar na borda do painel, que ele guarda em ~/.claude.json (pluginPanes.dockColumns) e lê ao iniciar.
Os post-its ficam no store do plugin, em ~/.claude/plugins/store/, fora deste repositório, guardados pela pasta onde a sessão começou. Um /cd no meio da sessão não troca de quadro; a próxima sessão aberta na outra pasta mostra o quadro dela.
claude --plugin-dir . # carrega o mod desta pasta numa sessão
claude plugin validate . # confere o manifesto e o módulo
claude plugin test . # roda tests/*.test.ts
Os tipos da API (.claude-plugin/types/) são gerados pelo Claude Code ao carregar o mod; depois disso tsc -p . checa os tipos.
hooks/register.tsx 585 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderViewport, Timer } from 'claude-code'
3
4import type { Note, Subtask } from '../types'
5
6const PANE = 'post-its'
7const TITLE = 'Post-its'
8// Cores dos post-its, na ordem em que são distribuídas: o post-it criado com o contador em n
9// recebe a cor da posição n % 6. A cor fica gravada nele, então mudar a lista não repinta os antigos.
10const PALETTE = {
11 laranja: '#E07B53',
12 azul: '#4A9EFF',
13 amarelo: '#E5C07B',
14 verde: '#5FB878',
15 ciano: '#3CC8C8',
16 roxo: '#A47DE8',
17} as const
18type ColorName = keyof typeof PALETTE
19const COLOR_ORDER = Object.keys(PALETTE) as ColorName[]
20
21const notes = atom({ plugin: 'post-its', key: 'notes' } as const, [])
22const tab = atom({ plugin: 'post-its', key: 'tab' } as const, 'open')
23// O post-it cujo campo de subtarefa está aberto, ou nenhum.
24const addingSubtaskTo = atom({ plugin: 'post-its', key: 'addingSubtaskTo' } as const, null)
25const editingSubtask = atom({ plugin: 'post-its', key: 'editingSubtask' } as const, null)
26
27function isSubtask(value: unknown): value is Subtask {
28 if (typeof value !== 'object' || value === null) return false
29 const sub = value as Record<string, unknown>
30
31 return typeof sub.id === 'string' && typeof sub.text === 'string' && typeof sub.isDone === 'boolean'
32}
33
34// Lê um post-it do store; os gravados antes das subtarefas existirem entram com a lista vazia.
35function toNote(value: unknown): Note | undefined {
36 if (typeof value !== 'object' || value === null) return undefined
37 const note = value as Record<string, unknown>
38 const isValid =
39 typeof note.id === 'string' &&
40 typeof note.text === 'string' &&
41 typeof note.createdAt === 'number' &&
42 (note.doneAt === null || typeof note.doneAt === 'number')
43 if (!isValid) return undefined
44
45 return {
46 id: note.id as string,
47 text: note.text as string,
48 createdAt: note.createdAt as number,
49 doneAt: note.doneAt as number | null,
50 subtasks: Array.isArray(note.subtasks) ? note.subtasks.filter(isSubtask) : [],
51 // Sem cor válida fica vazio: o session.start distribui as cores que faltam.
52 color: isColorName(note.color) ? note.color : '',
53 }
54}
55
56// O estado da sessão pode ainda ter post-its de antes das subtarefas (um reload desenha antes
57// do session.start normalizar): quem lê a lista passa por aqui.
58const withSubtasks = (note: Note): Note => ({ ...note, subtasks: note.subtasks ?? [] })
59
60const newId = (now: number) => `${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
61
62const pad = (n: number) => String(n).padStart(2, '0')
63
64function formatDate(ms: number): string {
65 const d = new Date(ms)
66
67 return `${pad(d.getDate())}/${pad(d.getMonth() + 1)} ${pad(d.getHours())}:${pad(d.getMinutes())}`
68}
69
70const isColorName = (value: unknown): value is ColorName =>
71 typeof value === 'string' && Object.hasOwn(PALETTE, value)
72
73const colorAt = (count: number): ColorName => COLOR_ORDER[count % COLOR_ORDER.length] ?? 'laranja'
74
75const colorOf = (note: Note) => PALETTE[isColorName(note.color) ? note.color : 'laranja']
76
77// Cada pasta tem o seu quadro: os post-its e o contador de cores ficam no store sob a pasta onde a
78// sessão começou. Um /cd no meio da sessão não troca de quadro; a próxima sessão naquela pasta, sim.
79let folder: string | undefined
80
81async function boardKey($: EngineInterface, name: 'notes' | 'colorCounter') {
82 folder ??= await $.session.root()
83
84 return `${name}:${folder}`
85}
86
87// O contador só sobe (apagar um post-it não o faz voltar) e fica no store, entre sessões.
88async function readColorCounter($: EngineInterface) {
89 const stored = await $.store.get(await boardKey($, 'colorCounter'))
90
91 return typeof stored === 'number' ? stored : 0
92}
93
94async function nextColor($: EngineInterface): Promise<ColorName> {
95 const count = await readColorCounter($)
96 await $.store.set(await boardKey($, 'colorCounter'), count + 1)
97
98 return colorAt(count)
99}
100
101// Toda mudança passa por aqui: grava no estado da sessão (redesenha o painel)
102// e no store do plugin (sobrevive entre sessões).
103async function change($: EngineInterface, fn: (list: Note[]) => Note[]) {
104 const saved = await update($, notes, list => fn(list.map(withSubtasks)))
105 await $.store.set(await boardKey($, 'notes'), saved)
106}
107
108async function add($: EngineInterface, text: string) {
109 const trimmed = text.trim()
110 if (trimmed === '') return
111
112 const now = await $.clock.now()
113 const color = await nextColor($)
114 await change($, list => [
115 ...list,
116 { id: newId(now), text: trimmed, createdAt: now, doneAt: null, subtasks: [], color },
117 ])
118}
119
120// Abre (ou fecha, se já aberto) o campo de subtarefa do post-it e leva o foco até ele.
121async function toggleSubtaskField($: EngineInterface, noteId: string) {
122 const target = await update($, addingSubtaskTo, current => (current === noteId ? null : noteId))
123 if (target === noteId) {
124 await $.ui.focus({ requestId: PANE, key: `subtask:${noteId}` }).catch(() => undefined)
125 }
126}
127
128// Enter com texto cria a subtarefa; Enter vazio só fecha o campo.
129async function addSubtask($: EngineInterface, noteId: string, text: string) {
130 const trimmed = text.trim()
131 if (trimmed !== '') {
132 const subtask = { id: newId(await $.clock.now()), text: trimmed, isDone: false }
133 await change($, list =>
134 list.map(note =>
135 note.id === noteId ? { ...note, subtasks: [...note.subtasks, subtask] } : note,
136 ),
137 )
138 }
139 await update($, addingSubtaskTo, () => null)
140}
141
142const toggleSubtask = ($: EngineInterface, noteId: string, subtaskId: string) =>
143 change($, list =>
144 list.map(note =>
145 note.id === noteId
146 ? {
147 ...note,
148 subtasks: note.subtasks.map(sub =>
149 sub.id === subtaskId ? { ...sub, isDone: !sub.isDone } : sub,
150 ),
151 }
152 : note,
153 ),
154 )
155
156// Abre (ou fecha, se já aberta) a edição da subtarefa e leva o foco até o campo.
157async function toggleSubtaskEdit($: EngineInterface, noteId: string, subtaskId: string) {
158 const key = `${noteId}:${subtaskId}`
159 const target = await update($, editingSubtask, current => (current === key ? null : key))
160 if (target === key) {
161 await $.ui.focus({ requestId: PANE, key: `editsub:${key}` }).catch(() => undefined)
162 }
163}
164
165// Enter com texto salva; Enter vazio cancela e deixa o texto como estava.
166async function saveSubtask($: EngineInterface, noteId: string, subtaskId: string, text: string) {
167 const trimmed = text.trim()
168 if (trimmed !== '') {
169 await change($, list =>
170 list.map(note =>
171 note.id === noteId
172 ? {
173 ...note,
174 subtasks: note.subtasks.map(sub =>
175 sub.id === subtaskId ? { ...sub, text: trimmed } : sub,
176 ),
177 }
178 : note,
179 ),
180 )
181 }
182 await update($, editingSubtask, () => null)
183}
184
185const removeSubtask = ($: EngineInterface, noteId: string, subtaskId: string) =>
186 change($, list =>
187 list.map(note =>
188 note.id === noteId
189 ? { ...note, subtasks: note.subtasks.filter(sub => sub.id !== subtaskId) }
190 : note,
191 ),
192 )
193
194async function complete($: EngineInterface, id: string) {
195 const now = await $.clock.now()
196 await change($, list => list.map(note => (note.id === id ? { ...note, doneAt: now } : note)))
197}
198
199const reopen = ($: EngineInterface, id: string) =>
200 change($, list => list.map(note => (note.id === id ? { ...note, doneAt: null } : note)))
201
202const remove = ($: EngineInterface, id: string) =>
203 change($, list => list.filter(note => note.id !== id))
204
205// ── Lugar e largura do painel ─────────────────────────────────────────────────────────────
206// Como o Claude Code se comporta (medido e lido no código dele, versão 2.1.292):
207// - o painel só fica na lateral em tela cheia e com o terminal em 110 colunas ou mais; abaixo
208// disso ele desce para cima do prompt, e não há como forçar a lateral;
209// - a largura da lateral é a salva no ~/.claude.json (`pluginPanes.dockColumns`, onde vai a
210// largura arrastada na borda), lida quando o Claude Code inicia; sem ela, 45% do terminal
211// (até 90 colunas). O mod não define largura: o pedido dele perde para a salva;
212// - aberto sem a pessoa pedir (por timer), o painel espera escondido até o terminal ter 110
213// colunas, e então aparece na lateral.
214
215const DOCK_MIN_COLUMNS = 110
216// Espera o terminal parar de mudar de tamanho antes de esconder o painel, para não piscar.
217const RESIZE_SETTLE_MS = 400
218
219const isNarrow = (isFullscreen: boolean | undefined, terminal: number) =>
220 isFullscreen === true && terminal < DOCK_MIN_COLUMNS
221
222const openPane = ($: EngineInterface, focus?: true) =>
223 $.ui.open({ id: PANE, title: TITLE, ...(focus ? { focus } : {}) })
224
225// Fecha e abre sem a pessoa pedir: o painel sai de cima do prompt e espera escondido até o
226// terminal alargar.
227async function hidePane($: EngineInterface) {
228 await $.ui.close({ id: PANE })
229
230 return openPane($)
231}
232
233// Abre por timer, sem a pessoa pedir: com o terminal estreito, espera escondido até alargar.
234function openWhenWide($: EngineInterface) {
235 $.clock.after(0, () => void openPane($))
236}
237
238// Esconder-até-alargar deste carregamento do módulo: o timer que espera o redimensionamento
239// parar, e a largura para a qual já escondeu, para não fechar e abrir sem fim.
240let settleTimer: Timer | undefined
241let hiddenFor: number | undefined
242
243// Chamado a cada desenho do painel (o Claude Code redesenha quando o terminal muda de largura).
244// Se o painel desceu para cima do prompt porque o terminal estreitou, esconde e espera alargar.
245// Fora da tela cheia não há lateral, então ali ele fica onde está.
246function keepDocked(
247 $: EngineInterface,
248 placement: 'dock' | 'inline',
249 viewport: RenderViewport | undefined,
250) {
251 settleTimer?.cancel()
252 if (placement === 'dock') hiddenFor = undefined
253 if (placement !== 'inline' || viewport === undefined) return
254
255 // Acima do prompt a conversa ocupa o terminal inteiro: a largura dela é a do terminal.
256 const terminal = viewport.columns
257 settleTimer = $.clock.after(RESIZE_SETTLE_MS, () => {
258 if (!isNarrow(viewport.isFullscreen, terminal) || hiddenFor === terminal) return
259 hiddenFor = terminal
260 void hidePane($).catch(() => undefined)
261 })
262}
263
264export const register: Register = on => {
265 on('session.start', async ($, e, next) => {
266 folder = await $.session.root()
267 const saved = await $.store.get(await boardKey($, 'notes'))
268 let list = Array.isArray(saved)
269 ? saved.map(toNote).filter((note): note is Note => note !== undefined)
270 : []
271
272 // Post-its de antes das cores recebem as suas na ordem em que foram criados.
273 const uncolored = list.filter(note => note.color === '').sort((a, b) => a.createdAt - b.createdAt)
274 if (uncolored.length > 0) {
275 let count = await readColorCounter($)
276 const colors = new Map(uncolored.map(note => [note.id, colorAt(count++)]))
277 list = list.map(note => ({ ...note, color: colors.get(note.id) ?? note.color }))
278 await $.store.set(await boardKey($, 'colorCounter'), count)
279 await $.store.set(await boardKey($, 'notes'), list)
280 }
281
282 await update($, notes, () => list)
283
284 // Restos das versões anteriores: o dimensionamento e o quadro único, de antes de um por pasta.
285 for (const key of [
286 'widthColumns',
287 'paneColumns',
288 'widthDebug',
289 'widthPct',
290 'paneSize',
291 'notes',
292 'colorCounter',
293 ]) {
294 await $.store.delete(key)
295 }
296
297 await $.command.register({
298 name: 'postits',
299 description: 'Abre ou fecha o painel de post-its',
300 })
301
302 // Estava aberto na sessão anterior: reabre.
303 if ((await $.store.get('isOpen')) === true) void openPane($).catch(() => undefined)
304
305 return next(e)
306 })
307
308 on('command.run', { command: 'postits' }, async ($, e) => {
309 const terminal = e.presentation.columns
310 const pane = (await $.ui.panes()).find(one => one.id === PANE)
311
312 // Fecha se está à vista, ou se está esperando o terminal alargar.
313 if (pane?.isShown === true || (pane !== undefined && !pane.isPlaced)) {
314 await $.ui.close({ id: PANE })
315 await $.store.set('isOpen', false)
316
317 return { text: 'Post-its fechado.' }
318 }
319
320 await $.store.set('isOpen', true)
321
322 if (isNarrow(e.presentation.isFullscreen, terminal)) {
323 openWhenWide($)
324
325 return {
326 text: `O terminal tem ${terminal} colunas e o painel lateral precisa de ${DOCK_MIN_COLUMNS}: ele aparece sozinho quando o terminal alargar.`,
327 }
328 }
329
330 await openPane($, true)
331
332 return { text: 'Post-its aberto.' }
333 })
334
335 // Só o fechar da pessoa conta: o do próprio mod (esconder até alargar) mantém o painel ligado.
336 on('ui.close', { id: 'post-its' }, async ($, e, next) => {
337 if (e.origin.kind === 'person') await $.store.set('isOpen', false)
338
339 return next(e)
340 })
341
342 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
343 keepDocked($, e.props.placement, e.viewport)
344
345 const ui = $.ui.resolve(e)
346 const { Box, Text, Button } = ui
347 // O celular não desenha campo de texto.
348 const Input = 'Input' in ui && e.surface !== 'mobile' ? ui.Input : undefined
349 const list = (await read($, notes)).map(withSubtasks)
350 const current = await read($, tab)
351 const adding = await read($, addingSubtaskTo)
352 const editing = await read($, editingSubtask)
353 // Fundo do card de subtarefa: um tom acima do painel, claro ou escuro conforme o tema.
354 const isLight = await $.config.list().then(
355 rows => String(rows.find(row => row.key === 'theme')?.value ?? '').startsWith('light'),
356 () => false,
357 )
358 const cardBackground = isLight ? '#e6e6e6' : '#333333'
359
360 const open = list.filter(note => note.doneAt === null).reverse()
361 const done = list
362 .filter(note => note.doneAt !== null)
363 .sort((a, b) => (b.doneAt ?? 0) - (a.doneAt ?? 0))
364
365 // Texto do post-it à esquerda, data no canto superior direito.
366 const header = (text: string, date: string, isDim: boolean) => (
367 <Box justifyContent="space-between" gap={2}>
368 <Box flexShrink={1}>
369 <Text dimColor={isDim}>{text}</Text>
370 </Box>
371 <Box flexShrink={0}>
372 <Text dimColor>{date}</Text>
373 </Box>
374 </Box>
375 )
376
377 // Ações no canto direito, separadas por uma barra para ficar claro onde um botão termina e o
378 // outro começa, e uma linha em branco acima, para não colar no texto.
379 const actions = (buttons: JSX.Element[]) => (
380 <Box gap={1} flexWrap="wrap" justifyContent="flex-end" marginTop={1}>
381 {buttons.flatMap((button, i) => (i === 0 ? [button] : [<Text dimColor>│</Text>, button]))}
382 </Box>
383 )
384
385 // Título do painel: o terminal não muda o tamanho da fonte, então destaca com negrito e cor.
386 const title = (
387 <Text key="title" bold color="claude">
388 Claude Post-its
389 </Text>
390 )
391
392 const tabs = (
393 <Box gap={1} flexWrap="wrap">
394 <Button
395 key="tab:open"
396 label={`Abertos (${open.length})`}
397 variant={current === 'open' ? 'primary' : 'secondary'}
398 onPress={() => update($, tab, () => 'open')}
399 />
400 <Button
401 key="tab:done"
402 label={`Concluídos (${done.length})`}
403 variant={current === 'done' ? 'primary' : 'secondary'}
404 onPress={() => update($, tab, () => 'done')}
405 />
406 </Box>
407 )
408
409 if (current === 'done') {
410 return (
411 <Box flexDirection="column" gap={1}>
412 {title}
413 {tabs}
414 {done.length === 0 && <Text dimColor>Nada concluído ainda.</Text>}
415 {done.map(note => (
416 <Box
417 key={`note:${note.id}`}
418 flexDirection="column"
419 borderStyle="round"
420 borderDimColor
421 paddingX={2}
422 >
423 {header(note.text, `✓ ${formatDate(note.doneAt ?? note.createdAt)}`, true)}
424 {note.subtasks.length > 0 && (
425 <Box flexDirection="column" paddingLeft={4} gap={1}>
426 {note.subtasks.map(sub => (
427 <Box paddingX={1} backgroundColor={cardBackground}>
428 <Text dimColor>
429 {sub.isDone ? '[✓]' : '[ ]'} {sub.text}
430 </Text>
431 </Box>
432 ))}
433 </Box>
434 )}
435 {actions([
436 <Button
437 key={`reopen:${note.id}`}
438 plain
439 dimColor
440 label="↺ reabrir"
441 onPress={() => reopen($, note.id)}
442 />,
443 <Button
444 key={`remove:${note.id}`}
445 plain
446 dimColor
447 label="✕ apagar"
448 onPress={() => remove($, note.id)}
449 />,
450 ])}
451 </Box>
452 ))}
453 </Box>
454 )
455 }
456
457 return (
458 <Box flexDirection="column" gap={1}>
459 {title}
460 {tabs}
461 {Input ? (
462 <Input
463 key="new"
464 placeholder="Novo post-it… (Enter cola)"
465 submitLabel="colar"
466 value=""
467 autoFocus
468 onSubmit={text => add($, text)}
469 />
470 ) : (
471 <Text dimColor>Crie post-its pelo terminal ou pelo desktop.</Text>
472 )}
473 {open.length === 0 && <Text dimColor>Nenhum post-it aberto.</Text>}
474 {open.map(note => (
475 <Box
476 key={`note:${note.id}`}
477 flexDirection="column"
478 borderStyle="round"
479 borderColor={colorOf(note)}
480 paddingX={2}
481 >
482 {header(note.text, formatDate(note.createdAt), false)}
483 {(note.subtasks.length > 0 || adding === note.id) && (
484 <Box flexDirection="column" paddingLeft={4} gap={1}>
485 {note.subtasks.map(sub => {
486 const subKey = `${note.id}:${sub.id}`
487
488 return (
489 <Box
490 justifyContent="space-between"
491 gap={2}
492 paddingX={1}
493 backgroundColor={cardBackground}
494 >
495 {Input && editing === subKey ? (
496 <Box flexGrow={1}>
497 <Input
498 key={`editsub:${subKey}`}
499 value={sub.text}
500 placeholder="Vazio cancela"
501 submitLabel="salvar"
502 onSubmit={text => saveSubtask($, note.id, sub.id, text)}
503 />
504 </Box>
505 ) : (
506 <Box gap={1} flexShrink={1}>
507 <Button
508 key={`check:${subKey}`}
509 plain
510 dimColor={sub.isDone}
511 label={sub.isDone ? '[✓]' : '[ ]'}
512 onPress={() => toggleSubtask($, note.id, sub.id)}
513 />
514 <Text dimColor={sub.isDone} strikethrough={sub.isDone}>
515 {sub.text}
516 </Text>
517 </Box>
518 )}
519 <Box flexShrink={0} gap={1}>
520 {Input && (
521 <Button
522 key={`editbtn:${subKey}`}
523 plain
524 dimColor
525 label="(✎)"
526 onPress={() => toggleSubtaskEdit($, note.id, sub.id)}
527 />
528 )}
529 <Button
530 key={`rmsub:${subKey}`}
531 plain
532 dimColor
533 label="(✕)"
534 onPress={() => removeSubtask($, note.id, sub.id)}
535 />
536 </Box>
537 </Box>
538 )
539 })}
540 {Input && adding === note.id && (
541 <Box paddingX={1} backgroundColor={cardBackground}>
542 <Input
543 key={`subtask:${note.id}`}
544 placeholder="Subtarefa… (Enter cria, vazio cancela)"
545 submitLabel="criar"
546 value=""
547 onSubmit={text => addSubtask($, note.id, text)}
548 />
549 </Box>
550 )}
551 </Box>
552 )}
553 {actions([
554 <Button
555 key={`done:${note.id}`}
556 plain
557 label="✓ concluir"
558 onPress={() => complete($, note.id)}
559 />,
560 ...(Input
561 ? [
562 <Button
563 key={`addsub:${note.id}`}
564 plain
565 dimColor
566 label="+ subtarefa"
567 onPress={() => toggleSubtaskField($, note.id)}
568 />,
569 ]
570 : []),
571 <Button
572 key={`remove:${note.id}`}
573 plain
574 dimColor
575 label="✕ apagar"
576 onPress={() => remove($, note.id)}
577 />,
578 ])}
579 </Box>
580 ))}
581 </Box>
582 )
583 })
584}
585types/index.d.ts 30 lines1export type Subtask = {
2 id: string
3 text: string
4 isDone: boolean
5}
6
7export type Note = {
8 id: string
9 text: string
10 createdAt: number
11 doneAt: number | null
12 subtasks: Subtask[]
13 // Nome da cor na paleta (laranja, azul, ...), gravado quando o post-it é criado.
14 color: string
15}
16
17export type Tab = 'open' | 'done'
18
19declare module 'claude-code' {
20 interface PluginState {
21 'post-its': {
22 notes: Note[]
23 tab: Tab
24 addingSubtaskTo: string | null
25 // `<noteId>:<subtaskId>` da subtarefa em edição, ou nenhuma.
26 editingSubtask: string | null
27 }
28 }
29}
30