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
10.1 KB
Raw Blame
// The Env, once per load: the cache folder, Typst, the terminal, its font
// and Frame (then kept by the Frame watcher), the theme and the mode.
import { atom, update } from 'claude-code'
import type { EngineInterface } from 'claude-code'

import {
  BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,
} from './settings'
import { DEFAULT_METRICS, refresh, S, settingsSet, type Env } from './state'
import { OSC11_TRIES, resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
import { canDrawIn, inlineOf, isHerdrIn, isSet, needsSetup } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
import { parseEditor } from './open'
import { registerCommand } from './command'
import { osc11Due, readHerdrClient, readHostMode, setOuter, termFontOf, watchHost } from './host'
import { readFrame, refontAfterStart, setFrame, watchFrame } from './frame'
import { offerSetup } from './setup'
import { findClipWay } from './clipboard'
import { findTypst, measureFonts } from './typst'
import { checkUpdates } from './updates'
import { cfgs, getenv, ls, stat, pluginRoot, exec, cwd, ver, load, toast } from './api'

// The `isOn` atom, which setUp turns off when the stored setting says so (a
// copy of its own: see state.ts).
const isOn = atom({ plugin: 'cc-intelligent-ui', key: 'isOn' } as const, true)

// Makes the cache folder (stops when it is a link or not this user's),
// drops key folders not touched for 2 days, makes the designs folder
// (outside the tmp cache) and drops design files not touched for
// DESIGNS_KEPT_DAYS; prints the cache folder, the OS name and the designs
// folder (when the cache folder can not be made private: the OS name, then
// that folder on the fourth line).
export const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"; mkdir "$d" 2>/dev/null; [ ! -L "$d" ] && [ -d "$d" ] && [ -O "$d" ] && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; } || printf '\\n%s\\n\\n%s\\n' "$(uname -s)" "$d"`

// Once per load: the cache folder, Typst, the terminal and its font, the
// theme, the cell. A failed setup is tried again on the next call.
export function setUp($: EngineInterface): Promise<Env> {
  S.envLoading ??= (async () => {
    await registerCommand($)
    const made = await exec($, ['sh', '-c', CACHE_SH]).catch(() => null)
    const [made1 = '', os = '', made3 = '', refused = ''] = (made?.stdout ?? '').split('\n')
    // No private cache folder: nothing is drawn (no shared folder instead).
    const cache = made1.trim()
    S.cacheProblem = cache ? '' : refused.trim() ? `the cache folder ${refused.trim()} is a link, not a folder, or not yours` : 'the cache folder could not be made'
    // The key folders on disk now: a key found here is read back at once.
    const listed = cache ? await ls($, cache).catch(() => []) : []
    S.onDisk = new Set(listed.filter(entry => entry.kind === 'dir' && entry.name !== 'pkg-cache').map(entry => entry.name))
    const program = (await getenv($, 'TERM_PROGRAM')) ?? ''
    const term = (await getenv($, 'TERM')) ?? ''
    const ssh = !!(await getenv($, 'SSH_CONNECTION')) || !!(await getenv($, 'SSH_TTY'))
    const terminalDraws = canDrawIn({
      program,
      term,
      kitty: !!(await getenv($, 'KITTY_WINDOW_ID')),
      tmux: !!(await getenv($, 'TMUX')) || !!(await getenv($, 'STY')) || /^tmux|^screen/i.test(term),
      ssh,
      background: (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',
      engineForced: isSet(await getenv($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),
      modForced: isSet(await getenv($, 'IUI_FORCE')),
    })
    const canDraw = terminalDraws && !!cache
    const root = pluginRoot($)
    const template = await stat($, `${root}/render/md.typ`).catch(() => null)
    const rows = await cfgs($).catch(() => [])
    const raw = rows.find(row => row.key === 'theme')?.value
    S.settingRaw = typeof raw === 'string' ? raw : ''
    S.setting = settingOf(raw)
    S.hostOs = os.trim()
    S.termProgram = program
    S.termName = term
    S.isHerdr = isHerdrIn({ program, herdrEnv: await getenv($, 'HERDR_ENV') })
    S.herdrVersion = S.isHerdr ? ((await getenv($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''
    S.herdrDraws = S.isHerdr && canDraw
    // Off when it starts (the stored setting), unless an /iui command set it meanwhile.
    const enabled = await load($, 'enabled').catch(() => undefined)
    const off = settingsSet.has('enabled') ? S.isOff : enabled === false
    // Under herdr the client in use gives the terminal (the one of before stays while the app in front has none); else (none found) the server's variables.
    // The clients' processes are read only while the mod is on and draws pictures.
    const was = S.herdrClient
    S.herdrClient = null
    S.osc11Kept = null
    S.herdrClients = []
    S.herdrScanFront = null
    S.herdrScanAt = null
    if (S.herdrDraws && !off) await readHerdrClient($, was).catch(() => false)
    await setOuter($)
    S.isRemote = ssh
    S.debug = isSet(await getenv($, 'IUI_DEBUG'))
    S.isIterm = isItermIn({
      program,
      profile: (await getenv($, 'ITERM_PROFILE')) || undefined,
      session: (await getenv($, 'ITERM_SESSION_ID')) || undefined,
      lcTerminal: (await getenv($, 'LC_TERMINAL')) || undefined,
    })
    S.setupNeeded = needsSetup({
      iterm: S.isIterm,
      herdr: S.isHerdr,
      draws: terminalDraws,
      ssh,
      os: S.hostOs,
      tmux: !!(await getenv($, 'TMUX')) || !!(await getenv($, 'STY')),
      background: (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',
    })
    if (S.setupNeeded) void offerSetup($).catch(() => undefined)
    S.userFontPaths = (await getenv($, 'TYPST_FONT_PATHS')) ?? ''
    // Under herdr with auto, its OSC 11 answer is asked at the start (osc11Due).
    S.osc11Tries = S.setting === 'auto' ? OSC11_TRIES : 0
    if (S.setting === 'auto') S.host = (await readHostMode($, await osc11Due($, off)).catch(() => null)) ?? S.host
    S.theme = resolveMode(S.setting, S.host)
    watchHost($)
    // The stored settings, but not one an /iui command set meanwhile (settingsSet).
    const kept = Number(await load($, 'size').catch(() => undefined))
    if (!settingsSet.has('size')) S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE
    const width = await load($, 'width').catch(() => undefined)
    if (!settingsSet.has('width')) {
      S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH
    }
    const height = await load($, 'height').catch(() => undefined)
    if (!settingsSet.has('height')) {
      S.height = height === 'half' || height === 'full' ? height
        : Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT
    }
    const grid = (await load($, 'grid').catch(() => undefined)) !== false
    if (!settingsSet.has('grid')) S.grid = grid
    const select = (await load($, 'select').catch(() => undefined)) !== false
    if (!settingsSet.has('select')) S.select = select
    const editor = await load($, 'editor').catch(() => undefined)
    if (!settingsSet.has('editor')) S.editor = typeof editor === 'string' && parseEditor(editor) ? editor : 'auto'
    // An engine with no version call is older than picture select.
    S.engine = await Promise.resolve().then(() => ver($)).then(v => v.base ?? v.version, () => '')
    if (enabled === false && !settingsSet.has('enabled')) {
      S.isOff = true
      watchHost($)
      await update($, isOn, () => false).catch(() => undefined)
    }
    const isMac = os.trim() === 'Darwin'
    // Linux, on this computer: the clipboard tools, for the copy.
    if (S.hostOs === 'Linux' && !ssh) void findClipWay($).catch(() => undefined)
    setFrame(await readFrame($))
    if (canDraw) watchFrame($)
    const typst = await findTypst($)
    if (S.cacheProblem && terminalDraws) {
      try {
        toast($, `Intelligent UI: no pictures, ${S.cacheProblem} (see /iui details)`, { timeoutMs: 8000 })
      } catch {}
    } else if (!typst) {
      try {
        toast($, noTypstOf(isMac), { timeoutMs: 8000 })
      } catch {}
    }
    const termFont = await termFontOf($, isMac).catch(() => '')
    const home = (await getenv($, 'HOME')) ?? ''
    const designs = made3.trim() || (home ? `${home}/.cache/cc-intelligent-ui/designs` : cache ? `${cache}/designs` : '')
    const stored = await load($, 'theme-name').catch(() => undefined)
    const wanted = typeof stored === 'string' && stored ? stored : DEFAULT_THEME
    const applied = await applyTheme($, root, home, wanted).catch(() => null)
    if (!applied) S.look = { name: BASE_THEME, dir: `${root}/render/themes/${BASE_THEME}`, stamp: '0' }
    else if (applied.chosen.isFallback) {
      try {
        toast($, `Intelligent UI: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })
      } catch {}
    }
    S.env = {
      typst,
      canDraw,
      inline: inlineOf(ssh, await getenv($, 'IUI_INLINE')) && canDraw,
      herdr: S.isHerdr,
      cache,
      cwd: await cwd($).catch(() => '/'),
      root,
      isMac,
      stamp: String(template?.mtimeMs ?? 0),
      home,
      claudeTmp: claudeTmpOf({
        tmpdir: (await getenv($, 'CLAUDE_CODE_TMPDIR')) || undefined,
        uid: await exec($, ['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),
        isMac,
      }),
      termFont,
      designs,
      metrics: typst && cache ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,
    }
    refresh($)
    refontAfterStart($)
    // The start is done: the update check now, and nothing waits for it.
    void checkUpdates($)
    return S.env
  })().catch((err: unknown) => {
    S.envLoading = null
    throw err
  })
  return S.envLoading
}