Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(terminal): font picker with real installed-font detection, weights, contrast
enes8e77822635f6
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 1dc1a0f75..12d21c851 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -23,6 +23,7 @@ import {SHIFT_ENTER_SEQ,CO_ATTACH_MOUSE_SEQ} from '../../terminal/terminal-config'+import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'import { resolveSshRemote } from '../../nodes/TerminalNode'import { buildSshArgs, type SshConnection } from '@shared/ssh'@@ -69,17 +70,8 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Modaconst fitRef = useRef<FitAddon | null>(null)const transportRef = useRef<LocalTransport | null>(null)const agentSessionId = useAgentStatus((s) => s.byId[nodeId]?.sessionId)- // Scoped selectors (not the whole settings object), same discipline as TerminalNode: a modal- // holding a live terminal must not re-render on every unrelated settings edit.- const fontSize = useSettings((s) => s.settings.fontSize)- const fontFamily = useSettings((s) => s.settings.fontFamily)- const cursorBlink = useSettings((s) => s.settings.cursorBlink)- const cursorStyle = useSettings((s) => s.settings.cursorStyle)- const cursorInactiveStyle = useSettings((s) => s.settings.cursorInactiveStyle)- const terminalLineHeightSetting = useSettings((s) => s.settings.terminalLineHeight)- const terminalLetterSpacingSetting = useSettings((s) => s.settings.terminalLetterSpacing)- const terminalTheme = useSettings((s) => s.settings.terminalTheme)- const tmuxScrollback = useSettings((s) => s.settings.tmuxScrollback)+ // One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.+ const visual = useXtermVisualSettings()const [dropping, setDropping] = useState(false)const [uploading, setUploading] = useState(false)@@ -286,32 +278,12 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: ModauseEffect(() => {const term = termRef.currentif (!term) return- const { metricsChanged } = applyLiveOptions(term, {- fontFamily,- fontSize,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeight: terminalLineHeightSetting,- terminalLetterSpacing: terminalLetterSpacingSetting,- terminalTheme,- tmuxScrollback- })+ const { metricsChanged } = applyLiveOptions(term, visual)if (!metricsChanged) returnfitRef.current?.fit()const sid = sessionIdRef.currentif (sid) transportRef.current?.resize(sid, term.cols, term.rows)- }, [- fontSize,- fontFamily,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeightSetting,- terminalLetterSpacingSetting,- terminalTheme,- tmuxScrollback- ])+ }, [visual])// File drop → paste the path(s) into the co-attached session, just like the canvas node.const onDragOver = (e: React.DragEvent) => {diff --git a/src/renderer/components/settings/FontPicker.tsx b/src/renderer/components/settings/FontPicker.tsxnew file mode 100644index 000000000..79de6a970--- /dev/null+++ b/src/renderer/components/settings/FontPicker.tsx@@ -0,0 +1,137 @@+import { useEffect, useMemo, useState } from 'react'+import { Input } from '@renderer/ui/Input'+import { Select } from '@renderer/ui/Select'+import { Button } from '@renderer/ui/Button'+import {+ MONO_FONT_CATALOG,+ buildFontStack,+ createCanvasMeasurer,+ detectInstalled,+ isFontAvailable,+ primaryFamily+} from '@renderer/lib/fontDetect'++/** Marks the free-text row in the dropdown — anything not in the detected list. */+const CUSTOM = '__custom__'++/**+ * Whether this browser exposes the Local Font Access API. Chromium-only, and in the Server+ * Edition it additionally needs a secure context — so it is an ENHANCEMENT, never the mechanism:+ * the catalogue scan below works everywhere and is what the picker is actually built on.+ */+function hasLocalFontAccess(): boolean {+ return typeof (window as { queryLocalFonts?: unknown }).queryLocalFonts === 'function'+}++async function queryAllFamilies(): Promise<string[]> {+ const q = (window as unknown as { queryLocalFonts: () => Promise<{ family: string }[]> })+ .queryLocalFonts+ const fonts = await q()+ return [...new Set(fonts.map((f) => f.family))].sort((a, b) => a.localeCompare(b))+}++/**+ * Font family picker: a list of fonts that are actually INSTALLED, plus the raw CSS stack for+ * anything the list doesn't cover.+ *+ * The free-text field alone was the whole control before, and it fails silently — type a font you+ * don't have and the terminal renders the next fallback with no indication anything went wrong.+ * So the list is filtered by real detection (`fontDetect`), and the text field grew a warning.+ */+export function FontPicker({+ value,+ onChange+}: {+ value: string+ onChange: (stack: string) => void+}): React.JSX.Element {+ // One measurer for the lifetime of the picker: it holds a single reused canvas, and building one+ // per probe is what turns a 31-font scan into a visible hitch.+ const measure = useMemo(() => createCanvasMeasurer(), [])+ const [extraFamilies, setExtraFamilies] = useState<string[]>([])+ const [browseError, setBrowseError] = useState<string | null>(null)++ // Fonts can finish loading after first paint, so re-scan once the document says it's done.+ const [fontsReady, setFontsReady] = useState(0)+ useEffect(() => {+ let alive = true+ void document.fonts?.ready.then(() => {+ if (alive) setFontsReady((n) => n + 1)+ })+ return () => {+ alive = false+ }+ }, [])++ const installed = useMemo(() => {+ if (!measure) return []+ const all = [...new Set([...MONO_FONT_CATALOG, ...extraFamilies])].sort((a, b) =>+ a.localeCompare(b)+ )+ return detectInstalled(all, measure)+ // fontsReady is a re-scan trigger, not a value.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [measure, extraFamilies, fontsReady])++ const primary = primaryFamily(value)+ // `measure` being null (no canvas) means we cannot tell — and "unknown" must not render as a+ // warning that the user's font is missing.+ const missing = !!measure && !!primary && !isFontAvailable(primary, measure)+ const selectValue = installed.includes(primary) ? primary : CUSTOM++ async function browseAll(): Promise<void> {+ setBrowseError(null)+ try {+ setExtraFamilies(await queryAllFamilies())+ } catch {+ // Permission denied, or no transient activation. Not an error worth a dialog — the catalogue+ // scan and the text field both still work.+ setBrowseError('Font list unavailable — type the font name instead.')+ }+ }++ return (+ <div className="flex flex-col items-end gap-2">+ <Select+ className="w-64"+ value={selectValue}+ aria-label="Font family"+ onChange={(e) => {+ if (e.target.value !== CUSTOM) onChange(buildFontStack(e.target.value))+ }}+ >+ {installed.length > 0 && (+ <optgroup label="Installed">+ {installed.map((f) => (+ <option key={f} value={f}>+ {f}+ </option>+ ))}+ </optgroup>+ )}+ <optgroup label="Other">+ <option value={CUSTOM}>Custom…</option>+ </optgroup>+ </Select>+ <Input+ className="w-64"+ value={value}+ aria-label="Font stack"+ onChange={(e) => onChange(e.target.value)}+ />+ {missing ? (+ <p className="text-[12px] leading-relaxed text-[#ff9f0a]">+ “{primary}” isn’t installed — the next font in the stack is being used.+ </p>+ ) : null}+ {hasLocalFontAccess() && !extraFamilies.length ? (+ <Button onClick={() => void browseAll()}>+ Browse all installed fonts+ </Button>+ ) : null}+ {browseError ? (+ <p className="text-[12px] leading-relaxed text-muted">{browseError}</p>+ ) : null}+ </div>+ )+}diff --git a/src/renderer/components/settings/TerminalPreview.tsx b/src/renderer/components/settings/TerminalPreview.tsxindex fc4f0a176..704b77fce 100644--- a/src/renderer/components/settings/TerminalPreview.tsx+++ b/src/renderer/components/settings/TerminalPreview.tsx@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react'import { Terminal } from '@xterm/xterm'import { useSettings } from '../../state/settings'import { applyLiveOptions, xtermOptionsFromSettings } from '../../terminal/terminal-config'+import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'/** Fixed grid — the preview is a sample, not a fitted terminal, so there is no FitAddon and no* ResizeObserver to keep in sync. Wide enough for the sample lines below without wrapping. */@@ -45,15 +46,7 @@ export function TerminalPreview(): React.JSX.Element {const hostRef = useRef<HTMLDivElement>(null)const termRef = useRef<Terminal | null>(null)- const fontSize = useSettings((s) => s.settings.fontSize)- const fontFamily = useSettings((s) => s.settings.fontFamily)- const cursorBlink = useSettings((s) => s.settings.cursorBlink)- const cursorStyle = useSettings((s) => s.settings.cursorStyle)- const cursorInactiveStyle = useSettings((s) => s.settings.cursorInactiveStyle)- const terminalLineHeight = useSettings((s) => s.settings.terminalLineHeight)- const terminalLetterSpacing = useSettings((s) => s.settings.terminalLetterSpacing)- const terminalTheme = useSettings((s) => s.settings.terminalTheme)- const tmuxScrollback = useSettings((s) => s.settings.tmuxScrollback)+ const visual = useXtermVisualSettings()useEffect(() => {const s = useSettings.getState().settings@@ -77,28 +70,8 @@ export function TerminalPreview(): React.JSX.Element {useEffect(() => {const term = termRef.currentif (!term) return- applyLiveOptions(term, {- fontFamily,- fontSize,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeight,- terminalLetterSpacing,- terminalTheme,- tmuxScrollback- })- }, [- fontSize,- fontFamily,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeight,- terminalLetterSpacing,- terminalTheme,- tmuxScrollback- ])+ applyLiveOptions(term, visual)+ }, [visual])return (<div className="settings-term-preview">diff --git a/src/renderer/components/settings/sections/TerminalSection.tsx b/src/renderer/components/settings/sections/TerminalSection.tsxindex f48a66afd..b84538625 100644--- a/src/renderer/components/settings/sections/TerminalSection.tsx+++ b/src/renderer/components/settings/sections/TerminalSection.tsx@@ -3,7 +3,7 @@ import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'import { TerminalPreview } from '../TerminalPreview'-import { Input } from '@renderer/ui/Input'+import { FontPicker } from '../FontPicker'import { Switch } from '@renderer/ui/Switch'import { Select } from '@renderer/ui/Select'import { NumberField } from '@renderer/ui/NumberField'@@ -47,6 +47,27 @@ const ROWS = {'light']},+ fontWeight: {+ title: 'Font weight',+ keywords: ['font', 'weight', 'bold', 'thin', 'light', 'heavy']+ },+ boldBright: {+ title: 'Bold text uses bright colours',+ keywords: ['bold', 'bright', 'color', 'colour', 'intense']+ },+ minContrast: {+ title: 'Minimum contrast',+ keywords: [+ 'contrast',+ 'readable',+ 'legible',+ 'accessibility',+ 'a11y',+ 'wcag',+ 'dim',+ 'unreadable'+ ]+ },cursorStyle: {title: 'Cursor style',keywords: ['cursor', 'style', 'block', 'bar', 'beam', 'underline']@@ -71,6 +92,28 @@ const ROWS = {}const ENTRIES = Object.values(ROWS)+const FONT_WEIGHTS: { value: number; label: string }[] = [+ { value: 100, label: 'Thin' },+ { value: 200, label: 'Extra light' },+ { value: 300, label: 'Light' },+ { value: 400, label: 'Regular' },+ { value: 500, label: 'Medium' },+ { value: 600, label: 'Semibold' },+ { value: 700, label: 'Bold' },+ { value: 800, label: 'Extra bold' },+ { value: 900, label: 'Black' }+]++// xterm reads 1 as "no adjustment"; the named steps are the WCAG ratios, and 21 is the maximum+// possible (black on white), i.e. force every foreground to one or the other.+const MIN_CONTRAST_OPTIONS: { value: number; label: string }[] = [+ { value: 1, label: 'Off' },+ { value: 3, label: 'Low (3:1)' },+ { value: 4.5, label: 'WCAG AA (4.5:1)' },+ { value: 7, label: 'WCAG AAA (7:1)' },+ { value: 21, label: 'Maximum' }+]+const CURSOR_STYLES: { value: TerminalCursorStyle; label: string }[] = [{ value: 'block', label: 'Block' },{ value: 'bar', label: 'Bar' },@@ -140,12 +183,58 @@ export function TerminalSection({ isActive }: { isActive: boolean }): React.JSX.<SearchableRow {...ROWS.fontFamily}><FieldRowlabel="Font family"- description="A CSS font stack. Names that aren't installed are skipped, so keep a generic monospace last."+ description="Only fonts installed on this machine are listed. The field below is the full CSS stack — keep a generic monospace last, so the setting still works on a machine without your font."control={- <Input- className="w-64"+ <FontPickervalue={settings.fontFamily}- onChange={(e) => update({ fontFamily: e.target.value })}+ onChange={(stack) => update({ fontFamily: stack })}+ />+ }+ />+ </SearchableRow>+ <SearchableRow {...ROWS.fontWeight}>+ <FieldRow+ label="Font weight"+ control={+ <span className="flex items-center gap-2">+ <Select+ className="w-32"+ value={String(settings.fontWeight)}+ onChange={(e) => update({ fontWeight: Number(e.target.value) })}+ aria-label="Font weight"+ >+ {FONT_WEIGHTS.map((w) => (+ <option key={w.value} value={w.value}>+ {w.label}+ </option>+ ))}+ </Select>+ <span className="text-[13px] text-muted">bold</span>+ <Select+ className="w-32"+ value={String(settings.fontWeightBold)}+ onChange={(e) => update({ fontWeightBold: Number(e.target.value) })}+ aria-label="Bold font weight"+ >+ {FONT_WEIGHTS.map((w) => (+ <option key={w.value} value={w.value}>+ {w.label}+ </option>+ ))}+ </Select>+ </span>+ }+ />+ </SearchableRow>+ <SearchableRow {...ROWS.boldBright}>+ <FieldRow+ label="Bold text uses bright colours"+ description="The historical terminal convention, and xterm's default. Turn it off to keep bold purely a weight, so a program's colour choice survives."+ control={+ <Switch+ checked={settings.drawBoldTextInBrightColors}+ onChange={(v) => update({ drawBoldTextInBrightColors: v })}+ ariaLabel="Bold text uses bright colours"/>}/>@@ -189,6 +278,26 @@ export function TerminalSection({ isActive }: { isActive: boolean }): React.JSX.<TerminalPreview /></div></SearchableRow>+ <SearchableRow {...ROWS.minContrast}>+ <FieldRow+ label="Minimum contrast"+ description="Lightens or darkens foreground colours that fall below the ratio against their background — the fix for a theme whose dark blue is unreadable. Costs per-cell work in the renderer, so it is off by default."+ control={+ <Select+ className="w-44"+ value={String(settings.terminalMinContrast)}+ onChange={(e) => update({ terminalMinContrast: Number(e.target.value) })}+ aria-label="Minimum contrast"+ >+ {MIN_CONTRAST_OPTIONS.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </Select>+ }+ />+ </SearchableRow><SearchableRow {...ROWS.cursorStyle}><div className="space-y-3">diff --git a/src/renderer/lib/fontDetect.test.ts b/src/renderer/lib/fontDetect.test.tsnew file mode 100644index 000000000..31d3298a0--- /dev/null+++ b/src/renderer/lib/fontDetect.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest'+import {+ MONO_FONT_CATALOG,+ buildFontStack,+ detectInstalled,+ isFontAvailable,+ isGenericFamily,+ primaryFamily,+ quoteFamily,+ type MeasureText+} from './fontDetect'++/**+ * A measurer standing in for the canvas: every generic base has its own width, and each font in+ * `installed` shifts it — which is exactly the signal `isFontAvailable` reads. A font NOT in the+ * set leaves the width at the base's, i.e. it fell through to the fallback.+ */+function fakeMeasure(installed: readonly string[]): MeasureText {+ const baseWidth: Record<string, number> = { monospace: 100, serif: 110, 'sans-serif': 120 }+ return (font: string) => {+ const m = /^\d+px (.*)$/.exec(font)+ if (!m) return 0+ const families = m[1].split(',').map((f) => f.trim().replace(/^["']|["']$/g, ''))+ const base = families[families.length - 1]+ const named = families.slice(0, -1)+ const hit = named.find((f) => installed.includes(f))+ return hit ? baseWidth[base] + hit.length : (baseWidth[base] ?? 0)+ }+}++describe('primaryFamily', () => {+ it('takes the first family of a stack', () => {+ expect(primaryFamily('Menlo, Monaco, "Courier New", monospace')).toBe('Menlo')+ })++ it('strips quotes', () => {+ expect(primaryFamily('"JetBrains Mono", monospace')).toBe('JetBrains Mono')+ expect(primaryFamily("'Fira Code', monospace")).toBe('Fira Code')+ })++ it('handles a single family and stray whitespace', () => {+ expect(primaryFamily(' Hack ')).toBe('Hack')+ expect(primaryFamily('monospace')).toBe('monospace')+ })++ it('returns empty for empty input', () => {+ expect(primaryFamily('')).toBe('')+ expect(primaryFamily(' ')).toBe('')+ })+})++describe('isGenericFamily', () => {+ it('knows the CSS generics, case-insensitively', () => {+ expect(isGenericFamily('monospace')).toBe(true)+ expect(isGenericFamily('UI-Monospace')).toBe(true)+ expect(isGenericFamily('system-ui')).toBe(true)+ })++ it('is false for real family names', () => {+ expect(isGenericFamily('Menlo')).toBe(false)+ expect(isGenericFamily('JetBrains Mono')).toBe(false)+ })+})++describe('quoteFamily / buildFontStack', () => {+ it('quotes only what needs quoting', () => {+ expect(quoteFamily('Menlo')).toBe('Menlo')+ expect(quoteFamily('Fira-Code')).toBe('Fira-Code')+ expect(quoteFamily('JetBrains Mono')).toBe('"JetBrains Mono"')+ expect(quoteFamily('0xProto')).toBe('"0xProto"') // leading digit isn't a valid bare ident+ })++ // The setting travels between machines (and to the Server Edition's browser); a bare single+ // family would render as something arbitrary wherever it isn't installed.+ it('always keeps fallbacks after the chosen family', () => {+ expect(buildFontStack('JetBrains Mono')).toBe(+ '"JetBrains Mono", Menlo, Monaco, "Courier New", monospace'+ )+ })++ it('collapses an empty or generic choice to plain monospace', () => {+ expect(buildFontStack('')).toBe('monospace')+ expect(buildFontStack(' ')).toBe('monospace')+ expect(buildFontStack('monospace')).toBe('monospace')+ })+})++describe('isFontAvailable', () => {+ const measure = fakeMeasure(['Menlo', 'JetBrains Mono'])++ it('detects an installed font by its metrics differing from a generic base', () => {+ expect(isFontAvailable('Menlo', measure)).toBe(true)+ expect(isFontAvailable('JetBrains Mono', measure)).toBe(true)+ })++ it('reports a missing font — it measures exactly like the fallback', () => {+ expect(isFontAvailable('Fira Code', measure)).toBe(false)+ expect(isFontAvailable('Nonexistent Font', measure)).toBe(false)+ })++ it('accepts a quoted name', () => {+ expect(isFontAvailable('"JetBrains Mono"', measure)).toBe(true)+ })++ it('treats the generics as always available (they ARE the fallback)', () => {+ expect(isFontAvailable('monospace', measure)).toBe(true)+ expect(isFontAvailable('system-ui', measure)).toBe(true)+ })++ it('is false for an empty name', () => {+ expect(isFontAvailable('', measure)).toBe(false)+ })++ // A broken measurer must not turn into "your font is missing" on every row — an unknown answer+ // is not evidence of absence.+ it('reports not-available rather than guessing when the measurer returns nothing', () => {+ expect(isFontAvailable('Menlo', () => 0)).toBe(false)+ })+})++describe('detectInstalled', () => {+ it('filters the catalogue to what is installed, preserving order', () => {+ const measure = fakeMeasure(['Menlo', 'Hack', 'Consolas'])+ expect(detectInstalled(['Hack', 'Fira Code', 'Menlo', 'Consolas'], measure)).toEqual([+ 'Hack',+ 'Menlo',+ 'Consolas'+ ])+ })++ it('returns nothing when none are installed', () => {+ expect(detectInstalled(['A', 'B'], fakeMeasure([]))).toEqual([])+ })+})++describe('MONO_FONT_CATALOG', () => {+ it('has no duplicates and is sorted, so the picker reads predictably', () => {+ expect(new Set(MONO_FONT_CATALOG).size).toBe(MONO_FONT_CATALOG.length)+ expect([...MONO_FONT_CATALOG]).toEqual([...MONO_FONT_CATALOG].sort())+ })+})diff --git a/src/renderer/lib/fontDetect.ts b/src/renderer/lib/fontDetect.tsnew file mode 100644index 000000000..acfb99ebf--- /dev/null+++ b/src/renderer/lib/fontDetect.ts@@ -0,0 +1,172 @@+/**+ * Is this font actually installed?+ *+ * `settings.fontFamily` is a free-text CSS stack, so a user who types "Fira Code" without having+ * installed it gets silently rendered in the next fallback — the setting appears to do nothing and+ * there is no error anywhere. Detecting availability is what lets the UI say so.+ *+ * **`document.fonts.check()` cannot answer this.** It reports on the FontFaceSet — web fonts the+ * document loaded — and returns `true` for any syntactically valid family name that resolves+ * through fallback, which is every name. The only technique that works for OS-installed fonts is+ * the width comparison below: render a sample string in `"<family>", <generic>` and in `<generic>`+ * alone, and see whether the metrics move. If the family doesn't exist, both render as the generic+ * and measure identically.+ *+ * All of this is pure over an injected `measure`, so the real canvas is only needed at the edge.+ */++/** CSS generic families — always "available" (they ARE the fallback), never worth measuring. */+const GENERIC_FAMILIES = new Set([+ 'monospace',+ 'serif',+ 'sans-serif',+ 'cursive',+ 'fantasy',+ 'system-ui',+ 'ui-monospace',+ 'ui-serif',+ 'ui-sans-serif',+ 'ui-rounded',+ 'math',+ 'emoji',+ 'fangsong',+ 'inherit',+ 'initial',+ 'unset'+])++/**+ * Bases to compare against. Three, not one: a font whose metrics happen to match the monospace+ * default would read as missing if monospace were the only probe. A real font is very unlikely to+ * match all three.+ */+const PROBE_BASES = ['monospace', 'serif', 'sans-serif'] as const++/** Mixed widths — proportional and monospace fonts diverge hard on these. */+const PROBE_TEXT = 'mmmmmmmmmmlliWWWiiil0O'++/** Big enough that a sub-pixel per-glyph difference accumulates past any rounding. */+const PROBE_SIZE = 72++/** Measures a CSS `font` shorthand and returns the sample string's width. */+export type MeasureText = (font: string) => number++export function isGenericFamily(family: string): boolean {+ return GENERIC_FAMILIES.has(family.trim().toLowerCase())+}++/**+ * The first family in a CSS font stack, unquoted. This is the one the terminal actually renders+ * with when it exists, so it is the one worth warning about.+ */+export function primaryFamily(stack: string): string {+ const first = stack.split(',')[0]?.trim() ?? ''+ return unquote(first)+}++function unquote(name: string): string {+ const t = name.trim()+ if (t.length >= 2 && (t[0] === '"' || t[0] === "'") && t[t.length - 1] === t[0]) {+ return t.slice(1, -1).trim()+ }+ return t+}++/** Quote a family name for use in a CSS stack, if it needs it. */+export function quoteFamily(family: string): string {+ return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(family) ? family : `"${family}"`+}++/**+ * A stack that starts with `family` and keeps sensible fallbacks, so picking a font from the list+ * can never leave the user with a single name that might not exist on their OTHER machine (the+ * setting travels; the font may not).+ */+export function buildFontStack(family: string): string {+ const trimmed = family.trim()+ if (!trimmed || isGenericFamily(trimmed)) return 'monospace'+ return `${quoteFamily(trimmed)}, Menlo, Monaco, "Courier New", monospace`+}++/**+ * Whether `family` resolves to a real installed font.+ *+ * Generic families are true by definition. Everything else is available only if it measures+ * DIFFERENTLY from at least one generic base — identical metrics against all three mean the name+ * resolved to nothing and fell through.+ */+export function isFontAvailable(family: string, measure: MeasureText): boolean {+ const name = unquote(family)+ if (!name) return false+ if (isGenericFamily(name)) return true+ const quoted = quoteFamily(name)+ return PROBE_BASES.some((base) => {+ const baseline = measure(`${PROBE_SIZE}px ${base}`)+ const candidate = measure(`${PROBE_SIZE}px ${quoted}, ${base}`)+ // A zero-width measurement means the canvas gave us nothing (no 2D context, a detached+ // document): report "not different" rather than inventing an answer, so a broken measurer+ // degrades to "unknown", never to a false accusation that a font is missing.+ if (!baseline || !candidate) return false+ return baseline !== candidate+ })+}++/** The installed subset of `families`, in the order given. */+export function detectInstalled(families: readonly string[], measure: MeasureText): string[] {+ return families.filter((f) => isFontAvailable(f, measure))+}++/**+ * Well-known coding fonts, offered as a starting point. This is a CATALOGUE, not a whitelist — it+ * is filtered by what is actually installed, and the free-text field still accepts anything, so a+ * font nobody thought to list here is never out of reach.+ */+export const MONO_FONT_CATALOG: readonly string[] = [+ '0xProto',+ 'Anonymous Pro',+ 'Berkeley Mono',+ 'Cascadia Code',+ 'Cascadia Mono',+ 'Comic Mono',+ 'Consolas',+ 'Courier New',+ 'DejaVu Sans Mono',+ 'Departure Mono',+ 'Fira Code',+ 'Fira Mono',+ 'Geist Mono',+ 'Hack',+ 'IBM Plex Mono',+ 'Inconsolata',+ 'Iosevka',+ 'JetBrains Mono',+ 'Liberation Mono',+ 'Maple Mono',+ 'Menlo',+ 'Monaco',+ 'MonoLisa',+ 'Noto Sans Mono',+ 'PT Mono',+ 'Roboto Mono',+ 'SF Mono',+ 'Source Code Pro',+ 'Space Mono',+ 'Ubuntu Mono',+ 'Victor Mono'+]++/**+ * A canvas-backed measurer, or null where there is no 2D context to measure with.+ *+ * One canvas is reused for every probe: creating one per measurement is what turns a 30-font scan+ * into a visible hitch.+ */+export function createCanvasMeasurer(): MeasureText | null {+ if (typeof document === 'undefined') return null+ const ctx = document.createElement('canvas').getContext('2d')+ if (!ctx) return null+ return (font: string) => {+ ctx.font = font+ return ctx.measureText(PROBE_TEXT).width+ }+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex fb0e85d1f..6990db620 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -54,6 +54,7 @@ import {CO_ATTACH_MOUSE_SEQ,type SessionLife} from '../terminal/terminal-config'+import { useXtermVisualSettings } from '../terminal/useXtermVisualSettings'import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'import { deliverCommand, type DeliveryIo } from '../terminal/command-delivery'import {@@ -365,15 +366,8 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// Scoped selectors (not the whole settings object) so this node only re-renders when a// field it actually uses changes — not on every unrelated settings edit.const panHoverDelay = useSettings((s) => s.settings.panHoverDelay)- const fontSize = useSettings((s) => s.settings.fontSize)- const fontFamily = useSettings((s) => s.settings.fontFamily)- const cursorBlink = useSettings((s) => s.settings.cursorBlink)- const cursorStyle = useSettings((s) => s.settings.cursorStyle)- const cursorInactiveStyle = useSettings((s) => s.settings.cursorInactiveStyle)- const terminalLineHeightSetting = useSettings((s) => s.settings.terminalLineHeight)- const terminalLetterSpacingSetting = useSettings((s) => s.settings.terminalLetterSpacing)- const terminalTheme = useSettings((s) => s.settings.terminalTheme)- const tmuxScrollback = useSettings((s) => s.settings.tmuxScrollback)+ // One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.+ const visual = useXtermVisualSettings()const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)// Header buttons the user chose to hide (Settings). A selector, so toggling one re-renders every// mounted node right away instead of waiting for a remount. Search, Close and the worktree-move@@ -1567,30 +1561,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNuseEffect(() => {const term = termRef.currentif (!term) return- const { metricsChanged, themeChanged } = applyLiveOptions(term, {- fontFamily,- fontSize,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeight: terminalLineHeightSetting,- terminalLetterSpacing: terminalLetterSpacingSetting,- terminalTheme,- tmuxScrollback- })+ const { metricsChanged, themeChanged } = applyLiveOptions(term, visual)if (metricsChanged) applyFitRef.current?.()if (themeChanged) fullRepaintRef.current?.()- }, [- fontSize,- fontFamily,- cursorBlink,- cursorStyle,- cursorInactiveStyle,- terminalLineHeightSetting,- terminalLetterSpacingSetting,- terminalTheme,- tmuxScrollback- ])+ }, [visual])// Kanban board opened/closed: re-evaluate our size vote. Open → applyFit reports null (yield the// grid to a card-modal viewer); close → it re-reports the real fit. On the first run boardOpendiff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.tsindex 10a95ef35..a357156bc 100644--- a/src/renderer/terminal/terminal-config.test.ts+++ b/src/renderer/terminal/terminal-config.test.ts@@ -651,6 +651,10 @@ describe('repaintResync', () => {const visual = (p: Partial<XtermVisualSettings> = {}): XtermVisualSettings => ({fontFamily: 'Menlo',fontSize: 13,+ fontWeight: 400,+ fontWeightBold: 700,+ drawBoldTextInBrightColors: true,+ terminalMinContrast: 1,cursorBlink: true,cursorStyle: 'block',cursorInactiveStyle: 'outline',@@ -788,6 +792,39 @@ describe('applyLiveOptions', () => {)})+ // The font WEIGHTS are the interesting case: xterm's CharSizeService re-measures the cell only+ // on fontFamily/fontSize, so a weight change repaints but never moves the grid. Reporting it as+ // a metrics change would push a pointless resize at the shared pty on every weight tweak.+ it.each([+ ['fontWeight', { fontWeight: 300 }],+ ['fontWeightBold', { fontWeightBold: 600 }],+ ['drawBoldTextInBrightColors', { drawBoldTextInBrightColors: false }],+ ['terminalMinContrast', { terminalMinContrast: 4.5 }]+ ] as const)('applies %s without reporting a cell-geometry change', (_name, patch) => {+ const term = fakeTerm(visual())+ const r = applyLiveOptions(term, visual(patch as Partial<XtermVisualSettings>))+ expect(r).toEqual({ metricsChanged: false, themeChanged: false })+ expect(term.writes).toHaveLength(1)+ })++ it('clamps a hand-edited weight and contrast rather than passing them to xterm', () => {+ const o = xtermOptionsFromSettings(+ visual({ fontWeight: 5000, fontWeightBold: 0, terminalMinContrast: 99 })+ )+ expect(o.fontWeight).toBe(900)+ expect(o.fontWeightBold).toBe(100)+ expect(o.minimumContrastRatio).toBe(21)+ })++ it('falls back for a NaN weight or contrast', () => {+ const o = xtermOptionsFromSettings(+ visual({ fontWeight: NaN, fontWeightBold: NaN, terminalMinContrast: NaN })+ )+ expect(o.fontWeight).toBe(400)+ expect(o.fontWeightBold).toBe(700)+ expect(o.minimumContrastRatio).toBe(1)+ })+it('applies a theme change and reports themeChanged', () => {const term = fakeTerm(visual())const r = applyLiveOptions(term, visual({ terminalTheme: 'tokyo-night' }))diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.tsindex 56103a542..7d061268c 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -1,4 +1,4 @@-import type { ITheme } from '@xterm/xterm'+import type { FontWeight, ITheme } from '@xterm/xterm'import type { ClientId } from '@shared/presence'import type { Settings, TerminalCursorInactiveStyle, TerminalCursorStyle } from '@shared/types'import { resolveTerminalTheme } from './themes'@@ -193,12 +193,32 @@ export function terminalLetterSpacing(value: number): number {return clamp(value, TERMINAL_LETTER_SPACING_MIN, TERMINAL_LETTER_SPACING_MAX, 0)}+/** CSS numeric font weights. */+export const TERMINAL_FONT_WEIGHT_MIN = 100+export const TERMINAL_FONT_WEIGHT_MAX = 900++export function terminalFontWeight(value: number, fallback: number): number {+ return clamp(value, TERMINAL_FONT_WEIGHT_MIN, TERMINAL_FONT_WEIGHT_MAX, fallback)+}++/** xterm's contrast bounds: 1 disables the adjustment, 21 is black-on-white. */+export const TERMINAL_MIN_CONTRAST_MIN = 1+export const TERMINAL_MIN_CONTRAST_MAX = 21++export function terminalMinContrast(value: number): number {+ return clamp(value, TERMINAL_MIN_CONTRAST_MIN, TERMINAL_MIN_CONTRAST_MAX, 1)+}+/** The slice of `Settings` that decides how a terminal LOOKS. Narrowed to a structural type so* the helpers below are callable from a test with a plain object literal. */export type XtermVisualSettings = Pick<Settings,| 'fontFamily'| 'fontSize'+ | 'fontWeight'+ | 'fontWeightBold'+ | 'drawBoldTextInBrightColors'+ | 'terminalMinContrast'| 'cursorBlink'| 'cursorStyle'| 'cursorInactiveStyle'@@ -208,10 +228,35 @@ export type XtermVisualSettings = Pick<| 'tmuxScrollback'>+/** The keys `XtermVisualSettings` is made of — the single list the settings hook selects by, so a+ * new appearance option cannot be added to the type and then forgotten in the subscription. */+export const XTERM_VISUAL_KEYS = [+ 'fontFamily',+ 'fontSize',+ 'fontWeight',+ 'fontWeightBold',+ 'drawBoldTextInBrightColors',+ 'terminalMinContrast',+ 'cursorBlink',+ 'cursorStyle',+ 'cursorInactiveStyle',+ 'terminalLineHeight',+ 'terminalLetterSpacing',+ 'terminalTheme',+ 'tmuxScrollback'+] as const satisfies readonly (keyof XtermVisualSettings)[]+/** The appearance-derived options, resolved and clamped. */export interface XtermVisualOptions {fontFamily: stringfontSize: number+ // xterm widens these to `FontWeight` ('normal' | 'bold' | '100'… | number). We only ever WRITE+ // numbers, but the type has to match what `term.options` exposes or the live target can't be+ // compared against a real terminal.+ fontWeight: FontWeight+ fontWeightBold: FontWeight+ drawBoldTextInBrightColors: boolean+ minimumContrastRatio: numbercursorBlink: booleancursorStyle: TerminalCursorStylecursorInactiveStyle: TerminalCursorInactiveStyle@@ -234,6 +279,10 @@ export function xtermOptionsFromSettings(return {fontFamily: s.fontFamily,fontSize: s.fontSize,+ fontWeight: terminalFontWeight(s.fontWeight, 400),+ fontWeightBold: terminalFontWeight(s.fontWeightBold, 700),+ drawBoldTextInBrightColors: s.drawBoldTextInBrightColors,+ minimumContrastRatio: terminalMinContrast(s.terminalMinContrast),cursorBlink: s.cursorBlink,cursorStyle: s.cursorStyle,cursorInactiveStyle: s.cursorInactiveStyle,@@ -288,6 +337,9 @@ export function applyLiveOptions(): LiveOptionEffects {const next = xtermOptionsFromSettings(s)const o = term.options+ // Deliberately NOT including the font WEIGHTS. xterm derives its cell size from+ // `CharSizeService`, which re-measures only on `fontFamily`/`fontSize` — a weight change never+ // moves the grid, so re-fitting on one would report a resize to the shared pty for nothing.const metricsChanged =o.fontFamily !== next.fontFamily ||o.fontSize !== next.fontSize ||@@ -301,6 +353,14 @@ export function applyLiveOptions(if (o.fontSize !== next.fontSize) o.fontSize = next.fontSizeif (o.lineHeight !== next.lineHeight) o.lineHeight = next.lineHeightif (o.letterSpacing !== next.letterSpacing) o.letterSpacing = next.letterSpacing+ if (o.fontWeight !== next.fontWeight) o.fontWeight = next.fontWeight+ if (o.fontWeightBold !== next.fontWeightBold) o.fontWeightBold = next.fontWeightBold+ if (o.drawBoldTextInBrightColors !== next.drawBoldTextInBrightColors) {+ o.drawBoldTextInBrightColors = next.drawBoldTextInBrightColors+ }+ if (o.minimumContrastRatio !== next.minimumContrastRatio) {+ o.minimumContrastRatio = next.minimumContrastRatio+ }if (o.cursorBlink !== next.cursorBlink) o.cursorBlink = next.cursorBlinkif (o.cursorStyle !== next.cursorStyle) o.cursorStyle = next.cursorStyleif (o.cursorInactiveStyle !== next.cursorInactiveStyle) {diff --git a/src/renderer/terminal/useXtermVisualSettings.ts b/src/renderer/terminal/useXtermVisualSettings.tsnew file mode 100644index 000000000..98d9445df--- /dev/null+++ b/src/renderer/terminal/useXtermVisualSettings.ts@@ -0,0 +1,27 @@+import { useShallow } from 'zustand/react/shallow'+import { useSettings } from '../state/settings'+import { XTERM_VISUAL_KEYS, type XtermVisualSettings } from './terminal-config'++/**+ * The appearance slice of Settings, as ONE subscription.+ *+ * Every component that owns an xterm needs the same thirteen fields, and the alternative — one+ * `useSettings((s) => s.settings.x)` per field — was already a wall of near-identical lines that+ * had to be kept in sync across three components AND repeated in each effect's dependency array.+ * Adding an option meant touching six places, which is exactly how a surface gets left behind.+ *+ * `useShallow` is what makes this safe: selecting the settings OBJECT would re-render on every+ * unrelated settings edit (a new object identity each time), and a canvas full of live terminals+ * is the last thing that should re-render because a notification toggle moved. Shallow-comparing+ * the picked keys keeps the old behaviour — re-render only when an appearance value actually+ * changes — while collapsing the effect dependency to a single stable value.+ */+export function useXtermVisualSettings(): XtermVisualSettings {+ return useSettings(+ useShallow((s) => {+ const out = {} as Record<string, unknown>+ for (const k of XTERM_VISUAL_KEYS) out[k] = s.settings[k]+ return out as unknown as XtermVisualSettings+ })+ )+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 95d012761..a31e581e9 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -688,6 +688,19 @@ export interface Settings {* (settings.json is hand-editable): an unknown id falls back to the default theme, whose* colours reproduce the pre-feature hardcoded `#1e1e1e`/`#e6e6e6` exactly. */terminalTheme: string+ /** Weight for normal text. xterm's own default is `normal` (400). */+ fontWeight: number+ /** Weight for BOLD text. xterm's own default is `bold` (700). Lowering it is how you keep bold+ * legible in a thin font that renders 700 as a smear. */+ fontWeightBold: number+ /** Render bold text in the palette's BRIGHT colours (xterm's default, and the historical+ * terminal convention). Off keeps bold purely a weight, so colour still means what the program+ * said it meant. */+ drawBoldTextInBrightColors: boolean+ /** Minimum foreground/background contrast ratio, 1–21. 1 (xterm's default) disables the+ * adjustment entirely; 4.5 is WCAG AA, 7 is AAA, 21 forces black or white. Costs per-cell work+ * in the renderer, so it stays off unless asked for. */+ terminalMinContrast: number/** Cursor shape. */cursorStyle: TerminalCursorStyle/** Cursor shape while the terminal does NOT have focus. `outline` (xterm's own default) is what@@ -844,6 +857,10 @@ export const DEFAULT_SETTINGS: Settings = {// carries the old hardcoded background/foreground, and block/outline/1/0 are xterm's own// defaults. Picking a theme is opt-in — an update must not repaint anybody's terminals.terminalTheme: 'nodeterm-dark',+ fontWeight: 400,+ fontWeightBold: 700,+ drawBoldTextInBrightColors: true,+ terminalMinContrast: 1,cursorStyle: 'block',cursorInactiveStyle: 'outline',terminalLineHeight: 1,