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
Updates: a daily check for a new version, its toast and /iui updates on|off; the Update docs
razorback1601331a7dc1e0
diff --git a/README.md b/README.mdindex 715f534..8c9139d 100644--- a/README.md+++ b/README.md@@ -22,6 +22,8 @@ Then, in Claude Code:It works at once, with no restart.+To get new versions, turn on auto-update for the `razorback16` marketplace in `/plugin`, or update manually. Refer to [Update](docs/install.md#update). The mod also shows a notice when a new version is available (`/iui updates off` stops it).+You need Claude Code 2.1.298 or later, [Typst](https://typst.app) 0.15 and macOS. The pictures show only in some terminals:| Terminal | Pictures | What to do |@@ -80,6 +82,7 @@ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Ma| `/iui theme <name>` | Changes the theme: `claude-code`, `vscode-modern`, `vscode` or your own || `/iui size <80–200>` | Text size in percent of your terminal text || `/iui grid on` / `off` | Puts each line of text on the terminal rows, so that a mouse selection covers the text (off by default) |+| `/iui updates on` / `off` | Turns the daily check for a new version on or off (on by default) || `/iui details` | Shows the terminal, font, mode and Typst that the mod found || `/iui setup` | iTerm2: adds the shell line that turns pictures on || `/iui grab` | Copies the text under your last mouse selection of pictures |@@ -89,7 +92,7 @@ All commands are in [Usage](docs/usage.md).## Docs-- [Install](docs/install.md): requirements and terminal support+- [Install](docs/install.md): requirements, terminal support and updates- [Usage](docs/usage.md): what it draws, commands, copy, plan approval- [Themes](docs/themes.md): built-in themes and your own- [How it works](docs/how-it-works.md): the render steps and light or dark modediff --git a/docs/development.md b/docs/development.mdindex cf51f0b..11906eb 100644--- a/docs/development.md+++ b/docs/development.md@@ -21,7 +21,7 @@ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines## Module layout-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.diff --git a/docs/install.md b/docs/install.mdindex 9d28323..ba8d4cd 100644--- a/docs/install.md+++ b/docs/install.md@@ -39,6 +39,37 @@ From a shell:claude plugin install cc-intelligent-ui --marketplace razorback16/cc-intelligent-ui```+## Update++Claude Code finds a new version of the mod from the version number in its `plugin.json`. For a marketplace that is not from Anthropic, such as `razorback16`, auto-update is off by default.++### Turn on auto-update++1. In Claude Code, type `/plugin`.+2. Go to **Marketplaces**, then select **razorback16**.+3. Select **Enable auto-update**.++Claude Code then updates the mod in approximately 10 minutes after the first message of a session. The new version starts in the next session, or after you type `/reload-plugins`.++### Update manually++From a shell:++```+claude plugin marketplace update razorback16+claude plugin update cc-intelligent-ui@razorback16+```++Then type `/reload-plugins` in Claude Code, or start a new session.++### The update notice++The mod looks for a new version one time each day at most, after a session starts. When there is a newer version, a toast shows the new version, your version and the update commands. A toast for one version shows one time each day at most. `/iui` and `/iui details` also show the new version.++- Network use: one GET request for a public file on GitHub (`https://raw.githubusercontent.com/razorback16/cc-intelligent-ui/main/.claude-plugin/plugin.json`) each day at most. The mod sends no data about you or your sessions. The request goes through Claude Code.+- `/iui updates off` stops the check and the toast (kept for later sessions). `/iui updates on` starts them again.+- The mod does not look for a new version when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_UPDATES` or `DISABLE_AUTOUPDATER` is set, in a background session, or with `claude -p`.+## Try it from a cloneTo try it from a clone without installing:diff --git a/docs/usage.md b/docs/usage.mdindex f213dbf..f649886 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -33,8 +33,8 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr| Command | What it does ||---|---|-| `/iui` | Shows the state, the theme, the text size, the width, the image height and the row grid, and a problem that keeps pictures away |-| `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path, why the terminal can or cannot show pictures, and if the automatic copy is on (`Auto copy:`) |+| `/iui` | Shows the state, the theme, the text size, the width, the image height and the row grid, a problem that keeps pictures away, and a new version when there is one |+| `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path, why the terminal can or cannot show pictures, if the automatic copy is on (`Auto copy:`), and the state of the update check (`Update checks:`) || `/iui on` / `off` | Turns the pictures on or off (kept for later sessions) || `/iui setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) || `/iui size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |@@ -48,6 +48,9 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr| `/iui grid` | Shows the row grid setting: on or off || `/iui grid on` | Puts each line of text in a picture on the terminal rows (kept for later sessions). Refer to [Selection and the row grid](#selection-and-the-row-grid). || `/iui grid off` | Lines of text in a picture have the usual spacing (kept for later sessions). This is the default. |+| `/iui updates` | Shows the update check: on or off, and the newest version that it found |+| `/iui updates on` | Looks for a new version one time each day at most, and shows a toast when there is one (kept for later sessions). This is the default. Refer to [Update](install.md#update). |+| `/iui updates off` | Stops the check for a new version and its toast (kept for later sessions) || `/iui theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes || `/iui theme <name>` | Changes to that theme (kept for later sessions) || `/iui grab` | Copies the text under your last mouse selection of pictures. Refer to [Copy text from a picture](#copy-text-from-a-picture). |diff --git a/hooks/lib/api.ts b/hooks/lib/api.tsindex 30600f0..c9d398e 100644--- a/hooks/lib/api.ts+++ b/hooks/lib/api.ts@@ -4,15 +4,16 @@// declaration that spells the call `$.noun.method(...)` (the validator// follows `$` into a declaration only), with the types of EngineInterface.import type {- AskOptions, CommandSpec, EngineInterface, FsBytes, FsReadBytesOptions, FsReadOptions, FsStatOptions, InvalidatableEventName,+ AskOptions, CommandSpec, EngineInterface, FsBytes, FsReadBytesOptions, FsReadOptions, FsStatOptions, HttpInit, InvalidatableEventName,OpEventOf, ProcessRunInit, ProcessSpawnRequest, ResolveInput, ToastOptions, UiCopyArgs, UiLogOptions,} from 'claude-code'// The environment variables the mod reads. `$.env.get` takes a literal name// (the validator lists them), so envGet has one call per name.export type EnvName =- | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'- | 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'GHOSTTY_RESOURCES_DIR' | 'HOME'+ | 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'+ | 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES'+ | 'GHOSTTY_RESOURCES_DIR' | 'HOME'| 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'| 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'XDG_CONFIG_HOME' | 'ZDOTDIR'@@ -25,6 +26,10 @@ export function clockEvery($: EngineInterface, ms: number, fn: () => void) {return $.clock.every(ms, fn)}+export function clockNow($: EngineInterface) {+ return $.clock.now()+}+export function commandRegister($: EngineInterface, command: CommandSpec) {return $.command.register(command)}@@ -39,6 +44,7 @@ export function configList($: EngineInterface) {export function envGet($: EngineInterface, name: EnvName): Promise<string | undefined> {switch (name) {+ case 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC': return $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC')case 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES': return $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')case 'CLAUDE_CODE_SESSION_KIND': return $.env.get('CLAUDE_CODE_SESSION_KIND')case 'CLAUDE_CODE_TMPDIR': return $.env.get('CLAUDE_CODE_TMPDIR')@@ -46,6 +52,8 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | undecase 'CMUX_SURFACE_ID': return $.env.get('CMUX_SURFACE_ID')case 'CMUX_WORKSPACE_ID': return $.env.get('CMUX_WORKSPACE_ID')case 'COLORFGBG': return $.env.get('COLORFGBG')+ case 'DISABLE_AUTOUPDATER': return $.env.get('DISABLE_AUTOUPDATER')+ case 'DISABLE_UPDATES': return $.env.get('DISABLE_UPDATES')case 'GHOSTTY_RESOURCES_DIR': return $.env.get('GHOSTTY_RESOURCES_DIR')case 'HOME': return $.env.get('HOME')case 'ITERM_PROFILE': return $.env.get('ITERM_PROFILE')@@ -93,6 +101,10 @@ export function fsWrite($: EngineInterface, path: string, text: string) {return $.fs.write(path, text)}+export function httpFetch($: EngineInterface, url: string, init?: HttpInit) {+ return $.http.fetch(url, init)+}+export function pluginRoot($: EngineInterface) {return $.plugin.root}diff --git a/hooks/lib/command.ts b/hooks/lib/command.tsindex a25723e..efc87f1 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -10,16 +10,18 @@ import { isThemeName, type ThemeInfo } from './themes'import { commandRegister } from './api'// `/iui` arguments: on, off, size <80-200>, width [40-400|full],-// height [6-200|half|full], grid [on|off], details (all Intelligent UI-// found), grab (copy the text of the last mouse selection of pictures), dump-// (how the last clipboard with picture cells was read), or nothing (show-// state). A `width`, `height` or `grid` with no value shows it.+// height [6-200|half|full], grid [on|off], updates [on|off], details (all+// Intelligent UI found), grab (copy the text of the last mouse selection of+// pictures), dump (how the last clipboard with picture cells was read), or+// nothing (show state). A `width`, `height`, `grid` or `updates` with no+// value shows it.export type Command =| { kind: 'on' | 'off' | 'show' | 'details' | 'probe' | 'grab' | 'dump' }| { kind: 'size'; percent: number }| { kind: 'width'; width?: Width }| { kind: 'height'; height?: Height }| { kind: 'grid'; grid?: boolean }+ | { kind: 'updates'; on?: boolean }| { kind: 'theme'; name?: string }| { kind: 'setup'; remove: boolean }| { kind: 'bad' }@@ -55,11 +57,13 @@ export function parseCommand(args: string): Command {}if (words[0] === 'grid' && words.length === 1) return { kind: 'grid' }if (words[0] === 'grid' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'grid', grid: words[1] === 'on' }+ if (words[0] === 'updates' && words.length === 1) return { kind: 'updates' }+ if (words[0] === 'updates' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'updates', on: words[1] === 'on' }return { kind: 'bad' }}-// The /iui arguments, and the sizes, widths, heights and grid values the-// typeahead offers.+// The /iui arguments, and the sizes, widths, heights, grid and updates+// values the typeahead offers.const SUBCOMMANDS = [{ name: 'on', description: 'draw answers as pictures' },{ name: 'off', description: 'show answers as text' },@@ -67,6 +71,7 @@ const SUBCOMMANDS = [{ name: 'width', description: `the most columns a picture takes, ${MIN_WIDTH}-${MAX_WIDTH} or full` },{ name: 'height', description: `the most rows an image or a Typst drawing takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },{ name: 'grid', description: 'each line of text on whole terminal rows, on or off' },+ { name: 'updates', description: 'look for a new version once a day, on or off' },{ name: 'theme', description: 'list the themes, or switch to one' },{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },{ name: 'details', description: 'the mode source, the terminal font, Typst and the terminal' },@@ -77,16 +82,17 @@ const SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]const WIDTHS: readonly Width[] = [80, 100, 120, 160, 200, 'full']const HEIGHTS: readonly Height[] = ['half', 'full', 12, 24, 36]const GRIDS = ['on', 'off'] as const+const UPDATES = ['on', 'off'] as const// Typeahead rows for `/iui` arguments: the word at the cursor (`token`,// starting at `start` in `text`) completed as a subcommand, a theme name, a-// size, a width, a height or a grid value. Right after `theme`, `size`,-// `width`, `height` or `grid`, rows hold the word and its argument, since-// the typeahead asks only while a word is at the cursor.+// size, a width, a height, a grid or an updates value. Right after `theme`,+// `size`, `width`, `height`, `grid` or `updates`, rows hold the word and its+// argument, since the typeahead asks only while a word is at the cursor.export type Suggestion = { text: string; label?: string; description?: string }export function commandSuggestions(text: string, token: string, start: number,- o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height; grid?: boolean },+ o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height; grid?: boolean; updates?: boolean },): Suggestion[] {const head = /^\s*\/iui\s+/.exec(text)if (!head || start < head[0].length) return []@@ -124,12 +130,17 @@ export function commandSuggestions(const gridRows = (prefix: string, lead: string) => GRIDS.filter(g => g.startsWith(prefix)).map(g => ({ text: `${lead}${g}`, label: g, description: g === grid ? 'current' : g === 'off' ? 'the default' : undefined }))+ const updates = o.updates === false ? 'off' : 'on'+ const updateRows = (prefix: string, lead: string) => UPDATES+ .filter(u => u.startsWith(prefix))+ .map(u => ({ text: `${lead}${u}`, label: u, description: u === updates ? 'current' : u === 'on' ? 'the default' : undefined }))if (before.length === 0) {if (word === 'theme') return themeRows('', 'theme ')if (word === 'height') return heightRows('', 'height ')if (word === 'size') return sizeRows('', 'size ')if (word === 'width') return widthRows('', 'width ')if (word === 'grid') return gridRows('', 'grid ')+ if (word === 'updates') return updateRows('', 'updates ')return SUBCOMMANDS.filter(c => c.name.startsWith(word)).map(c => ({ text: c.name, description: c.description }))}if (before.length === 1 && before[0] === 'theme') return themeRows(word, '')@@ -137,6 +148,7 @@ export function commandSuggestions(if (before.length === 1 && before[0] === 'width') return widthRows(word, '')if (before.length === 1 && before[0] === 'height') return heightRows(word, '')if (before.length === 1 && before[0] === 'grid') return gridRows(word, '')+ if (before.length === 1 && before[0] === 'updates') return updateRows(word, '')return []}@@ -145,7 +157,7 @@ export function commandSuggestions(export async function registerCommand($: EngineInterface) {await commandRegister($, {name: 'iui',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",- argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|theme [name]|grab|dump]',+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",+ argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|updates [on|off]|theme [name]|grab|dump]',}).catch(() => undefined)}diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex b9ccc15..caf16c0 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -17,6 +17,7 @@ import { readHostMode, termFontOf, watchHost } from './host'import { readFrame, setFrame, watchFrame } from './frame'import { offerSetup } from './setup'import { findTypst, measureFonts } from './typst'+import { checkUpdates } from './updates'import { configList, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, storeGet, uiToast } from './api'// The `isOn` atom, which setUp turns off when the stored setting says so (a@@ -130,6 +131,8 @@ export function setUp($: EngineInterface): Promise<Env> {metrics: typst ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,}refresh($)+ // The start is done: the update check now, and nothing waits for it.+ void checkUpdates($)return S.env})().catch((err: unknown) => {S.envLoading = nulldiff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex ee4d091..6a8af65 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -9,6 +9,7 @@ import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'import type { Drawn } from './copy'import type { GridMetrics } from './grid'+import type { Checked } from './updates'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'import { uiInvalidate } from './api'@@ -176,6 +177,18 @@ export const S = {planVerdict: null as PlanVerdict | null,planAsking: '',planCode: null as string | null,+ // The update check (updates.ts), read once per load (`updatesLoading`):+ // `/iui updates` (on by default), the variable that turns the check off+ // ('' none), this mod's version ('' not known) and the last check (null:+ // none stored). `updateDone`: this load's check ran or was not due;+ // `updateBusy`: one runs now.+ updates: true,+ updatesOff: '',+ ownVersion: '',+ updateChecked: null as Checked | null,+ updatesLoading: null as Promise<void> | null,+ updateDone: false,+ updateBusy: false,}// The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).export const results = new Map<string, Result | 'failed'>()diff --git a/hooks/lib/updates.ts b/hooks/lib/updates.tsnew file mode 100644index 0000000..65435c5--- /dev/null+++ b/hooks/lib/updates.ts@@ -0,0 +1,202 @@+// The update check: at most once a day, the version in this mod's+// plugin.json on GitHub against the version installed; a newer one is told+// in a toast and in /iui. Claude Code finds a plugin update by that version,+// but its auto-update is off for a third-party marketplace, so without this+// a user does not learn of a new version.+import type { EngineInterface } from 'claude-code'++import { S } from './state'+import { isSet } from './terminal'+import { clockAfter, clockNow, envGet, fsRead, httpFetch, pluginRoot, sessionSurfaces, storeGet, storeSet, uiToast, type EnvName } from './api'++// The manifest of the newest release (a release changes its `version`).+export const UPDATE_URL = 'https://raw.githubusercontent.com/razorback16/cc-intelligent-ui/main/.claude-plugin/plugin.json'+export const MARKETPLACE = 'razorback16'+export const PLUGIN_ID = `cc-intelligent-ui@${MARKETPLACE}`+// One check in this time at most; the toast of one version as often.+export const UPDATE_EVERY_MS = 24 * 60 * 60 * 1000+// A fetch with no answer in this time is a failure.+export const UPDATE_FETCH_MS = 10000+export const UPDATE_TOAST_MS = 12000+// Claude Code's variables that stop its own update checks and other traffic+// that is not needed: any one set stops this check too.+export const UPDATE_ENV: readonly EnvName[] = ['CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC', 'DISABLE_UPDATES', 'DISABLE_AUTOUPDATER']++// The numbers of a dotted version (`1.2.3`, `v1.2.3`, 1 to 4 parts); null+// for any other text (`1.2.3-beta`, '').+export function parseVersion(text: unknown): number[] | null {+ if (typeof text !== 'string') return null+ const m = /^v?(\d+(?:\.\d+){0,3})$/.exec(text.trim())+ return m ? m[1]!.split('.').map(Number) : null+}++// Less than, equal to or more than 0 as `a` is older than, the same as or+// newer than `b` (a missing part is 0); null when one does not parse.+export function compareVersions(a: string, b: string): number | null {+ const x = parseVersion(a)+ const y = parseVersion(b)+ if (!x || !y) return null+ for (let i = 0; i < Math.max(x.length, y.length); i++) {+ const d = (x[i] ?? 0) - (y[i] ?? 0)+ if (d) return d+ }+ return 0+}+export const isNewer = (latest: string, own: string) => (compareVersions(latest, own) ?? 0) > 0++// The version in the text of this mod's plugin.json (no `v`); null when the+// text is not JSON, names another plugin, or has no version that parses.+export function versionOf(text: string): string | null {+ let json: unknown+ try {+ json = JSON.parse(text)+ } catch {+ return null+ }+ if (!json || typeof json !== 'object') return null+ const { name, version } = json as { name?: unknown; version?: unknown }+ if (name !== undefined && name !== 'cc-intelligent-ui') return null+ return parseVersion(version) ? String(version).trim().replace(/^v/, '') : null+}++// The last check in the store (`update-check`): when it ran, and the newest+// version a check found ('' none yet).+export type Checked = { at: number; latest: string }+export function checkedOf(value: unknown): Checked | null {+ if (!value || typeof value !== 'object') return null+ const { at, latest } = value as { at?: unknown; latest?: unknown }+ if (typeof at !== 'number' || !Number.isFinite(at)) return null+ return { at, latest: parseVersion(latest) ? String(latest).trim().replace(/^v/, '') : '' }+}+// A check is due with none stored, UPDATE_EVERY_MS after the last one, or+// when the clock went back.+export const isDue = (checked: Checked | null, now: number) => !checked || now - checked.at >= UPDATE_EVERY_MS || now < checked.at++// The last toast in the store (`update-told`): its version and time. A+// version is told once a day at most (many sessions a day do not each show+// it); a newer version is told at once.+export type Told = { version: string; at: number }+export function toldOf(value: unknown): Told | null {+ if (!value || typeof value !== 'object') return null+ const { version, at } = value as { version?: unknown; at?: unknown }+ return typeof version === 'string' && typeof at === 'number' && Number.isFinite(at) ? { version, at } : null+}+export const shouldTell = (told: Told | null, latest: string, now: number) =>+ !told || told.version !== latest || now - told.at >= UPDATE_EVERY_MS || now < told.at++export const UPDATE_STEPS = `claude plugin marketplace update ${MARKETPLACE}, then claude plugin update ${PLUGIN_ID}, then /reload-plugins`+export const updateToast = (latest: string, own: string) =>+ `Intelligent UI ${latest} is available (you have ${own}): run ${UPDATE_STEPS}`++// A time in the past, in words.+export function agoText(ms: number): string {+ const hours = Math.floor(Math.max(0, ms) / 3600000)+ if (hours < 1) return 'less than 1 hour ago'+ if (hours < 48) return `${hours} hour${hours === 1 ? '' : 's'} ago`+ return `${Math.floor(hours / 24)} days ago`+}++// The state of the check, in words (/iui details, /iui updates). `on`: the+// setting; `off`: the variable that stops the check ('' none); `own`: the+// version installed ('' not known).+export type UpdateState = { on: boolean; off: string; own: string; checked: Checked | null; now: number }+export function updateLine(o: UpdateState): string {+ if (!o.on) return 'off'+ if (o.off) return `off (${o.off} is set)`+ if (!o.own) return 'on, the version installed is not known'+ const latest = o.checked?.latest ?? ''+ if (latest && isNewer(latest, o.own)) return `on, ${latest} is available (you have ${o.own})`+ if (!o.checked) return `on, not checked yet (you have ${o.own})`+ const ago = agoText(o.now - o.checked.at)+ return latest ? `on, up to date (${o.own}, checked ${ago})` : `on, no version found yet (you have ${o.own}, last try ${ago})`+}+// The line of the /iui reply when a newer version is known; '' otherwise.+export function updateNotice(o: UpdateState): string {+ const latest = o.checked?.latest ?? ''+ if (!o.on || o.off || !o.own || !latest || !isNewer(latest, o.own)) return ''+ return `Intelligent UI ${latest} is available (you have ${o.own}). To update: ${UPDATE_STEPS}.`+}++// The setting, the variables, the version installed and the last check,+// read once per load. Never rejects.+export function loadUpdates($: EngineInterface): Promise<void> {+ S.updatesLoading ??= (async () => {+ S.updates = (await storeGet($, 'updates').catch(() => undefined)) !== false+ S.updatesOff = ''+ for (const name of UPDATE_ENV) {+ if (!isSet(await envGet($, name).catch(() => undefined))) continue+ S.updatesOff = name+ break+ }+ const manifest = await fsRead($, `${pluginRoot($)}/.claude-plugin/plugin.json`).catch(() => '')+ S.ownVersion = versionOf(manifest) ?? ''+ S.updateChecked = checkedOf(await storeGet($, 'update-check').catch(() => undefined))+ })().catch(() => {+ S.updatesLoading = null+ })+ return S.updatesLoading+}++// The version on GitHub now; null on any failure (no network, a status not+// 2xx, no answer in UPDATE_FETCH_MS, a text that is not this mod's+// plugin.json).+export async function fetchLatest($: EngineInterface): Promise<string | null> {+ let late = (_: null) => {}+ const timeout = new Promise<null>(resolve => (late = resolve))+ let timer: { cancel: () => void } | undefined+ try {+ timer = clockAfter($, UPDATE_FETCH_MS, () => late(null))+ const got = await Promise.race([httpFetch($, UPDATE_URL).catch(() => null), timeout])+ return got?.ok ? versionOf(got.text) : null+ } catch {+ return null+ } finally {+ timer?.cancel()+ }+}++// The toast for a newer version than the one installed (shouldTell).+async function tellUpdate($: EngineInterface, now: number) {+ const latest = S.updateChecked?.latest ?? ''+ if (!latest || !isNewer(latest, S.ownVersion)) return+ if (!shouldTell(toldOf(await storeGet($, 'update-told').catch(() => undefined)), latest, now)) return+ await storeSet($, 'update-told', { version: latest, at: now }).catch(() => undefined)+ uiToast($, updateToast(latest, S.ownVersion), { timeoutMs: UPDATE_TOAST_MS })+}++// Once per load, after the start (the end of setUp, or a turn's start, or+// /iui updates on): with the check on and a terminal that shows a toast, the+// version on GitHub when a check is due (isDue), then the toast when it is+// newer. The time of a check is stored before its fetch, so a failed fetch+// is not tried again for UPDATE_EVERY_MS either. Nothing waits for it; it+// never rejects.+export async function checkUpdates($: EngineInterface): Promise<void> {+ if (S.updateDone || S.updateBusy) return+ S.updateBusy = true+ try {+ await loadUpdates($)+ if (!S.updates || S.updatesOff || !S.ownVersion) return+ if ((await envGet($, 'CLAUDE_CODE_SESSION_KIND').catch(() => undefined)) === 'bg') {+ S.updateDone = true+ return+ }+ // None in a -p run; tried again at the next turn.+ const surfaces = await sessionSurfaces($).catch(() => [] as readonly string[])+ if (!surfaces.includes('terminal')) return+ S.updateDone = true+ const now = await clockNow($)+ if (isDue(S.updateChecked, now)) {+ S.updateChecked = { at: now, latest: S.updateChecked?.latest ?? '' }+ await storeSet($, 'update-check', S.updateChecked).catch(() => undefined)+ const found = await fetchLatest($)+ if (found) {+ S.updateChecked = { at: now, latest: found }+ await storeSet($, 'update-check', S.updateChecked).catch(() => undefined)+ }+ }+ await tellUpdate($, now)+ } catch {+ } finally {+ S.updateBusy = false+ }+}diff --git a/hooks/register.tsx b/hooks/register.tsxindex 34f64f2..f5ddfcc 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -14,9 +14,9 @@// mutable state `S`), markdown, terminal, terminals, mode, themes, command,// setup, host, typst, draw, stream, answer (one text through the pipeline),// env, images, pictures, plan (the plan approval flow), copy (the text under-// a mouse copy of the pictures) and probe (the drawn pages, and the words of-// a page a copy reads). This file joins them to the hooks, and gives the-// tests the names they import.+// a mouse copy of the pictures), probe (the drawn pages, and the words of a+// page a copy reads) and updates (the daily check for a new version). This+// file joins them to the hooks, and gives the tests the names they import.import { atom, read, update } from 'claude-code'import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'@@ -42,7 +42,8 @@ import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/fraimport { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'import { pasteDir, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'-import { fsWrite, processRun, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'+import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'+import { clockNow, fsWrite, processRun, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -82,6 +83,10 @@ export {export { nextJob } from './lib/stream'export * from './lib/images'export * from './lib/copy'+export {+ agoText, checkedOf, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS, UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS,+ UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,+} from './lib/updates'export {choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,@@ -348,6 +353,13 @@ function autoCopyOf(isOn: boolean): string {return now?.clip && !now.ended ? 'on' : 'off (the watcher does not run)'}+// The update check's state now, for /iui, /iui details and /iui updates.+async function updateState($: EngineInterface): Promise<UpdateState> {+ await loadUpdates($)+ const now = await clockNow($).catch(() => Date.now())+ return { on: S.updates, off: S.updatesOff, own: S.ownVersion, checked: S.updateChecked, now }+}+// /iui grab: the last mouse selection, read and copied.async function grab($: EngineInterface): Promise<string> {const selected = await uiSelection($).catch(() => undefined)@@ -444,7 +456,10 @@ export const register: Register = on => {const got = await next(e)if (!/^\s*\/iui\s/.test(e.text)) return gotif (!S.themeChoices.length) await setUp($).catch(() => null)- const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width, height: S.height, grid: S.grid })+ await loadUpdates($)+ const mine = commandSuggestions(e.text, e.token, e.start, {+ themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width, height: S.height, grid: S.grid, updates: S.updates,+ })return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got})@@ -498,6 +513,17 @@ export const register: Register = on => {const head = asked.grid === undefined ? 'The row grid is' : 'The row grid is now'return { text: `${head} ${gridText(S.grid)}. With the grid on, a mouse selection over a picture covers the lines it copies. Use /iui grid on, or /iui grid off (the default).` }}+ if (asked.kind === 'updates') {+ await loadUpdates($)+ if (asked.on !== undefined) {+ S.updates = asked.on+ await storeSet($, 'updates', S.updates)+ // On: the check of this load, if it did not run (it waits 24 h after the last one).+ if (S.updates) void checkUpdates($)+ }+ const head = asked.on === undefined ? 'Update checks' : 'Update checks are now'+ return { text: `${head}: ${updateLine(await updateState($))}. When on, Intelligent UI gets its plugin.json from GitHub once a day at most (one GET, no data sent) and shows a toast when a new version is available. Use /iui updates on (the default), or /iui updates off.` }+ }if (asked.kind === 'setup') {await setUp($).catch(() => null)return { text: await runSetup($, asked.remove) }@@ -544,7 +570,8 @@ export const register: Register = on => {? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'const auto = `Auto copy: ${autoCopyOf(state === 'on')}`- return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, row grid ${S.grid ? 'on' : 'off'}, ${font}. ${typst}; ${terminal}.\n${auto}` }+ const updates = `Update checks: ${updateLine(await updateState($))}`+ return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, row grid ${S.grid ? 'on' : 'off'}, ${font}. ${typst}; ${terminal}.\n${auto}\n${updates}` }}// The short state: what is set, and only the problems that keep pictures away.const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)@@ -552,7 +579,9 @@ export const register: Register = on => {if (S.setupNeeded) lines.push('In iTerm2, run /iui setup once to show pictures.')else if (!ready.canDraw) lines.push('This terminal shows no pictures, so answers stay text. Pictures show in kitty, Ghostty and iTerm2 3.6+.')if (!ready.typst) lines.push('Typst is not installed, so answers stay text. Install it: brew install typst')- lines.push('Change: /iui on | off | size | width | height | grid | theme. More: /iui details')+ const notice = updateNotice(await updateState($))+ if (notice) lines.push(notice)+ lines.push('Change: /iui on | off | size | width | height | grid | updates | theme. More: /iui details')return { text: bad + lines.join('\n') }})@@ -757,6 +786,8 @@ export const register: Register = on => {// The main loop's running turn, which "clear context" ends.on('turn.start', async ($, e, next) => {if (e.agentId === undefined) S.mainTurnId = e.turnId+ // The update check, when the end of setUp could not run it (no terminal yet).+ void checkUpdates($)// The clipboard part, if it is not on (a picture drawn while it was off).if (await read($, isOn)) watchClipboard($)return next(e)diff --git a/tests/updates.test.ts b/tests/updates.test.tsnew file mode 100644index 0000000..4dc7a1a--- /dev/null+++ b/tests/updates.test.ts@@ -0,0 +1,269 @@+import { expect, mock, test } from 'claude-code/testing'++import {+ agoText, checkedOf, commandSuggestions, compareVersions, isDue, isNewer, parseCommand, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS,+ UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS, UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,+} from '../hooks/register'++const HOUR = 60 * 60 * 1000+const NOW = 1_800_000_000_000++test('versions compare as dotted numbers; other text does not parse', () => {+ expect(parseVersion('0.2.0')).toEqual([0, 2, 0])+ expect(parseVersion(' v1.10.3 ')).toEqual([1, 10, 3])+ expect(parseVersion('2')).toEqual([2])+ for (const bad of ['', '1.2.3-beta', '1..2', 'x.y.z', '1.2.3.4.5', 3, null, undefined]) expect(parseVersion(bad)).toBe(null)+ expect(compareVersions('0.3.0', '0.2.0')! > 0).toBe(true)+ expect(compareVersions('0.10.0', '0.9.9')! > 0).toBe(true)+ expect(compareVersions('1.0', '1.0.0')).toBe(0)+ expect(compareVersions('0.2.0', '0.2.1')! < 0).toBe(true)+ expect(compareVersions('0.3.0-rc1', '0.2.0')).toBe(null)+ expect(isNewer('0.3.0', '0.2.0')).toBe(true)+ expect(isNewer('0.2.0', '0.2.0')).toBe(false)+ expect(isNewer('0.1.9', '0.2.0')).toBe(false)+ expect(isNewer('next', '0.2.0')).toBe(false)+})++test('the version of a plugin.json: only this mod, only a version that parses', () => {+ expect(versionOf('{"name":"cc-intelligent-ui","version":"0.3.0"}')).toBe('0.3.0')+ expect(versionOf('{"version":"v0.3.0"}')).toBe('0.3.0')+ expect(versionOf('{"name":"other","version":"9.0.0"}')).toBe(null)+ expect(versionOf('{"name":"cc-intelligent-ui","version":"0.3.0-beta"}')).toBe(null)+ expect(versionOf('{"name":"cc-intelligent-ui"}')).toBe(null)+ expect(versionOf('404: Not Found')).toBe(null)+ expect(versionOf('[]')).toBe(null)+ expect(versionOf('null')).toBe(null)+})++test('a check is due 24 h after the last one; a version is told once a day', () => {+ expect(isDue(null, NOW)).toBe(true)+ expect(isDue({ at: NOW - 23 * HOUR, latest: '0.3.0' }, NOW)).toBe(false)+ expect(isDue({ at: NOW - UPDATE_EVERY_MS, latest: '0.3.0' }, NOW)).toBe(true)+ // The clock went back: due.+ expect(isDue({ at: NOW + HOUR, latest: '' }, NOW)).toBe(true)+ expect(checkedOf({ at: NOW, latest: '0.3.0' })).toEqual({ at: NOW, latest: '0.3.0' })+ expect(checkedOf({ at: NOW, latest: 'junk' })).toEqual({ at: NOW, latest: '' })+ expect(checkedOf({ at: 'now' })).toBe(null)+ expect(checkedOf('x')).toBe(null)+ expect(toldOf({ version: '0.3.0', at: NOW })).toEqual({ version: '0.3.0', at: NOW })+ expect(toldOf({ version: 3, at: NOW })).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)+})++test('the toast, the details line and the /iui notice', () => {+ expect(updateToast('0.3.0', '0.2.0')).toBe(+ 'Intelligent UI 0.3.0 is available (you have 0.2.0): run claude plugin marketplace update razorback16, then claude plugin update cc-intelligent-ui@razorback16, then /reload-plugins')+ expect(UPDATE_STEPS).toBe('claude plugin marketplace update razorback16, then claude plugin update cc-intelligent-ui@razorback16, then /reload-plugins')+ const o = { on: true, off: '', own: '0.2.0', checked: { at: NOW - 3 * HOUR, latest: '0.3.0' }, now: NOW }+ expect(updateLine(o)).toBe('on, 0.3.0 is available (you have 0.2.0)')+ expect(updateLine({ ...o, checked: { at: NOW - 3 * HOUR, latest: '0.2.0' } })).toBe('on, up to date (0.2.0, checked 3 hours ago)')+ expect(updateLine({ ...o, checked: { at: NOW - 3 * HOUR, latest: '' } })).toBe('on, no version found yet (you have 0.2.0, last try 3 hours ago)')+ expect(updateLine({ ...o, checked: null })).toBe('on, not checked yet (you have 0.2.0)')+ 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')+ 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('')+ expect(updateNotice({ ...o, own: '0.3.0' })).toBe('')+ 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')+})++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] ?? ''+ return commandSuggestions(text, token, text.length - token.length, { ...o, ...more })+ }+ expect(at('/iui u').map(r => r.text)).toEqual(['updates'])+ expect(at('/iui u')[0]!.description).toBe('look for a new version once a day, on or off')+ const rows = at('/iui updates')+ expect(rows.map(r => r.text)).toEqual(['updates on', 'updates off'])+ // on is the default; with no value given, it is current.+ expect(rows.map(r => r.description)).toEqual(['current', undefined])+ expect(at('/iui updates of', { updates: false }).map(r => [r.text, r.description])).toEqual([['off', 'current']])+ expect(at('/iui updates o', { updates: false }).map(r => r.description)).toEqual(['the default', 'current'])+ expect(at('/iui updates on extra')).toEqual([])+})++type Answer = { status: number; text: string } | 'throw' | 'never'++// A session in a terminal with version `own` installed; GitHub answers+// `answer`. The store, the fetches and the toasts are kept.+function world(on: any, o: { answer?: Answer; own?: string; stored?: Record<string, unknown>; env?: Record<string, string>; surfaces?: 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)+ return { value: undefined }+ })+ const clock = mock.clock(on, { now: NOW })+ mock.env(on, { HOME: '/h', ...o.env })+ on('session.surfaces', async () => ({ value: o.surfaces ?? ['terminal'] }))+ on('fs.read', async ($: any, e: any, next: any) =>+ e.path.endsWith('/.claude-plugin/plugin.json') ? { value: JSON.stringify({ name: 'cc-intelligent-ui', version: o.own ?? '0.2.0' }) } : next(e))+ const fetched: string[] = []+ const answer = o.answer ?? { status: 200, text: '{"name":"cc-intelligent-ui","version":"0.3.0"}' }+ on('http.fetch', async ($: any, e: any) => {+ fetched.push(e.url)+ if (answer === 'throw') throw new Error('offline')+ if (answer === 'never') {+ await clock.sleep(10 * UPDATE_FETCH_MS)+ return { value: { status: 200, ok: true, headers: {}, text: '{"version":"9.9.9"}' } }+ }+ return { value: { status: answer.status, ok: answer.status >= 200 && answer.status < 300, headers: {}, text: answer.text } }+ })+ const toasts: { text: string; timeoutMs?: number }[] = []+ on('ui.toast', async ($: any, e: any) => (toasts.push({ text: e.text, timeoutMs: e.timeoutMs }), { value: undefined }))+ return { store, clock, fetched, toasts }+}++// A turn starts (the check's moment when setUp could not run it), and all it+// started settles.+async function turn($: any, w: { clock: { settle: () => Promise<void> } }) {+ await $.turn.start({ text: 'hi', turnId: 't1' }).catch(() => undefined)+ await w.clock.settle()+}++const updatesReply = async ($: any, args = 'updates') => (await $.command.run({ command: 'iui', args })).text as string++test('a due check fetches the manifest once, keeps the version, and shows one long toast', async ($, on) => {+ const w = world(on)+ await turn($, w)+ await turn($, w)+ expect(w.fetched).toEqual([UPDATE_URL])+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.3.0' })+ expect(w.store.get('update-told')).toEqual({ version: '0.3.0', at: NOW })+ expect(w.toasts).toEqual([{ text: updateToast('0.3.0', '0.2.0'), timeoutMs: UPDATE_TOAST_MS }])+ expect(UPDATE_TOAST_MS).toBe(12000)+ expect(await updatesReply($)).toContain('Update checks: on, 0.3.0 is available (you have 0.2.0).')+})++test('in the 24 h window the stored version is used with no fetch; the toast once a day', async ($, on) => {+ const w = world(on, { stored: { 'update-check': { at: NOW - 2 * HOUR, latest: '0.3.0' } } })+ await turn($, w)+ expect(w.fetched).toEqual([])+ expect(w.toasts.map(t => t.text)).toEqual([updateToast('0.3.0', '0.2.0')])+})++test('a version told in the last 24 h is not told again', 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 - HOUR } } })+ await turn($, w)+ expect(w.fetched).toEqual([])+ expect(w.toasts).toEqual([])+})++test('24 h after the last check, it fetches again', async ($, on) => {+ const w = world(on, { stored: { 'update-check': { at: NOW - UPDATE_EVERY_MS, latest: '0.2.0' } }, answer: { status: 200, text: '{"version":"0.4.0"}' } })+ await turn($, w)+ expect(w.fetched).toEqual([UPDATE_URL])+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.4.0' })+ expect(w.toasts.map(t => t.text)).toEqual([updateToast('0.4.0', '0.2.0')])+})++test('up to date: no toast, and the details say when it checked', async ($, on) => {+ const w = world(on, { own: '0.3.0' })+ await turn($, w)+ expect(w.fetched.length).toBe(1)+ expect(w.toasts).toEqual([])+ expect(await updatesReply($)).toContain('Update checks: on, up to date (0.3.0, checked less than 1 hour ago).')+})++for (const [name, answer] of [+ ['no network', 'throw'],+ ['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 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) => {+ const w = world(on, { answer })+ await turn($, w)+ expect(w.fetched.length).toBe(1)+ expect(w.toasts).toEqual([])+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '' })+ expect(await updatesReply($)).toContain('Update checks: on, no version found yet (you have 0.2.0, last try less than 1 hour ago).')+ })+}++test('a failed fetch keeps the version found before', async ($, on) => {+ const w = world(on, { answer: 'throw', stored: { 'update-check': { at: NOW - 2 * UPDATE_EVERY_MS, latest: '0.3.0' } } })+ await turn($, w)+ expect(w.fetched.length).toBe(1)+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '0.3.0' })+ expect(w.toasts.map(t => t.text)).toEqual([updateToast('0.3.0', '0.2.0')])+})++test('a fetch with no answer in time is a failure', async ($, on) => {+ const w = world(on, { answer: 'never' })+ await $.turn.start({ text: 'hi', turnId: 't1' } as any).catch(() => undefined)+ await w.clock.settle()+ expect(w.fetched.length).toBe(1)+ await w.clock.advance(UPDATE_FETCH_MS)+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '' })+ await w.clock.advance(10 * UPDATE_FETCH_MS)+ expect(w.store.get('update-check')).toEqual({ at: NOW, latest: '' })+ expect(w.toasts).toEqual([])+})++test('/iui updates off: no fetch and no toast; on stores it and checks', async ($, on) => {+ const w = world(on, { stored: { updates: false, 'update-check': { at: NOW - HOUR, latest: '0.3.0' } } })+ await turn($, w)+ expect(w.fetched).toEqual([])+ expect(w.toasts).toEqual([])+ expect(await updatesReply($)).toMatch(/^Update checks: off\. /)+ expect(await updatesReply($, 'updates on')).toContain('Update checks are now: on, 0.3.0 is available (you have 0.2.0).')+ await w.clock.settle()+ expect(w.store.get('updates')).toBe(true)+ // Checked 1 h ago: no fetch, but the toast.+ expect(w.fetched).toEqual([])+ expect(w.toasts.length).toBe(1)+ expect(await updatesReply($, 'updates off')).toContain('Update checks are now: off.')+ expect(w.store.get('updates')).toBe(false)+})++test('the setting off from the start: the check never fetches', async ($, on) => {+ const w = world(on, { stored: { updates: false } })+ await turn($, w)+ await turn($, w)+ expect(w.fetched).toEqual([])+ expect(w.store.has('update-check')).toBe(false)+})++for (const name of ['CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC', 'DISABLE_UPDATES', 'DISABLE_AUTOUPDATER']) {+ test(`${name} stops the check`, async ($, on) => {+ const w = world(on, { env: { [name]: '1' }, stored: { 'update-check': { at: NOW - HOUR, latest: '0.3.0' } } })+ await turn($, w)+ expect(w.fetched).toEqual([])+ expect(w.toasts).toEqual([])+ expect(await updatesReply($)).toContain(`Update checks: off (${name} is set).`)+ })+}++test('a variable set to 0 does not stop the check', async ($, on) => {+ const w = world(on, { env: { DISABLE_UPDATES: '0' } })+ await turn($, w)+ expect(w.fetched).toEqual([UPDATE_URL])+})++test('with no terminal (a -p run) there is no check', async ($, on) => {+ const w = world(on, { surfaces: [] })+ await turn($, w)+ expect(w.fetched).toEqual([])+})++test('a background session does not check', async ($, on) => {+ const w = world(on, { env: { CLAUDE_CODE_SESSION_KIND: 'bg' } })+ await turn($, w)+ expect(w.fetched).toEqual([])+})