Hides tool calls and output while Claude works, and shows a plain-English checklist of the plan above the prompt.

Hides tool calls and output while Claude works; shows a plain checklist above the prompt.
Clean View: ON/OFF button at the right of the band above the prompt, or run /simple on, /simple off or /simple (flips it). The setting is saved across sessions. It starts on.plan_steps and report_progress, and blocks every other tool until a plan exists. The optional plan_steps.title names the job; replanning without a title keeps the existing one. A to-do list (TodoWrite, TaskCreate) also counts as the plan.plan_steps updates the list and keeps finished steps checked off.[!WARNING] Where an organization manages Claude Code, a managed plugin can skip a mod's
prompt.composeandclassic.*hooks. The system prompt section is then skipped; the tool descriptions and the plan-first gate still steer Claude to plan. The permission mode is then unknown, so Needs you can show for an ask auto mode settles alone; the next model request clears it.
hooks/register.tsx 8 lines1import type { Register } from 'claude-code'
2
3import { registerCleanView } from './clean-view'
4
5export const register: Register = on => {
6 registerCleanView(on)
7}
8hooks/clean-view.tsx 780 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, Timer } from 'claude-code'
3
4import type { CleanViewActivity, CleanViewChecklist, CleanViewLogEntry, CleanViewTask } from '../types'
5import {
6 EMPTY,
7 METER_CELLS,
8 PLACEHOLDER_PREFIX,
9 addTask,
10 appendLog,
11 asksPerson,
12 clampPercent,
13 duration,
14 endsWithQuestion,
15 errorSentence,
16 fit,
17 fromTodos,
18 hasPlan,
19 isRunning,
20 isUserRejection,
21 label,
22 meter,
23 newJob,
24 planSteps,
25 reportProgress,
26 taskElapsed,
27 updateTask,
28} from './logic'
29
30const PLUGIN = 'clean-view'
31const COMMAND = 'simple'
32const STORE_KEY = 'cleanViewEnabled'
33const PLAN_TOOL = `mcp__${PLUGIN}__plan_steps`
34const PROGRESS_TOOL = `mcp__${PLUGIN}__report_progress`
35const FRAME_MS = 100
36const COLLAPSE_MS = 5000
37const FAILURES_TO_STUCK = 3
38const PLACEHOLDER_TITLE = 'Your request'
39const DETAILS_PANE = 'clean-view-details'
40// Cells the `[ Details ]` button takes at the end of each task row.
41const DETAILS_BUTTON_CELLS = 11
42const ALWAYS_ALLOWED = new Set(['ToolSearch', 'TodoWrite', 'TaskCreate', 'TaskUpdate', 'AskUserQuestion', PLAN_TOOL, PROGRESS_TOOL])
43// Tools that update the checklist directly.
44const PLAN_UPDATERS = new Set([PLAN_TOOL, PROGRESS_TOOL, 'TodoWrite', 'TaskCreate', 'TaskUpdate'])
45
46const NEEDS_OK = 'Claude needs your OK to continue'
47const HAS_QUESTION = 'Claude has a question for you'
48const WAITING = 'Claude is waiting for your reply'
49const ASKED = 'Claude asked you a question above'
50// Phases where a plan was left part way; its active step draws as Paused.
51const PAUSED = new Set(['needsYou', 'stuck', 'stopped', 'waiting', 'ended'])
52// An agent in one of these is still at work and will report back on its own.
53const AGENT_AT_WORK = new Set(['pending', 'running', 'waiting'])
54const SAID_NO = 'you said no to a step, so Claude paused'
55const KEEPS_FAILING = 'a step keeps failing, Claude is trying another way'
56const REFUSED = "Claude couldn't help with that request"
57
58const enabled = atom({ plugin: 'clean-view', key: 'cleanViewEnabled' } as const, true)
59const checklist = atom({ plugin: 'clean-view', key: 'checklist' } as const, EMPTY)
60const selectedTaskId = atom({ plugin: 'clean-view', key: 'selectedTaskId' } as const, null as string | null)
61const taskLogs = atom({ plugin: 'clean-view', key: 'taskLogs' } as const, {} as Record<string, CleanViewLogEntry[]>)
62const logScroll = atom({ plugin: 'clean-view', key: 'logScroll' } as const, 0)
63const tick = atom({ plugin: 'clean-view', key: 'tick' } as const, 0)
64
65const SECTION = `# Clean View checklist
66
67The person sees a plain checklist of your plan instead of your tool calls.
68
69- For every request, even a quick question, call \`${PLAN_TOOL}\` first with a short job title and every step of the job, 1 to 8 short names in order. Only include steps that perform actual work; never add a filler final step like "Prepare next action" or "Summarize findings". Load it with ToolSearch if it is deferred. If this session has TodoWrite or TaskCreate, you may use your to-do list as the plan instead.
70- Never spend a turn calling \`${PROGRESS_TOOL}\` or \`${PLAN_TOOL}\` alone. Always call them in the same response as your next real tool call.
71- Call \`${PROGRESS_TOOL}\` with 100 when a step finishes (bundled with the first tool call of the next step), or alongside a tool call when a step has taken several tool calls. Only pass 100 after you have read a step's tool output and confirmed the step is done; when the final step is ready to answer, reply directly and Clean View completes it automatically.
72- Keep internal reasoning before tool calls brief (1 to 2 sentences) so the checklist never sits idle on a long thinking pause.
73- If the job grows past your plan (extra checks, cleanup, undoing changes, a new kind of work), call \`${PLAN_TOOL}\` again with the full updated list before you do it. Keep finished step names the same so they stay checked off.
74- Write every step name in plain English a non-technical person understands, under 40 characters, starting with a verb, like "Build the pricing section".
75- Never put file paths, file names, commands, code or tool names in a step name.`
76
77type $ = EngineInterface
78
79let ticker: Timer | undefined
80let failures = 0
81let enforcedForRun = true
82let isNextTurnCommand = false
83// The next turn is a background agent reporting back, not a new request.
84let isNextTurnReport = false
85// The session's permission mode, as the last classic hook carried it; unknown until one does.
86let permissionMode: string | undefined
87// The main loop's running turn, which the details pane's Stop ends.
88let mainTurnId: string | undefined
89// The pane button holding the focus ring; the per-frame redraw would otherwise reset it to Prev.
90let focusedButton: string | undefined
91// Files read during the active step, so the activity shows real progress the model hasn't reported.
92let readsInStep = 0
93let readsStepId: string | null = null
94let logSeq = 0
95let maxLogScroll = 0
96let pendingPlanUpdate: Promise<unknown> = Promise.resolve()
97
98function queuePlanUpdate<T>(fn: () => Promise<T>): Promise<T> {
99 const next = pendingPlanUpdate.then(fn, fn)
100 pendingPlanUpdate = next.then(() => undefined, () => undefined)
101 return next
102}
103
104function countRead(list: CleanViewChecklist): string {
105 const stepId = list.tasks.find(one => one.status === 'active')?.id ?? null
106 if (stepId !== readsStepId) {
107 readsStepId = stepId
108 readsInStep = 0
109 }
110 readsInStep++
111 return `Read ${readsInStep} file${readsInStep === 1 ? '' : 's'} in this step`
112}
113
114function startTicker($: $) {
115 if (ticker !== undefined) return
116 ticker = $.clock.every(FRAME_MS, () => {
117 void update($, tick, n => (n ?? 0) + 1)
118 })
119}
120
121function stopTicker() {
122 ticker?.cancel()
123 ticker = undefined
124}
125
126async function isOn($: $) {
127 return read($, enabled)
128}
129
130async function edit($: $, fn: (list: CleanViewChecklist) => CleanViewChecklist) {
131 await update($, checklist, list => fn(list ?? EMPTY))
132}
133
134async function recordActivity($: $, summary: string, inProgress: boolean, at?: number) {
135 const timestamp = at ?? await $.clock.now()
136 await edit($, list => ({ ...list, activity: { summary, at: timestamp, inProgress } }))
137}
138
139async function recordTaskLog($: $, kind: CleanViewLogEntry['kind'], text: string, streamKey?: string) {
140 const stepId = (await read($, checklist)).tasks.find(one => one.status === 'active')?.id
141 if (!stepId) return
142 const key = streamKey ?? `${kind}-${++logSeq}`
143 await update($, taskLogs, logs => {
144 const current = logs?.[stepId] ?? []
145 const piece = streamKey !== undefined && current.at(-1)?.key !== key ? `💭 ${text}` : text
146 return { ...(logs ?? {}), [stepId]: appendLog(current, kind, key, piece) }
147 })
148}
149
150async function openDetails($: $, taskId: string) {
151 await update($, selectedTaskId, () => taskId)
152 await update($, logScroll, () => 0)
153 focusedButton = undefined
154 await $.ui.open({ id: DETAILS_PANE, title: 'Task details', focus: true, closeOnEscape: true, holdToasts: true, rows: 24 })
155}
156
157async function pageDetails($: $, step: number) {
158 const list = await read($, checklist)
159 const id = await read($, selectedTaskId)
160 const index = Math.max(0, list.tasks.findIndex(one => one.id === id))
161 const next = list.tasks[Math.min(list.tasks.length - 1, Math.max(0, index + step))]
162 if (next) {
163 await update($, selectedTaskId, () => next.id)
164 await update($, logScroll, () => 0)
165 }
166}
167
168function toolActivity(tool: string, finished = false): string {
169 switch (tool.toLowerCase()) {
170 case 'bash': return finished ? 'Finished running a command' : 'Running a command'
171 case 'read': return finished ? 'Finished reading a file' : 'Reading a file'
172 case 'grep':
173 case 'find':
174 case 'ls': return finished ? 'Finished searching the project' : 'Searching the project'
175 case 'edit':
176 case 'write': return finished ? 'Finished updating files' : 'Updating files'
177 case 'codemode': return finished ? 'Finished running a script' : 'Running a script'
178 default: return finished ? 'Finished using a tool' : 'Using a tool'
179 }
180}
181
182async function setEnabled($: $, value: boolean) {
183 await update($, enabled, () => value)
184 await $.store.set(STORE_KEY, value)
185 $.ui.toast(value ? 'Clean View on: showing the plan, hiding the technical details' : 'Clean View off: showing everything')
186}
187
188async function startJob($: $) {
189 const startedAt = await $.clock.now()
190 failures = 0
191 await update($, selectedTaskId, () => null)
192 await update($, taskLogs, () => ({}))
193 await update($, logScroll, () => 0)
194 await edit($, () => newJob(startedAt, PLACEHOLDER_TITLE))
195 startTicker($)
196}
197
198/** Starts a job for a plan that arrives while none runs (a skill, a slash command). */
199async function ensureJob($: $) {
200 if (!isRunning(await read($, checklist))) await startJob($)
201}
202
203function needsYou(reason: string) {
204 return (list: CleanViewChecklist): CleanViewChecklist =>
205 isRunning(list) ? { ...list, phase: 'needsYou', needsYouReason: reason } : list
206}
207
208function backToWork(list: CleanViewChecklist): CleanViewChecklist {
209 return list.phase === 'needsYou' && list.finishedAt === null ? { ...list, phase: 'working', needsYouReason: null } : list
210}
211
212function stuck(reason: string) {
213 return (list: CleanViewChecklist): CleanViewChecklist =>
214 isRunning(list) ? { ...list, phase: 'stuck', stuckReason: reason, needsYouReason: null } : list
215}
216
217function unstuck(list: CleanViewChecklist): CleanViewChecklist {
218 return list.phase === 'stuck' && list.finishedAt === null ? { ...list, phase: 'working', stuckReason: null } : list
219}
220
221async function finish($: $, fn: (list: CleanViewChecklist, now: number) => CleanViewChecklist) {
222 const now = await $.clock.now()
223 stopTicker()
224 await edit($, list => {
225 if (list.phase === 'idle') return list
226 const finished = fn({ ...list, finishedAt: now }, now)
227 const summary = finished.phase === 'stopped' ? 'Run stopped' : finished.phase === 'stuck' ? 'Run needs attention' : finished.phase === 'waiting' ? 'Waiting for background work' : finished.phase === 'needsYou' ? 'Waiting for your reply' : finished.phase === 'ended' ? 'Run ended' : 'Run finished'
228 return { ...finished, activity: { summary, at: now, inProgress: false } }
229 })
230}
231
232export function registerCleanView(on: On) {
233 on('session.start', async ($, e, next) => {
234 const saved = await $.store.get(STORE_KEY)
235 await update($, enabled, () => (typeof saved === 'boolean' ? saved : true))
236 await $.command.register({
237 name: COMMAND,
238 description: 'Clean View: hide tool details and show a plain checklist (on, off, or flip)',
239 argumentHint: 'on|off',
240 })
241 await $.tool.register({
242 name: 'plan_steps',
243 description:
244 'Lay out every step of the job up front so the person sees the plan: 1 to 8 short plain-English step names in order, each under 40 characters and starting with a verb. The first step starts right away. If the job grows past the plan, call it again with the full updated list and keep finished step names unchanged.',
245 inputSchema: {
246 type: 'object',
247 properties: {
248 title: { type: 'string', description: 'Short 2 to 6 word plain-English job title starting with a verb, without code, file names or paths.' },
249 steps: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 8 },
250 },
251 required: ['steps'],
252 },
253 isDeferred: false,
254 })
255 await $.tool.register({
256 name: 'report_progress',
257 description:
258 'Report progress on the current step by its plain-English name, with a percent from 0 to 100. Report 100 the moment a step finishes; the next one then starts.',
259 inputSchema: {
260 type: 'object',
261 properties: { task: { type: 'string' }, percent: { type: 'number', minimum: 0, maximum: 100 } },
262 required: ['task', 'percent'],
263 },
264 isDeferred: false,
265 })
266 if (isRunning(await read($, checklist))) startTicker($)
267 return next(e)
268 })
269
270 on('command.run', { command: COMMAND }, async ($, e) => {
271 const arg = e.args.trim().toLowerCase()
272 const value = arg === 'on' ? true : arg === 'off' ? false : !(await isOn($))
273 await setEnabled($, value)
274 return { text: value ? 'Clean View is on.' : 'Clean View is off.' }
275 })
276
277 on('prompt.compose', async ($, e, next) => {
278 const composed = await next(e)
279 if (!(await isOn($))) return composed
280 return { sections: [...composed.sections, { id: `${PLUGIN}:checklist`, text: SECTION, scope: 'session' as const }] }
281 })
282
283 on('prompt.submit', async ($, e, next) => {
284 isNextTurnCommand = e.command !== undefined
285 isNextTurnReport = e.origin.kind === 'task-notification' && e.turnId === undefined
286 // A slash command's output would sit under a stale band; clear one left waiting.
287 if (isNextTurnCommand) await edit($, list => (list.phase === 'working' ? list : { ...list, phase: 'idle' }))
288 return next(e)
289 }).catch(($, e, next) => next(e))
290
291 on('turn.start', async ($, e, next) => {
292 if (e.agentId === undefined) {
293 mainTurnId = e.turnId
294 enforcedForRun = await isOn($)
295 const isCommand = isNextTurnCommand
296 const isReport = isNextTurnReport
297 isNextTurnCommand = false
298 isNextTurnReport = false
299 const list = await read($, checklist)
300 // A plan left part way (Esc, a pause, a question, background work) carries on:
301 // a typed prompt is usually a re-steer, and a report is the work coming back.
302 const isPaused = PAUSED.has(list.phase) && hasPlan(list)
303 const resumes = isReport ? list.phase === 'waiting' : !isCommand && e.text.trim() !== '' && isPaused
304 if (resumes) {
305 const resumedAt = await $.clock.now()
306 await edit($, current => {
307 const pauseMs = current.finishedAt !== null ? Math.max(0, resumedAt - current.finishedAt) : 0
308 return {
309 ...current,
310 phase: 'working',
311 startedAt: current.startedAt + pauseMs,
312 tasks: current.tasks.map(one =>
313 one.status === 'active' && one.startedAt !== undefined
314 ? { ...one, startedAt: one.startedAt + pauseMs }
315 : one,
316 ),
317 activity: { summary: 'Resumed the task list', at: resumedAt, inProgress: true },
318 finishedAt: null,
319 isCollapsed: false,
320 needsYouReason: null,
321 stuckReason: null,
322 waitingOn: undefined,
323 }
324 })
325 startTicker($)
326 } else if (!isCommand && e.text.trim() !== '') {
327 await startJob($)
328 }
329 }
330 return next(e)
331 })
332
333 on('tool.call', async ($, e, next) => {
334 if (e.agentId !== undefined) return next(e)
335 const tool = String(e.tool)
336 if (tool === PLAN_TOOL || tool === PROGRESS_TOOL) {
337 return queuePlanUpdate(async () => {
338 await edit($, backToWork)
339 return next(e)
340 })
341 }
342 await pendingPlanUpdate
343 const list = await read($, checklist)
344 const isEnabled = await isOn($)
345 if (enforcedForRun && isEnabled && isRunning(list) && !hasPlan(list) && !ALWAYS_ALLOWED.has(tool)) {
346 return { deny: `Clean View: call ${PLAN_TOOL} first to lay out the steps of this job (load it with ToolSearch if it is deferred), then try again.` }
347 }
348
349 await edit($, backToWork)
350 if (!PLAN_UPDATERS.has(tool)) {
351 await recordActivity($, tool === 'AskUserQuestion' ? 'Waiting for your answer' : toolActivity(tool), tool !== 'AskUserQuestion')
352 }
353 if (!ALWAYS_ALLOWED.has(tool)) {
354 const { tool: _t, tool_use_id: _id, agentId: _a, consent: _c, requestMeta: _m, ...input } = e as Record<string, unknown>
355 await recordTaskLog($, 'call', `→ ${tool} ${JSON.stringify(input)}`)
356 }
357 if (e.tool === 'TodoWrite') {
358 await queuePlanUpdate(async () => {
359 const at = await $.clock.now()
360 await edit($, current => ({ ...fromTodos(current, e.todos, at), activity: { summary: 'Task list updated', at, inProgress: false } }))
361 })
362 }
363 if (e.tool === 'TaskUpdate') {
364 await queuePlanUpdate(async () => {
365 const at = await $.clock.now()
366 await edit($, current => ({ ...updateTask(current, e.taskId, e.status, e.subject, at), activity: { summary: 'Task list updated', at, inProgress: false } }))
367 })
368 }
369 if (e.tool === 'AskUserQuestion') await edit($, needsYou(HAS_QUESTION))
370
371 const ran = await next(e)
372
373 await edit($, backToWork)
374 if (!ALWAYS_ALLOWED.has(tool) && ran.deny === undefined) {
375 const out = ran.text ?? (typeof ran.result === 'string' ? ran.result : JSON.stringify(ran.result) ?? '')
376 await recordTaskLog($, ran.isError === true ? 'error' : 'result', ran.isError === true ? `← error: ${out}` : `← ${out}`)
377 }
378 if (tool === 'AskUserQuestion' && ran.deny === undefined) await recordActivity($, 'Answer received', false)
379 if (!PLAN_UPDATERS.has(tool) && tool !== 'AskUserQuestion') {
380 const summary = ran.isError === true
381 ? 'A tool call failed'
382 : tool.toLowerCase() === 'read'
383 ? countRead(await read($, checklist))
384 : toolActivity(tool, true)
385 await recordActivity($, summary, false)
386 }
387 if (e.tool === 'TaskCreate' && ran.deny === undefined && ran.isError !== true) {
388 const made = ran.result as { task?: { id?: string; subject?: string } } | undefined
389 if (made?.task?.id !== undefined) {
390 const at = await $.clock.now()
391 await edit($, current => ({ ...addTask(current, made.task!.id!, made.task!.subject ?? e.subject, at), activity: { summary: 'Task list updated', at, inProgress: false } }))
392 }
393 }
394 if (ran.deny !== undefined) return ran
395 if (ran.isError === true) {
396 if (isUserRejection(ran.text)) {
397 failures = 0
398 await edit($, stuck(SAID_NO))
399 } else if (++failures >= FAILURES_TO_STUCK) {
400 await edit($, stuck(KEEPS_FAILING))
401 }
402 } else {
403 failures = 0
404 await edit($, unstuck)
405 }
406 return ran
407 }).catch(($, e, next) => next(e))
408
409 // A permission dialog is about to open, unless the mode settles the ask with
410 // nobody asked (auto mode's classifier, a bypass). classic.Notification says
411 // the same, but does not reach a mod where an organization manages Claude Code.
412 on('tool.check', async ($, e, next) => {
413 const verdict = await next(e)
414 const isMain = e.agentId === undefined && e.tool_use_id !== undefined
415 if (verdict.decision === 'ask' && isMain && asksPerson(permissionMode)) {
416 await edit($, needsYou(NEEDS_OK))
417 await recordActivity($, 'Waiting for permission', false)
418 }
419 return verdict
420 }).catch(($, e, next) => next(e))
421
422 // Shift+Tab can change the mode mid-turn, so each prompt and each tool's end refreshes it.
423 on('classic.UserPromptSubmit', async ($, e, next) => {
424 if (e.permission_mode !== undefined) permissionMode = e.permission_mode
425 return next(e)
426 }).catch(($, e, next) => next(e))
427
428 on('classic.PostToolUse', async ($, e, next) => {
429 if (e.permission_mode !== undefined) permissionMode = e.permission_mode
430 return next(e)
431 }).catch(($, e, next) => next(e))
432
433 // An ask the classifier refused never reaches tool.call, so nothing else clears Needs you.
434 on('classic.PermissionDenied', async ($, e, next) => {
435 await edit($, backToWork)
436 return next(e)
437 }).catch(($, e, next) => next(e))
438
439 // A new model request means any ask was settled, even where a managed plugin
440 // skips the classic hooks that carry the mode and the classifier's refusal.
441 on('turn.step', async function* ($, e, next) {
442 if (e.agentId === undefined) await edit($, backToWork)
443 const stream = next(e)
444 for await (const chunk of stream) {
445 if (e.agentId === undefined && chunk.kind === 'thinking' && chunk.text !== '') {
446 await recordTaskLog($, 'thinking', chunk.text, `thinking-${e.turnId}-${e.index}-${chunk.index}`)
447 }
448 yield chunk
449 }
450 return await stream.result
451 })
452
453 on('tool.call', { tool: PLAN_TOOL }, async ($, e) => {
454 const input = e as { steps?: unknown; title?: unknown }
455 const names = Array.isArray(input.steps) ? input.steps.filter((s): s is string => typeof s === 'string') : []
456 const title = typeof input.title === 'string' ? input.title : undefined
457 await ensureJob($)
458 const at = await $.clock.now()
459 await edit($, list => ({ ...planSteps(list, names, at, title), activity: { summary: 'Plan updated', at, inProgress: false } }))
460 await update($, selectedTaskId, () => null)
461 const updated = await read($, checklist)
462 const activeTask = updated.tasks.find(one => one.status === 'active')
463 const placeholderKey = `${PLACEHOLDER_PREFIX}thinking`
464 if (activeTask) {
465 await update($, taskLogs, logs => {
466 const pre = logs?.[placeholderKey]
467 if (!pre || pre.length === 0) return logs ?? {}
468 const { [placeholderKey]: _, ...rest } = logs ?? {}
469 return { ...rest, [activeTask.id]: [...pre, ...(rest[activeTask.id] ?? [])] }
470 })
471 }
472 const doneCount = updated.tasks.filter(one => one.status === 'done').length
473 const result =
474 doneCount > 0 && activeTask
475 ? `Planned ${updated.tasks.length} steps (${doneCount} already done). Active step: "${activeTask.name}" — do not re-report finished steps.`
476 : `Planned ${updated.tasks.length} steps. The first one has started.`
477 return { result }
478 })
479
480 on('tool.call', { tool: PROGRESS_TOOL }, async ($, e) => {
481 const input = e as { task?: unknown; percent?: unknown }
482 const name = typeof input.task === 'string' ? input.task : ''
483 const percent = typeof input.percent === 'number' ? input.percent : Number(input.percent)
484 await ensureJob($)
485 const at = await $.clock.now()
486 await edit($, list => ({ ...reportProgress(list, name, percent, at), activity: { summary: 'Progress reported', at, inProgress: false } }))
487 return { result: `Progress noted: ${clampPercent(percent)}%.` }
488 })
489
490 on('classic.Notification', async ($, e, next) => {
491 if (e.notification_type === 'permission_prompt') {
492 await edit($, needsYou(NEEDS_OK))
493 await recordActivity($, 'Waiting for permission', false)
494 }
495 if (e.notification_type === 'elicitation_dialog') {
496 await edit($, needsYou(HAS_QUESTION))
497 await recordActivity($, 'Waiting for your answer', false)
498 }
499 return next(e)
500 }).catch(($, e, next) => next(e))
501
502 on('turn.complete', async ($, e, next) => {
503 if (e.agentId !== undefined) return next(e)
504 // An Esc-stopped turn can end after a queued prompt's turn started; it must not stop that one.
505 if (mainTurnId !== undefined && e.turnId !== mainTurnId) return next(e)
506 if (e.reason === 'error') {
507 await finish($, list => ({ ...list, phase: 'stuck', stuckReason: errorSentence(e.answer), needsYouReason: null }))
508 } else if (e.reason === 'refusal') {
509 await finish($, list => ({ ...list, phase: 'stuck', stuckReason: REFUSED, needsYouReason: null }))
510 } else if (e.reason === 'aborted') {
511 await finish($, list => ({ ...list, phase: 'stopped', needsYouReason: null }))
512 } else {
513 const atWork = (await $.agent.list().catch(() => [])).filter(agent => AGENT_AT_WORK.has(agent.status)).length
514 await finish($, list => {
515 if (list.phase === 'stuck') return list
516 // No plan means no tools ran (the plan gate): a plain reply, nothing to track.
517 if (!hasPlan(list)) return { ...list, phase: 'idle', needsYouReason: null }
518 // Steps left over need the person only when the turn ended on a question;
519 // with agents still at work, Claude carries on when they report back.
520 if (list.tasks.some(one => one.status !== 'done')) {
521 if (endsWithQuestion(e.answer)) return { ...list, phase: 'needsYou', needsYouReason: ASKED }
522 if (atWork > 0) return { ...list, phase: 'waiting', needsYouReason: null, waitingOn: atWork }
523 const active = list.tasks.find(one => one.status === 'active')
524 if (!list.tasks.some(one => one.status === 'upcoming') && !(active?.hasReported && active.percent < 100)) {
525 const finishedAt = list.finishedAt ?? 0
526 return {
527 ...list,
528 phase: 'done',
529 tasks: list.tasks.map(one => ({
530 ...one,
531 status: 'done',
532 percent: 100,
533 startedAt: one.startedAt ?? finishedAt,
534 finishedAt: one.finishedAt ?? finishedAt,
535 })),
536 needsYouReason: null,
537 }
538 }
539 return { ...list, phase: 'ended', needsYouReason: null }
540 }
541 return { ...list, phase: 'done', needsYouReason: null }
542 })
543 const done = await read($, checklist)
544 if (done.phase === 'done' || done.phase === 'ended') {
545 $.clock.after(COLLAPSE_MS, () => {
546 void edit($, list => (list.startedAt === done.startedAt && list.phase === done.phase ? { ...list, isCollapsed: true } : list))
547 })
548 }
549 }
550 return next(e)
551 })
552
553 for (const component of ['ToolUse', 'ToolResult', 'ToolGroup'] as const) {
554 on('ui.render', { component }, async ($, e, next) => {
555 if (!(await isOn($))) return next(e)
556 const { Box } = $.ui.resolve(e)
557 return <Box display="none" />
558 })
559 }
560
561 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
562 if (!(await isOn($))) return next(e)
563 return next({ ...e, props: { ...e.props, hint: '' } })
564 })
565
566 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
567 if (e.props.hasSurvey) return next(e)
568 const { Box, Text, Button } = $.ui.resolve(e)
569 const isEnabled = await isOn($)
570 const button = (
571 <Button
572 key="clean-view-toggle"
573 label={isEnabled ? '● Clean View: ON' : '○ Clean View: OFF'}
574 onPress={() => setEnabled($, !isEnabled)}
575 />
576 )
577 const list = await read($, checklist)
578 if (!isEnabled || list.phase === 'idle') {
579 return (
580 <Box flexDirection="row" justifyContent="flex-end">
581 {button}
582 </Box>
583 )
584 }
585
586 const isLive = isRunning(list)
587 const frame = isLive ? await read($, tick) : 0
588 const now = isLive ? await $.clock.now() : (list.finishedAt ?? list.startedAt)
589 const took = duration(now - list.startedAt)
590 const header = headerOf(list, took, Text)
591 const firstUpcoming = list.tasks.findIndex(one => one.status === 'upcoming')
592
593 // A blank line above the band keeps it clear of the spinner line.
594 if ((list.phase === 'done' || list.phase === 'ended') && list.isCollapsed) {
595 return (
596 <Box key="clean-view-band" marginTop={1} flexDirection="row" justifyContent="space-between">
597 {header}
598 {button}
599 </Box>
600 )
601 }
602
603 // icon + space, name, space, 10-cell meter, two spaces, 7-cell label, a gap, the Details button
604 const nameWidth = Math.max(8, e.props.bodyColumns - (2 + 1 + METER_CELLS + 2 + 7 + 1 + DETAILS_BUTTON_CELLS))
605 return (
606 <Box key="clean-view-band" marginTop={1} flexDirection="column">
607 <Box key="clean-view-header" flexDirection="row" justifyContent="space-between" marginBottom={1}>
608 {header}
609 {button}
610 </Box>
611 {list.tasks.map((one, i) => (
612 <Box key={`clean-view-task-row-${one.id}`} flexDirection="row" justifyContent="space-between">
613 {row(one, i === firstUpcoming, PAUSED.has(list.phase), frame, nameWidth, Text)}
614 <Button key={`clean-view-task-inspect-${one.id}`} label="Details" onPress={() => void openDetails($, one.id)} />
615 </Box>
616 ))}
617 </Box>
618 )
619 })
620
621 on('ui.focus', { requestId: DETAILS_PANE }, async ($, e, next) => {
622 focusedButton = e.element
623 return next(e)
624 }).catch(($, e, next) => next(e))
625
626 on('ui.scroll', { requestId: DETAILS_PANE }, async ($, e) => {
627 await update($, logScroll, offset => Math.max(0, Math.min(maxLogScroll, (offset ?? 0) + e.by)))
628 return {}
629 }).catch(($, e, next) => next(e))
630
631 on('ui.close', async ($, e, next) => {
632 if (e.id === DETAILS_PANE) await update($, selectedTaskId, () => null)
633 return next(e)
634 })
635
636 // Reading the tick redraws the pane each frame, so its times and progress stay live.
637 on('ui.render', { component: 'Pane', requestId: DETAILS_PANE }, async ($, e) => {
638 const { Box, Text, Button } = $.ui.resolve(e)
639 const list = await read($, checklist)
640 const id = await read($, selectedTaskId)
641 const index = Math.max(0, list.tasks.findIndex(one => one.id === id))
642 const task = list.tasks[index]
643 if (!task) return <Text dimColor>No task to show.</Text>
644 const logs = [...((await read($, taskLogs))[task.id] ?? [])].reverse()
645 const lines = logs.flatMap(entry =>
646 entry.text.split('\n').map((line, i) => ({ key: `${entry.key}-${i}`, kind: entry.kind, text: fit(line, Math.max(10, e.props.bodyColumns - 8)) })),
647 )
648 const innerRows = Math.max(4, Math.min(12, e.props.scroll.bodyRows - 18))
649 maxLogScroll = Math.max(0, lines.length - innerRows)
650 const offset = Math.min(await read($, logScroll), maxLogScroll)
651 const visible = lines.slice(offset, offset + innerRows)
652
653 const isLive = isRunning(list)
654 if (isLive) await read($, tick)
655 const now = isLive ? await $.clock.now() : (list.finishedAt ?? list.startedAt)
656 const isPaused = PAUSED.has(list.phase)
657 const tone = task.status === 'done' ? 'green' : task.status === 'upcoming' ? 'gray' : isPaused ? 'yellow' : 'cyan'
658 const status = label(task, index === list.tasks.findIndex(one => one.status === 'upcoming'), isPaused)
659 const progress = task.status === 'done' ? 'Complete' : task.hasReported ? `${task.percent}% reported` : 'No percentage reported yet'
660 const activity = list.activity
661 ? `${list.activity.summary} · ${list.activity.inProgress ? `for ${duration(now - list.activity.at)}` : `${duration(now - list.activity.at)} ago`}`
662 : 'No visible activity recorded yet'
663 const field = (name: string, value: string, color?: string) => (
664 <Text key={`clean-view-details-${name}`}>
665 <Text dimColor>{name.padEnd(10)}</Text>
666 <Text color={color}>{value}</Text>
667 </Text>
668 )
669
670 return (
671 <Box flexDirection="column" paddingX={2} paddingY={1}>
672 <Text>
673 <Text color={tone}>●</Text> <Text bold>{task.name}</Text> <Text dimColor>{index + 1}/{list.tasks.length}</Text>
674 </Text>
675 <Text> </Text>
676 {field('Status', status, tone)}
677 <Text key="clean-view-details-Progress">
678 <Text dimColor>{'Progress'.padEnd(10)}</Text>
679 <Text color={tone}>{meter(task, 0)}</Text> {progress}
680 </Text>
681 {field('Elapsed', taskElapsed(task, list.finishedAt ?? now))}
682 {field('Activity', activity)}
683 <Text> </Text>
684 <Text>
685 <Text bold>Step log · newest first</Text>
686 {lines.length > innerRows && <Text dimColor>{` ${offset + 1}-${offset + visible.length} of ${lines.length} (scroll to view)`}</Text>}
687 </Text>
688 <Box borderStyle="round" borderDimColor flexDirection="column" height={innerRows + 2} overflow="hidden" paddingX={1}>
689 {visible.length === 0 ? (
690 <Text dimColor>Nothing recorded for this step yet</Text>
691 ) : (
692 visible.map(line => (
693 <Text key={`clean-view-log-${line.key}`} color={line.kind === 'error' ? 'red' : undefined} dimColor={line.kind === 'result'}>{line.text}</Text>
694 ))
695 )}
696 </Box>
697 <Text> </Text>
698 <Box flexDirection="column">
699 <Button key="clean-view-details-prev" label="Previous task" autoFocus={focusedButton === 'clean-view-details-prev' || undefined} onPress={() => void pageDetails($, -1)} />
700 <Button key="clean-view-details-next" label="Next task" autoFocus={focusedButton === 'clean-view-details-next' || undefined} onPress={() => void pageDetails($, 1)} />
701 {isLive && mainTurnId !== undefined && (
702 <Button key="clean-view-details-stop" label="Stop entire run" autoFocus={focusedButton === 'clean-view-details-stop' || undefined} onPress={() => void $.turn.abort({ turnId: mainTurnId! })} />
703 )}
704 <Button key="clean-view-details-close" label="Close" autoFocus={focusedButton === 'clean-view-details-close' || undefined} onPress={() => void $.ui.close({ id: DETAILS_PANE })} />
705 </Box>
706 <Text dimColor>Stop ends the entire run · Esc closes this pane</Text>
707 </Box>
708 )
709 })
710}
711
712type TextElement = ReturnType<EngineInterface['ui']['resolve']>['Text']
713
714function headerOf(list: CleanViewChecklist, took: string, Text: TextElement) {
715 switch (list.phase) {
716 case 'needsYou':
717 return (
718 <Text>
719 <Text bold color="black" backgroundColor="yellow">
720 {' Needs you '}
721 </Text>{' '}
722 {list.needsYouReason ?? WAITING}
723 </Text>
724 )
725 case 'stuck':
726 return <Text color="yellow">⚠ Stuck: {list.stuckReason}</Text>
727 case 'stopped':
728 return <Text>■ Stopped · {list.title} · you pressed Esc</Text>
729 case 'waiting':
730 return (
731 <Text>
732 ⏳ Waiting on {list.waitingOn ?? 1} background agent{list.waitingOn === 1 ? '' : 's'} · {list.title}
733 </Text>
734 )
735 case 'ended':
736 return (
737 <Text>
738 ■ Ended · {list.title} · {list.tasks.filter(one => one.status === 'done').length} of {list.tasks.length} steps done
739 </Text>
740 )
741 case 'done':
742 return (
743 <Text>
744 <Text color="green">✓ All done</Text> · {list.title} · took {took}
745 </Text>
746 )
747 default:
748 return (
749 <Text>
750 <Text bold>{list.title === PLACEHOLDER_TITLE ? list.activity?.summary ?? 'Thinking...' : list.title}</Text> · {took}
751 </Text>
752 )
753 }
754}
755
756function row(one: CleanViewTask, isFirstUpcoming: boolean, isPaused: boolean, frame: number, width: number, Text: TextElement) {
757 const name = fit(one.name, width)
758 const bar = meter(one, frame)
759 const tag = label(one, isFirstUpcoming, isPaused)
760 if (one.status === 'done') {
761 return (
762 <Text key={one.id}>
763 <Text color="green">✓</Text> <Text dimColor>{name}</Text> <Text color="green">{bar}</Text> <Text dimColor>{tag}</Text>
764 </Text>
765 )
766 }
767 if (one.status === 'active') {
768 return (
769 <Text key={one.id}>
770 <Text color="cyan">{isPaused ? '‖' : '▶'}</Text> <Text bold>{name}</Text> <Text color="cyan">{bar}</Text> {tag}
771 </Text>
772 )
773 }
774 return (
775 <Text key={one.id} dimColor>
776 ○ {name} {bar} {tag}
777 </Text>
778 )
779}
780hooks/logic.ts 330 lines1import type { CleanViewChecklist, CleanViewLogEntry, CleanViewTask } from '../types'
2
3export const MAX_NAME = 40
4export const METER_CELLS = 10
5export const FALLBACK_NAME = 'Working on it'
6export const PLACEHOLDER_PREFIX = 'placeholder-'
7
8const CODE_FILE =
9 /\.(tsx?|jsx?|mjs|cjs|mts|cts|py|go|rs|rb|java|kt|swift|c|cc|cpp|h|hpp|cs|php|sh|bash|zsh|json|ya?ml|toml|md|html?|css|scss|sql|lock|xml|ini|env|vue|svelte)[)\].,:;!?'"]*$/i
10
11/** One plain name: no code, no paths, no file names, at most 40 characters. */
12export function cleanName(raw: string): string {
13 const words = raw
14 .replace(/`[^`]*`/g, ' ')
15 .replace(/`/g, ' ')
16 .split(/\s+/)
17 .filter(word => word !== '' && !/[/\\]/.test(word) && !CODE_FILE.test(word))
18 let name = words.join(' ').trim()
19 if (name === '') return FALLBACK_NAME
20 name = name[0].toUpperCase() + name.slice(1)
21 if (name.length <= MAX_NAME) return name
22 const cut = name.slice(0, MAX_NAME - 1)
23 const space = cut.lastIndexOf(' ')
24 return `${(space > 0 ? cut.slice(0, space) : cut).trimEnd()}…`
25}
26
27export function clampPercent(percent: number): number {
28 if (!Number.isFinite(percent)) return 0
29 return Math.round(Math.min(100, Math.max(0, percent)))
30}
31
32export const EMPTY: CleanViewChecklist = {
33 title: '',
34 phase: 'idle',
35 tasks: [],
36 activity: null,
37 needsYouReason: null,
38 stuckReason: null,
39 startedAt: 0,
40 finishedAt: null,
41 isCollapsed: false,
42}
43
44export function isRunning(list: CleanViewChecklist): boolean {
45 return list.phase === 'working' || list.phase === 'needsYou' || (list.phase === 'stuck' && list.finishedAt === null)
46}
47
48export function hasPlan(list: CleanViewChecklist): boolean {
49 return list.tasks.length > 0 && list.tasks.every(task => !task.id.startsWith(PLACEHOLDER_PREFIX))
50}
51
52function task(id: string, name: string, status: CleanViewTask['status'], at?: number): CleanViewTask {
53 return {
54 id,
55 name,
56 status,
57 percent: status === 'done' ? 100 : 0,
58 hasReported: false,
59 ...(status !== 'upcoming' && at !== undefined ? { startedAt: at } : {}),
60 ...(status === 'done' && at !== undefined ? { finishedAt: at } : {}),
61 }
62}
63
64export function newJob(startedAt: number, title: string): CleanViewChecklist {
65 return {
66 ...EMPTY,
67 title,
68 phase: 'working',
69 startedAt,
70 activity: { summary: 'Thinking...', at: startedAt, inProgress: true },
71 tasks: [task(`${PLACEHOLDER_PREFIX}thinking`, 'Thinking...', 'active', startedAt)],
72 }
73}
74
75/** Lays out the plan: steps already done stay done, and the first unfinished one starts now. */
76export function planSteps(list: CleanViewChecklist, steps: readonly string[], at = list.startedAt, title?: string): CleanViewChecklist {
77 const kept = new Map(list.tasks.map(one => [one.name.toLowerCase(), one]))
78 const names = steps.map(cleanName).slice(0, 8)
79 let tasks = (names.length > 0 ? names : [FALLBACK_NAME]).map((name, i): CleanViewTask => {
80 const before = kept.get(name.toLowerCase())
81 if (before?.status === 'done') {
82 return {
83 ...task(`step-${i}-${name}`, name, 'done', at),
84 startedAt: before.startedAt ?? at,
85 finishedAt: before.finishedAt ?? at,
86 }
87 }
88 return {
89 ...task(`step-${i}-${name}`, name, 'upcoming'),
90 ...(before?.startedAt !== undefined ? { startedAt: before.startedAt } : {}),
91 }
92 })
93 const first = tasks.findIndex(one => one.status !== 'done')
94 if (first !== -1) {
95 tasks = tasks.map((one, i) => (i === first ? { ...one, status: 'active', startedAt: one.startedAt ?? at } : one))
96 }
97 const nextTitle = title?.trim() ? cleanName(title) : list.title
98 return { ...list, title: nextTitle, tasks }
99}
100
101function same(a: string, b: string): boolean {
102 return a.toLowerCase() === b.toLowerCase()
103}
104
105/** Every step from `index` on: the one at `index` active, the rest upcoming unless done. */
106function activate(tasks: CleanViewTask[], index: number, percent: number, hasReported: boolean, at: number): CleanViewTask[] {
107 return tasks.map((one, i) => {
108 if (i < index) {
109 return {
110 ...one,
111 status: 'done',
112 percent: 100,
113 startedAt: one.startedAt ?? at,
114 finishedAt: one.finishedAt ?? at,
115 }
116 }
117 if (i === index) {
118 return {
119 ...one,
120 status: 'active',
121 percent,
122 hasReported,
123 startedAt: one.startedAt ?? at,
124 finishedAt: undefined,
125 }
126 }
127 return one.status === 'active' ? { ...one, status: 'upcoming', finishedAt: undefined } : one
128 })
129}
130
131/** Moves the plan forward for a report on `name`: earlier steps check off, 100 starts the next. */
132export function reportProgress(list: CleanViewChecklist, name: string, percent: number, at = list.startedAt): CleanViewChecklist {
133 const clean = cleanName(name)
134 const p = clampPercent(percent)
135 let tasks = list.tasks.filter(one => !one.id.startsWith(PLACEHOLDER_PREFIX))
136 let index = tasks.findIndex(one => same(one.name, clean))
137 if (index === -1) {
138 const active = tasks.findIndex(one => one.status === 'active')
139 index = active === -1 ? tasks.length : active
140 tasks = [...tasks.slice(0, index), task(`step-x${tasks.length}-${clean}`, clean, 'upcoming'), ...tasks.slice(index)]
141 }
142 tasks = activate(tasks, index, p, true, at)
143 if (p >= 100) {
144 tasks = tasks.map((one, i) =>
145 i === index
146 ? { ...one, status: 'done', percent: 100, startedAt: one.startedAt ?? at, finishedAt: one.finishedAt ?? at }
147 : one,
148 )
149 const next = tasks.findIndex((one, i) => i > index && one.status !== 'done')
150 if (next !== -1) tasks = activate(tasks, next, 0, false, at)
151 }
152 return { ...list, tasks }
153}
154
155type TodoItem = { content: string; status: 'pending' | 'in_progress' | 'completed'; activeForm?: string }
156
157/** A to-do list as the plan: completed rows done, the in-progress one active. */
158export function fromTodos(list: CleanViewChecklist, todos: readonly TodoItem[], at = list.startedAt): CleanViewChecklist {
159 const kept = new Map(list.tasks.map(one => [one.name.toLowerCase(), one]))
160 let tasks = todos.map((todo, i): CleanViewTask => {
161 const name = cleanName(todo.content)
162 const before = kept.get(name.toLowerCase())
163 if (todo.status === 'completed') {
164 return {
165 ...task(`todo-${i}-${name}`, name, 'done', at),
166 startedAt: before?.startedAt ?? at,
167 finishedAt: before?.finishedAt ?? at,
168 }
169 }
170 if (todo.status === 'in_progress') {
171 return {
172 id: `todo-${i}-${name}`,
173 name,
174 status: 'active',
175 percent: before?.percent ?? 0,
176 hasReported: before?.hasReported ?? false,
177 startedAt: before?.startedAt ?? at,
178 }
179 }
180 return task(`todo-${i}-${name}`, name, 'upcoming')
181 })
182 if (!tasks.some(one => one.status === 'active')) {
183 const first = tasks.findIndex(one => one.status === 'upcoming')
184 if (first !== -1) {
185 tasks = tasks.map((one, i) => (i === first ? { ...one, status: 'active', startedAt: one.startedAt ?? at } : one))
186 }
187 }
188 return { ...list, tasks }
189}
190
191/** A task the TaskCreate tool made, added as an upcoming row (or the active one if none is). */
192export function addTask(list: CleanViewChecklist, id: string, subject: string, at = list.startedAt): CleanViewChecklist {
193 const tasks = list.tasks.filter(one => !one.id.startsWith(PLACEHOLDER_PREFIX))
194 const status = tasks.some(one => one.status === 'active') ? 'upcoming' : 'active'
195 return { ...list, tasks: [...tasks, task(`task-${id}`, cleanName(subject), status, at)] }
196}
197
198/** A TaskUpdate: its new status and subject on the matching row. */
199export function updateTask(
200 list: CleanViewChecklist,
201 id: string,
202 status: 'pending' | 'in_progress' | 'completed' | 'deleted' | undefined,
203 subject: string | undefined,
204 at = list.startedAt,
205): CleanViewChecklist {
206 const key = `task-${id}`
207 const index = list.tasks.findIndex(one => one.id === key)
208 if (index === -1) return list
209 if (status === 'deleted') return { ...list, tasks: list.tasks.filter(one => one.id !== key) }
210 let tasks = list.tasks.map(one => (one.id === key && subject !== undefined ? { ...one, name: cleanName(subject) } : one))
211 if (status === 'in_progress') {
212 tasks = tasks.map((one, i) =>
213 i === index
214 ? { ...one, status: 'active', startedAt: one.startedAt ?? at, finishedAt: undefined }
215 : one.status === 'active'
216 ? { ...one, status: 'upcoming', finishedAt: undefined }
217 : one,
218 )
219 } else if (status === 'completed') {
220 tasks = tasks.map((one, i) =>
221 i === index
222 ? { ...one, status: 'done', percent: 100, startedAt: one.startedAt ?? at, finishedAt: one.finishedAt ?? at }
223 : one,
224 )
225 if (!tasks.some(one => one.status === 'active')) {
226 const next = tasks.findIndex(one => one.status === 'upcoming')
227 if (next !== -1) {
228 tasks = tasks.map((one, i) => (i === next ? { ...one, status: 'active', startedAt: one.startedAt ?? at } : one))
229 }
230 }
231 } else if (status === 'pending') {
232 tasks = tasks.map((one, i) =>
233 i === index ? { ...one, status: 'upcoming', percent: 0, startedAt: undefined, finishedAt: undefined } : one,
234 )
235 }
236 return { ...list, tasks }
237}
238
239/** The calm sentence for a turn an API error ended. */
240export function errorSentence(answer: string): string {
241 if (/rate.?limit|usage limit|\b429\b|quota/i.test(answer)) return 'you hit your usage limit, try again a little later'
242 if (/overload|\b529\b|capacity/i.test(answer)) return "Claude's servers are busy, try again in a minute"
243 if (/too long|context (window|length|limit)|maximum context/i.test(answer)) return 'type /compact and try again'
244 if (/network|connection|econn|fetch failed|socket|offline|timed? ?out|dns/i.test(answer)) return 'the internet connection dropped'
245 if (/auth|\b401\b|\b403\b|log ?in|api key|oauth|credential/i.test(answer)) return 'type /login'
246 return 'something went wrong talking to Claude, try again'
247}
248
249export function isUserRejection(text: string | undefined): boolean {
250 return text !== undefined && /doesn.t want to proceed|was rejected|user (denied|rejected|declined)/i.test(text)
251}
252
253export function duration(ms: number): string {
254 const seconds = Math.max(0, Math.floor(ms / 1000))
255 const m = Math.floor(seconds / 60)
256 const s = seconds % 60
257 return m > 0 ? `${m}m ${s}s` : `${s}s`
258}
259
260export function taskElapsed(one: CleanViewTask, now: number): string {
261 if (one.status === 'upcoming' || one.startedAt === undefined) return 'Not started yet'
262 return duration((one.finishedAt ?? now) - one.startedAt)
263}
264
265/** Ten cells: full, filled to the percent, a moving sweep, or empty. */
266export function meter(one: CleanViewTask, frame: number): string {
267 if (one.status === 'done') return '█'.repeat(METER_CELLS)
268 if (one.status === 'upcoming') return '░'.repeat(METER_CELLS)
269 if (!one.hasReported) {
270 const at = frame % METER_CELLS
271 return Array.from({ length: METER_CELLS }, (_, i) => ((i - at + METER_CELLS) % METER_CELLS < 3 ? '█' : '░')).join('')
272 }
273 const filled = Math.round(one.percent / 10)
274 // Between reports the next cell pulses, so a step waiting on its next report still looks alive.
275 if (filled >= METER_CELLS || frame % 2 === 0) return '█'.repeat(filled) + '░'.repeat(METER_CELLS - filled)
276 return '█'.repeat(filled) + '▒' + '░'.repeat(METER_CELLS - filled - 1)
277}
278
279// Modes that settle a permission ask with nobody asked: a classifier, a bypass, a refusal.
280const SETTLED_ALONE = new Set(['auto', 'bypassPermissions', 'dontAsk'])
281
282/** True when an ask in this permission mode opens a dialog for the person; an unknown mode might. */
283export function asksPerson(mode: string | undefined): boolean {
284 return mode === undefined || !SETTLED_ALONE.has(mode)
285}
286
287/** True when a turn's last words put a question to the person. */
288export function endsWithQuestion(answer: string): boolean {
289 return answer.trim().endsWith('?')
290}
291
292export function label(one: CleanViewTask, isFirstUpcoming: boolean, isPaused = false): string {
293 if (one.status === 'done') return 'Done'
294 if (one.status === 'active' && isPaused) return 'Paused'
295 if (one.status === 'active') return one.hasReported ? `${one.percent}%` : 'Working'
296 return isFirstUpcoming ? 'Next' : 'Up next'
297}
298
299// The newest entries a step's raw log keeps, and the characters each summary line keeps.
300export const LOG_ENTRIES = 200
301export const LOG_ENTRY_CHARS = 160
302
303const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g
304const CONTROL = /[\x00-\x08\x0b-\x1f\x7f-\x9f\ud800-\udfff\u{10eeee}]/gu
305
306function sanitizeLog(text: string): string {
307 return text.slice(0, LOG_ENTRY_CHARS * 4).replace(ANSI, '').replace(/[\r\n\t]+/g, ' ').toWellFormed().replace(CONTROL, '')
308}
309
310function clip(text: string): string {
311 const clean = sanitizeLog(text)
312 return clean.length <= LOG_ENTRY_CHARS ? clean : `${clean.slice(0, LOG_ENTRY_CHARS).toWellFormed()}…`
313}
314
315/**
316 * Adds `text` to the last entry when it has the same `key` (a block streaming
317 * in pieces), else a new entry at the end; keeps the newest LOG_ENTRIES.
318 */
319export function appendLog(log: readonly CleanViewLogEntry[], kind: CleanViewLogEntry['kind'], key: string, text: string): CleanViewLogEntry[] {
320 const last = log.at(-1)
321 if (last?.key === key) return [...log.slice(0, -1), { ...last, text: clip(last.text + text) }]
322 return [...log, { kind, key, text: clip(text) }].slice(-LOG_ENTRIES)
323}
324
325/** A name sized to the column: cut with "…" when it would wrap, padded otherwise. */
326export function fit(name: string, width: number): string {
327 if (name.length <= width) return name.padEnd(width)
328 return `${name.slice(0, Math.max(0, width - 1)).toWellFormed()}…`
329}
330types/index.d.ts 54 lines1export type CleanViewTaskStatus = 'done' | 'active' | 'upcoming'
2
3export type CleanViewActivity = {
4 summary: string
5 at: number
6 inProgress: boolean
7}
8
9export type CleanViewTask = {
10 id: string
11 name: string
12 status: CleanViewTaskStatus
13 percent: number
14 hasReported: boolean
15 startedAt?: number
16 finishedAt?: number
17}
18
19/** One item of a step's raw log: a thinking block, a tool call as the model wrote it, or a tool's result. */
20export type CleanViewLogEntry = {
21 kind: 'thinking' | 'call' | 'result' | 'error'
22 key: string
23 text: string
24}
25
26export type CleanViewPhase = 'idle' | 'working' | 'needsYou' | 'stuck' | 'stopped' | 'waiting' | 'ended' | 'done'
27
28export type CleanViewChecklist = {
29 title: string
30 phase: CleanViewPhase
31 tasks: CleanViewTask[]
32 activity: CleanViewActivity | null
33 needsYouReason: string | null
34 stuckReason: string | null
35 startedAt: number
36 finishedAt: number | null
37 isCollapsed: boolean
38 /** Background agents still at work when the turn ended (phase `waiting`). */
39 waitingOn?: number
40}
41
42declare module 'claude-code' {
43 interface PluginState {
44 'clean-view': {
45 cleanViewEnabled: boolean
46 checklist: CleanViewChecklist
47 selectedTaskId: string | null
48 taskLogs: Record<string, CleanViewLogEntry[]>
49 logScroll: number
50 tick: number
51 }
52 }
53}
54