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

Tests: fill the gaps, one table for parseCommand

razorback1616f097337f40
diff --git a/tests/command.test.ts b/tests/command.test.ts
index 0925723..30724b3 100644
--- a/tests/command.test.ts
+++ b/tests/command.test.ts
@@ -1,6 +1,6 @@
import { expect, mock, test } from 'claude-code/testing'
-import { commandSuggestions, type ThemeInfo } from '../hooks/register'
+import { commandSuggestions, parseCommand, type ThemeInfo } from '../hooks/register'
const theme = (name: string, isUser = false, description = ''): ThemeInfo => ({ name, dir: `/t/${name}`, isUser, title: name, description, syntax: {} })
const themes = [theme('vscode-modern', false, 'default look'), theme('vscode'), theme('nord', true, 'my nord'), theme('github-light')]
@@ -82,6 +82,113 @@ test('other prompts get no rows', () => {
expect(at('/other theme')).toEqual([])
})
+const BAD = { kind: 'bad' }
+const parses: [string, object][] = [
+ // nothing, on, off
+ ['', { kind: 'show' }],
+ [' on ', { kind: 'on' }],
+ ['OFF', { kind: 'off' }],
+ // width: 40 to 400, full, or nothing to show it
+ ['width', { kind: 'width' }],
+ ['width full', { kind: 'width', width: 'full' }],
+ ['WIDTH Full', { kind: 'width', width: 'full' }],
+ ['width 40', { kind: 'width', width: 40 }],
+ ['width 160', { kind: 'width', width: 160 }],
+ ['width 400', { kind: 'width', width: 400 }],
+ ['width 39', BAD],
+ ['width 401', BAD],
+ ['width 12.5', BAD],
+ ['width wide', BAD],
+ ['width 120 full', BAD],
+ // height: half, full, 6 to 200 rows, or nothing to show it
+ ['height', { kind: 'height' }],
+ ['height half', { kind: 'height', height: 'half' }],
+ ['HEIGHT Full', { kind: 'height', height: 'full' }],
+ ['height 6', { kind: 'height', height: 6 }],
+ ['height 200', { kind: 'height', height: 200 }],
+ ['height 5', BAD],
+ ['height 201', BAD],
+ ['height tall', BAD],
+ ['height 12 rows', BAD],
+ // size: 80 to 200 percent
+ ['size 130', { kind: 'size', percent: 130 }],
+ ['size 80%', { kind: 'size', percent: 80 }],
+ ['size 200', { kind: 'size', percent: 200 }],
+ ['size 79', BAD],
+ ['size 201', BAD],
+ ['size', BAD],
+ ['size big', BAD],
+ ['bigger', BAD],
+ // grid: on, off, or nothing to show it
+ ['grid', { kind: 'grid' }],
+ ['grid on', { kind: 'grid', grid: true }],
+ ['GRID Off', { kind: 'grid', grid: false }],
+ ['grid yes', BAD],
+ ['grid on off', BAD],
+ // theme: a name kept as typed
+ ['theme', { kind: 'theme' }],
+ ['THEME', { kind: 'theme' }],
+ ['theme vscode', { kind: 'theme', name: 'vscode' }],
+ ['theme My.Dark_Theme-2', { kind: 'theme', name: 'My.Dark_Theme-2' }],
+ ['theme a b', BAD],
+ ['theme ../up', BAD],
+ ['theme a/b', BAD],
+ // the words without arguments
+ ['probe', { kind: 'probe' }],
+ ['details', { kind: 'details' }],
+ ['probe 3', BAD],
+ ['grab', { kind: 'grab' }],
+ ['dump', { kind: 'dump' }],
+ ['grab now', BAD],
+ // setup
+ ['setup', { kind: 'setup', remove: false }],
+ ['Setup Remove', { kind: 'setup', remove: true }],
+ ['setup now', BAD],
+ // updates
+ ['updates', { kind: 'updates' }],
+ ['Updates ON', { kind: 'updates', on: true }],
+ ['updates off', { kind: 'updates', on: false }],
+ ['updates maybe', BAD],
+ ['updates on now', BAD],
+]
+
+test('each command line parses to its command, or to bad', () => {
+ for (const [line, want] of parses) expect(parseCommand(line)).toEqual(want)
+})
+
+test('a word with extra words, a sign or a fraction is not understood', () => {
+ for (const args of ['on now', 'off x', 'details x', 'dump now', 'grab 1', 'probe 3', 'setup remove now', 'setup add', 'size 90.5', 'size -90', 'size 1e2', 'size 100 %', 'theme a b', 'updates 1']) {
+ expect(parseCommand(args)).toEqual({ kind: 'bad' })
+ }
+ expect(parseCommand('SETUP REMOVE')).toEqual({ kind: 'setup', remove: true })
+ expect(parseCommand('\t size \t 150 ')).toEqual({ kind: 'size', percent: 150 })
+})
+
+test('a size row takes a % after the number, and marks the one in use and the terminal size', () => {
+ expect(at('/iui size 15%').map(r => r.text)).toEqual(['150'])
+ expect(at('/iui size 12').map(r => [r.label, r.description])).toEqual([['120%', undefined], ['125%', undefined]])
+ const sized = (text: string, size: number) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, size })
+ expect(sized('/iui size 1', 125).filter(r => r.description).map(r => [r.text, r.description])).toEqual([['100', 'the terminal text size'], ['125', 'in use']])
+ expect(sized('/iui size', 80)[0]).toEqual({ text: 'size 80', label: '80%', description: 'in use' })
+})
+
+test('right after the command name and a space, every subcommand is offered by its bare name', () => {
+ const rows = commandSuggestions('/iui ', '', 5, o)
+ expect(rows.map(r => r.text)).toEqual(['on', 'off', 'size', 'width', 'height', 'grid', 'updates', 'theme', 'setup', 'details', 'grab', 'dump'])
+ expect(rows.every(r => r.description)).toBe(true)
+})
+
+test('a subcommand word matches in any case, and the command name does not', () => {
+ expect(at('/iui THEME').map(r => r.label)).toEqual(['github-light', 'nord', 'vscode', 'vscode-modern'])
+ expect(at('/iui Up').map(r => r.text)).toEqual(['updates'])
+ expect(at('/IUI t')).toEqual([])
+})
+
+test('a subcommand with no value to offer gets no rows after it', () => {
+ for (const text of ['/iui on ', '/iui setup r', '/iui details x', '/iui dump d']) expect(at(text)).toEqual([])
+ expect(at('/iui grab g')).toEqual([])
+})
+
test('the hook adds theme rows from the themes found at start', async ($, on) => {
mock.store(on)
mock.env(on, { HOME: '/fake-home' })
@@ -97,3 +204,110 @@ test('the hook adds theme rows from the themes found at start', async ($, on) =>
const other = await ($ as any).prompt.autocomplete({ text: 'hello', cursor: 5, token: 'hello', start: 0 })
expect(other.suggestions).toEqual([])
})
+
+// ---- The command run ----------------------------------------------------------
+
+type Out = { exitCode: number; stdout: string }
+// A Mac session; the store is kept by key. `sh`: what setUp's probe prints
+// (the cache folder, the OS, then Typst's path when it is found).
+function world(on: any, o: { stored?: Record<string, unknown>; env?: Record<string, string>; sh?: string } = {}) {
+ const store = new Map(Object.entries(o.stored ?? {}))
+ on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))
+ on('store.set', async ($: any, e: any) => (store.set(e.key, e.value), { value: undefined }))
+ const clock = mock.clock(on)
+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...o.env })
+ on('process.run', async ($: any, e: any, next: any) =>
+ e.argv[0] === 'sh' && /cc-intelligent-ui-/.test(e.argv.join(' '))
+ ? { value: { exitCode: 0, stdout: o.sh ?? '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } as Out }
+ : next(e))
+ return { store, clock }
+}
+const run = async ($: any, args: string) => (await $.command.run({ command: 'iui', args })).text as string
+
+test('on and off say so, keep the setting, and a later show agrees', async ($, on) => {
+ const { store } = world(on)
+ expect(await run($, 'off')).toBe('Intelligent UI is off.')
+ expect(store.get('enabled')).toBe(false)
+ expect(await run($, '')).toMatch(/^Intelligent UI is off: /)
+ expect(await run($, 'ON')).toBe('Intelligent UI is on.')
+ expect(store.get('enabled')).toBe(true)
+ expect(await run($, '')).toMatch(/^Intelligent UI is on: /)
+})
+
+test('size says the percent and keeps it; a size out of range is not understood and keeps nothing', async ($, on) => {
+ const { store } = world(on)
+ expect(await run($, 'size 125%')).toBe("Intelligent UI draws text at 125% of the terminal's text size (100% matches it).")
+ expect(store.get('size')).toBe(125)
+ const bad = await run($, 'size 201')
+ expect(bad).toContain('Not understood: "size 201".')
+ expect(store.get('size')).toBe(125)
+ expect(await run($, '')).toContain('text 125%')
+})
+
+test('width, height and grid with a value keep it; the reply names the new value', async ($, on) => {
+ const { store } = world(on)
+ expect(await run($, 'width 120')).toContain('Intelligent UI pictures now take at most: 120 columns.')
+ expect(store.get('width')).toBe(120)
+ expect(await run($, 'height 24')).toContain('Intelligent UI images and Typst drawings now take at most: 24 rows.')
+ expect(store.get('height')).toBe(24)
+ expect(await run($, 'grid off')).toContain('The row grid is now off.')
+ expect(store.get('grid')).toBe(false)
+ const state = await run($, '')
+ expect(state).toContain('width 120 columns, height 24 rows, grid off.')
+})
+
+test('width, height and grid with no value show the setting and keep nothing', async ($, on) => {
+ const { store } = world(on, { stored: { width: 160, height: 'full', grid: false } })
+ expect(await run($, 'width')).toContain('The most columns a picture takes: 160 columns.')
+ expect(await run($, 'height')).toContain('The most rows an image or a Typst drawing takes: full')
+ expect(await run($, 'grid')).toContain('The row grid is off.')
+ expect([...store.keys()].sort()).toEqual(['grid', 'height', 'width'])
+ expect(store.get('width')).toBe(160)
+})
+
+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 ')
+ expect(text.startsWith('Not understood: "bigger please".\nIntelligent UI is on: theme ')).toBe(true)
+ expect(text).toContain('Change: /iui on | off | size | width | height | grid | updates | theme. More: /iui details')
+})
+
+test('the state tells when Typst is not found, and when the terminal shows no pictures', async ($, on) => {
+ world(on, { env: { TERM: 'xterm-256color' } })
+ const text = await run($, '')
+ expect(text).toContain('Typst is not installed, so answers stay text.')
+ expect(text).toContain('This terminal shows no pictures, so answers stay text.')
+})
+
+// A version 0.2.0 is installed, and the check of the day already ran: 99.0.0 is the newest.
+function updated(on: any, stored: Record<string, unknown> = {}) {
+ const w = world(on, { stored: { 'update-check': { at: 1_800_000_000_000, latest: '99.0.0' }, ...stored } })
+ on('fs.read', async ($: any, e: any, next: any) =>
+ e.path.endsWith('/.claude-plugin/plugin.json') ? { value: '{"name":"cc-intelligent-ui","version":"0.2.0"}' } : next(e))
+ on('ui.toast', async () => ({ value: undefined }))
+ return w
+}
+
+test('the state has the update notice when a newer version is known', async ($, on) => {
+ updated(on)
+ expect(await run($, '')).toContain('Intelligent UI 99.0.0 is available (you have 0.2.0). To update: ')
+})
+
+test('the state has no update notice when updates are off', async ($, on) => {
+ updated(on, { updates: false })
+ expect(await run($, '')).not.toContain('is available')
+})
+
+test('the command is registered as iui at the session start, with a hint that names every subcommand', async ($, on) => {
+ world(on)
+ const specs: any[] = []
+ on('command.register', async ($: any, e: any) => (specs.push(e), { value: undefined } as any))
+ await ($ as any).session.start({ source: 'startup' }).catch(() => undefined)
+ expect(specs.length).toBeGreaterThan(0)
+ const spec = specs[0]
+ expect(spec.name).toBe('iui')
+ for (const word of ['on', 'off', 'size', 'width', 'height', 'grid', 'updates', 'theme', 'grab', 'dump']) {
+ expect(spec.argumentHint).toContain(word)
+ expect(spec.description).toContain(word)
+ }
+})
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 2828b52..4307db3 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -1,13 +1,15 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, pageTopsOf, parseCommand, pickPages,
+ codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, pageTopsOf, pickPages,
placeholderCell, isSafePage, positionsOf, screenOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
type Place,
} from '../hooks/register'
import { joinItems } from '../hooks/lib/copy'
import { WATCH_RESTART_MS } from '../hooks/lib/frame'
import { rowsAfter, type Under } from '../hooks/lib/pictures'
+import { forgetProbed, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from '../hooks/lib/probe'
+import { clip, drawnAnswers, lastKey, results, type Job, type Result } from '../hooks/lib/state'
import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'
// One screen row of a picture as Claude Code draws it: `lead` (the gutter),
@@ -364,12 +366,106 @@ test('the padding beside inline code is not a space; a space next to it is', ()
expect(joinAll([par, noto(0, 'forbids', 36), noto(41.217, 'list', 26.49, true), noto(72.924, 'as', 11)])).toBe('forbids list as')
})
+// ---- The drawings noted and their words -----------------------------------
+
+const noted = (name: string): Result => ({
+ bulletRow: 0, pages: [{ file: `/c/${name}/a-1.png`, width: 1000, height: 500, columns: 60, rows: 20 }, { file: `/c/${name}/a-2.png`, width: 1000, height: 500, columns: 60, rows: 20 }] as any,
+})
+
+// Runs `fn` with the drawings and keys of this module empty, then empties them.
+async function withDrawn(fn: () => Promise<void> | void) {
+ try {
+ drawnAnswers.clear()
+ lastKey.clear()
+ results.clear()
+ forgetProbed()
+ await fn()
+ } finally {
+ drawnAnswers.clear()
+ lastKey.clear()
+ results.clear()
+ forgetProbed()
+ }
+}
+
+test('a drawing is noted at the box it is drawn at, with the rows under its pages; the same drawing again keeps its seq and takes the new place', () =>
+ withDrawn(() => {
+ noteDrawn('ans-1', { ...noted('k1'), note: 'Typst error' }, 30, { top: 1, after: 2 })
+ const first = drawnAnswers.get('ans-1')!
+ expect(first.dir).toBe('/c/k1')
+ expect(first.pages.map(p => [p.columns, p.rows])).toEqual([[30, 10], [30, 10]])
+ expect(first.place).toEqual({ top: 1, below: 3 })
+ const seq = first.seq
+ // Same files and boxes: the place changes, the seq does not.
+ noteDrawn('ans-1', noted('k1'), 30, { after: 1 })
+ expect(drawnAnswers.get('ans-1')!.seq).toBe(seq)
+ expect(drawnAnswers.get('ans-1')!.place).toEqual({ below: 1 })
+ // Another room is a new drawing, drawn after.
+ noteDrawn('ans-1', noted('k1'), 40, {})
+ expect(drawnAnswers.get('ans-1')!.seq).toBe(seq + 1)
+ expect(clip.seq).toBe(seq + 1)
+ }))
+
+test('a drawing keeps the Job of the key it was drawn from, only when that key is its folder', () =>
+ withDrawn(() => {
+ const job = { env: { cache: '/c' } } as Job
+ lastKey.set('ans-1', { key: 'k1', textHash: 'h', job })
+ noteDrawn('ans-1', noted('k1'), 60)
+ expect(drawnAnswers.get('ans-1')!.job).toBe(job)
+ lastKey.set('ans-2', { key: 'other', textHash: 'h', job })
+ noteDrawn('ans-2', noted('k2'), 60)
+ expect(drawnAnswers.get('ans-2')!.job).toBeUndefined()
+ }))
+
+test('a memo hit notes a drawing again only when it was forgotten and the result of its key is a drawing', () =>
+ withDrawn(() => {
+ noteDrawnAgain('ans-1', 60)
+ expect(drawnAnswers.has('ans-1')).toBe(false)
+ lastKey.set('ans-1', { key: 'k1', textHash: 'h', job: { env: { cache: '/c' } } as Job })
+ results.set('k1', 'failed')
+ noteDrawnAgain('ans-1', 60)
+ expect(drawnAnswers.has('ans-1')).toBe(false)
+ results.set('k1', noted('k1'))
+ noteDrawnAgain('ans-1', 60, { top: 1 })
+ expect(drawnAnswers.get('ans-1')!.place).toEqual({ top: 1, below: 0 })
+ // Already noted: kept as it is.
+ const kept = drawnAnswers.get('ans-1')
+ noteDrawnAgain('ans-1', 60, { top: 5 })
+ expect(drawnAnswers.get('ans-1')).toBe(kept)
+ }))
+
+test('the rows on screen are kept on a drawing noted, null when outside the viewport, and dropped when the surface says none', () =>
+ withDrawn(() => {
+ noteOnScreen('none', { first: 0, last: 1, of: 2 })
+ expect(drawnAnswers.has('none')).toBe(false)
+ noteDrawn('ans-1', noted('k1'), 60)
+ noteOnScreen('ans-1', { first: 3, last: 9, of: 44 })
+ expect(drawnAnswers.get('ans-1')!.onScreen).toEqual({ first: 3, last: 9, of: 44 })
+ noteOnScreen('ans-1', null)
+ expect(drawnAnswers.get('ans-1')!.onScreen).toBeNull()
+ noteOnScreen('ans-1', 'junk')
+ expect(drawnAnswers.get('ans-1')!.onScreen).toBeUndefined()
+ }))
+
+test('the words of a page: none with no Job or no such page; a drawing with no probe file gives none and is not kept', () =>
+ withDrawn(async () => {
+ const fail$ = { fs: { read: async () => { throw new Error('ENOENT') } } } as any
+ noteDrawn('ans-1', noted('k1'), 60)
+ const d = drawnAnswers.get('ans-1')!
+ expect(await wordsOf(fail$, d, 0)).toBe(null)
+ const job = { env: { cache: '/c', typst: '/usr/bin/typst' } } as Job
+ expect(await wordsOf(fail$, { ...d, job }, 5)).toBe(null)
+ // A failure is not kept: the next copy runs the probe again.
+ let reads = 0
+ const reading$ = { fs: { read: async () => (reads++, { value: 'not json' }) } } as any
+ expect(await wordsOf(reading$, { ...d, job }, 0)).toBe(null)
+ expect(await wordsOf(reading$, { ...d, job }, 0)).toBe(null)
+ expect(reads).toBe(2)
+ }))
+
// ---- The command ------------------------------------------------------------
test('/iui grab and dump are commands with typeahead rows; dump with nothing seen says so', async $ => {
- expect(parseCommand('grab')).toEqual({ kind: 'grab' })
- expect(parseCommand('dump')).toEqual({ kind: 'dump' })
- expect(parseCommand('grab now')).toEqual({ kind: 'bad' })
const rows = commandSuggestions('/iui gra', 'gra', 5, { themes: [], active: 'claude-code', size: 100 })
expect(rows).toEqual([{ text: 'grab', description: 'copy the text of the pictures you last selected (or copied, on the main screen)' }])
expect(commandSuggestions('/iui du', 'du', 5, { themes: [], active: 'claude-code', size: 100 }).map(r => r.text)).toEqual(['dump'])
diff --git a/tests/designs.test.ts b/tests/designs.test.ts
index 34707b6..a449369 100644
--- a/tests/designs.test.ts
+++ b/tests/designs.test.ts
@@ -1,6 +1,7 @@
import { expect, test } from 'claude-code/testing'
import { designKey, designPath, designText, hashOf, loadDesign, parseDesign, recordDesign } from '../hooks/register'
+import { DESIGNS_IN_MEMORY, designInMemory, forgetDesigns, noteDesign } from '../hooks/lib/designs'
import { forgetTouches, TOUCH_BATCH } from '../hooks/lib/typst'
import { TOUCH_FLUSH_MS } from '../hooks/lib/settings'
@@ -35,8 +36,9 @@ test('a bad or empty design file is missing', () => {
// A fake engine with an in-memory fs: the files, and what the host did.
// Its clock runs a timer only at `advance` (by the time asked of it).
-function disk(files: Record<string, string>) {
+function disk(files: Record<string, string>, failWrite = false) {
forgetTouches()
+ forgetDesigns()
const seen = { reads: [] as string[], writes: [] as string[], touches: [] as string[], runs: [] as string[][] }
let timers: Array<{ ms: number; fn: () => void; isOff: boolean }> = []
const advance = (ms: number) => {
@@ -60,6 +62,7 @@ function disk(files: Record<string, string>) {
},
exists: async (path: string) => path in files,
write: async (path: string, text: string) => {
+ if (failWrite) throw new Error('EACCES')
seen.writes.push(path)
files[path] = text
},
@@ -136,3 +139,59 @@ test('record then load gives the value without a read', async () => {
expect(await loadDesign($, '/d', 'ff00000000000006')).toEqual(d)
expect(seen.reads).toEqual([])
})
+
+test('a design noted at queue time is in memory, is not replaced by a later note, and is saved by record', async () => {
+ const { $, seen } = disk({})
+ const first = { widthPt: 400, heightPt: 250 }
+ expect(designInMemory('gg00000000000007')).toBe(undefined)
+ noteDesign('gg00000000000007', first)
+ noteDesign('gg00000000000007', { widthPt: 1, heightPt: 1 })
+ expect(designInMemory('gg00000000000007')).toEqual(first)
+ expect(await loadDesign($, '/d', 'gg00000000000007')).toEqual(first)
+ expect(seen.reads).toEqual([])
+ await recordDesign($, '/d', 'gg00000000000007', first)
+ expect(seen.writes).toEqual(['/d/gg/gg00000000000007'])
+ await recordDesign($, '/d', 'gg00000000000007', first)
+ expect(seen.writes.length).toBe(1)
+})
+
+test('a missing design is null in memory, not undefined', async () => {
+ const { $ } = disk({})
+ await loadDesign($, '/d', 'hh00000000000008')
+ expect(designInMemory('hh00000000000008')).toBe(null)
+})
+
+test('record keeps the design of a file another session wrote first, and writes nothing', async () => {
+ const path = designPath('/d', 'ii00000000000009')
+ const { $, seen } = disk({ [path]: '500 300' })
+ noteDesign('ii00000000000009', { widthPt: 1, heightPt: 1 })
+ await recordDesign($, '/d', 'ii00000000000009', { widthPt: 1, heightPt: 1 })
+ expect(seen.writes).toEqual([])
+ expect(designInMemory('ii00000000000009')).toEqual({ widthPt: 500, heightPt: 300 })
+ // Saved now, so a second record returns at once, with no read.
+ const reads = seen.reads.length
+ await recordDesign($, '/d', 'ii00000000000009', { widthPt: 2, heightPt: 2 })
+ expect(seen.reads.length).toBe(reads)
+})
+
+test('record writes over a file that is not a design', async () => {
+ const path = designPath('/d', 'jj0000000000000a')
+ const { $, seen } = disk({ [path]: 'junk' })
+ await recordDesign($, '/d', 'jj0000000000000a', { widthPt: 400, heightPt: 250 })
+ expect(seen.writes).toEqual([path])
+ expect(await loadDesign($, '/d', 'jj0000000000000a')).toEqual({ widthPt: 400, heightPt: 250 })
+})
+
+test('record never throws when the write fails; the design stays only noted', async () => {
+ const { $ } = disk({}, true)
+ noteDesign('kk0000000000000b', { widthPt: 400, heightPt: 250 })
+ await recordDesign($, '/d', 'kk0000000000000b', { widthPt: 400, heightPt: 250 })
+ expect(designInMemory('kk0000000000000b')).toEqual({ widthPt: 400, heightPt: 250 })
+})
+
+test('the designs in memory are bounded: the oldest go', () => {
+ disk({})
+ for (let i = 0; i <= DESIGNS_IN_MEMORY; i++) noteDesign(`m${i}`, { widthPt: 1, heightPt: 1 })
+ expect(designInMemory('m0')).toBe(undefined)
+ expect(designInMemory(`m${DESIGNS_IN_MEMORY}`)).toEqual({ widthPt: 1, heightPt: 1 })
+})
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 2591cb9..e5cd95f 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -5,6 +5,8 @@ import {
RESIZE_QUIET_MS, resolveLinks, SEGMENT_ROWS, WATCH_PL,
} from '../hooks/register'
import { TABLE_GRID } from './table-fixture'
+// This file's own copy of the drawing code, called with a fake `$`.
+import { drawPages, linksFor } from '../hooks/lib/draw'
// ---- Where pictures draw ----------------------------------------------------
@@ -686,21 +688,6 @@ test('two rows, one compile held: both keep the old picture, then both swap in o
expect(redraws).toBe(2)
})
-test('a redraw with a new onScreen makes no file or process call and draws the same picture', async ($, on) => {
- const { clock, calls } = world(on, { TERM: 'xterm-kitty' })
- await $.command.run({ command: 'iui', args: '' } as any)
- const ui = await $.ui.mount(message('scroll-1', 'Some **bold** text.'))
- await clock.settle()
- await ui.redraw(props('Some **bold** text.'))
- const [first] = images(await ui.drawn())
- const before = calls.length
- for (const onScreen of [{ first: 0, last: 3, of: 9 }, null, { first: 2, last: 8, of: 9 }, undefined]) {
- await ui.redraw({ ...props('Some **bold** text.'), onScreen })
- expect(images(await ui.drawn())[0].props).toEqual(first.props)
- }
- expect(calls.slice(before)).toEqual([])
-})
-
test('a font size change with the same columns compiles once, with a new key', async ($, on) => {
const { clock, compiles, emit } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY })
await $.command.run({ command: 'iui', args: '' } as any)
@@ -785,8 +772,6 @@ test('a first render of a diagram: the design is the space now (factor 1), kept
expect(images(await ui.drawn()).length).toBe(1)
const [inputs] = compiles
expect(Number(inputs!.height)).toBeGreaterThan(0)
- expect(inputs!['design-w']).toBe(inputs!.width)
- expect(inputs!['design-h']).toBe(inputs!.height)
const kept = [...files].filter(([path]) => path.includes('/designs/'))
expect(kept.length).toBe(1)
expect(kept[0]![1]).toBe(`${inputs!.width} ${inputs!.height}`)
@@ -939,6 +924,40 @@ test('an answer draws its links, files and commands under its pages, one dim row
expect(toasts).toContain('Copied')
})
+test('a press on a command row that cannot copy toasts the reason, or none', async ($, on) => {
+ const { clock, toasts } = world(on, { TERM: 'xterm-kitty' })
+ let reply: any = { isCopied: false, reason: 'no clipboard' }
+ on('ui.copy', async () => (reply instanceof Error ? { deny: reply.message } : { value: reply }))
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const text = 'Run:\n\n```sh\nnpm test\n```'
+ const ui = await $.ui.mount(message('links-3', text))
+ await clock.settle()
+ await ui.redraw(props(text))
+ const [button] = all(await ui.drawn(), 'Button')
+ await ui.press({ key: button.props.key })
+ reply = new Error('boom')
+ await ui.press({ key: button.props.key })
+ expect(toasts.filter(t => t.startsWith('Could not copy'))).toEqual(['Could not copy: no clipboard', 'Could not copy'])
+})
+
+test('the link rows of a text are none when a file check throws', async () => {
+ const $ = { fs: { exists: () => { throw new Error('gone') } } } as any
+ expect(await linksFor($, 'See `src/never-checked.ts`.', '/w')).toEqual([])
+})
+
+test('a page with a note draws it under the pages, and with gutter 0 draws no bullet column', () => {
+ const $ = { ui: { resolve: () => ({ Box: 'Box', Text: 'Text', Image: 'Image' }) } } as any
+ const page = { file: '/c/k/a-1.png', width: 1568, height: 64, alt: 'x', columns: 98, rows: 2 }
+ const e = { viewport: { columns: 100, rows: 40 } } as any
+ const noted: any = drawPages($, e, { pages: [page], bulletRow: 0, note: 'bad font' })
+ expect(textOf(noted)).toContain('Typst error: bad font')
+ expect(all(noted, 'Box').some(b => b.props.width === 2)).toBe(true)
+ const bare: any = drawPages($, e, { pages: [page], bulletRow: 0 }, undefined, { gutter: 0 })
+ expect(textOf(bare)).not.toContain('Typst error')
+ expect(all(bare, 'Box').some(b => b.props.width !== undefined)).toBe(false)
+ expect(images(bare).length).toBe(1)
+})
+
test('an answer with no links draws as before: no row under its pages', async ($, on) => {
const { clock } = world(on, { TERM: 'xterm-kitty' })
await $.command.run({ command: 'iui', args: '' } as any)
diff --git a/tests/epoch.test.ts b/tests/epoch.test.ts
index 3cdf9ae..6a6d9f5 100644
--- a/tests/epoch.test.ts
+++ b/tests/epoch.test.ts
@@ -252,3 +252,77 @@ test('a job that ends with no epoch open redraws; during a burst it redraws once
releaseJobs($)
expect(await redraws()).toBe(2)
})
+
+test('a cancel that throws does not stop the new epoch: the others are cancelled, the queue emptied', async () => {
+ await fresh()
+ const cancelled: string[] = []
+ running.set('a', { job: job('a'), cancel: () => void cancelled.push('a'), signal: SIGNAL })
+ running.set('bad', { job: job('bad'), cancel: () => { throw new Error('gone') }, signal: SIGNAL })
+ running.set('c', { job: job('c'), cancel: () => void cancelled.push('c'), signal: SIGNAL })
+ queue.push(job('d'))
+ beginEpoch($, frame(80))
+ expect(cancelled).toEqual(['a', 'c'])
+ expect(queue.length).toBe(0)
+ expect(epochOpen()).toBe(true)
+})
+
+test('a commit shows the target with its height setting and epoch; before it the old ones stay', async () => {
+ await fresh()
+ S.height = 'half'
+ S.shownHeight = 'half'
+ const before = S.shownEpoch
+ S.height = 24
+ beginEpoch($, frame(80))
+ expect(S.shownHeight).toBe('half')
+ expect(S.shownEpoch).toBe(before)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(S.shownHeight).toBe(24)
+ expect(S.shownEpoch).toBe(S.epoch)
+ expect(S.epoch).toBe(before + 1)
+})
+
+test('a new epoch forgets a job that ended during a burst: no redraw at the release but the commit\'s', async () => {
+ await fresh()
+ holdJobs()
+ jobDone($)
+ expect(S.missed).toBe(true)
+ beginEpoch($, frame(80))
+ expect(S.missed).toBe(false)
+ expect(await redraws()).toBe(1)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(await redraws()).toBe(2)
+})
+
+test('a job that ends during a burst in an open epoch does not redraw at the release; the commit does', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ holdJobs()
+ jobDone($)
+ expect(S.missed).toBe(true)
+ releaseJobs($)
+ expect(S.missed).toBe(false)
+ // The begin only: the epoch is not ready yet, and the job's end made no redraw.
+ expect(epochOpen()).toBe(true)
+ expect(await redraws()).toBe(1)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(await redraws()).toBe(2)
+})
+
+test('a job that ends in an open epoch before it is ready only waits: no redraw, no early commit', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ jobDone($)
+ expect(epochOpen()).toBe(true)
+ expect(await redraws()).toBe(1)
+})
+
+test('with no target at all, an epoch begins and commits with the target still none', async () => {
+ await fresh()
+ S.frame = null
+ S.shown = null
+ beginEpoch($)
+ expect(S.frame).toBe(null)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toBe(null)
+})
diff --git a/tests/fonts.test.ts b/tests/fonts.test.ts
index a76f1a8..1a18a0d 100644
--- a/tests/fonts.test.ts
+++ b/tests/fonts.test.ts
@@ -111,6 +111,17 @@ test('no lean set when it could draw differently', () => {
expect(leanFiles(list, '', { ...FONTS, code: ['DejaVu Sans Mono'] })).not.toBeNull()
})
+test('a terminal font that is a skipped name is kept when it is the first installed font', () => {
+ const list = fontListOf(LISTING)
+ expect(leanFiles(list, 'PingFang SC', FONTS)).toContain('/System/Library/AssetsV2/PingFang.ttc')
+ expect(leanFiles(list, '', { body: ['PingFang SC'], code: ['Menlo'], plain: true })).toBeNull()
+})
+
+test('a font list with no files gives no lean set', () => {
+ expect(leanFiles(fontListOf(''), '', FONTS)).toBeNull()
+ expect(leanFiles(fontListOf('DejaVu Sans Mono\n └ (Embedded)\n Style: Normal\n'), '', { body: ['DejaVu Sans Mono'], code: ['DejaVu Sans Mono'], plain: true })).toBeNull()
+})
+
test('the lean folder is named by its files', () => {
expect(leanDirOf('/c', ['/a.ttf'])).toBe(leanDirOf('/c', ['/a.ttf']))
expect(leanDirOf('/c', ['/a.ttf'])).not.toBe(leanDirOf('/c', ['/b.ttf']))
diff --git a/tests/frame.test.ts b/tests/frame.test.ts
index 6d91422..8732cf6 100644
--- a/tests/frame.test.ts
+++ b/tests/frame.test.ts
@@ -5,7 +5,7 @@ import {
WATCH_RESTART_MS, WATCH_RESTARTS, watchFrame, watchLineOf, watchState, type Frame, type WatchLine,
} from '../hooks/lib/frame'
import { COMMIT_MIN_MS, DEFAULT_CELL, IMAGE_MAX_COLUMNS, RESIZE_QUIET_MS } from '../hooks/lib/settings'
-import { INLINE_MAX_SIDE } from '../hooks/lib/terminal'
+import { INLINE_MAX_SIDE, isGhosttyHere } from '../hooks/lib/terminal'
import { perlFor, WATCH_PL } from '../hooks/lib/host'
// The module state the Frame reads and sets (this file's copy of the
// modules is the one imported above).
@@ -518,3 +518,24 @@ test('a clip child that ends on its own starts again after WATCH_RESTART_MS, WAT
expect(children.length).toBe(before + WATCH_RESTARTS)
expect(watchState()).toEqual({ clip: true, ended: true })
})
+
+test('Ghostty is told by TERM_PROGRAM or TERM, and cmux (its engine) counts too', () => {
+ const was = { program: S.termProgram, name: S.termName, cmux: S.isCmux }
+ try {
+ S.isCmux = false
+ S.termProgram = 'ghostty'
+ S.termName = 'xterm-256color'
+ expect(isGhosttyHere()).toBe(true)
+ S.termProgram = ''
+ S.termName = 'xterm-ghostty'
+ expect(isGhosttyHere()).toBe(true)
+ S.termName = 'xterm-kitty'
+ expect(isGhosttyHere()).toBe(false)
+ S.isCmux = true
+ expect(isGhosttyHere()).toBe(true)
+ } finally {
+ S.termProgram = was.program
+ S.termName = was.name
+ S.isCmux = was.cmux
+ }
+})
diff --git a/tests/images.test.ts b/tests/images.test.ts
index 35aff94..ac7b35b 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -1,8 +1,9 @@
import { expect, mock, test } from 'claude-code/testing'
+import { onScreenOf } from '../hooks/lib/images'
import {
claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, factsAfter, folderOf, imageKindOf, isMarkdownPath, isNoPageError, isPdfPath, lastKnownPage,
- NO_FACTS, pageControls, pageCountOf, pageOf, parsePage, pasteDirOf, pastedImagePath, pastedNumbers, COMMIT_MIN_MS, DEFAULT_HEIGHT, parseCommand, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,
+ NO_FACTS, pageControls, pageCountOf, pageOf, parsePage, pasteDirOf, pastedImagePath, pastedNumbers, COMMIT_MIN_MS, DEFAULT_HEIGHT, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,
pictureRowsFor, projectSlug, renderKey, rowsAfter, sentFiles, sentImages, shortError, type Under,
} from '../hooks/register'
@@ -20,6 +21,17 @@ test('a picture keeps its aspect, is never made larger, and fits the box', () =>
expect(pictureCells({ width: 4, height: 4 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 1, rows: 1 })
})
+test('a row\'s onScreen: null is off screen, a range is on screen, none is not known', () => {
+ expect(onScreenOf(null)).toBe(false)
+ expect(onScreenOf({ first: 1, last: 4 })).toBe(true)
+ expect(onScreenOf(undefined)).toBe(undefined)
+ expect(onScreenOf(0)).toBe(undefined)
+})
+
+test('a picture is never more than 255 cells, even for a huge box', () => {
+ expect(pictureCells({ width: 100000, height: 100000 }, 1000, 1000, { width: 1, height: 1 })).toEqual({ columns: 255, rows: 255 })
+})
+
test('a picture takes at most half the viewport, within 6 and 24 rows', () => {
expect(DEFAULT_HEIGHT).toBe('half')
expect(pictureRowsFor(undefined, 'half')).toBe(PICTURE_MAX_ROWS)
@@ -41,18 +53,6 @@ test('height full: the viewport less 16 rows; a number: at most that, never unde
expect(pictureRowsFor(400, 'full')).toBe(255)
})
-test('the height command: half, full, 6 to 200 rows, or nothing to show it', () => {
- expect(parseCommand('height')).toEqual({ kind: 'height' })
- expect(parseCommand('height half')).toEqual({ kind: 'height', height: 'half' })
- expect(parseCommand('HEIGHT Full')).toEqual({ kind: 'height', height: 'full' })
- expect(parseCommand('height 6')).toEqual({ kind: 'height', height: 6 })
- expect(parseCommand('height 200')).toEqual({ kind: 'height', height: 200 })
- expect(parseCommand('height 5')).toEqual({ kind: 'bad' })
- expect(parseCommand('height 201')).toEqual({ kind: 'bad' })
- expect(parseCommand('height tall')).toEqual({ kind: 'bad' })
- expect(parseCommand('height 12 rows')).toEqual({ kind: 'bad' })
-})
-
test('only PNG, JPEG, WebP, SVG and PDF attachments are drawn', () => {
expect(sentImages({
attachments: [
@@ -291,6 +291,23 @@ test('the [Image #N] marks of a prompt, each once', () => {
expect(pastedNumbers('no image, [Image #x], [image #4]')).toEqual([])
})
+test('a hint count that is not under the page keeps the missing page as it is', () => {
+ const made = factsAfter(NO_FACTS, 3, null)
+ expect(factsAfter(made, 3, NO_PAGE(3, 3)).missing).toBe(3)
+ expect(factsAfter(made, 4, NO_PAGE(4, 3))).toEqual({ made: 3, missing: 4, pages: 3, errors: {} })
+})
+
+test('a Typst error with no error line gives its first line; sentFiles skips an empty path', () => {
+ expect(shortError('\n \nsomething broke\nmore')).toBe('something broke')
+ expect(sentFiles({ attachments: [{ path: '', size: 1, isImage: true }, { path: '/t/a.png', size: 1, isImage: true }] })).toEqual([{ path: '/t/a.png', kind: 'png' }])
+})
+
+test('an [Image #0] mark and a uid that is not a number give nothing', () => {
+ expect(pastedNumbers('[Image #0] [Image #01]')).toEqual([1])
+ expect(claudeTmpOf({ uid: 'me', isMac: true })).toBe('')
+ expect(claudeTmpOf({ tmpdir: ' ', uid: '7', isMac: false })).toBe('/tmp/claude-7')
+})
+
test('the pasted-image path follows Claude Code folder names', () => {
expect(projectSlug('/Users/subhagato/Development/apps/claude-intelligent-ui')).toBe('-Users-subhagato-Development-apps-claude-intelligent-ui')
expect(projectSlug('/home/me/my_app.v2')).toBe('-home-me-my-app-v2')
diff --git a/tests/links.test.ts b/tests/links.test.ts
index 78a3665..b3ee729 100644
--- a/tests/links.test.ts
+++ b/tests/links.test.ts
@@ -102,3 +102,26 @@ test('each item once, the first, in the order of the text', () => {
].join('\n')
expect(linksOf(md)).toEqual([file('README.md'), web('the site', 'https://x.io'), command('npm test')])
})
+
+test('a file:// link is a local file; a query or fragment is cut; an empty label shows the URL', () => {
+ expect(linksOf('[x](file:///abs/a.md#top) [y](docs/b.ts?raw=1)')).toEqual([file('/abs/a.md'), file('docs/b.ts')])
+ expect(linksOf('[](https://x.io/e)')).toEqual([web('https://x.io/e')])
+})
+
+test('an image written as a reference is not a link', () => {
+ expect(linksOf('![logo][g] and ![logo]\n\n[g]: https://x.io/logo.png\n[logo]: https://x.io/l.png')).toEqual([])
+})
+
+test('a ~ path and a ../ path are files; a URL with a path is not', () => {
+ expect(linksOf('See ~/notes/a.md and ../up/b.json.')).toEqual([file('~/notes/a.md'), file('../up/b.json')])
+ expect(linksOf('https://x.io/docs/a.md')).toEqual([web('https://x.io/docs/a.md')])
+})
+
+test('a fence that never closes still gives its command; a ~~~ shell fence works', () => {
+ expect(linksOf('```bash\nnpm i')).toEqual([command('npm i')])
+ expect(linksOf('~~~sh\nls\n~~~')).toEqual([command('ls')])
+})
+
+test('a console block: output lines between prompts are dropped', () => {
+ expect(linksOf('```console\n$ a\nout\n$ b\n```')).toEqual([command('a (+1 line)', 'a\nb')])
+})
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index 3fe9f80..b79f154 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -5,6 +5,8 @@ import {
placeholderCell, schemeOfPortal, SETUP_NOT_MAC, WATCH_PL, WL_WATCH_SH, X11_WATCH_SH, type ClipWay,
} from '../hooks/register'
import { CACHE_SH } from '../hooks/lib/env'
+import { clipboardNow, clipWatchArgs, clipWayReady, findClipWay } from '../hooks/lib/clipboard'
+import { S } from '../hooks/lib/state'
import { SMALL_MARKS, SMALL_MD } from './copy-fixture'
const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })
@@ -96,6 +98,72 @@ test('the automatic copy line: the macOS texts as they were, the Linux way or wh
expect(autoCopyText({ ...linux, hostOs: 'FreeBSD' })).toBe('off (not macOS or Linux)')
})
+// A $ whose process.run answers `got` (or throws) and whose env.get reads `env`; `argvs` keeps each call.
+const fake$ = (got: { exitCode: number; stdout: string } | Error, env: Record<string, string> = {}) => {
+ const argvs: string[][] = []
+ const $ = {
+ process: { run: async (argv: string[]) => (argvs.push(argv), got instanceof Error ? Promise.reject(got) : { stderr: '', ...got }) },
+ env: { get: async (name: string) => env[name] },
+ } as any
+ return { $, argvs }
+}
+
+// Runs `fn` with S.env and S.clipWay as given, then puts them back.
+async function withClip<T>(isMac: boolean, clipWay: ClipWay | null, fn: () => Promise<T> | T): Promise<T> {
+ const was = { env: S.env, clipWay: S.clipWay }
+ try {
+ S.env = { isMac } as any
+ S.clipWay = clipWay
+ return await fn()
+ } finally {
+ S.env = was.env
+ S.clipWay = was.clipWay
+ }
+}
+
+const WL_WAY = clipWayOf({ wayland: true, x11: false, desktop: 'sway', found: ALL })
+
+test('the watcher arguments after clip: none on macOS, the notifier on Linux, null where changes can not be seen', async () => {
+ await withClip(true, null, () => expect(clipWatchArgs(true)).toEqual([]))
+ await withClip(false, WL_WAY, () => expect(clipWatchArgs(false)).toEqual(['/usr/bin/wl-paste', '--watch', 'sh', '-c', WL_WATCH_SH]))
+ await withClip(false, { off: 'no Wayland or X11 display' }, () => expect(clipWatchArgs(false)).toBe(null))
+ await withClip(false, null, () => expect(clipWatchArgs(false)).toBe(null))
+})
+
+test('the clipboard now: pbpaste on macOS (UTF-8), the way found on Linux; null when it can not be read', async () => {
+ const mac = fake$({ exitCode: 0, stdout: 'héllo' })
+ expect(await withClip(true, null, () => clipboardNow(mac.$))).toBe('héllo')
+ expect(mac.argvs).toEqual([['pbpaste']])
+ const lin = fake$({ exitCode: 0, stdout: 'text' })
+ expect(await withClip(false, WL_WAY, () => clipboardNow(lin.$))).toBe('text')
+ expect(lin.argvs).toEqual([['/usr/bin/wl-paste', '-n', '-t', 'text']])
+ // A read that fails, throws, or has no tool to run.
+ expect(await withClip(true, null, () => clipboardNow(fake$({ exitCode: 1, stdout: 'x' }).$))).toBe(null)
+ expect(await withClip(false, WL_WAY, () => clipboardNow(fake$(new Error('timeout')).$))).toBe(null)
+ const none = fake$({ exitCode: 0, stdout: 'x' })
+ expect(await withClip(false, { off: 'no wl-paste' }, () => clipboardNow(none.$))).toBe(null)
+ expect(await withClip(false, null, () => clipboardNow(none.$))).toBe(null)
+ expect(none.argvs).toEqual([])
+})
+
+test('looking up the clipboard way sets S.clipWay from the display, the desktop and the tools found; clipWayReady waits for it', async () => {
+ const found = fake$({ exitCode: 0, stdout: 'xclip /usr/bin/xclip\nclipnotify /usr/bin/clipnotify\n' }, { DISPLAY: ':0', XDG_CURRENT_DESKTOP: 'XFCE' })
+ const was = S.clipWay
+ try {
+ const way = findClipWay(found.$)
+ await clipWayReady()
+ expect(await way).toMatchObject({ name: 'clipnotify and xclip (X11)', wayland: false })
+ expect(S.clipWay).toBe(await way)
+ expect(found.argvs).toEqual([['sh', '-c', FIND_SH]])
+ // The tools can not be looked up: no tool, so the way is off.
+ const failed = findClipWay(fake$(new Error('boom'), { DISPLAY: ':0' }).$)
+ await clipWayReady()
+ expect(await failed).toEqual({ off: 'no xclip, xsel or GTK 3 for Python, and no clipnotify' })
+ } finally {
+ S.clipWay = was
+ }
+})
+
// ---- Light or dark: the desktop portal ---------------------------------------------
test("the portal's color-scheme, as gdbus and busctl print it (Read and ReadOne)", () => {
diff --git a/tests/mode.test.ts b/tests/mode.test.ts
index eae1c43..2931cd5 100644
--- a/tests/mode.test.ts
+++ b/tests/mode.test.ts
@@ -289,3 +289,42 @@ test('with the theme on auto, iTerm2 with no TERM_PROGRAM is found by ITERM_PROF
const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
expect(ran.text).toContain('mode dark (auto, from iTerm2: profile Default background)')
})
+
+// A fixed theme (or none) never asks the OS or the terminal.
+for (const [theme, mode, shown] of [
+ [undefined, 'dark', 'dark'], ['dark', 'dark', 'dark'], ['light', 'light', 'light'], ['dark-daltonized', 'dark', 'dark-daltonized'],
+ ['light-ansi', 'light', 'light-ansi'], ['', 'dark', 'dark'],
+] as const) {
+ test(`with the theme ${theme === undefined ? 'not set' : JSON.stringify(theme)}, the mode is ${mode} and no OS read is made`, async ($, on) => {
+ mock.store(on)
+ mock.clock(on)
+ mock.env(on, { HOME: '/fake-home' })
+ on('config.list', async () => ({ value: (theme === undefined ? [] : [{ key: 'theme', value: theme }]) as any }))
+ const asked: string[] = []
+ on('process.run', async ($: any, e: any, next: any) => {
+ const argv: string[] = e.argv
+ if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(argv.join(' '))) return { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }
+ if (argv[0] === 'defaults') asked.push('macOS')
+ return next(e)
+ })
+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
+ expect(ran.text).toContain(`mode ${mode} (Claude Code theme ${shown})`)
+ expect(asked).toEqual([])
+ })
+}
+
+test('a theme setting that names no mode (a custom theme) follows the OS like auto', async ($, on) => {
+ mock.store(on)
+ mock.clock(on)
+ mock.env(on, { HOME: '/fake-home' })
+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'custom:night-owl' }] as any }))
+ on('process.run', async ($: any, e: any, next: any) => {
+ const argv: string[] = e.argv
+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
+ if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(argv.join(' '))) return ok('/tmp/mdp\nDarwin\n')
+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('Dark\n')
+ return next(e)
+ })
+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
+ expect(ran.text).toContain('mode dark (auto, from macOS)')
+})
diff --git a/tests/plan.test.ts b/tests/plan.test.ts
index 88c033e..099e1da 100644
--- a/tests/plan.test.ts
+++ b/tests/plan.test.ts
@@ -2,9 +2,12 @@ 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_HEADER, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf, planOf, planOptions,
+ PLAN_FEEDBACK, PLAN_HEADER, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, 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.
+import { currentPlan, decidePlan, scheduleClear } from '../hooks/lib/plan'
+import { S } from '../hooks/lib/state'
// ---- Pure helpers -----------------------------------------------------------
@@ -46,6 +49,18 @@ test('a short path', () => {
expect(shortPath('/h/.claude/plans/p.md', '/h')).toBe('~/.claude/plans/p.md')
expect(shortPath('/other/p.md', '/h')).toBe('/other/p.md')
expect(shortPath('/h/p.md', '')).toBe('/h/p.md')
+ expect(shortPath('/h/p.md', '/h/')).toBe('~/p.md')
+ expect(shortPath('/h', '/h')).toBe('/h')
+ expect(shortPath('/hx/p.md', '/h')).toBe('/hx/p.md')
+ expect(shortPath('/h/p.md', '/')).toBe('/h/p.md')
+})
+
+test('a path with a trailing slash, a root, an empty path and dots', () => {
+ expect(normalPath('/')).toBe('/')
+ expect(normalPath('')).toBe('')
+ expect(normalPath('/a/')).toBe('/a')
+ expect(normalPath('../../a')).toBe('../../a')
+ expect(normalPath('a/..')).toBe('')
})
test('the question: four options, the edit option only with an editor; any other answer is feedback', () => {
@@ -83,6 +98,15 @@ test('the editor: VS Code when found, else TextEdit on a local Mac, else none',
expect(editorArgv({ code: '', isMac: false, isRemote: false }, '/h/p.md')).toBe(null)
})
+test('the editor on Linux: a GUI editor that waits, never over ssh, VS Code first', () => {
+ const gui = ['/usr/bin/gedit', '--wait']
+ expect(editorArgv({ code: '', isMac: false, isRemote: false, gui }, '/h/p.md')).toEqual(['/usr/bin/gedit', '--wait', '/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)
+ 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'])
+})
+
test('only the question Intelligent UI asks now is the plan question', () => {
const q = (question: string, header = PLAN_HEADER) => [{ question, header, options: [], multiSelect: false }]
expect(isPlanQuestion(q(PLAN_QUESTION), PLAN_QUESTION)).toBe(true)
@@ -122,6 +146,7 @@ function world($: any, on: any, o: {
failCompile?: boolean
raise?: boolean
onAsk?: () => Promise<void>
+ hold?: Promise<void>
} = {}) {
mock.store(on)
const clock = mock.clock(on)
@@ -148,6 +173,7 @@ function world($: any, on: any, o: {
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'))
return { value: { code: 0, signal: null } }
}
@@ -529,3 +555,244 @@ test('the line above the dialog is for the Intelligent UI question alone', async
// Once answered, the same question draws as the engine's.
expect(await (await $.ui.mount(dialog(PLAN_QUESTION, PLAN_HEADER, 'tu-ask-3'))).drawn()).toMatchObject({ type: 'engine' })
})
+
+test('while the plan compiles the row shows the drawing line, then the pictures', async ($, on) => {
+ let release!: () => void
+ const hold = new Promise<void>(r => (release = r))
+ const { clock } = world($, on, { hold })
+ await ready($)
+ const ui = await $.ui.mount(use())
+ await clock.settle()
+ await ui.redraw(use().props)
+ const waiting: any = await ui.drawn()
+ expect(waiting.children[0]).toMatchObject(ENGINE)
+ expect(texts(waiting)).toContain(PLAN_DRAWING)
+ expect(images(waiting)).toEqual([])
+ release()
+ await clock.settle()
+ await ui.redraw(use().props)
+ const done: any = await ui.drawn()
+ expect(texts(done)).not.toContain(PLAN_DRAWING)
+ expect(images(done).length).toBe(1)
+})
+
+test('an approved result with no plan file shows the header alone', async ($, on) => {
+ const { clock } = world($, on)
+ await ready($)
+ await $.ui.mount(use())
+ await clock.settle()
+ const shown = texts(await (await $.ui.mount(result({ plan: PLAN, isAgent: false }))).drawn()).join('\n')
+ expect(shown).toContain("User approved Claude's plan")
+ expect(shown).not.toContain('Plan saved to')
+})
+
+// ---- The flow with a fake `$` ------------------------------------------------------
+
+// `answers`: the replies to the question in order (an Error rejects). `run` answers a process
+// by its argv (default: it fails); `files` is the file system, which `run` may change.
+function fake(o: {
+ answers?: (string | Error)[]
+ run?: (argv: string[], files: Record<string, string>) => { exitCode: number; stdout: string } | Error | undefined
+ files?: Record<string, string>
+ env?: Record<string, string>
+} = {}) {
+ const asked: string[] = []
+ const options: string[][] = []
+ const during: string[] = []
+ const runs: string[][] = []
+ const files = { ...o.files }
+ const answers = [...(o.answers ?? [])]
+ const $ = {
+ ui: {
+ ask: async (question: string, opts: { options: string[] }) => {
+ asked.push(question)
+ options.push(opts.options)
+ during.push(S.planAsking)
+ const answer = answers.shift()
+ if (answer === undefined || answer instanceof Error) throw answer ?? new Error('dismissed')
+ return answer
+ },
+ },
+ process: {
+ run: async (argv: string[]) => {
+ runs.push(argv)
+ const got = o.run?.(argv, files) ?? { exitCode: 1, stdout: '' }
+ if (got instanceof Error) throw got
+ return { stderr: '', isStdoutTruncated: false, isStderrTruncated: false, ...got }
+ },
+ },
+ fs: {
+ read: async (path: string) => {
+ if (!(path in files)) throw new Error('ENOENT')
+ return files[path]!
+ },
+ },
+ env: { get: async (name: string) => o.env?.[name] },
+ } as any
+ S.planCode = null
+ S.planGui = null
+ S.planAsking = ''
+ return { $, asked, options, during, runs, files }
+}
+const CODE = '/usr/bin/code'
+const hasCode = (argv: string[]) => (argv.join(' ').includes('command -v code') ? { exitCode: 0, stdout: `${CODE}\n` } : undefined)
+const plain = (file = FILE) => ({ plan: PLAN, callPlan: PLAN, file, isMac: false, isRemote: false, onEdited: () => undefined })
+
+test('with no plan file there is no editor: the edit answer is feedback', async () => {
+ const w = fake({ answers: [PLAN_EDIT] })
+ const got = await decidePlan(w.$, plain(''))
+ expect(got).toEqual({ kind: 'feedback', message: `${PLAN_FEEDBACK} ${PLAN_EDIT}` })
+ expect(w.options[0]).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR])
+ expect(w.runs).toEqual([])
+})
+
+test('a rejected ask denies the plan and clears the question', async () => {
+ const w = fake({ answers: [new Error('dismissed')] })
+ const got = await decidePlan(w.$, plain(''))
+ expect(got).toEqual({ kind: 'verdict', verdict: { kind: 'deny', message: PLAN_REJECTED } })
+ expect(w.during).toEqual([PLAN_QUESTION])
+ expect(S.planAsking).toBe('')
+})
+
+test('an empty or blank file after an edit is ignored, and the question repeats', async () => {
+ const edited: string[] = []
+ const w = fake({
+ answers: [PLAN_EDIT, PLAN_EDIT, PLAN_AUTO],
+ files: { [FILE]: PLAN },
+ run: (argv, files) => {
+ if (argv[0] === CODE && argv[1] === '--wait') {
+ files[FILE] = files[FILE] === PLAN ? '' : ' \n'
+ return { exitCode: 0, stdout: '' }
+ }
+ return hasCode(argv)
+ },
+ })
+ const got = await decidePlan(w.$, { ...plain(), onEdited: p => edited.push(p) })
+ expect(w.asked).toEqual([PLAN_QUESTION, PLAN_QUESTION, PLAN_QUESTION])
+ expect(edited).toEqual([])
+ expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', plan: PLAN, isEdited: false } })
+})
+
+test('an editor process that rejects leaves the plan as it was', async () => {
+ const w = fake({
+ answers: [PLAN_EDIT, PLAN_MANUAL],
+ files: { [FILE]: PLAN },
+ run: argv => (argv[0] === CODE && argv[1] === '--wait' ? new Error('spawn failed') : hasCode(argv)),
+ })
+ const got = await decidePlan(w.$, plain())
+ expect(w.asked).toEqual([PLAN_QUESTION, PLAN_QUESTION])
+ expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', mode: 'default', plan: PLAN, isEdited: false } })
+})
+
+test('editing back to the original text is not an edit', async () => {
+ const edited: string[] = []
+ const w = fake({
+ answers: [PLAN_EDIT, PLAN_EDIT, PLAN_AUTO],
+ files: { [FILE]: PLAN },
+ run: (argv, files) => {
+ if (argv[0] === CODE && argv[1] === '--wait') {
+ files[FILE] = files[FILE] === PLAN ? EDITED : PLAN
+ return { exitCode: 0, stdout: '' }
+ }
+ return hasCode(argv)
+ },
+ })
+ const got = await decidePlan(w.$, { ...plain(), onEdited: p => edited.push(p) })
+ expect(w.asked).toEqual([PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_QUESTION])
+ expect(edited).toEqual([EDITED, PLAN])
+ expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', plan: PLAN, isEdited: false } })
+})
+
+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 })
+ expect(got).toMatchObject({ kind: 'verdict', verdict: { kind: 'allow', mode: 'acceptEdits', plan: EDITED, isEdited: true } })
+})
+
+test('the code command: -lc fails, -c finds it, and the path is cached', async () => {
+ const w = fake({
+ answers: [PLAN_AUTO, PLAN_AUTO],
+ run: argv => (argv[1] === '-c' ? hasCode(argv) : { exitCode: 1, stdout: '' }),
+ })
+ await decidePlan(w.$, plain())
+ expect(w.options[0]).toContain(PLAN_EDIT)
+ expect(w.runs.map(a => a[1])).toEqual(['-lc', '-c'])
+ expect(S.planCode).toBe(CODE)
+ await decidePlan(w.$, plain())
+ expect(w.runs.length).toBe(2)
+})
+
+test('a code path that is not absolute is refused, and the refusal is cached', async () => {
+ const w = fake({ answers: [PLAN_AUTO, PLAN_AUTO], run: () => ({ exitCode: 0, stdout: 'code\n' }) })
+ await decidePlan(w.$, plain())
+ expect(w.options[0]).not.toContain(PLAN_EDIT)
+ expect(S.planCode).toBe('')
+ const looked = w.runs.length
+ await decidePlan(w.$, plain())
+ expect(w.runs.length).toBe(looked)
+})
+
+test('on Linux a GUI editor is looked for only with a display, and the result is cached', async () => {
+ const gedit = (argv: string[]) => (argv[2]?.includes('command -v "$c"') ? { exitCode: 0, stdout: 'gedit /usr/bin/gedit\n' } : undefined)
+ const none = fake({ answers: [PLAN_AUTO], run: gedit })
+ await decidePlan(none.$, plain())
+ expect(none.options[0]).not.toContain(PLAN_EDIT)
+ expect(none.runs.some(a => a[2]?.includes('command -v "$c"'))).toBe(false)
+ expect(S.planGui).toEqual([])
+ for (const name of ['DISPLAY', 'WAYLAND_DISPLAY']) {
+ const w = fake({ answers: [PLAN_AUTO, PLAN_AUTO], run: gedit, env: { [name]: ':0' } })
+ await decidePlan(w.$, plain())
+ expect(w.options[0]).toContain(PLAN_EDIT)
+ expect(S.planGui).toEqual(['/usr/bin/gedit', '--wait'])
+ const looked = w.runs.length
+ await decidePlan(w.$, plain())
+ expect(w.runs.length).toBe(looked)
+ }
+})
+
+test('the GUI editor is not looked for on a Mac, over ssh or when VS Code is found', async () => {
+ const mac = fake({ answers: [PLAN_AUTO], env: { DISPLAY: ':0' } })
+ await decidePlan(mac.$, { ...plain(), isMac: true })
+ expect(S.planGui).toBe(null)
+ const remote = fake({ answers: [PLAN_AUTO], env: { DISPLAY: ':0' } })
+ await decidePlan(remote.$, { ...plain(), isRemote: true })
+ expect(S.planGui).toBe(null)
+ const code = fake({ answers: [PLAN_AUTO], env: { DISPLAY: ':0' }, run: hasCode })
+ await decidePlan(code.$, plain())
+ expect(S.planGui).toBe(null)
+})
+
+test('the current plan: the file, else the fallback when it is missing, unreadable or blank', async () => {
+ const read = (files: Record<string, string>) => ({ fs: { read: async (p: string) => (p in files ? files[p]! : Promise.reject(new Error('EACCES'))) } }) as any
+ expect(await currentPlan(read({ [FILE]: EDITED }), FILE, PLAN)).toBe(EDITED)
+ expect(await currentPlan(read({ [FILE]: EDITED }), '', PLAN)).toBe(PLAN)
+ expect(await currentPlan(read({}), FILE, PLAN)).toBe(PLAN)
+ expect(await currentPlan(read({ [FILE]: ' \n' }), FILE, PLAN)).toBe(PLAN)
+})
+
+test('clear context: no abort without a turn id, and no step failure stops the next', async () => {
+ const run = (o: { abort?: boolean; command?: boolean; submit?: boolean } = {}) => {
+ const calls: string[] = []
+ let later!: () => Promise<void>
+ const fail = (name: string, is?: boolean) => async () => {
+ calls.push(name)
+ if (is) throw new Error(name)
+ return undefined
+ }
+ const $ = {
+ clock: { after: (_: number, fn: () => Promise<void>) => ((later = fn), { cancel: () => undefined }) },
+ turn: { abort: fail('abort', o.abort) },
+ command: { run: fail('clear', o.command) },
+ prompt: { submit: fail('submit', o.submit) },
+ } as any
+ return { $, calls, fire: () => later() }
+ }
+ const empty = run()
+ scheduleClear(empty.$, PLAN, '')
+ await empty.fire()
+ expect(empty.calls).toEqual(['clear', 'submit'])
+ const broken = run({ abort: true, command: true, submit: true })
+ scheduleClear(broken.$, PLAN, 'turn-1')
+ await broken.fire()
+ expect(broken.calls).toEqual(['abort', 'clear', 'submit'])
+})
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index d038386..e94e9c4 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from 'claude-code/testing'
import {
- alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseCommand, parseFontSpec, typstCall,
+ alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseFontSpec, typstCall,
blocksOf, canDrawIn, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS,
parseOd, plainOf, pngSize, shouldRetrySafe, sizeOf, sizing, splitSegments, themeOf, TYPST_PROMPT,
escapeControls, luminanceOf, modeOfLuminance, OSC11_PL, parseOsc11, pickProfile, itermAppearanceOf, itermModeOf,
@@ -10,9 +10,10 @@ import {
BASE_THEME, DEFAULT_THEME, chooseTheme, isSyntaxPath, isThemeName, measureCall, pickThemes, renderKey, themeEntry, themeFiles, themeListing,
needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, rowsOfBlock, splitInTwo, typstInputs,
composeFrame, fitBox, pictureColumns, roomColumns, scaledBulletRow,
+ firstLine, gridText, heightText, isTypstInfo, widthText,
} from '../hooks/register'
import { DRAWING_ROWS } from '../hooks/lib/settings'
-import { wrapPid } from '../hooks/lib/typst'
+import { noNetworkEnv, wrapPid } from '../hooks/lib/typst'
import { S, type Env, type Job } from '../hooks/lib/state'
import { placeFirstLine } from '../hooks/lib/draw'
import { DEFAULT_GRID, gridFirstRow, gridOf, gridRowsOf } from '../hooks/lib/grid'
@@ -181,45 +182,6 @@ test('the width: full by default (the viewport less the bullet), a cap when set,
expect(columnsFor(400, 'full', null)).toBe(IMAGE_MAX_COLUMNS)
})
-test('the width command: a value of 40 to 400, full, or nothing to show it', () => {
- expect(parseCommand('width')).toEqual({ kind: 'width' })
- expect(parseCommand('width full')).toEqual({ kind: 'width', width: 'full' })
- expect(parseCommand('WIDTH Full')).toEqual({ kind: 'width', width: 'full' })
- expect(parseCommand('width 40')).toEqual({ kind: 'width', width: 40 })
- expect(parseCommand('width 160')).toEqual({ kind: 'width', width: 160 })
- expect(parseCommand('width 400')).toEqual({ kind: 'width', width: 400 })
- expect(parseCommand('width 39')).toEqual({ kind: 'bad' })
- expect(parseCommand('width 401')).toEqual({ kind: 'bad' })
- expect(parseCommand('width 12.5')).toEqual({ kind: 'bad' })
- expect(parseCommand('width wide')).toEqual({ kind: 'bad' })
- expect(parseCommand('width 120 full')).toEqual({ kind: 'bad' })
-})
-
-test('the size command takes 80 to 200 percent', () => {
- expect(parseCommand('')).toEqual({ kind: 'show' })
- expect(parseCommand(' on ')).toEqual({ kind: 'on' })
- expect(parseCommand('OFF')).toEqual({ kind: 'off' })
- expect(parseCommand('size 130')).toEqual({ kind: 'size', percent: 130 })
- expect(parseCommand('size 80%')).toEqual({ kind: 'size', percent: 80 })
- expect(parseCommand('size 200')).toEqual({ kind: 'size', percent: 200 })
- expect(parseCommand('size 79')).toEqual({ kind: 'bad' })
- expect(parseCommand('size 201')).toEqual({ kind: 'bad' })
- expect(parseCommand('size')).toEqual({ kind: 'bad' })
- expect(parseCommand('size big')).toEqual({ kind: 'bad' })
- expect(parseCommand('bigger')).toEqual({ kind: 'bad' })
- expect(parseCommand('probe')).toEqual({ kind: 'probe' })
- expect(parseCommand('details')).toEqual({ kind: 'details' })
- expect(parseCommand('probe 3')).toEqual({ kind: 'bad' })
-})
-
-test('the grid command: on, off, or nothing to show it', () => {
- expect(parseCommand('grid')).toEqual({ kind: 'grid' })
- expect(parseCommand('grid on')).toEqual({ kind: 'grid', grid: true })
- expect(parseCommand('GRID Off')).toEqual({ kind: 'grid', grid: false })
- expect(parseCommand('grid yes')).toEqual({ kind: 'bad' })
- expect(parseCommand('grid on off')).toEqual({ kind: 'bad' })
-})
-
test('the first line of an answer is told by how it starts', () => {
expect(firstLineOf('\n\nSome text')).toBe('para')
expect(firstLineOf('# Title')).toBe('h1')
@@ -583,14 +545,7 @@ test('Claude is told about typst blocks', () => {
})
-test('the theme command lists, or switches to a name kept as typed', () => {
- expect(parseCommand('theme')).toEqual({ kind: 'theme' })
- expect(parseCommand('THEME')).toEqual({ kind: 'theme' })
- expect(parseCommand('theme vscode')).toEqual({ kind: 'theme', name: 'vscode' })
- expect(parseCommand('theme My.Dark_Theme-2')).toEqual({ kind: 'theme', name: 'My.Dark_Theme-2' })
- expect(parseCommand('theme a b')).toEqual({ kind: 'bad' })
- expect(parseCommand('theme ../up')).toEqual({ kind: 'bad' })
- expect(parseCommand('theme a/b')).toEqual({ kind: 'bad' })
+test('a theme name is a plain word, not a hidden file', () => {
expect(isThemeName('.hidden')).toBe(false)
expect(isThemeName('nord')).toBe(true)
})
@@ -843,3 +798,244 @@ test('a picture of the target always fits the room of the same viewport', () =>
}
}
})
+
+// ---- Markdown blocks and text ------------------------------------------------
+
+test('a ~~~ fence is a block; a closing mark needs the same char, as many marks, and nothing after it', () => {
+ const tilde = blocksOf('~~~sh\nls\n~~~')
+ expect(tilde).toEqual([{ lines: ['~~~sh', 'ls', '~~~'], fence: { mark: '~~~', info: 'sh' } }])
+ // A ``` line in a ~~~ fence, a shorter mark and a mark with an info do not close it.
+ const open = ['````md', '```', 'x', '```js', '````'].join('\n')
+ expect(blocksOf(`${open}\n\nAfter`).map(b => b.lines.length)).toEqual([5, 1])
+ expect(blocksOf('~~~\n```\n~~~').length).toBe(1)
+})
+
+test('a fence that never closes runs to the end of the text', () => {
+ const blocks = blocksOf('Intro\n\n```js\na()\n\nb()')
+ expect(blocks.length).toBe(2)
+ expect(blocks[1]!.lines).toEqual(['```js', 'a()', '', 'b()'])
+})
+
+test('an indented fence stays in its list item; a fence at the margin is a block of its own', () => {
+ const item = blocksOf('- item\n ```js\n x\n\n y\n ```\n- next')
+ expect(item.length).toBe(1)
+ expect(item[0]!.fence).toBe(undefined)
+ expect(item[0]!.lines.length).toBe(7)
+ expect(blocksOf('text\n```\nx\n```\nmore').map(b => !!b.fence)).toEqual([false, true, false])
+})
+
+test('a $$ math block keeps its blank lines and is marked', () => {
+ const blocks = blocksOf('$$\na = 1\n\nb = 2\n$$\n\nAfter')
+ expect(blocks.length).toBe(2)
+ expect(blocks[0]).toEqual({ lines: ['$$', 'a = 1', '', 'b = 2', '$$'], isMath: true })
+ expect(blocks[1]!.isMath).toBe(undefined)
+})
+
+test('line ends of any kind (CRLF, CR) give the same blocks as LF', () => {
+ const lf = blocksOf('a\nb\n\nc')
+ expect(blocksOf('a\r\nb\r\n\r\nc')).toEqual(lf)
+ expect(blocksOf('a\rb\r\rc')).toEqual(lf)
+ expect(blocksOf('')).toEqual([])
+})
+
+test('a typst info is typst or typ in any case, nothing longer', () => {
+ for (const info of ['typst', 'typ', 'Typst', 'TYP']) expect(isTypstInfo(info)).toBe(true)
+ for (const info of ['', 'typescript', 'typst2', 'ty']) expect(isTypstInfo(info)).toBe(false)
+})
+
+test('rows of a block: a heading of level 1 or 2 takes more; code rows are shorter than text rows; size scales it', () => {
+ const rows = (md: string, size?: number) => rowsOfBlock(blocksOf(md)[0]!, 100, size)
+ near(rows('text'), 1 + 1.3)
+ near(rows('# Title'), 1 + 1.3 + 1.5)
+ near(rows('## Title'), rows('# Title'))
+ near(rows('### Title'), rows('text'))
+ near(rows('```\nx\n```'), 1 + 3 * 1.1)
+ near(rows('text', 200), 1 + 1.3 * 2)
+ // An empty line counts as one character, so it takes a row.
+ near(rowsOfBlock({ lines: ['', ''] }, 100), 1 + 2 * 1.3)
+})
+
+test('a long line wraps into rows at the column count', () => {
+ const rows = (n: number, columns: number) => rowsOfBlock({ lines: ['x'.repeat(n)] }, columns)
+ expect(rows(114, 100)).toBe(1 + 1.3)
+ expect(rows(116, 100)).toBe(1 + 2 * 1.3)
+ expect(rows(116, 50)).toBe(1 + 3 * 1.3)
+})
+
+test('a short code fence of 2 lines is not cut, however long its lines', () => {
+ const md = `${'x'.repeat(5000)}\n\n\`\`\`\n\`\`\``
+ expect(splitSegments(md, 80, 5).join('').includes('```\n```')).toBe(true)
+ expect(splitSegments(`\`\`\`\n${'x'.repeat(5000)}\n\`\`\``, 80, 5)[0]!.startsWith('```\n')).toBe(true)
+})
+
+test('footnotes in a code fence do not join the answer; link definitions in a fence are not repeated', () => {
+ const long = Array.from({ length: 120 }, (_, i) => para(i)).join('\n\n')
+ expect(splitSegments(`${long}\n\n\`\`\`md\n[^1]: A note.\n\`\`\``, 80).length).toBeGreaterThan(1)
+ const segments = splitSegments(`${long}\n\n\`\`\`md\n[docs]: https://example.com\n\`\`\``, 80)
+ expect(segments.filter(s => s.endsWith('[docs]: https://example.com\n```')).length).toBe(1)
+ expect(segments.every(s => !s.endsWith('\n\n'))).toBe(true)
+})
+
+test('a link definition already in a segment is not added to it again', () => {
+ const long = Array.from({ length: 120 }, (_, i) => para(i)).join('\n\n')
+ const segments = splitSegments(`${long}\n\n[docs]: https://example.com`, 80)
+ for (const s of segments) expect(s.split('[docs]: https://example.com').length - 1).toBe(1)
+})
+
+test('images: angle brackets, a title, several on a line, and URLs with a scheme other than file are not local', () => {
+ expect(localImages('![a](<a.png>) ![b](c.png "t")')).toEqual(['a.png', 'c.png'])
+ expect(localImages('![](data:image/png;base64,AA) ![](http://x/y.png) ![](FILE:///a.png)')).toEqual(['FILE:///a.png'])
+ expect(localImages('![x](~~~)\n~~~\n![y](z.png)\n~~~\n![w](w.png)')).toEqual(['~~~', 'w.png'])
+ expect(imagePathOf(' a.png ', '/repo//')).toBe('/repo/a.png')
+ expect(imagePathOf('FILE:///a%20b.png', '/repo')).toBe('/a b.png')
+})
+
+test('the alt: an image gives its alt, a fence line is dropped, quotes, numbers and tags are stripped, and a long text ends with …', () => {
+ expect(plainOf('![a chart](x.png) and [a link](u)')).toBe('a chart and a link')
+ expect(plainOf('```js\ncode()\n```')).toBe('code()')
+ expect(plainOf('> quote\n\n1. one\n2) two\n\n<b>tag</b>')).toBe('quote one two tag')
+ expect(plainOf('~~gone~~ __x__ | a | b |')).toBe('gone x a b')
+ expect(plainOf('abcdefghij', 5)).toBe('abcd…')
+ expect(plainOf('abcde', 5)).toBe('abcde')
+ expect(plainOf('```\n```')).toBe(' ')
+})
+
+test('the first line is the first line with text, trimmed', () => {
+ expect(firstLine('\n \n Hello \nWorld')).toBe('Hello')
+ expect(firstLine('')).toBe('')
+ expect(firstLine(' \n\t')).toBe('')
+})
+
+test('a text with an image in a fence only does not need the room; a typst fence with ~~~ does', () => {
+ expect(needsRoom('```md\n![x](a.png)\n```')).toBe(false)
+ expect(needsRoom('~~~typst\n#circle()\n~~~')).toBe(true)
+ expect(needsRoom('```typescript\nx\n```')).toBe(false)
+})
+
+// ---- Settings text and the grid numbers --------------------------------------
+
+test('the settings as words', () => {
+ expect(widthText('full')).toBe('full (the terminal width)')
+ expect(widthText(120)).toBe('120 columns')
+ expect(heightText('half')).toBe('half (half the terminal, 6 to 24 rows)')
+ expect(heightText('full')).toBe('full (the terminal height less 16 rows)')
+ expect(heightText(30)).toBe('30 rows')
+ expect(gridText(true)).toBe('on (each line of text on whole terminal rows)')
+ expect(gridText(false)).toBe('off')
+})
+
+test('a grid number must be a finite number of 0 or more; the code size must be over 0', () => {
+ const ok = {
+ body: 1, heading: [1, 1, 1, 1, 1, 1], code: 1, 'code-size': 1, pad: { quote: 0, code: 0, table: 0 }, 'table-style': 'rules',
+ }
+ expect(gridOf(ok)).not.toBe(null)
+ expect(gridOf({ ...ok, body: -1 })).toBe(null)
+ expect(gridOf({ ...ok, body: NaN })).toBe(null)
+ expect(gridOf({ ...ok, code: Infinity })).toBe(null)
+ expect(gridOf({ ...ok, heading: [1, 1, 1, 1, 1, -1] })).toBe(null)
+ expect(gridOf({ ...ok, heading: [1, 1, 1, 1, 1, 1, 1] })).toBe(null)
+ expect(gridOf({ ...ok, 'code-size': 0 })).toBe(null)
+ expect(gridOf({ ...ok, 'code-size': undefined })).toBe(null)
+ expect(gridOf({ ...ok, pad: undefined })).toBe(null)
+ expect(gridOf({ ...ok, pad: { ...ok.pad, table: -1 } })).toBe(null)
+ expect(gridOf(null)).toBe(null)
+ expect(gridOf('grid')).toBe(null)
+})
+
+test('grid rows: at least 1, and a small excess over whole rows is not a row', () => {
+ expect(gridRowsOf(0, 10)).toBe(1)
+ expect(gridRowsOf(10, 10)).toBe(1)
+ expect(gridRowsOf(10.0009, 10)).toBe(1)
+ expect(gridRowsOf(10.1, 10)).toBe(2)
+ expect(gridRowsOf(25, 10)).toBe(3)
+})
+
+// ---- Themes ------------------------------------------------------------------
+
+test('a theme name and description that are not strings are empty; the title is the folder name then', () => {
+ expect(themeEntry('t', '/u/t', true, '{"name":3,"description":null}')).toMatchObject({ title: 't', description: '' })
+ expect(themeEntry('t', '/u/t', true, '{"name":""}')).toMatchObject({ title: 't' })
+})
+
+test('a theme folder name with a bad character gives a reason; "syntax": null is not an object', () => {
+ expect(themeEntry('a b', '/u/a b', false, '{}')).toEqual({
+ name: 'a b', dir: '/u/a b', isUser: false, reason: 'the folder name has characters other than letters, digits, ., _ and -',
+ })
+ expect(themeEntry('a', '/u/a', true, '{"syntax":null}')).toMatchObject({ reason: '"syntax" is not an object of file names' })
+ expect(themeEntry('a', '/u/a', true, '{"syntax":{"dark":"../x"}}')).toMatchObject({ reason: expect.stringContaining('"syntax.dark"') })
+ expect(themeEntry('a', '/u/a', true, '{"syntax":{"sepia":"x.tmTheme"}}')).toMatchObject({ syntax: {} })
+})
+
+test('a syntax path is a non-empty relative name inside the folder', () => {
+ for (const bad of [undefined, null, 3, '', ' ', '/x', '..', 'a/../b', 'a\\b']) expect(isSyntaxPath(bad)).toBe(false)
+ for (const ok of ['x.tmTheme', 'sub/x.tmTheme', 'a..b']) expect(isSyntaxPath(ok)).toBe(true)
+})
+
+test('the theme names: a letter or digit first, then letters, digits, ., _ and -', () => {
+ for (const ok of ['a', '9', 'Sun.Light', 'a_b-c']) expect(isThemeName(ok)).toBe(true)
+ for (const bad of ['', '-a', '_a', 'a b', 'a/b', 'é']) expect(isThemeName(bad)).toBe(false)
+})
+
+test('the theme list is sorted by name, tells when there are none, and shows the folder as given without a home', () => {
+ const { themes, problems } = pickThemes([themeEntry('b', '/m/b', false, '{}'), themeEntry('a', '/m/a', false, '{"description":"first"}')])
+ const lines = themeListing(themes, problems, 'zzz', '/u/themes').split('\n')
+ expect(lines).toEqual(['Themes:', '- a: first', '- b', '', 'Change it with /iui theme <name>. Your own themes go in /u/themes/<name>/theme.json.'])
+ expect(themeListing(new Map(), [], 'x', '/u/themes')).toContain('Themes:\n- none found\n')
+ expect(themeListing(new Map(), [], 'x', '/home/me/t', '/home/me')).toContain('~/t/<name>/theme.json')
+ expect(themeListing(new Map(), [], 'x', '/homer/t', '/home')).toContain('/homer/t/')
+ expect(themeListing(new Map(), [{ name: 'p', dir: '/m/p', isUser: false, reason: 'bad' }], 'x', '/u')).toContain('- p: not usable, bad')
+})
+
+test('a built-in problem is listed without "(yours)"; a user theme of the base name does not replace the base for the fallback', () => {
+ const { themes, problems } = pickThemes([
+ themeEntry('x', '/m/x', false, '[]'),
+ themeEntry(BASE_THEME, '/u/vscode', true, '{}'),
+ ])
+ expect(problems.map(p => p.name)).toEqual(['x'])
+ expect(chooseTheme(themes, 'gone', '/mod')).toEqual({ name: BASE_THEME, dir: '/u/vscode', isFallback: true })
+})
+
+test('the stamp files: a base theme with its own syntax files is used for a mode the theme does not name', () => {
+ const base = themeEntry('vscode', '/mod/render/themes/vscode', false, '{"syntax":{"dark":"d2.tmTheme"}}') as any
+ const own = themeEntry('own', '/u/own', true, '{}') as any
+ expect(themeFiles(own, base, '/mod')).toEqual([
+ '/u/own/theme.json', '/mod/render/themes/vscode/theme.json', '/mod/render/themes/vscode/d2.tmTheme', '/mod/render/themes/vscode/light.tmTheme',
+ ])
+})
+
+test('the room is the smaller of the viewport and the tty, less the bullet; one of them alone is used', () => {
+ const saved = { tty: S.tty, view: S.viewColumns, frame: S.frame }
+ try {
+ S.frame = null
+ S.viewColumns = null
+ S.tty = null
+ expect(roomColumns({ columns: 100 })).toBe(98)
+ S.tty = { columns: 80, rows: 24, cell: { width: 16, height: 32 } } as any
+ expect(roomColumns({ columns: 100 })).toBe(78)
+ expect(roomColumns({ columns: 60 })).toBe(58)
+ expect(roomColumns(null)).toBe(78)
+ S.viewColumns = 70
+ expect(roomColumns()).toBe(68)
+ } finally {
+ S.tty = saved.tty
+ S.viewColumns = saved.view
+ S.frame = saved.frame
+ }
+})
+
+test('typst gets no network in either case of the proxy variables, and its package cache; fonts only when set', () => {
+ const saved = S.fontPaths
+ try {
+ S.fontPaths = ''
+ const env = noNetworkEnv('/c')
+ for (const k of ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'all_proxy']) expect(env[k]).toBe('http://127.0.0.1:9')
+ expect(env.NO_PROXY).toBe('')
+ expect(env.no_proxy).toBe('')
+ expect(env.TYPST_PACKAGE_CACHE_PATH).toBe('/c/pkg-cache')
+ expect('TYPST_FONT_PATHS' in env).toBe(false)
+ S.fontPaths = '/f1:/f2'
+ expect(noNetworkEnv('/c').TYPST_FONT_PATHS).toBe('/f1:/f2')
+ } finally {
+ S.fontPaths = saved
+ }
+})
diff --git a/tests/setup.test.ts b/tests/setup.test.ts
index 0bc5f45..e918669 100644
--- a/tests/setup.test.ts
+++ b/tests/setup.test.ts
@@ -1,6 +1,6 @@
import { expect, mock, test } from 'claude-code/testing'
-import { hasSetup, parseCommand, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup } from '../hooks/register'
+import { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup } from '../hooks/register'
test('the setup writes the start file of the login shell', () => {
expect(shellRcOf({ shell: '/bin/zsh', home: '/h', isMac: true })).toEqual({ path: '/h/.zshrc', kind: 'sh' })
@@ -11,6 +11,14 @@ test('the setup writes the start file of the login shell', () => {
expect(shellRcOf({ shell: '/bin/tcsh', home: '/h', isMac: true })).toBe(null)
})
+test('the start file: an empty ZDOTDIR or XDG_CONFIG_HOME is not used, a shell with no path works, no shell gives none', () => {
+ expect(shellRcOf({ shell: 'zsh', home: '/h', zdotdir: '', isMac: false })!.path).toBe('/h/.zshrc')
+ expect(shellRcOf({ shell: '/usr/bin/fish', home: '/h', xdgConfig: '/x', isMac: false })!.path).toBe('/x/fish/conf.d/cc-intelligent-ui.fish')
+ expect(shellRcOf({ shell: '/usr/bin/fish', home: '/h', xdgConfig: '', isMac: false })!.path).toBe('/h/.config/fish/conf.d/cc-intelligent-ui.fish')
+ expect(shellRcOf({ shell: '', home: '/h', isMac: true })).toBe(null)
+ expect(shellRcOf({ shell: '/bin/zsh-5.9', home: '/h', isMac: true })).toBe(null)
+})
+
test('the block sets the variable in iTerm2 only, not in tmux or screen', () => {
const sh = setupBlock('sh')
expect(sh.startsWith(`${SETUP_START}\n`)).toBe(true)
@@ -31,17 +39,31 @@ test('adding the block twice keeps one; removing it gives the file back', () =>
expect(withoutSetup(`a\n${SETUP_START}\nb`)).toBe(`a\n${SETUP_START}\nb`)
})
-test('/iui setup and setup remove are commands', () => {
- expect(parseCommand('setup')).toEqual({ kind: 'setup', remove: false })
- expect(parseCommand('Setup Remove')).toEqual({ kind: 'setup', remove: true })
- expect(parseCommand('setup now')).toEqual({ kind: 'bad' })
+test('removing the block leaves the lines around it; every block goes; a file with none is the same', () => {
+ const block = setupBlock('sh')
+ expect(withoutSetup(`a\n\n${block}\nb\n`)).toBe('a\n\nb\n')
+ expect(withoutSetup(`${block}b\n`)).toBe('b\n')
+ expect(withoutSetup(`a\n\n${block}\nb\n\n${block}`)).toBe('a\n\nb\n')
+ expect(withoutSetup('a\nb\n')).toBe('a\nb\n')
+ expect(withoutSetup('')).toBe('')
+ expect(hasSetup('a\n')).toBe(false)
+})
+
+test('a block of the other kind is replaced, not added next to the first', () => {
+ const fish = withSetup('set -x A 1\n', 'fish')
+ const sh = withSetup(fish, 'sh')
+ expect(sh.split(SETUP_START).length).toBe(2)
+ expect(sh).not.toContain('set -gx')
+ expect(sh.startsWith('set -x A 1\n\n')).toBe(true)
})
// An iTerm2 session on a Mac with the engine's pictures off and a zsh user.
-const iterm = (on: any, files: Record<string, string>, answer: string | null) => {
- mock.store(on)
+const iterm = (on: any, files: Record<string, string>, answer: string | null, o: { env?: Record<string, string>; stored?: Record<string, unknown> } = {}) => {
+ const store = new Map(Object.entries(o.stored ?? {}))
+ on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))
+ on('store.set', async ($: any, e: any) => (store.set(e.key, e.value), { value: undefined }))
const clock = mock.clock(on)
- mock.env(on, { HOME: '/h', SHELL: '/bin/zsh', TERM_PROGRAM: 'iTerm.app', ITERM_PROFILE: 'Default' })
+ mock.env(on, { HOME: '/h', SHELL: '/bin/zsh', TERM_PROGRAM: 'iTerm.app', ITERM_PROFILE: 'Default', ...o.env })
const asked: string[] = []
// $.ui.ask runs as a call of the AskUserQuestion tool.
on('tool.call', { tool: 'AskUserQuestion' }, async ($: any, e: any) => {
@@ -52,12 +74,15 @@ const iterm = (on: any, files: Record<string, string>, answer: string | null) =>
})
const toasts: string[] = []
const logs: string[] = []
+ const mkdirs: string[] = []
on('ui.toast', async ($: any, e: any) => (toasts.push(e.text), { value: undefined }))
on('ui.log', async ($: any, e: any) => (logs.push(e.text), { value: undefined }))
- on('process.run', async ($: any, e: any, next: any) =>
- e.argv[0] === 'sh' && /cc-intelligent-ui-/.test(e.argv.join(' '))
+ on('process.run', async ($: any, e: any, next: any) => {
+ if (e.argv[0] === 'mkdir') return mkdirs.push(e.argv.slice(1).join(' ')), { value: { exitCode: 0, stdout: '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }
+ return e.argv[0] === 'sh' && /cc-intelligent-ui-/.test(e.argv.join(' '))
? { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }
- : next(e))
+ : next(e)
+ })
on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.startsWith('/h/') ? { deny: 'no such file' } : next(e)))
on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/h/') ? { value: e.path in files } : next(e)))
on('fs.write', async ($: any, e: any, next: any) => {
@@ -65,7 +90,7 @@ const iterm = (on: any, files: Record<string, string>, answer: string | null) =>
files[e.path] = e.text
return { value: undefined }
})
- return { asked, clock, toasts, logs }
+ return { asked, clock, toasts, logs, store, mkdirs }
}
test('in iTerm2 with pictures off, the plugin asks once and adds the block on yes', async ($, on) => {
@@ -96,3 +121,106 @@ test('a dismissed question changes no file', async ($, on) => {
expect(asked.length).toBe(1)
expect(files['/h/.zshrc']).toBe('export A=1\n')
})
+
+test('"Never ask" is kept, and later loads do not ask', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ const first = iterm(on, files, 'Never ask')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await first.clock.settle()
+ expect(first.asked.length).toBe(1)
+ expect(first.store.get('setup')).toBe('never')
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+ expect(first.toasts.filter(t => /tab|transcript/.test(t))).toEqual([])
+})
+
+test('a block already there means no question', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': withSetup('export A=1\n', 'sh') }
+ const { asked, clock } = iterm(on, files, 'Add the line')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked).toEqual([])
+})
+
+test('a stored "never" means no question', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ const { asked, clock } = iterm(on, files, 'Add the line', { stored: { setup: 'never' } })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked).toEqual([])
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+})
+
+test('"Not now" changes no file and is not kept', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ const { asked, clock, store } = iterm(on, files, 'Not now')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked.length).toBe(1)
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+ expect(store.has('setup')).toBe(false)
+})
+
+test('the question is asked once per load, not at each /iui', async ($, on) => {
+ const { asked, clock } = iterm(on, { '/h/.zshrc': '' }, 'Not now')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked.length).toBe(1)
+})
+
+test('with a shell it does not know, /iui setup changes no file and names the line to add; the question says the start file is unknown', async ($, on) => {
+ const files: Record<string, string> = {}
+ const { asked, clock } = iterm(on, files, 'Not now', { env: { SHELL: '/bin/tcsh' } })
+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(ran.text).toContain('does not know your shell, so it changed no file')
+ expect(ran.text).toContain('export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1')
+ await clock.settle()
+ expect(asked[0]).toContain("your shell's start file")
+ expect(files).toEqual({})
+})
+
+test('/iui setup remove with no block says so and writes nothing', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ iterm(on, files, 'Not now', { stored: { setup: 'never' } })
+ const ran = await $.command.run({ command: 'iui', args: 'setup remove' } as any)
+ expect(ran.text).toBe('/h/.zshrc has no Intelligent UI block.')
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+})
+
+test('/iui setup makes a start file that does not exist yet, with only the block', async ($, on) => {
+ const files: Record<string, string> = {}
+ iterm(on, files, 'Not now', { stored: { setup: 'never' } })
+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(ran.text).toContain('Added the Intelligent UI block to /h/.zshrc.')
+ expect(files['/h/.zshrc']).toBe(setupBlock('sh'))
+})
+
+test('for fish, /iui setup makes the conf.d folder first and writes the fish block; XDG_CONFIG_HOME is used', async ($, on) => {
+ const files: Record<string, string> = {}
+ const { mkdirs } = iterm(on, files, 'Not now', { stored: { setup: 'never' }, env: { SHELL: '/usr/bin/fish', XDG_CONFIG_HOME: '/h/x' } })
+ await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(mkdirs).toEqual(['-p /h/x/fish/conf.d'])
+ expect(files['/h/x/fish/conf.d/cc-intelligent-ui.fish']).toBe(setupBlock('fish'))
+ const removed = await $.command.run({ command: 'iui', args: 'setup remove' } as any)
+ expect(removed.text).toContain('Removed the Intelligent UI block from /h/x/fish/conf.d/cc-intelligent-ui.fish.')
+ expect(files['/h/x/fish/conf.d/cc-intelligent-ui.fish']).toBe('')
+})
+
+test('the question shows the start file with ~ for the home folder, and ZDOTDIR moves it', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zsh/.zshrc': '' }
+ const { asked, clock } = iterm(on, files, 'Not now', { env: { ZDOTDIR: '/h/.zsh' } })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked[0]).toContain('~/.zsh/.zshrc')
+})
+
+test('a yes with a shell it does not know changes no file; the toast points to the transcript', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': '' }
+ const { clock, toasts } = iterm(on, files, 'Add the line', { env: { SHELL: '/bin/tcsh' } })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ // The shell is not known: the question was asked, a yes changes no file.
+ expect(files['/h/.zshrc']).toBe('')
+ expect(toasts.filter(t => /transcript|tab/.test(t))).toEqual(['See the transcript for the setup.'])
+})
diff --git a/tests/stream.test.ts b/tests/stream.test.ts
index 12322e2..b663b14 100644
--- a/tests/stream.test.ts
+++ b/tests/stream.test.ts
@@ -5,9 +5,13 @@ import { DEFAULT_CELL, DEFAULT_METRICS, DEFAULT_THEME, fontFit, hashOf, nextJob,
// driven with this test's `$`: pagesOf and the queue and results it fills
// are module state, which register.tsx does not export.
import { epochOpen, lastKey, queue, results, running, S, type Env } from '../hooks/lib/state'
+import { finalized, inlined, INLINE_KEPT, live, pending, type Job } from '../hooks/lib/state'
+import { enqueue, finalizeAll, forget, pump, waitBlank } from '../hooks/lib/stream'
+import { inlineOf } from '../hooks/lib/draw'
import { pagesOf } from '../hooks/lib/answer'
import { beginEpoch } from '../hooks/lib/epoch'
import { forgetTouches } from '../hooks/lib/typst'
+import { INLINE_MAX_BYTES } from '../hooks/lib/terminal'
import { COMMIT_MIN_MS, TOUCH_FLUSH_MS } from '../hooks/lib/settings'
// The world beneath the mod for one compile: a cache folder, a typst whose
@@ -574,3 +578,209 @@ test('a row drawn late in an epoch (150 ms after its begin) still swaps at the c
expect(redraws()).toBe(before + 1)
for (const id of ids) expect(await draw(id, narrow)).toMatchObject({ kind: 'pages', result: { pages: [{ columns: 78 }] } })
})
+
+// ---- The queue and the blocks on their own ----------------------------------------
+
+const jobOf = (key: string, requestId = key, more: Partial<Job> = {}): Job =>
+ ({
+ key, requestId, text: `Text of ${key}.`, columns: 98, cell: DEFAULT_CELL, theme: 'dark', size: 100, grid: false, themeDir: '/mod/t', env: ENV, epoch: 0, ...more,
+ }) as Job
+const RESULT = { pages: [{ ...PAGE, file: '/c/k/a-1.png' }], bulletRow: 0 }
+// The state a test of this part starts from, with no job able to start.
+function idle() {
+ const w = compiler()
+ live.clear()
+ pending.clear()
+ finalized.clear()
+ return w
+}
+
+test('a key that has a result is not queued', () => {
+ const { $ } = idle()
+ S.resizing = true
+ results.set('done', RESULT)
+ enqueue($, jobOf('done'))
+ expect(queue.length).toBe(0)
+ expect(running.size).toBe(0)
+})
+
+test('a job takes the place of one of the same request or the same key', () => {
+ const { $ } = idle()
+ S.resizing = true
+ enqueue($, jobOf('a', 'r1'))
+ enqueue($, jobOf('b', 'r1'))
+ expect(queue.map(j => j.key)).toEqual(['b'])
+ enqueue($, jobOf('b', 'r2'))
+ expect(queue.map(j => [j.key, j.requestId])).toEqual([['b', 'r2']])
+ enqueue($, jobOf('c', 'r3'))
+ expect(queue.length).toBe(2)
+})
+
+test('no job starts during a burst, and the queue runs once it ends', async () => {
+ const { $, runs } = idle()
+ S.resizing = true
+ enqueue($, jobOf('a'))
+ pump($)
+ await drain()
+ expect(running.size).toBe(0)
+ expect(runs.length).toBe(0)
+ S.resizing = false
+ pump($)
+ await drain()
+ expect(running.has('a')).toBe(true)
+ expect(runs.length).toBe(1)
+})
+
+test('a key that runs is not queued again; one that was cancelled is', async () => {
+ const { $, runs } = idle()
+ enqueue($, jobOf('a', 'r1'))
+ await drain()
+ const first = running.get('a')!
+ enqueue($, jobOf('a', 'r2'))
+ expect(queue.length).toBe(0)
+ expect(running.get('a')).toBe(first)
+ first.cancel()
+ enqueue($, jobOf('a', 'r3'))
+ expect(running.get('a')).not.toBe(first)
+ expect(running.get('a')!.job.requestId).toBe('r3')
+ for (const run of runs) run.end(null)
+ await drain()
+})
+
+test('a blocks still live is final at once by finalizeAll: queued, blank, and drawn again', async () => {
+ const { $, redraws } = idle()
+ S.resizing = true
+ const cancelled: string[] = []
+ for (const id of ['x', 'y']) live.set(id, { job: jobOf(id), still: { cancel: () => cancelled.push(id) } })
+ finalizeAll($)
+ await drain()
+ expect(cancelled).toEqual(['x', 'y'])
+ expect(live.size).toBe(0)
+ expect([...finalized]).toEqual(['x', 'y'])
+ expect(queue.map(j => j.requestId)).toEqual(['x', 'y'])
+ expect([...pending.keys()]).toEqual(['x', 'y'])
+ expect(pending.get('x')).toMatchObject({ showText: false, textHash: hashOf(['Text of x.']) })
+ expect(redraws()).toBe(2)
+})
+
+test('forget stops the live and pending timers of a block', () => {
+ idle()
+ const cancelled: string[] = []
+ live.set('f', { job: jobOf('f'), still: { cancel: () => cancelled.push('still') } })
+ pending.set('f', { textHash: 'h', showText: false, timer: { cancel: () => cancelled.push('timer') } })
+ forget('f')
+ expect(cancelled).toEqual(['still', 'timer'])
+ expect(live.has('f')).toBe(false)
+ expect(pending.has('f')).toBe(false)
+ forget('f')
+ expect(cancelled.length).toBe(2)
+})
+
+test('a final block stays blank for ms; the same text keeps its timer, another text starts a new one', async () => {
+ const { $, advance, redraws } = idle()
+ waitBlank($, 'w', 'h1', 100)
+ const first = pending.get('w')!
+ waitBlank($, 'w', 'h1', 100)
+ expect(pending.get('w')).toBe(first)
+ advance(99)
+ await drain()
+ expect(first.showText).toBe(false)
+ expect(redraws()).toBe(0)
+ advance(1)
+ await drain()
+ expect(first.showText).toBe(true)
+ expect(redraws()).toBe(1)
+ waitBlank($, 'w', 'h2', 100)
+ expect(pending.get('w')).not.toBe(first)
+ expect(pending.get('w')).toMatchObject({ textHash: 'h2', showText: false })
+})
+
+test('a compile that throws leaves a failed result, and a failed result draws as text', async () => {
+ const { $, runs } = idle()
+ $.fs.write = async () => {
+ throw new Error('disk full')
+ }
+ const draw = () => pagesOf($, { id: 'boom', text: 'Boom.', frame: FRAME, env: ENV, canStream: false, onScreen: true })
+ expect((await draw()).kind).toBe('blank')
+ await drain()
+ expect(runs.length).toBe(0)
+ expect(results.get(keyOf('Boom.'))).toBe('failed')
+ expect(running.size).toBe(0)
+ expect(await draw()).toEqual({ kind: 'text' })
+ expect(queue.length).toBe(0)
+})
+
+test('a pages.json that is not valid drops its key from the keys on disk, and the text compiles', async () => {
+ const { $, runs } = idle()
+ $.fs.read = async () => '{"pages": []}'
+ const key = keyOf('Old.')
+ S.onDisk = new Set([key])
+ const drawing = await pagesOf($, { id: 'bad-disk', text: 'Old.', frame: FRAME, env: ENV, canStream: false, onScreen: true })
+ expect(S.onDisk.has(key)).toBe(false)
+ expect(drawing.kind).toBe('blank')
+ await drain()
+ expect(runs.length).toBe(1)
+})
+
+// ---- Pages as bytes over ssh ----------------------------------------------------------
+
+function sshFs(read: (path: string) => Promise<{ base64: string }>) {
+ const reads: string[] = []
+ const $ = {
+ fs: {
+ read: async (path: string) => {
+ reads.push(path)
+ return read(path)
+ },
+ },
+ } as any
+ inlined.clear()
+ return { $, reads }
+}
+const small = (file: string, height = 64) => ({ ...PAGE, file, width: 1600, height })
+
+test('over ssh a page goes as its bytes, read once', async () => {
+ const { $, reads } = sshFs(async () => ({ base64: 'AAAA' }))
+ const result = { pages: [small('/c/i/a-1.png'), small('/c/i/a-2.png')], bulletRow: 0 }
+ expect(await inlineOf($, result)).toEqual(['AAAA', 'AAAA'])
+ expect(await inlineOf($, result)).toEqual(['AAAA', 'AAAA'])
+ expect(reads).toEqual(['/c/i/a-1.png', '/c/i/a-2.png'])
+})
+
+test('over ssh a page too tall for bytes is not read', async () => {
+ const { $, reads } = sshFs(async () => ({ base64: 'AAAA' }))
+ expect(await inlineOf($, { pages: [small('/c/t/a-1.png'), small('/c/t/a-2.png', 5000)], bulletRow: 0 })).toBe(null)
+ expect(reads).toEqual(['/c/t/a-1.png'])
+ expect(await inlineOf($, { pages: [small('/c/t/a-3.png', 5000)], bulletRow: 0 })).toBe(null)
+ expect(reads.length).toBe(1)
+})
+
+test('over ssh a file that can not be read is read again next time; one that is too large is not', async () => {
+ let readable = false
+ const { $, reads } = sshFs(async () => {
+ if (!readable) throw new Error('EACCES')
+ return { base64: 'A'.repeat(Math.ceil(INLINE_MAX_BYTES / 3) * 4 + 4) }
+ })
+ const result = { pages: [small('/c/u/a-1.png')], bulletRow: 0 }
+ expect(await inlineOf($, result)).toBe(null)
+ expect(inlined.has('/c/u/a-1.png')).toBe(false)
+ readable = true
+ expect(await inlineOf($, result)).toBe(null)
+ expect(inlined.get('/c/u/a-1.png')).toBe(null)
+ expect(await inlineOf($, result)).toBe(null)
+ expect(reads.length).toBe(2)
+})
+
+test('over ssh the bytes of the oldest files go past INLINE_KEPT', async () => {
+ const { $, reads } = sshFs(async () => ({ base64: 'AAAA' }))
+ const file = (i: number) => `/c/e/a-${i}.png`
+ for (let i = 0; i < INLINE_KEPT + 6; i++) await inlineOf($, { pages: [small(file(i))], bulletRow: 0 })
+ expect(inlined.size).toBe(INLINE_KEPT)
+ expect(inlined.has(file(0))).toBe(false)
+ expect(inlined.has(file(INLINE_KEPT + 5))).toBe(true)
+ const read = reads.length
+ await inlineOf($, { pages: [small(file(INLINE_KEPT + 5))], bulletRow: 0 })
+ expect(reads.length).toBe(read)
+ await inlineOf($, { pages: [small(file(0))], bulletRow: 0 })
+ expect(reads.length).toBe(read + 1)
+})
diff --git a/tests/terminals.test.ts b/tests/terminals.test.ts
index 9244c69..e435608 100644
--- a/tests/terminals.test.ts
+++ b/tests/terminals.test.ts
@@ -43,6 +43,28 @@ test('kitty includes are read in place, each file once (no loops); other include
expect(await kittyEntriesOf('/none', async () => null, { home: '/h' })).toEqual([])
})
+test('kitty reads at most 32 files; a chain of includes stops there', async () => {
+ const read: string[] = []
+ const entries = await kittyEntriesOf('/k/0.conf', async p => {
+ read.push(p)
+ const n = Number(/(\d+)\.conf$/.exec(p)![1])
+ return `font_size ${n}\ninclude ${n + 1}.conf\n`
+ }, { home: '/h' })
+ expect(read.length).toBe(32)
+ expect(entries.length).toBe(32)
+ expect(kittyValueOf(entries, 'font_size')).toBe('31')
+})
+
+test('kitty config lines: tabs and indents split the key, a key needs a letter first, # lines are comments even when indented', () => {
+ expect(kittyLinesOf('\tbackground\t#101010\n # background #ffffff\n1x y\nforeground#000')).toEqual([['background', '#101010']])
+})
+
+test('a kitty include of ~ alone is the home folder, and a trailing-slash folder gets one slash', () => {
+ expect(kittyIncludePath('~', '/d', { home: '/h' })).toBe('/h')
+ expect(kittyIncludePath('a.conf', '/d//', { home: '/h' })).toBe('/d/a.conf')
+ expect(kittyIncludePath(' b.conf ', '/d', { home: '/h' })).toBe('/d/b.conf')
+})
+
test('kitty config folders: KITTY_CONFIG_DIRECTORY alone, else XDG, ~/.config, and on macOS ~/Library/Preferences', () => {
expect(kittyConfigDirsOf({ kittyDir: '/x', xdgConfig: '/xdg', home: '/h', isMac: true })).toEqual(['/x'])
expect(kittyConfigDirsOf({ home: '/h', isMac: false })).toEqual(['/h/.config/kitty'])
@@ -123,6 +145,12 @@ test('the TOML reader: tables, dotted and quoted keys, strings, inline tables, c
expect(v['navigation.renderer.backend']).toBe('Metal')
})
+test('the TOML reader: array tables count as tables, numbers and arrays are skipped, a bad line is skipped', () => {
+ const v = tomlStringsOf(['[[keyboard.bindings]]', 'key = "q"', 'with = \'literal \\n\'', 'list = ["a", "b"]', 'not a line', '= "x"', 'ok = "y" # c'].join('\n'))
+ expect(v).toEqual({ 'keyboard.bindings.key': 'q', 'keyboard.bindings.with': 'literal \\n', 'keyboard.bindings.ok': 'y' })
+ expect(tomlStringsOf('')).toEqual({})
+})
+
test('Rio config folder and theme files', () => {
expect(rioConfigDirOf({ rioHome: '/r', xdgConfig: '/xdg', home: '/h', isMac: false })).toBe('/r')
expect(rioConfigDirOf({ xdgConfig: '/xdg', home: '/h', isMac: false })).toBe('/xdg/rio')
@@ -194,6 +222,22 @@ test("cmux settings: app.appearance and terminal.adaptiveDefaultTheme, nested or
expect(cmuxAppearanceOf('light', 'dark')).toBe('light')
})
+test('cmux appearance: the saved value is read in any case, a word it does not know is system', () => {
+ expect(cmuxAppearanceOf(undefined, ' Light\n')).toBe('light')
+ expect(cmuxAppearanceOf(undefined, 'DARK')).toBe('dark')
+ expect(cmuxAppearanceOf(undefined, 'sepia')).toBe('system')
+ expect(cmuxSettingsOf({ 'terminal.adaptiveDefaultTheme': true })).toEqual({ adaptive: true })
+ expect(cmuxSettingsOf({ app: 'x', terminal: null })).toEqual({})
+ expect(cmuxSettingsOf([])).toEqual({})
+})
+
+test('JSONC: a comment marker inside a string stays, an unclosed block comment is not valid, a trailing comma in an array goes', () => {
+ expect(jsoncOf('{"u": "http://x/y", "a": [1, 2,],}')).toEqual({ u: 'http://x/y', a: [1, 2] })
+ expect(jsoncOf('{"a": 1 /* open')).toBe(null)
+ expect(jsoncOf('// only a comment')).toBe(null)
+ expect(jsoncOf('{"a": "x,}"}')).toEqual({ a: 'x,}' })
+})
+
test('Ghostty colours of your own: a theme, background, foreground or palette', () => {
expect(ghosttyHasColors('font-family = Menlo\n')).toBe(false)
expect(ghosttyHasColors('theme = Night\n')).toBe(true)
diff --git a/tests/updates.test.ts b/tests/updates.test.ts
index ce59a8b..c57bd26 100644
--- a/tests/updates.test.ts
+++ b/tests/updates.test.ts
@@ -1,7 +1,7 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- agoText, checkedOf, commandSuggestions, compareVersions, isDue, isNewer, parseCommand, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS,
+ agoText, checkedOf, commandSuggestions, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS,
UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS, UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,
} from '../hooks/register'
@@ -33,6 +33,8 @@ test('the version of a plugin.json: only this mod, only a version that parses',
expect(versionOf('404: Not Found')).toBe(null)
expect(versionOf('[]')).toBe(null)
expect(versionOf('null')).toBe(null)
+ expect(versionOf('{"version":3}')).toBe(null)
+ expect(versionOf('{"version":" 1.2.3.4 "}')).toBe('1.2.3.4')
})
test('a check is due 24 h after the last one; a version is told once a day', () => {
@@ -45,12 +47,22 @@ test('a check is due 24 h after the last one; a version is told once a day', ()
expect(checkedOf({ at: NOW, latest: 'junk' })).toEqual({ at: NOW, latest: '' })
expect(checkedOf({ at: 'now' })).toBe(null)
expect(checkedOf('x')).toBe(null)
+ expect(checkedOf(null)).toBe(null)
+ expect(checkedOf({ at: Number.NaN, latest: '0.3.0' })).toBe(null)
+ expect(checkedOf({ at: Infinity, latest: '0.3.0' })).toBe(null)
+ expect(checkedOf({ at: NOW, latest: 'v0.3.0' })).toEqual({ at: NOW, latest: '0.3.0' })
+ expect(checkedOf({ at: NOW })).toEqual({ at: NOW, latest: '' })
expect(toldOf({ version: '0.3.0', at: NOW })).toEqual({ version: '0.3.0', at: NOW })
expect(toldOf({ version: 3, at: NOW })).toBe(null)
+ expect(toldOf({ version: '0.3.0', at: Number.NaN })).toBe(null)
+ expect(toldOf({ version: '0.3.0' })).toBe(null)
+ expect(toldOf(undefined)).toBe(null)
expect(shouldTell(null, '0.3.0', NOW)).toBe(true)
expect(shouldTell({ version: '0.3.0', at: NOW - HOUR }, '0.3.0', NOW)).toBe(false)
expect(shouldTell({ version: '0.3.0', at: NOW - UPDATE_EVERY_MS }, '0.3.0', NOW)).toBe(true)
expect(shouldTell({ version: '0.3.0', at: NOW - HOUR }, '0.4.0', NOW)).toBe(true)
+ // The clock went back: told again.
+ expect(shouldTell({ version: '0.3.0', at: NOW + HOUR }, '0.3.0', NOW)).toBe(true)
})
test('the toast, the details line and the /iui notice', () => {
@@ -65,6 +77,11 @@ test('the toast, the details line and the /iui notice', () => {
expect(updateLine({ ...o, on: false })).toBe('off')
expect(updateLine({ ...o, off: 'DISABLE_UPDATES' })).toBe('off (DISABLE_UPDATES is set)')
expect(updateLine({ ...o, own: '' })).toBe('on, the version installed is not known')
+ // A version older than the one installed is up to date too.
+ expect(updateLine({ ...o, own: '0.4.0' })).toBe('on, up to date (0.4.0, checked 3 hours ago)')
+ expect(updateLine({ ...o, on: false, off: 'DISABLE_UPDATES' })).toBe('off')
+ expect(updateNotice({ ...o, checked: null })).toBe('')
+ expect(updateNotice({ ...o, checked: { at: NOW, latest: '' } })).toBe('')
expect(updateNotice(o)).toBe(`Intelligent UI 0.3.0 is available (you have 0.2.0). To update: ${UPDATE_STEPS}.`)
expect(updateNotice({ ...o, on: false })).toBe('')
expect(updateNotice({ ...o, off: 'DISABLE_AUTOUPDATER' })).toBe('')
@@ -72,14 +89,13 @@ test('the toast, the details line and the /iui notice', () => {
expect(agoText(10 * 60 * 1000)).toBe('less than 1 hour ago')
expect(agoText(HOUR)).toBe('1 hour ago')
expect(agoText(72 * HOUR)).toBe('3 days ago')
+ expect(agoText(2 * HOUR)).toBe('2 hours ago')
+ expect(agoText(47 * HOUR + 59 * 60 * 1000)).toBe('47 hours ago')
+ expect(agoText(48 * HOUR)).toBe('2 days ago')
+ expect(agoText(-HOUR)).toBe('less than 1 hour ago')
})
test('/iui updates [on|off] is a command, with typeahead rows', () => {
- expect(parseCommand('updates')).toEqual({ kind: 'updates' })
- expect(parseCommand('Updates ON')).toEqual({ kind: 'updates', on: true })
- expect(parseCommand('updates off')).toEqual({ kind: 'updates', on: false })
- expect(parseCommand('updates maybe')).toEqual({ kind: 'bad' })
- expect(parseCommand('updates on now')).toEqual({ kind: 'bad' })
const o = { themes: [], active: 'claude-code', size: 100 }
const at = (text: string, more = {}) => {
const token = /\S+$/.exec(text)?.[0] ?? ''
@@ -184,6 +200,7 @@ for (const [name, answer] of [
['a 404', { status: 404, text: '404: Not Found' }],
['a text that is not JSON', { status: 200, text: '<html>' }],
['another plugin', { status: 200, text: '{"name":"other","version":"9.0.0"}' }],
+ ['a 500 with a good manifest', { status: 500, text: '{"name":"cc-intelligent-ui","version":"0.3.0"}' }],
['a version that does not parse', { status: 200, text: '{"name":"cc-intelligent-ui","version":"latest"}' }],
] as const) {
test(`a failed fetch (${name}) shows nothing, and waits 24 h too`, async ($, on) => {
@@ -267,3 +284,64 @@ test('a background session does not check', async ($, on) => {
await turn($, w)
expect(w.fetched).toEqual([])
})
+
+test('a version older than the one installed shows no toast, and the details say up to date', async ($, on) => {
+ const w = world(on, { answer: { status: 200, text: '{"version":"0.1.0"}' } })
+ await turn($, w)
+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.1.0' })
+ expect(w.toasts).toEqual([])
+ expect(w.store.has('update-told')).toBe(false)
+ expect(await updatesReply($)).toContain('Update checks: on, up to date (0.2.0, checked less than 1 hour ago).')
+})
+
+test('a check stored in the future (the clock went back) is due again', async ($, on) => {
+ const w = world(on, { stored: { 'update-check': { at: NOW + 5 * HOUR, latest: '0.2.0' } } })
+ await turn($, w)
+ expect(w.fetched).toEqual([UPDATE_URL])
+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.3.0' })
+})
+
+test('a toast told a day ago is shown again, with the time kept', async ($, on) => {
+ const w = world(on, { stored: { 'update-check': { at: NOW - 2 * HOUR, latest: '0.3.0' }, 'update-told': { version: '0.3.0', at: NOW - UPDATE_EVERY_MS } } })
+ await turn($, w)
+ expect(w.toasts.length).toBe(1)
+ expect(w.store.get('update-told')).toEqual({ version: '0.3.0', at: NOW })
+})
+
+test('a newer version than the one told is told at once', async ($, on) => {
+ const w = world(on, { stored: { 'update-check': { at: NOW - 2 * HOUR, latest: '0.4.0' }, 'update-told': { version: '0.3.0', at: NOW - HOUR } } })
+ await turn($, w)
+ expect(w.toasts.map(t => t.text)).toEqual([updateToast('0.4.0', '0.2.0')])
+})
+
+test('when the installed version is unknown, nothing is fetched and the details say so', async ($, on) => {
+ const w = world(on, { own: 'dev' })
+ await turn($, w)
+ expect(w.fetched).toEqual([])
+ expect(w.toasts).toEqual([])
+ expect(await updatesReply($)).toContain('Update checks: on, the version installed is not known.')
+})
+
+test('/iui updates on, with the last check over 24 h old, fetches at once', async ($, on) => {
+ const w = world(on, { stored: { updates: false, 'update-check': { at: NOW - 2 * UPDATE_EVERY_MS, latest: '0.2.0' } } })
+ await updatesReply($, 'updates on')
+ await w.clock.settle()
+ expect(w.fetched).toEqual([UPDATE_URL])
+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.3.0' })
+ expect(w.toasts.length).toBe(1)
+})
+
+test('a variable set to an off word (false, no, off) or to nothing does not stop the check', async ($, on) => {
+ const w = world(on, { env: { DISABLE_UPDATES: 'false', DISABLE_AUTOUPDATER: ' Off ', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '' } })
+ await turn($, w)
+ expect(w.fetched).toEqual([UPDATE_URL])
+})
+
+test('an answer that comes in time is used, and nothing waits for the timeout after it', async ($, on) => {
+ const w = world(on)
+ await turn($, w)
+ const before = w.store.get('update-check')
+ await w.clock.advance(UPDATE_FETCH_MS * 2)
+ expect(w.store.get('update-check')).toEqual(before)
+ expect(w.toasts.length).toBe(1)
+})