Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Plan: ask only once the plan's pictures show; edit on a Mac without open -W

razorback16e75763c697ba
diff --git a/docs/usage.md b/docs/usage.md
index 779285c..a15f9f6 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -192,14 +192,14 @@ When Claude exits plan mode, the mod draws the plan in the transcript. Under it,
| Yes, auto-accept edits | Approves. Claude Code then accepts file edits without asking (`acceptEdits` mode). |
| Yes, manually approve edits | Approves. Claude Code asks before each file edit (`default` mode). |
| Yes, clear context + auto-accept | Approves, stops the turn and runs `/clear`. Then sends "Implement this plan:" with the plan as a new prompt, in `acceptEdits` mode. |
-| Edit the plan | Opens the plan file in an editor and waits until you close it (10 minutes at most). Then asks "Approve the edited plan?". Claude gets the edited plan. |
+| Edit the plan | Opens the plan file in an editor and waits until you close it (10 minutes at most). On macOS without `code`, it waits until you choose "Done editing". Then asks "Approve the edited plan?". Claude gets the edited plan. |
| Type something | Sends your text to Claude as changes. Claude stays in plan mode and writes a new plan. |
| Esc | Rejects the plan and stops the turn. |
-**Editor.** VS Code (`code --wait`) when `code` is on your PATH. Else, on macOS, TextEdit (quit TextEdit when you are done). On Linux with a display, the first of VSCodium, Zed, Sublime Text, Kate, gedit and gvim on your PATH (close the file or window when you are done). Over ssh without `code`, or on Linux with none of these, "Edit the plan" does not show.
+**Editor.** VS Code (`code --wait`) when `code` is on your PATH. Else, on macOS, your default text editor (TextEdit if you did not change it). Save the file, then choose "Done editing". "Open the plan file again" opens it again if you closed it. On Linux with a display, the first of VSCodium, Zed, Sublime Text, Kate, gedit and gvim on your PATH (close the file or window when you are done). Over ssh without `code`, or on Linux with none of these, "Edit the plan" does not show.
**The plan you see is the plan Claude gets.** If Claude writes the plan file and exits plan mode in the same message, the mod waits for the write (5 s at most) and reads the file again.
-**When it applies.** Only when the mod can draw the plan: the mod is on, Typst is installed, the terminal shows pictures, and the plan is from the main conversation (not a subagent). Otherwise, or if the flow fails, Claude Code shows its own dialog.
+**When it applies.** Only when the mod can draw the plan: the mod is on, Typst is installed, the terminal shows pictures, and the plan is from the main conversation (not a subagent). The question waits until the pictures of the plan show (45 s at most). Otherwise, Claude Code shows its own dialog with the plan as text. This also occurs if the pictures do not show (for example, Typst fails, or over ssh a page is too large) or if the flow fails. After you edit the plan, the mod asks "Approve the edited plan?" also when its pictures do not show, so that Claude gets your edit. A toast tells you.
For the limits, see [Limitations](limitations.md).
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index 83ce24b..8c2dd3c 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -263,7 +263,8 @@ async function convertOnce($: EngineInterface, ready: Env, file: string, stamp:
await write($, `${dir}/source.txt`, `${file}\n`).catch(() => undefined)
// Typst writes a part file, moved to image.png only once it is whole, so
// a run that is killed or fails leaves no image.png for a later load.
- const part = `${dir}/image.part.png`
+ // Its own name per run: another session or load may convert the same key at once.
+ const part = `${dir}/image-${Math.random().toString(36).slice(2, 10)}.part.png`
const { argv, env } = convertCall({ typst: ready.typst!, root: ready.root, cache: ready.cache, file, box, out: part, page: pdf?.page })
const failed = (err: unknown) => ({ exitCode: 1, stdout: '', stderr: `did not run: ${String(err)}` })
const ran = await exec($, argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)
diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsx
index d3a1891..6ccba53 100644
--- a/hooks/lib/plan.tsx
+++ b/hooks/lib/plan.tsx
@@ -8,15 +8,17 @@
// engine's dialog never shows. An allow is honoured for this tool only with
// `updatedInput`, and its `setMode` ends plan mode. The rendered plan is in
// the ExitPlanMode ToolUse row, which the engine draws above the question.
+// The question waits for the plan's pictures; with none, the mod gives no
+// verdict and the engine's dialog (which shows the plan's text) asks.
import type { EngineInterface, PermissionRequestDecision, RenderComponent, RenderElement, RenderViewport, ResolveInput } from 'claude-code'
-import { GUTTER, bulletOf } from './settings'
+import { COMPILE_TIMEOUT_MS, GUTTER, bulletOf } from './settings'
import { S, writesLive } from './state'
import { firstLine } from './markdown'
import type { Drawing } from './answer'
import { drawPages, type ShownLink } from './draw'
-import { delay, runCmd, getenv, cat, exec, send, abort, ask, uiResolve } from './api'
-import { pathsOf } from './open'
+import { delay, runCmd, getenv, cat, exec, send, abort, ask, toast, uiResolve } from './api'
+import { OPEN_TIMEOUT_MS, pathsOf } from './open'
// The question's chip and its two wordings.
export const PLAN_HEADER = 'Plan'
@@ -27,11 +29,18 @@ export const PLAN_AUTO = 'Yes, auto-accept edits'
export const PLAN_MANUAL = 'Yes, manually approve edits'
export const PLAN_CLEAR = 'Yes, clear context + auto-accept'
export const PLAN_EDIT = 'Edit the plan'
+// The question while a Mac's text editor has the plan file open (`open`
+// does not wait), and its options.
+export const PLAN_EDITING = 'Save the plan in the editor, then choose Done editing.'
+export const PLAN_DONE = 'Done editing'
+export const PLAN_REOPEN = 'Open the plan file again'
// The line above Intelligent UI's question (the dialog takes 12 rows at most
// around it, so the plan itself is in the ToolUse row above).
export const PLAN_ASK_LINE = 'Intelligent UI: the rendered plan is above'
// The line in the ToolUse row while the plan's pictures compile.
export const PLAN_DRAWING = 'Intelligent UI: drawing the plan...'
+// The toast when a plan asked again after an edit has no pictures.
+export const PLAN_EDITED_UNDRAWN = "Intelligent UI: the edited plan's pictures did not draw; it is the text you saved"
// What the model reads when the person rejects the plan (Esc) or types changes.
export const PLAN_REJECTED = 'The user rejected the plan.'
export const PLAN_FEEDBACK = 'The user wants changes to the plan:'
@@ -42,6 +51,9 @@ export const EDIT_TIMEOUT_MS = 600000
// How long the plan waits for a Write or Edit of its file still running.
export const PLAN_WRITE_WAIT_MS = 5000
export const PLAN_WRITE_POLL_MS = 25
+// How long the question waits for the plan's pictures: a compile and its
+// retry in safe mode, and a moment in the queue.
+export const PLAN_DRAW_WAIT_MS = 2 * COMPILE_TIMEOUT_MS + 5000
// The delay before "clear context" acts: `$.command.run` rejects inside a hook
// the turn waits on, so it runs detached once the call has resolved.
export const CLEAR_DELAY_MS = 50
@@ -144,19 +156,23 @@ export function decisionOf(verdict: PlanVerdict, toolInput: unknown): Permission
return { behavior: 'allow', updatedInput: input, updatedPermissions: [{ type: 'setMode', mode: verdict.mode, destination: 'session' }] }
}
-// The editor that opens the plan file and waits until it is closed: VS Code
-// (`code --wait`) when it is on the PATH, else TextEdit on a Mac (`open -W`
-// waits until TextEdit quits), else on Linux a GUI editor that waits
-// (`gui`: its path and flag, LINUX_EDITORS). Not over ssh, where TextEdit
-// or the GUI editor is the remote computer's. A mod has no terminal, so no
+// The editor that opens the plan file: VS Code (`code --wait`) when it is on
+// the PATH, else on a Mac the default text editor (`open -t`: it does not
+// wait, as `open -W` waits until the whole app quits, not the window; the
+// person says when they are done, PLAN_EDITING), else on Linux a GUI editor
+// that waits (`gui`: its path and flag, LINUX_EDITORS). Not over ssh, where
+// that editor is the remote computer's. A mod has no terminal, so no
// terminal editor; xdg-open does not wait, so it is not used.
export function editorArgv(o: { code: string; isMac: boolean; isRemote: boolean; gui?: readonly string[] }, file: string): string[] | null {
if (o.code) return [o.code, '--wait', file]
- if (o.isMac && !o.isRemote) return ['open', '-W', '-t', file]
+ if (o.isMac && !o.isRemote) return ['open', '-t', file]
if (!o.isMac && !o.isRemote && o.gui?.length) return [...o.gui, file]
return null
}
+// Whether the editor's command returns only once the file is closed (not `open`).
+export const editorWaits = (argv: readonly string[]) => argv[0] !== 'open'
+
// The GUI editors on Linux that can wait until the file is closed, in the
// order they are looked for, with the flag that makes them wait.
export const LINUX_EDITORS: readonly (readonly [string, string])[] = [
@@ -197,18 +213,25 @@ async function findGuiEditor($: EngineInterface): Promise<string[]> {
return found
}
-// What the mod's question decided: a verdict for the PermissionRequest, or
-// the person's words (a deny of the call: Claude revises the plan).
-export type PlanOutcome = { kind: 'verdict'; verdict: PlanVerdict } | { kind: 'feedback'; message: string }
+// What the mod's question decided: a verdict for the PermissionRequest, the
+// person's words (a deny of the call: Claude revises the plan), or nothing
+// (`engine`: the plan's pictures did not draw, so the engine's dialog asks).
+export type PlanOutcome = { kind: 'verdict'; verdict: PlanVerdict } | { kind: 'feedback'; message: string } | { kind: 'engine' }
// Asks the mod's question about the plan, as often as the person edits it.
// `plan` is the text to ask about, `callPlan` the one the call carried (an
// approval sends `plan` when they differ). `onEdited` gets each edited text
-// (the ToolUse row draws it). Esc (the ask rejects; in a terminal session
-// that is a dismissal) rejects the plan.
+// (the ToolUse row draws it). `isDrawn` waits for a text's pictures: the
+// first ask needs them (else the engine's dialog asks); an ask after an edit
+// does not, as the engine's dialog would show the call's text and drop the
+// edit (the person wrote it; a toast says so). Esc (the ask rejects; in a
+// terminal session that is a dismissal) rejects the plan.
export async function decidePlan(
$: EngineInterface,
- o: { plan: string; callPlan: string; file: string; isMac: boolean; isRemote: boolean; onEdited: (plan: string) => void },
+ o: {
+ plan: string; callPlan: string; file: string; isMac: boolean; isRemote: boolean
+ onEdited: (plan: string) => void; isDrawn: (plan: string) => Promise<boolean>
+ },
): Promise<PlanOutcome> {
const code = o.file ? await findCode($) : ''
const gui = o.file && !code && !o.isMac && !o.isRemote ? await findGuiEditor($) : []
@@ -216,7 +239,14 @@ export async function decidePlan(
const canEdit = !!argv
let plan = o.plan
let isEdited = false
- for (;;) {
+ for (let isFirst = true; ; isFirst = false) {
+ // No pictures (a failed compile, a page too big over ssh, none in time): the engine's dialog shows the text.
+ if (!(await o.isDrawn(plan))) {
+ if (isFirst) return { kind: 'engine' }
+ try {
+ toast($, PLAN_EDITED_UNDRAWN, { timeoutMs: 8000 })
+ } catch {}
+ }
const question = isEdited ? PLAN_QUESTION_EDITED : PLAN_QUESTION
let answer: string
S.planAsking = question
@@ -230,7 +260,14 @@ export async function decidePlan(
const choice = choiceOf(answer, canEdit)
if (choice.kind === 'feedback') return { kind: 'feedback', message: feedbackOf(choice.text) }
if (choice.kind !== 'edit') return { kind: 'verdict', verdict: verdictOf(choice, plan, plan !== o.callPlan)! }
- await exec($, argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)
+ const waits = editorWaits(argv!)
+ await exec($, argv!, { timeoutMs: waits ? EDIT_TIMEOUT_MS : OPEN_TIMEOUT_MS }).catch(() => null)
+ // `open` returns at once: the file is read when the person is done (Esc too).
+ while (!waits) {
+ const done = await ask($, PLAN_EDITING, { header: PLAN_HEADER, options: [PLAN_DONE, PLAN_REOPEN] }).catch(() => PLAN_DONE)
+ if (done !== PLAN_REOPEN) break
+ await exec($, argv!, { timeoutMs: OPEN_TIMEOUT_MS }).catch(() => null)
+ }
const text = await cat($, o.file).catch(() => null)
if (typeof text === 'string' && text.trim() && text !== plan) {
plan = text
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index d346acd..11574da 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -285,6 +285,8 @@ export const live = new Map<string, { job: Job; still: { cancel: () => void } }>
export const finalized = new Set<string>()
// A final block not drawn yet: blank until `showText` (its deadline passed).
export const pending = new Map<string, { textHash: string; showText: boolean; timer: { cancel: () => void } }>()
+// Called once when the next compile ends, cancelled or not (the plan waits on it).
+export const jobEnds = new Set<() => void>()
// The jobs waiting, and the jobs that compile now by key (with the cancel
// of each: beginEpoch stops them; and its signal: an entry cancelled still
// holds its slot until its compile ends, but its key may be enqueued again).
diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.ts
index fe8b754..e8b726a 100644
--- a/hooks/lib/stream.ts
+++ b/hooks/lib/stream.ts
@@ -6,7 +6,7 @@
import type { EngineInterface } from 'claude-code'
import { BLANK_AFTER_LIVE_MS, MAX_RUNNING, RESULTS_KEPT } from './settings'
-import { finalized, keep, keepIn, live, pending, queue, refresh, results, running, S, type Job } from './state'
+import { finalized, jobEnds, keep, keepIn, live, pending, queue, refresh, results, running, S, type Job } from './state'
import { hashOf } from './draw'
import { noteDesign, recordDesign } from './designs'
import { compile, logDebug } from './typst'
@@ -55,6 +55,10 @@ export function pump($: EngineInterface) {
}
// A new run of the same key may have taken the entry.
if (running.get(job.key) === entry) running.delete(job.key)
+ for (const end of [...jobEnds]) {
+ jobEnds.delete(end)
+ end()
+ }
// A cancelled compile draws nothing new: no redraw.
if (result !== 'cancelled') jobDone($)
pump($)
diff --git a/hooks/register.tsx b/hooks/register.tsx
index aec579d..9de4ac4 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -25,7 +25,7 @@ import {
DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
SELECT_SINCE, selectText, typstHintOf, widthText,
} from './lib/settings'
-import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, keep, ownCopy, queue, refresh, running, S, settingsSet, subagentPlans, writesLive, type Env, type Job } from './lib/state'
+import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, jobEnds, keep, ownCopy, pending, queue, refresh, running, S, settingsSet, subagentPlans, writesLive, type Env, type Job } from './lib/state'
import { beginEpoch } from './lib/epoch'
import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'
import { applyTheme, themeListing, userThemesOf } from './lib/themes'
@@ -54,11 +54,11 @@ import { onScreenOf, pastedNumbers, sentFiles } from './lib/images'
import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'
import { drawPreviews, forgetPaths, keepPaths, pathPaste, pathsOf, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'
import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'
-import { nowMs, write, surf, save, copy, uiSelection, toast, sid, exec } from './lib/api'
+import { nowMs, write, surf, save, copy, uiSelection, toast, sid, exec, delay } from './lib/api'
import { detachedArgv, editorNow, OPEN_TIMEOUT_MS, openArgv, openedText, useName, type Use } from './lib/open'
import {
currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,
- planShownOf, scheduleClear, type PlanVerdict,
+ planShownOf, PLAN_DRAW_WAIT_MS, scheduleClear, type PlanVerdict,
} from './lib/plan'
// The names this module exported before the split (the tests import them).
@@ -107,9 +107,9 @@ export {
UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,
} from './lib/updates'
export {
- choiceOf, decisionOf, editorArgv, feedbackOf, guiEditorOf, LINUX_EDITORS, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,
- PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,
- planOf, planOptions, planShownOf, shortPath, verdictOf, type PlanChoice, type PlanVerdict,
+ choiceOf, decisionOf, editorArgv, editorWaits, feedbackOf, guiEditorOf, LINUX_EDITORS, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DONE,
+ PLAN_DRAW_WAIT_MS, PLAN_DRAWING, PLAN_EDIT, PLAN_EDITED_UNDRAWN, PLAN_EDITING, PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED,
+ PLAN_REJECTED, PLAN_REOPEN, planFileOf, planInputOf, planOf, planOptions, planShownOf, shortPath, verdictOf, type PlanChoice, type PlanVerdict,
} from './lib/plan'
// The atoms the hooks read and write (a copy of each in this file: see state.ts).
@@ -259,6 +259,40 @@ async function planDrawing(
return drawn
}
+// Whether a plan's pictures show (pages; over ssh each page can go): its
+// compile is waited for, at most PLAN_DRAW_WAIT_MS. False for a compile that
+// failed, a page too big for `{ png }`, or none in time: the engine's dialog
+// asks, as it shows the plan's text. The pages are the ToolUse row's (the
+// same text, id and Frame, at the last viewport noted: one compile).
+async function planShows($: EngineInterface, toolUseId: string, plan: string): Promise<boolean> {
+ const viewport = S.viewColumns === null ? undefined : { columns: S.viewColumns, rows: S.viewRows ?? 48 }
+ let isOver = false
+ let timer = { cancel: () => {} }
+ const late = new Promise<boolean>(resolve => {
+ timer = delay($, PLAN_DRAW_WAIT_MS, () => resolve(false))
+ })
+ const drawn = async (): Promise<boolean> => {
+ while (!isOver) {
+ // Set first: a compile that ends while this draws is not missed.
+ const ended = new Promise<void>(resolve => jobEnds.add(resolve))
+ const ready = await answerEnv($, {})
+ if (!ready) return false
+ const { drawing } = await planDrawing($, { ...(viewport ? { viewport } : {}), props: {} }, toolUseId, plan, ready)
+ if (drawing.kind === 'pages') return true
+ // Text with nothing pending is final (the compile failed); with it, the compile is slow.
+ if (drawing.kind === 'text' && !pending.has(`plan:${toolUseId}`)) return false
+ await ended
+ }
+ return false
+ }
+ try {
+ return await Promise.race([drawn(), late])
+ } finally {
+ isOver = true
+ timer.cancel()
+ }
+}
+
// Intelligent UI's own plan question: only on the main loop of a session drawn
// in a terminal, with Intelligent UI on, Typst found and a terminal that draws
// (the plan's pictures need all of them). Null otherwise: the engine's
@@ -1463,11 +1497,12 @@ export const register: Register = on => {
// dialog while PermissionRequest hooks run, so a question asked there waits
// behind it). The person's words deny the call (Claude revises the plan);
// a verdict waits for the PermissionRequest below, and is dropped once the
- // call resolves, so it never reaches a later call. No env, no plan, or a
- // failure: no verdict, and the engine's dialog asks. The engine may run
- // two calls at once, and a PermissionRequest does not say which call it
- // is for: a call that begins while another runs asks nothing (the
- // engine's dialog asks), and no verdict is used while two run.
+ // call resolves, so it never reaches a later call. No env, no plan, no
+ // pictures of it (planShows), or a failure: no verdict, and the engine's
+ // dialog asks. The engine may run two calls at once, and a
+ // PermissionRequest does not say which call it is for: a call that begins
+ // while another runs asks nothing (the engine's dialog asks), and no
+ // verdict is used while two run.
on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
if (e.agentId) {
subagentPlans.add(e.tool_use_id)
@@ -1494,9 +1529,10 @@ export const register: Register = on => {
editedPlans.set(id, text)
refresh($)
},
+ isDrawn: text => planShows($, id, text),
})
if (outcome.kind === 'feedback') return { deny: outcome.message }
- verdict = outcome.verdict
+ if (outcome.kind === 'verdict') verdict = outcome.verdict
}
} catch {
verdict = null
diff --git a/tests/images.test.ts b/tests/images.test.ts
index 0172812..8d326c4 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -364,6 +364,8 @@ function world(on: any, o: {
failConvert?: boolean
failConvertFrom?: number
failMove?: boolean
+ // Runs just before a move (`mv -f part out`), with the files.
+ beforeMove?: (argv: string[], files: Record<string, string>) => void
holdConvert?: number
holdRun?: { at: number; until: Promise<void> }
holdCompile?: Promise<void>
@@ -467,6 +469,7 @@ function world(on: any, o: {
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (argv[0] === 'mv') {
moves.push(argv)
+ o.beforeMove?.(argv, files)
if (o.failMove || !(argv[2]! in files)) return ok('', 1)
files[argv[3]!] = files[argv[2]!]!
delete files[argv[2]!]
@@ -700,7 +703,7 @@ test('a JPEG, a WebP and an SVG Claude sends are made PNGs by Typst once, and dr
expect(converts[0]).toContain('maxh=640')
// Typst writes a part file; only a whole one is moved to image.png.
const out = shown[0].props.source.file
- expect(converts[0]!.at(-1)).toBe(out.replace(/image\.png$/, 'image.part.png'))
+ expect(converts[0]!.at(-1)).toMatch(new RegExp(`^${out.replace(/image\.png$/, '')}image-[0-9a-z]+\\.part\\.png$`))
expect(moves[0]).toEqual(['mv', '-f', converts[0]!.at(-1), out])
// A redraw converts nothing again, and the JPEG's own bytes are never read as a PNG.
await ui.redraw(sent(output).props)
@@ -1129,6 +1132,26 @@ test('with no Typst, or a conversion that fails, a JPEG leaves the row as it is'
expect(converts.length).toBe(1)
})
+test('two sessions converting the same JPEG at once each move their own part file', async ($, on) => {
+ const out = convertedPath('/c', '/t/photo.jpg', '1:1000', BOX)
+ // The other session's run moves its part file (all runs once shared image.part.png) just before this one's move.
+ const theirs = out.replace(/image\.png$/, 'image.part.png')
+ const { converts, moves } = world(on, {
+ typst: true, files: { '/t/photo.jpg': JPEG },
+ beforeMove: (_, files) => {
+ if (!(theirs in files)) return
+ files[out] = files[theirs]!
+ delete files[theirs]
+ },
+ })
+ await ready($)
+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))
+ expect(images(await ui.drawn())[0].props.source.file).toBe(out)
+ expect(converts.length).toBe(1)
+ expect(converts[0]!.at(-1)).not.toBe(theirs)
+ expect(moves).toEqual([['mv', '-f', converts[0]!.at(-1), out]])
+})
+
test('a part file that can not be moved draws no picture; an image.png made before is used with no run', async ($, on) => {
const { converts, logs, files } = world(on, { typst: true, failMove: true, files: { '/t/photo.jpg': JPEG, '/t/old.jpg': JPEG } })
await ready($)
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index c9af3a8..4f5b313 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -259,8 +259,8 @@ test('the plan editor on Linux: code, else a GUI editor that waits, never over s
expect(editorArgv({ code: '', isMac: false, isRemote: false, gui }, '/h/p.md')).toEqual(['/usr/bin/kate', '--block', '/h/p.md'])
expect(editorArgv({ code: '', isMac: false, isRemote: true, gui }, '/h/p.md')).toBe(null)
expect(editorArgv({ code: '', isMac: false, isRemote: false, gui: [] }, '/h/p.md')).toBe(null)
- // macOS does not change: TextEdit, never a GUI editor of the list.
- expect(editorArgv({ code: '', isMac: true, isRemote: false, gui }, '/h/p.md')).toEqual(['open', '-W', '-t', '/h/p.md'])
+ // macOS does not change: the default text editor, never a GUI editor of the list.
+ expect(editorArgv({ code: '', isMac: true, isRemote: false, gui }, '/h/p.md')).toEqual(['open', '-t', '/h/p.md'])
})
// ---- A Linux session ---------------------------------------------------------------
diff --git a/tests/plan.test.ts b/tests/plan.test.ts
index 231a9ed..e158685 100644
--- a/tests/plan.test.ts
+++ b/tests/plan.test.ts
@@ -1,8 +1,9 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,
- PLAN_FEEDBACK, PLAN_HEADER, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf, planOf, planOptions,
+ choiceOf, decisionOf, editorArgv, editorWaits, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DONE,
+ PLAN_DRAW_WAIT_MS, PLAN_DRAWING, PLAN_EDIT, PLAN_EDITED_UNDRAWN, PLAN_EDITING, PLAN_FEEDBACK, PLAN_HEADER, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED,
+ PLAN_REJECTED, PLAN_REOPEN, planFileOf, planInputOf, planOf, planOptions,
planShownOf, shortPath, TYPST_PROMPT, verdictOf,
} from '../hooks/register'
// This file's own copy of the flow, driven with a fake `$`: the plugin's module is another one.
@@ -97,9 +98,13 @@ test('a verdict becomes the PermissionRequest decision', () => {
expect(decisionOf({ kind: 'deny', message: PLAN_REJECTED }, input)).toEqual({ behavior: 'deny', message: 'The user rejected the plan.', interrupt: true })
})
-test('the editor: VS Code when found, else TextEdit on a local Mac, else none', () => {
+test('the editor: VS Code when found, else the text editor on a local Mac, else none', () => {
expect(editorArgv({ code: '/usr/local/bin/code', isMac: true, isRemote: false }, '/h/p.md')).toEqual(['/usr/local/bin/code', '--wait', '/h/p.md'])
- expect(editorArgv({ code: '', isMac: true, isRemote: false }, '/h/p.md')).toEqual(['open', '-W', '-t', '/h/p.md'])
+ // Not `open -W`: it waits until the whole app quits, not until the window closes.
+ expect(editorArgv({ code: '', isMac: true, isRemote: false }, '/h/p.md')).toEqual(['open', '-t', '/h/p.md'])
+ expect(editorWaits(['open', '-t', '/h/p.md'])).toBe(false)
+ expect(editorWaits(['/usr/local/bin/code', '--wait', '/h/p.md'])).toBe(true)
+ expect(editorWaits(['/usr/bin/gedit', '--wait', '/h/p.md'])).toBe(true)
expect(editorArgv({ code: '', isMac: true, isRemote: true }, '/h/p.md')).toBe(null)
expect(editorArgv({ code: '', isMac: false, isRemote: false }, '/h/p.md')).toBe(null)
})
@@ -110,7 +115,7 @@ test('the editor on Linux: a GUI editor that waits, never over ssh, VS Code firs
expect(editorArgv({ code: '', isMac: false, isRemote: true, gui }, '/h/p.md')).toBe(null)
expect(editorArgv({ code: '', isMac: false, isRemote: false, gui: [] }, '/h/p.md')).toBe(null)
expect(editorArgv({ code: '/usr/bin/code', isMac: false, isRemote: false, gui }, '/h/p.md')).toEqual(['/usr/bin/code', '--wait', '/h/p.md'])
- expect(editorArgv({ code: '', isMac: true, isRemote: false, gui }, '/h/p.md')).toEqual(['open', '-W', '-t', '/h/p.md'])
+ expect(editorArgv({ code: '', isMac: true, isRemote: false, gui }, '/h/p.md')).toEqual(['open', '-t', '/h/p.md'])
})
test('only the question Intelligent UI asks now is the plan question', () => {
@@ -133,6 +138,8 @@ test('Claude is told that a plan is drawn like an answer', () => {
const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })
// The first 24 bytes of a 1600 x 64 PNG, as `od -An -v -tx1` prints them.
const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 00 40'
+// The same PNG's first bytes in base64, as a read of a page's bytes gives them (over ssh).
+const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'
const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
const PLANS = '/h/.claude/plans'
const FILE = `${PLANS}/p.md`
@@ -150,6 +157,10 @@ function world($: any, on: any, o: {
surfaces?: string[]
edit?: string
failCompile?: boolean
+ // The text whose compile fails (the others draw).
+ failText?: string
+ // Over ssh, the bytes of a page can not be read (it can not go as `{ png }`).
+ noBytes?: boolean
raise?: boolean
onAsk?: () => Promise<void>
hold?: Promise<void>
@@ -175,13 +186,14 @@ function world($: any, on: any, o: {
const argv: string[] = e.argv
if (argv[0] === 'sh' && argv[2] === 'echo $$; exec "$@"' && argv[4] === '/usr/bin/typst' && argv[5] === 'compile') {
yield { stream: 'stdout', text: `${pids++}\n` }
- if (o.failCompile) {
+ const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
+ const text = JSON.parse(files.get(doc)!).segments.join('\n\n')
+ if (o.failCompile || text === o.failText) {
yield { stream: 'stderr', text: 'error: boom' }
return { value: { code: 1, signal: null } }
}
- const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
await o.hold
- compiled.push(JSON.parse(files.get(doc)!).segments.join('\n\n'))
+ compiled.push(text)
return { value: { code: 0, signal: null } }
}
return { value: { code: 1, signal: null } }
@@ -211,6 +223,7 @@ function world($: any, on: any, o: {
return { value: undefined }
})
on('fs.read', async ($: any, e: any, next: any) => {
+ if (e.as === 'bytes' && e.path.startsWith('/c/')) return o.noBytes ? { deny: 'EACCES' } : { value: { base64: PNG } }
if (files.has(e.path)) return { value: files.get(e.path) }
return e.path.startsWith('/c/') || e.path.startsWith('/h/') || e.path.startsWith('/w/') ? { deny: 'ENOENT' } : next(e)
})
@@ -218,7 +231,8 @@ function world($: any, on: any, o: {
if (e.path.startsWith('/c/')) return { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] }
return e.path.startsWith('/h/') || e.path.startsWith('/w/') ? { deny: 'ENOENT' } : next(e)
})
- on('ui.toast', async () => ({ value: undefined }))
+ const toasts: string[] = []
+ on('ui.toast', async ($: any, e: any) => (toasts.push(e.text), { value: undefined }))
on('turn.abort', async ($: any, e: any) => (aborts.push(e.turnId), { value: undefined }))
on('command.run', { command: 'clear' }, async ($: any, e: any) => (commands.push(e.command), { text: '' }))
on('prompt.submit', async ($: any, e: any) => (submits.push(e), { text: e.text }))
@@ -249,7 +263,7 @@ function world($: any, on: any, o: {
})
// The dialog is the engine's own node (a dialog tree must hold it once).
on('ui.render', ($: any, e: any) => (e.component === 'AskUserQuestion' ? { type: 'engine', ref: 0 } : ENGINE))
- return { clock, compiled, asked, edits, decisions, aborts, commands, submits, files, engineAsks: () => engineAsks }
+ return { clock, compiled, asked, edits, decisions, aborts, commands, submits, files, toasts, engineAsks: () => engineAsks }
}
const use = (o: { id?: string; input?: unknown; output?: unknown; isRunning?: boolean; isErrored?: boolean } = {}) =>
@@ -377,7 +391,10 @@ test('an errored, empty or subagent result stays as the engine draws it', async
test('approve with auto-accept: the PermissionRequest allows with the input and acceptEdits, no engine dialog', async ($, on) => {
const w = world($, on, { answers: [PLAN_AUTO], code: true })
await ready($)
+ // The engine draws the row before the call: the question waits for its pictures, compiled once.
+ await $.ui.mount(use())
const got: any = await exitPlan($)
+ expect(w.compiled).toEqual([PLAN])
expect(w.asked).toMatchObject([{ question: PLAN_QUESTION, header: PLAN_HEADER }])
expect(w.asked[0].options.map((x: any) => x.label)).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR, PLAN_EDIT])
expect(w.decisions).toEqual([{ behavior: 'allow', updatedInput: { plan: PLAN, planFilePath: FILE }, updatedPermissions: setMode('acceptEdits') }])
@@ -413,6 +430,51 @@ test('Esc rejects the plan: the PermissionRequest denies and interrupts', async
expect(w.engineAsks()).toBe(0)
})
+test('a plan whose pictures fail to compile is not asked about: the engine dialog shows its text', async ($, on) => {
+ const w = world($, on, { failCompile: true, answers: [PLAN_AUTO] })
+ await ready($)
+ const got: any = await exitPlan($)
+ expect(w.asked).toEqual([])
+ expect(w.engineAsks()).toBe(1)
+ expect(w.decisions).toEqual([undefined])
+ expect(got.result.plan).toBe(PLAN)
+})
+
+test('over ssh, a plan whose pages can not go as bytes is not asked about', async ($, on) => {
+ const w = world($, on, { answers: [PLAN_AUTO], noBytes: true, vars: { SSH_CONNECTION: '1 2 3 4' } })
+ await ready($)
+ await exitPlan($)
+ expect(w.asked).toEqual([])
+ expect(w.engineAsks()).toBe(1)
+})
+
+test("the question waits until the plan's pictures are drawn", async ($, on) => {
+ let release!: () => void
+ const w = world($, on, { answers: [PLAN_AUTO], hold: new Promise<void>(r => (release = r)) })
+ await ready($)
+ const call = exitPlan($)
+ await w.clock.advance(3000)
+ expect(w.asked).toEqual([])
+ release()
+ await call
+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION])
+ expect(w.decisions).toMatchObject([{ behavior: 'allow' }])
+ expect(w.engineAsks()).toBe(0)
+})
+
+test('pictures that never come: no question, the engine dialog asks once the wait ends', async ($, on) => {
+ const w = world($, on, { answers: [PLAN_AUTO], hold: new Promise<void>(() => undefined) })
+ await ready($)
+ let isDone = false
+ const call = exitPlan($).then(() => (isDone = true))
+ await w.clock.advance(5000)
+ expect(isDone).toBe(false)
+ await w.clock.advance(PLAN_DRAW_WAIT_MS)
+ await call
+ expect(w.asked).toEqual([])
+ expect(w.engineAsks()).toBe(1)
+})
+
test('a plan written in the same message waits for the write, then the new text is asked, sent and drawn', async ($, on) => {
const w = world($, on, { answers: [PLAN_AUTO], code: true })
// Claude's Write of the plan file, still running when ExitPlanMode starts.
@@ -436,7 +498,7 @@ test('a plan written in the same message waits for the write, then the new text
expect(got.result.plan).toBe(EDITED)
await $.ui.mount(use())
await w.clock.settle()
- expect(w.compiled).toEqual([EDITED])
+ expect([...new Set(w.compiled)]).toEqual([EDITED])
})
test("an Edit in the same message: the row draws the file, not the message's older copy", async ($, on) => {
@@ -449,7 +511,7 @@ test("an Edit in the same message: the row draws the file, not the message's old
expect(got.result.plan).toBe(EDITED)
await $.ui.mount(use({ input: { plan: PLAN, planFilePath: FILE } }))
await w.clock.settle()
- expect(w.compiled).toEqual([EDITED])
+ expect([...new Set(w.compiled)]).toEqual([EDITED])
})
test("a teammate's or a subagent's result draws no plan, also after a call kept its text", async ($, on) => {
@@ -457,6 +519,8 @@ test("a teammate's or a subagent's result draws no plan, also after a call kept
await ready($)
await exitPlan($, { tool_use_id: 'tu-a' })
await exitPlan($, { tool_use_id: 'tu-b' })
+ // The calls' questions waited for the plan's pictures; the result rows compile nothing.
+ w.compiled.length = 0
const rows = [
use({ id: 'tu-a', output: { plan: PLAN, isAgent: false, awaitingLeaderApproval: true }, isRunning: false }),
use({ id: 'tu-b', output: { plan: PLAN, isAgent: true }, isRunning: false }),
@@ -472,7 +536,7 @@ test("the result's plan wins over the text read at the call (an edit in the engi
await exitPlan($)
await $.ui.mount(use({ output: { plan: EDITED, isAgent: false, filePath: FILE }, isRunning: false }))
await w.clock.settle()
- expect(w.compiled).toEqual([EDITED])
+ expect(w.compiled).toEqual([PLAN, EDITED])
})
test('the plan waits at most 5 s for a write that does not end', async ($, on) => {
@@ -490,6 +554,17 @@ test('the plan waits at most 5 s for a write that does not end', async ($, on) =
expect(got.result.plan).toBe(PLAN)
})
+test('an edit whose pictures fail is still asked, with a toast, and the approval sends the edited plan', async ($, on) => {
+ const w = world($, on, { answers: [PLAN_EDIT, PLAN_AUTO], code: true, edit: EDITED, failText: EDITED })
+ await ready($)
+ const got: any = await exitPlan($)
+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_QUESTION_EDITED])
+ expect(w.toasts).toContain(PLAN_EDITED_UNDRAWN)
+ expect(w.engineAsks()).toBe(0)
+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED, planFilePath: FILE } }])
+ expect(got.result.plan).toBe(EDITED)
+})
+
test('edit: VS Code opens the file, the edited plan is asked again, sent and drawn', async ($, on) => {
const w = world($, on, { answers: [PLAN_EDIT, PLAN_AUTO], code: true, edit: EDITED })
await ready($)
@@ -498,22 +573,34 @@ test('edit: VS Code opens the file, the edited plan is asked again, sent and dra
expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_QUESTION_EDITED])
expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED, planFilePath: FILE } }])
expect(got.result.plan).toBe(EDITED)
- // The row draws the edited text, the call's input notwithstanding.
+ // Each text is asked once its pictures are drawn; the row draws the edited text, the call's input notwithstanding.
await $.ui.mount(use())
await w.clock.settle()
- expect(w.compiled).toEqual([EDITED])
+ expect([...new Set(w.compiled)]).toEqual([PLAN, EDITED])
})
-test('edit with no VS Code on a Mac uses TextEdit', async ($, on) => {
- const w = world($, on, { answers: [PLAN_EDIT, PLAN_MANUAL], edit: PLAN })
+test('edit with no VS Code on a Mac opens the text editor, and the file is read when the person is done', async ($, on) => {
+ const w = world($, on, { answers: [PLAN_EDIT, PLAN_DONE, PLAN_MANUAL], edit: PLAN })
await ready($)
await exitPlan($)
- expect(w.edits).toEqual([['open', '-W', '-t', FILE]])
+ // `open` returns at once (no -W: it would wait until the app quits).
+ expect(w.edits).toEqual([['open', '-t', FILE]])
// The file did not change: the same question, and the plan as it was.
- expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_QUESTION])
+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_EDITING, PLAN_QUESTION])
+ expect(w.asked[1].options.map((x: any) => x.label)).toEqual([PLAN_DONE, PLAN_REOPEN])
expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: PLAN } }])
})
+test('on a Mac the file can be opened again; Esc is done, and the edited plan is asked', async ($, on) => {
+ const w = world($, on, { answers: [PLAN_EDIT, PLAN_REOPEN, null, PLAN_AUTO], edit: EDITED })
+ await ready($)
+ const got: any = await exitPlan($)
+ expect(w.edits).toEqual([['open', '-t', FILE], ['open', '-t', FILE]])
+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_EDITING, PLAN_EDITING, PLAN_QUESTION_EDITED])
+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED } }])
+ expect(got.result.plan).toBe(EDITED)
+})
+
test('clear context: once approved, the turn ends, /clear runs and the plan is sent', async ($, on) => {
const w = world($, on, { answers: [PLAN_CLEAR] })
await ready($)
@@ -593,7 +680,7 @@ test('two calls at once: the second asks nothing, and no verdict is used while b
await ready($)
// A is rejected (Esc), and waits for its PermissionRequest; B begins.
const a = exitPlan($, { tool_use_id: 'A' })
- await ticks()
+ await w.clock.settle()
const b = exitPlan($, { tool_use_id: 'B' })
await ticks()
expect(w.asked.length).toBe(1)
@@ -757,7 +844,7 @@ function fake(o: {
}
const CODE = '/usr/bin/code'
const hasCode = (argv: string[]) => (argv[0] === 'sh' && argv.at(-1) === 'code' ? { exitCode: 0, stdout: `code ${CODE}\n` } : undefined)
-const plain = (file = FILE) => ({ plan: PLAN, callPlan: PLAN, file, isMac: false, isRemote: false, onEdited: () => undefined })
+const plain = (file = FILE) => ({ plan: PLAN, callPlan: PLAN, file, isMac: false, isRemote: false, onEdited: () => undefined, isDrawn: async () => true })
test('with no plan file there is no editor: the edit answer is feedback', async () => {
const w = fake({ answers: [PLAN_EDIT] })
@@ -824,6 +911,19 @@ test('editing back to the original text is not an edit', async () => {
expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', plan: PLAN, isEdited: false } })
})
+test('an edited plan whose pictures do not draw is still asked (the engine dialog would drop the edit)', async () => {
+ const drawn: string[] = []
+ const w = fake({
+ answers: [PLAN_EDIT, PLAN_AUTO],
+ files: { [FILE]: PLAN },
+ run: (argv, files) => (argv[0] === CODE ? ((files[FILE] = EDITED), { exitCode: 0, stdout: '' }) : hasCode(argv)),
+ })
+ const got = await decidePlan(w.$, { ...plain(), isDrawn: async p => (drawn.push(p), p === PLAN) })
+ expect(drawn).toEqual([PLAN, EDITED])
+ expect(w.asked).toEqual([PLAN_QUESTION, PLAN_QUESTION_EDITED])
+ expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', plan: EDITED, isEdited: true } })
+})
+
test('a plan that differs from the call plan gives an edited verdict', async () => {
const w = fake({ answers: [PLAN_AUTO] })
const got = await decidePlan(w.$, { ...plain(''), plan: EDITED })