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

/iui theme one at a time; a setting set during the start stays

razorback1636f015d93bca
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index e26e1b7..6650b03 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -6,7 +6,7 @@ import type { EngineInterface } from 'claude-code'
import {
BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,
} from './settings'
-import { DEFAULT_METRICS, refresh, S, type Env } from './state'
+import { DEFAULT_METRICS, refresh, S, settingsSet, type Env } from './state'
import { resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
import { canDrawIn, isSet } from './terminal'
@@ -88,18 +88,26 @@ export function setUp($: EngineInterface): Promise<Env> {
if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host
S.theme = resolveMode(S.setting, S.host)
watchHost($)
+ // The stored settings, but not one an /iui command set meanwhile (settingsSet).
const kept = Number(await storeGet($, 'size').catch(() => undefined))
- S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE
+ if (!settingsSet.has('size')) S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE
const width = await storeGet($, 'width').catch(() => undefined)
- S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH
+ if (!settingsSet.has('width')) {
+ S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH
+ }
const height = await storeGet($, 'height').catch(() => undefined)
- S.height = height === 'half' || height === 'full' ? height
- : Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT
- S.grid = (await storeGet($, 'grid').catch(() => undefined)) !== false
- S.select = (await storeGet($, 'select').catch(() => undefined)) !== false
+ if (!settingsSet.has('height')) {
+ S.height = height === 'half' || height === 'full' ? height
+ : Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT
+ }
+ const grid = (await storeGet($, 'grid').catch(() => undefined)) !== false
+ if (!settingsSet.has('grid')) S.grid = grid
+ const select = (await storeGet($, 'select').catch(() => undefined)) !== false
+ if (!settingsSet.has('select')) S.select = select
// An engine with no version call is older than picture select.
S.engine = await Promise.resolve().then(() => sessionVersion($)).then(v => v.base ?? v.version, () => '')
- if ((await storeGet($, 'enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)
+ const enabled = await storeGet($, 'enabled').catch(() => undefined)
+ if (enabled === false && !settingsSet.has('enabled')) await update($, isOn, () => false).catch(() => undefined)
const isMac = os.trim() === 'Darwin'
// Linux, on this computer: the clipboard tools, for the copy.
if (S.hostOs === 'Linux' && !ssh) void findClipWay($).catch(() => undefined)
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 4b8574e..f341f28 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -226,6 +226,10 @@ export const S = {
updateDone: false,
updateBusy: false,
}
+// The settings an /iui command set in this load (`size`, `enabled`, ...): the
+// start (setUp) does not read them from the store, which may answer with the
+// value from before the command.
+export const settingsSet = new Set<string>()
// The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).
export const results = new Map<string, Result | 'failed'>()
// Streaming: model requests of the main loop in flight (`S.stepsLive`), the
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 104eb22..0ca119e 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -24,7 +24,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, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job } from './lib/state'
+import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, keep, 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'
@@ -623,6 +623,35 @@ function releaseSelect($: EngineInterface) {
forgetPages()
}
+// `/iui theme [name]`, one at a time (`themeRuns`): an older one still
+// reading the themes or measuring fonts would write its look, metrics,
+// epoch and stored name over a newer one's.
+let themeRuns: Promise<unknown> = Promise.resolve()
+function runTheme($: EngineInterface, name: string | undefined): Promise<string> {
+ const run = themeRuns.then(() => setTheme($, name))
+ themeRuns = run.catch(() => undefined)
+ return run
+}
+
+async function setTheme($: EngineInterface, name: string | undefined): Promise<string> {
+ const ready = await setUp($)
+ const was = S.look
+ const wanted = name ?? S.look?.name ?? DEFAULT_THEME
+ const { themes, problems, chosen } = await applyTheme($, ready.root, ready.home, wanted)
+ if (name && chosen.isFallback) {
+ if (was) S.look = was
+ return `No usable theme named ${name}.\n\n${themeListing(themes, problems, was?.name ?? DEFAULT_THEME, userThemesOf(ready.home), ready.home)}`
+ }
+ if (S.look?.name !== was?.name || S.look?.dir !== was?.dir || S.look?.stamp !== was?.stamp) {
+ // The theme's fonts set the column width and the code size.
+ if (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)
+ beginEpoch($)
+ }
+ if (name) await storeSet($, 'theme-name', chosen.name)
+ const head = name ? `Theme set to ${chosen.name}.\n\n` : ''
+ return `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home), ready.home)}`
+}
+
// ---- Hooks ----------------------------------------------------------------
export const register: Register = on => {
@@ -712,6 +741,7 @@ export const register: Register = on => {
if (asked.kind === 'grab') return { text: await grab($) }
if (asked.kind === 'dump') return { text: await dump($, await read($, isOn)) }
if (asked.kind === 'on' || asked.kind === 'off') {
+ settingsSet.add('enabled')
await update($, isOn, () => asked.kind === 'on')
// On: the clipboard part starts with the next picture drawn.
if (asked.kind === 'off') {
@@ -725,6 +755,7 @@ export const register: Register = on => {
// The epoch begins with the setting, so no row draws it with no epoch
// open (the store write waits for the host).
S.size = asked.percent
+ settingsSet.add('size')
beginEpoch($)
await storeSet($, 'size', S.size)
return { text: `Intelligent UI draws text at ${S.size}% of the terminal's text size (100% matches it).` }
@@ -733,6 +764,7 @@ export const register: Register = on => {
if (asked.width === undefined) await setUp($).catch(() => null)
else {
S.width = asked.width
+ settingsSet.add('width')
beginEpoch($)
await storeSet($, 'width', S.width)
}
@@ -744,6 +776,7 @@ export const register: Register = on => {
if (asked.height === undefined) await setUp($).catch(() => null)
else {
S.height = asked.height
+ settingsSet.add('height')
beginEpoch($)
await storeSet($, 'height', S.height)
}
@@ -754,6 +787,7 @@ export const register: Register = on => {
if (asked.grid === undefined) await setUp($).catch(() => null)
else {
S.grid = asked.grid
+ settingsSet.add('grid')
beginEpoch($)
await storeSet($, 'grid', S.grid)
}
@@ -764,6 +798,7 @@ export const register: Register = on => {
if (asked.on === undefined) await setUp($).catch(() => null)
else {
S.select = asked.on
+ settingsSet.add('select')
if (!S.select) releaseSelect($)
refresh($)
await storeSet($, 'select', S.select)
@@ -798,24 +833,7 @@ export const register: Register = on => {
}
return { text: `OSC 11 probe (the terminal's background), ${PROBE_RUNS} runs:\n${lines.join('\n')}\nThe poll uses it: ${USE_OSC11 ? 'yes' : 'no (off)'}.` }
}
- if (asked.kind === 'theme') {
- const ready = await setUp($)
- const was = S.look
- const wanted = asked.name ?? S.look?.name ?? DEFAULT_THEME
- const { themes, problems, chosen } = await applyTheme($, ready.root, ready.home, wanted)
- if (asked.name && chosen.isFallback) {
- if (was) S.look = was
- return { text: `No usable theme named ${asked.name}.\n\n${themeListing(themes, problems, was?.name ?? DEFAULT_THEME, userThemesOf(ready.home), ready.home)}` }
- }
- if (S.look?.name !== was?.name || S.look?.dir !== was?.dir || S.look?.stamp !== was?.stamp) {
- // The theme's fonts set the column width and the code size.
- if (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)
- beginEpoch($)
- }
- if (asked.name) await storeSet($, 'theme-name', chosen.name)
- const head = asked.name ? `Theme set to ${chosen.name}.\n\n` : ''
- return { text: `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home), ready.home)}` }
- }
+ if (asked.kind === 'theme') return { text: await runTheme($, asked.name) }
const state = (await read($, isOn)) ? 'on' : 'off'
const ready = await setUp($)
const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}".\n` : ''
diff --git a/tests/command.test.ts b/tests/command.test.ts
index 273eafe..0228d33 100644
--- a/tests/command.test.ts
+++ b/tests/command.test.ts
@@ -287,6 +287,34 @@ test('select off is kept and named; select with no value shows it', async ($, on
expect(await run($, 'details')).toContain('picture select off')
})
+test('a setting changed while the start reads the store is not set back to the stored one', async ($, on) => {
+ const store = new Map<string, unknown>([['size', 100], ['width', 'full'], ['height', 'half'], ['grid', true], ['select', true], ['enabled', false]])
+ // The commands run while the start's first read waits; its reads answer
+ // with the store as it was when they began.
+ let before: Map<string, unknown> | null = null
+ on('store.get', async (_: any, e: any) => {
+ if (e.key === 'size' && !before) {
+ before = new Map(store)
+ for (const args of ['size 150', 'width 120', 'height full', 'grid off', 'select off', 'on']) await run($, args)
+ }
+ return { value: (before ?? store).get(e.key) }
+ })
+ on('store.set', async (_: any, e: any) => (store.set(e.key, e.value), { value: undefined }))
+ mock.clock(on)
+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty' })
+ on('process.run', async (_: any, e: any, next: any) =>
+ e.argv[0] === 'sh' && /cc-intelligent-ui-/.test(e.argv.join(' '))
+ ? { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } as Out }
+ : next(e))
+ on('ui.toast', async () => ({ value: undefined }))
+ // The first run starts the start (its line was read before it).
+ await run($, '')
+ expect(before).not.toBe(null)
+ expect(await run($, '')).toContain('Intelligent UI is on: theme vscode, dark, text 150%, width 120 columns, height full, grid off.')
+ expect(await run($, 'select')).toContain('Picture select is off.')
+ expect([...store.entries()]).toEqual([['size', 150], ['width', 120], ['height', 'full'], ['grid', false], ['select', false], ['enabled', true]])
+})
+
test('a word that is not a subcommand gets the not-understood line, then the state', async ($, on) => {
world(on)
const text = await run($, ' bigger please ')
diff --git a/tests/themes.test.ts b/tests/themes.test.ts
index 579ed4c..d1e8ee6 100644
--- a/tests/themes.test.ts
+++ b/tests/themes.test.ts
@@ -85,3 +85,56 @@ test('a stored theme that is gone falls back to claude-code, with one toast', as
expect(ran.text).toContain('- claude-code (in use)')
expect(toasts.filter(t => t.includes('Intelligent UI: theme gone not found, using claude-code')).length).toBe(1)
})
+
+// An fs.stat of Sun.Light's files that waits for `release` (an older
+// /iui theme Sun.Light still stamping its files).
+const slowSunLight = (on: any) => {
+ let release!: () => void
+ const gate = new Promise<void>(r => (release = r))
+ on('fs.stat', async ($: any, e: any) => {
+ if (e.path.includes('Sun.Light')) await gate
+ return { value: { kind: 'file', size: 1, mtimeMs: 1, isLink: false } }
+ })
+ on('ui.toast', async () => ({ value: undefined }))
+ return () => release()
+}
+const flush = async () => {
+ for (let i = 0; i < 50; i++) await Promise.resolve()
+}
+// Until `run` ends, or 5000 turns of the microtask queue (a run that waits for an older one).
+const settled = async (run: Promise<unknown>) => {
+ let isDone = false
+ void run.then(() => (isDone = true))
+ for (let i = 0; i < 5000 && !isDone; i++) await Promise.resolve()
+}
+
+test('/iui theme runs one at a time: an older one that ends late does not write over a newer one', async ($, on) => {
+ const store = withThemes(on)
+ const release = slowSunLight(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const older = $.command.run({ command: 'iui', args: 'theme Sun.Light' } as any)
+ await flush()
+ const newer = $.command.run({ command: 'iui', args: 'theme nord' } as any)
+ await settled(newer)
+ release()
+ expect((await older).text).toContain('Theme set to Sun.Light.')
+ expect((await newer).text).toContain('Theme set to nord.')
+ // The last command the person ran wins: the look and the stored name.
+ expect(store['theme-name']).toBe('nord')
+ expect((await $.command.run({ command: 'iui', args: '' } as any)).text).toContain('theme nord')
+})
+
+test('/iui theme with no name, run while a theme is set, lists the one set as in use', async ($, on) => {
+ const store = withThemes(on)
+ const release = slowSunLight(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const set = $.command.run({ command: 'iui', args: 'theme Sun.Light' } as any)
+ await flush()
+ const listed = $.command.run({ command: 'iui', args: 'theme' } as any)
+ await settled(listed)
+ release()
+ await set
+ expect((await listed).text).toContain('- Sun.Light (yours, in use)')
+ expect(store['theme-name']).toBe('Sun.Light')
+ expect((await $.command.run({ command: 'iui', args: '' } as any)).text).toContain('theme Sun.Light')
+})