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(project-settings): project-scoped terminal theme/font (live) + panel theme select
enes0f492aad7e86
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 4c58bacb2..dff9a25c5 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -32,7 +32,12 @@ import {CO_ATTACH_MOUSE_SEQ} from '../../terminal/terminal-config'import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'-import { resolveSshRemote, reportSshDrop, sshConnectionScope } from '../../nodes/TerminalNode'+import {+ owningProjectId,+ resolveSshRemote,+ reportSshDrop,+ sshConnectionScope+} from '../../nodes/TerminalNode'import { buildSshArgs, type SshConnection } from '@shared/ssh'/** The subset of a node's `data` a SECOND client needs to attach to its session the same way the@@ -90,7 +95,11 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Modaconst transportRef = useRef<LocalTransport | null>(null)const agentSessionId = useAgentStatus((s) => s.byId[nodeId]?.sessionId)// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.- const visual = useXtermVisualSettings()+ // MIRROR TerminalNode: scoped to the OWNING project (`owningProjectId`, the active one — a modal+ // only ever opens over it), deliberately NOT this card's connection scope. `sshConnectionScope`+ // answers a project×host attachment id for a session on a foreign host, which names no project at+ // all — the per-project appearance would silently vanish for exactly those cards.+ const visual = useXtermVisualSettings(owningProjectId())const [dropping, setDropping] = useState(false)const [uploading, setUploading] = useState(false)// Same copy feedback as the canvas node — a copy here is the same act as a copy there, includingdiff --git a/src/renderer/components/settings/ProjectSettingsFamilies.tsx b/src/renderer/components/settings/ProjectSettingsFamilies.tsxindex a94d39421..2894aefc1 100644--- a/src/renderer/components/settings/ProjectSettingsFamilies.tsx+++ b/src/renderer/components/settings/ProjectSettingsFamilies.tsx@@ -10,7 +10,9 @@ import type {} from '@shared/project-settings'import { Button } from '@renderer/ui/Button'import { Input } from '@renderer/ui/Input'+import { Select } from '@renderer/ui/Select'import { Switch } from '@renderer/ui/Switch'+import { isKnownTerminalThemeId, TERMINAL_THEMES } from '@renderer/terminal/themes'import { useProjectSetup } from '../../state/projectSetup'import { useSettingsSearch } from './context'import { FieldRow } from './FieldRow'@@ -28,7 +30,7 @@ import { matchesQuery, type SettingsSearchEntry } from './search'* would have pushed that file well past ~400 lines.*/-type FieldKind = 'input' | 'textarea' | 'switch' | 'env' | 'list'+type FieldKind = 'input' | 'textarea' | 'switch' | 'env' | 'list' | 'theme'interface FieldConfig {key: string@@ -49,7 +51,12 @@ const FAMILY_CONFIG: Record<ProjectSettingsFamily, FamilyConfig> = {{key: 'setupScript',label: 'Setup script',- description: 'Runs once when a worktree for this project is created.',+ // Not only "when a worktree is created": `attachWorktree` is the single post-bind point, so+ // adopting an existing worktree and re-binding one to a group run it too (as does the failed+ // chip's Re-run). A script written for a fresh checkout only, and re-run over a working one,+ // is the kind of surprise the row itself has to warn about.+ description:+ 'Runs when a worktree for this project is created, adopted, or re-bound to a group.',kind: 'textarea'},{@@ -60,7 +67,13 @@ const FAMILY_CONFIG: Record<ProjectSettingsFamily, FamilyConfig> = {},{key: 'waitForSetup',- label: 'Wait for setup to finish before opening a terminal',+ // The old label ("…before opening a terminal") promised something this switch never did:+ // the terminal opens immediately either way. What waits is the node's QUEUED LAUNCH COMMAND+ // (`launchesToFire`'s setup gate) — the agent command must not race an `npm ci` still+ // writing node_modules under it.+ label: 'Hold queued launch commands until the setup script finishes',+ description:+ 'Nodes opened into a new worktree still open right away; only their queued command waits.',kind: 'switch'}]@@ -110,8 +123,21 @@ const FAMILY_CONFIG: Record<ProjectSettingsFamily, FamilyConfig> = {title: 'Terminal',fields: [{ key: 'shell', label: 'Shell', kind: 'input' },- { key: 'theme', label: 'Theme', kind: 'input' },- { key: 'fontFamily', label: 'Font family', kind: 'input' }+ // Neither description says the word "project": every row in this pane is a project setting,+ // so it discriminates nothing while making the query "project" match the whole pane — the+ // very thing `fieldEntry`'s keyword list is careful to avoid.+ {+ key: 'theme',+ label: 'Theme',+ description: 'Overrides the global terminal theme. Terminals already open repaint.',+ kind: 'theme'+ },+ {+ key: 'fontFamily',+ label: 'Font family',+ description: 'Overrides the global terminal font.',+ kind: 'input'+ }]}}@@ -294,6 +320,68 @@ function EnvField({)}+/**+ * The terminal `theme` row: a Select over the ids this build actually ships, not a free-text box.+ *+ * Three properties the plain Input could not have:+ * - the ids are not guessable ('catppuccin-mocha', 'tokyo-night'), and a typo used to be+ * indistinguishable from a working value — the merge ignores an unknown id, so the terminal just+ * kept the global theme with nothing on screen saying why.+ * - the empty option is INHERIT, not "no theme": it clears the field so this machine's global+ * setting (or, on a local row, the shared document) decides.+ * - a stored id this build does not know must still READ AS ITSELF rather than silently showing as+ * "inherit" — same precedent as the identity pane's unknown-account option. A teammate's newer+ * theme name, or one since removed, is a real value sitting in a real document; presenting the+ * box as empty would invite a save that erases it.+ */+function ThemeField({+ id,+ label,+ ariaLabel,+ description,+ note,+ value,+ disabled,+ onCommit+}: {+ id: string+ label: string+ ariaLabel?: string+ description?: string+ note?: string+ value: string+ disabled?: boolean+ onCommit: (value: string | undefined) => void+}): React.JSX.Element {+ const unknown = value !== '' && !isKnownTerminalThemeId(value)+ return (+ <FieldRow+ label={label}+ description={description}+ note={note}+ htmlFor={id}+ control={+ <Select+ id={id}+ className="w-72"+ aria-label={ariaLabel}+ value={value}+ disabled={disabled}+ onChange={(e) => onCommit(e.target.value === '' ? undefined : e.target.value)}+ >+ <option value="">Inherit (use this machine’s setting)</option>+ {TERMINAL_THEMES.map((t) => (+ <option key={t.id} value={t.id}>+ {t.label}+ </option>+ ))}+ {unknown ? <option value={value}>{value} (not in this version)</option> : null}+ </Select>+ }+ />+ )+}+function SwitchField({label,description,@@ -672,6 +760,20 @@ function FamilySection({/>)}+ if (f.kind === 'theme') {+ return (+ <ThemeField+ key={f.key}+ id={id}+ label={f.label}+ description={f.description}+ note={overrideNote}+ disabled={sharedDisabled}+ value={textOf(f.kind, sharedFamily?.[f.key])}+ onCommit={(v) => commitShared(f.key, v)}+ />+ )+ }return (<StringFieldkey={f.key}@@ -720,6 +822,21 @@ function FamilySection({/>)}+ if (f.kind === 'theme') {+ return (+ <ThemeField+ key={f.key}+ id={id}+ label={f.label}+ ariaLabel={`${f.label} (this machine)`}+ description={f.description}+ note={activeNote}+ disabled={localDisabled}+ value={textOf(f.kind, localFamily?.[f.key])}+ onCommit={(v) => commitLocal(f.key, v)}+ />+ )+ }return (<StringFieldkey={f.key}diff --git a/src/renderer/components/settings/TerminalPreview.tsx b/src/renderer/components/settings/TerminalPreview.tsxindex 1752f1826..557c054be 100644--- a/src/renderer/components/settings/TerminalPreview.tsx+++ b/src/renderer/components/settings/TerminalPreview.tsx@@ -48,6 +48,9 @@ export function TerminalPreview(): React.JSX.Element {const hostRef = useRef<HTMLDivElement>(null)const termRef = useRef<Terminal | null>(null)+ // No project id, deliberately: this preview exists to show the GLOBAL appearance settings sitting+ // right beside it. Scoping it to the active project would repaint the picture with that project's+ // override, so the row the user is dragging would appear to do nothing.const visual = useXtermVisualSettings()useEffect(() => {diff --git a/src/renderer/components/settings/project-settings-terminal-theme.test.tsx b/src/renderer/components/settings/project-settings-terminal-theme.test.tsxnew file mode 100644index 000000000..8e8ba3c32--- /dev/null+++ b/src/renderer/components/settings/project-settings-terminal-theme.test.tsx@@ -0,0 +1,168 @@+// @vitest-environment jsdom+//+// Settings → Project → Terminal: the theme row is a SELECT over the ids this build ships, not a+// free-text box — and the two copy corrections that ride with it.+//+// A typed theme id was unverifiable: the merge (`mergeProjectVisuals`) ignores an id it does not+// know, so a typo left the terminal on the global theme with nothing on screen saying why. The+// Select removes the failure mode; what it must NOT do is erase a value it does not recognise —+// a teammate's newer theme, or one since removed, is a real value in a real document.+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { ProjectSettingsDoc, ResolvedProjectSettings } from '@shared/project-settings'+import { TERMINAL_THEMES } from '@renderer/terminal/themes'+import { ProjectFamilyEditors } from './ProjectSettingsFamilies'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let root: Root+let host: HTMLElement+let sharedWrites: ProjectSettingsDoc[] = []+let localWrites: (ProjectSettingsDoc | undefined)[] = []++const EMPTY: ResolvedProjectSettings = { setup: {}, worktree: {}, agents: {}, terminal: {} }++function mount(opts: {+ shared?: ProjectSettingsDoc+ local?: ProjectSettingsDoc+ resolved?: ResolvedProjectSettings+}): void {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ act(() =>+ root.render(+ <ProjectFamilyEditors+ projectId="p1"+ snapshot={{+ shared: opts.shared+ ? { version: 1, rev: 1, savedAt: '2026-08-19T00:00:00.000Z', ...opts.shared }+ : null,+ local: opts.local+ }}+ resolved={opts.resolved ?? EMPTY}+ conflict={false}+ sharedEditable+ canRun+ saveShared={async (doc) => {+ sharedWrites.push(doc)+ return true+ }}+ saveLocal={async (update) => {+ localWrites.push(update(opts.local))+ return true+ }}+ reload={() => {}}+ />+ )+ )+}++/** The two theme controls: the shared row's select, then its "this machine" twin. */+function themeSelects(): HTMLSelectElement[] {+ return [+ host.querySelector('#project-terminal-theme-p1') as HTMLSelectElement,+ host.querySelector('#project-terminal-theme-local-p1') as HTMLSelectElement+ ]+}++const optionValues = (sel: HTMLSelectElement): string[] => [...sel.options].map((o) => o.value)++beforeEach(() => {+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {}+ sharedWrites = []+ localWrites = []+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++describe('Terminal family — the theme Select', () => {+ it('offers inherit plus every theme this build ships, on both rows', () => {+ mount({})+ const selects = themeSelects()+ expect(selects[0]).toBeTruthy()+ expect(selects[1]).toBeTruthy()+ for (const sel of selects) {+ // The REAL id list, read from the same module the renderer resolves against — a hand-written+ // copy here would let the two drift silently.+ expect(optionValues(sel)).toEqual(['', ...TERMINAL_THEMES.map((t) => t.id)])+ expect(sel.options[0].textContent).toMatch(/inherit/i)+ // Not a placeholder list: the ids are the ones the terminal actually resolves.+ expect(optionValues(sel)).toContain('nodeterm-dark')+ expect(optionValues(sel)).toContain('catppuccin-mocha')+ }+ expect(selects[0].value).toBe('') // unset reads as inherit, not as a theme+ })++ it('shows the stored id on the row that stores it', () => {+ mount({ shared: { terminal: { theme: 'dracula' } }, local: { terminal: { theme: 'nord' } } })+ const [shared, local] = themeSelects()+ expect(shared.value).toBe('dracula')+ expect(local.value).toBe('nord')+ })++ it('keeps an id this build does not know readable instead of showing it as inherit', () => {+ mount({ shared: { terminal: { theme: 'from-a-newer-version' } } })+ const [shared, local] = themeSelects()+ expect(shared.value).toBe('from-a-newer-version')+ expect([...shared.options].at(-1)?.textContent).toContain('from-a-newer-version')+ // Only where the value actually is — the local row sets nothing and stays on inherit.+ expect(local.value).toBe('')+ expect(optionValues(local)).not.toContain('from-a-newer-version')+ })++ it('writes the picked id, and clears the field when inherit is picked', () => {+ mount({ shared: { terminal: { theme: 'dracula' } } })+ const [shared] = themeSelects()+ act(() => {+ shared.value = 'nord'+ shared.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(sharedWrites).toEqual([{ terminal: { theme: 'nord' } }])+ act(() => {+ shared.value = ''+ shared.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(sharedWrites[1]).toEqual({ terminal: { theme: undefined } })+ })++ it('writes a local pick to the local overlay, leaving the shared document alone', () => {+ mount({ shared: { terminal: { theme: 'dracula' } } })+ const [, local] = themeSelects()+ act(() => {+ local.value = 'tokyo-night'+ local.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(localWrites).toEqual([{ terminal: { theme: 'tokyo-night' } }])+ expect(sharedWrites).toEqual([])+ })++ it('names the local row distinctly from its shared twin, for a screen reader', () => {+ mount({})+ const [shared, local] = themeSelects()+ expect(shared.getAttribute('aria-label')).toBeNull() // named by its own <label>+ expect(local.getAttribute('aria-label')).toBe('Theme (this machine)')+ })+})++describe('Setup family copy — what the rows actually promise', () => {+ it('names every trigger the setup script runs on, not just creation', () => {+ mount({})+ const text = host.textContent ?? ''+ expect(text).toContain('created, adopted, or re-bound to a group')+ })++ // The switch never held a terminal back: the node opens either way. What waits is its QUEUED+ // LAUNCH COMMAND (`launchesToFire`'s setup gate).+ it('describes waitForSetup as holding the queued command, not the terminal', () => {+ mount({})+ const text = host.textContent ?? ''+ expect(text).toContain('Hold queued launch commands until the setup script finishes')+ expect(text).toContain('only their queued command waits')+ expect(text).not.toContain('before opening a terminal')+ })+})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 4510537b8..1b46d0c11 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -201,7 +201,7 @@ export function sshConnectionScope(conn: SshConnection): string {* in the active project's React Flow (same reasoning `sshConnectionScope` states), so the active* project is its owner; an SSH project's own nodes answer the same id either way.*/-function owningProjectId(): string {+export function owningProjectId(): string {return useProjects.getState().activeProjectId}@@ -979,7 +979,9 @@ export function TerminalNode({// field it actually uses changes — not on every unrelated settings edit.const panHoverDelay = useSettings((s) => s.settings.panHoverDelay)// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.- const visual = useXtermVisualSettings()+ // Scoped to the OWNING project so its `terminal.theme` / `terminal.fontFamily` layer over the+ // global settings for this node, and for no other project's nodes.+ const visual = useXtermVisualSettings(owningProjectId())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-movediff --git a/src/renderer/state/projectLaunchInfo.ts b/src/renderer/state/projectLaunchInfo.tsindex 215493d6d..08bbe80ac 100644--- a/src/renderer/state/projectLaunchInfo.ts+++ b/src/renderer/state/projectLaunchInfo.ts@@ -1,4 +1,6 @@+import { create } from 'zustand'import type { ProjectLaunchInfo } from '@shared/project-settings'+import type { ProjectVisualOverrides } from '../terminal/terminal-config'/*** Warmed renderer cache of `project-settings:launch-info` (`projectLaunchInfoNow` /@@ -35,6 +37,60 @@ const generation = new Map<string, number>()* as `permissionMode.ts`'s `CAPS_WAIT_MS`. A launch must never block on this. */const ENSURE_WAIT_MS = 3000+/**+ * The REACTIVE mirror of the cache above — and only of the two cosmetic terminal values+ * (`terminal.theme` / `terminal.fontFamily`), never of the trust verdict.+ *+ * The cache is deliberately not a store: a launch READS it at the moment it launches, so nothing+ * needs to re-render when it changes. Live terminal appearance is the one consumer that does — a+ * project's theme has to reach terminals that are already on screen — and a module-level `Map` can+ * never notify them. Rather than turn the whole cache into a store (which would re-render every+ * terminal on the canvas whenever an unrelated launch field or trust bit moved), this carries the+ * appearance slice alone, so `useXtermVisualSettings` can subscribe shallowly to exactly what it+ * renders.+ *+ * Kept in lockstep with `cache` — written by the same generation-guarded branch, cleared by+ * `invalidate` — so the mirror never claims a value the cache has already dropped. Clearing on+ * invalidate does mean the panel's save path (`invalidate` then re-`ensure`) shows this machine's+ * GLOBAL appearance for the length of one round trip before the project's own comes back. That is+ * accepted deliberately: the alternative — holding the last-known value across an invalidate — keeps+ * a project's colours on screen indefinitely whenever the re-read fails, and a theme that cannot be+ * explained by any document on disk is a worse bug than a repaint the user sees correct itself.+ */+interface ProjectVisualsState {+ byProject: Record<string, ProjectVisualOverrides>+}+export const useProjectVisuals = create<ProjectVisualsState>(() => ({ byProject: {} }))++function sameVisuals(a: ProjectVisualOverrides | undefined, b: ProjectVisualOverrides): boolean {+ return a !== undefined && a.theme === b.theme && a.fontFamily === b.fontFamily+}++/** Push one project's appearance slice into the mirror. No-ops when nothing changed, INCLUDING the+ * object identity — a re-ensure that answers the same values must not re-render a canvas full of+ * terminals (the subscription is shallow, but the entry itself is what it compares). */+function syncVisuals(projectId: string, info: ProjectLaunchInfo | null): void {+ const terminal = info?.resolved.terminal+ const next: ProjectVisualOverrides = {+ theme: terminal?.theme?.value,+ fontFamily: terminal?.fontFamily?.value+ }+ useProjectVisuals.setState((s) => {+ if (sameVisuals(s.byProject[projectId], next)) return s+ return { byProject: { ...s.byProject, [projectId]: next } }+ })+}++/** Drop one project's mirrored appearance — its terminals fall back to the global settings until a+ * fresh answer lands. */+function clearVisuals(projectId: string): void {+ useProjectVisuals.setState((s) => {+ if (!(projectId in s.byProject)) return s+ const { [projectId]: _dropped, ...rest } = s.byProject+ return { byProject: rest }+ })+}+function currentGeneration(projectId: string): number {return generation.get(projectId) ?? 0}@@ -77,7 +133,10 @@ export function ensureProjectLaunchInfo(projectId: string): Promise<void> {// A newer claim since this fetch started means it was superseded (an invalidate, or this// very fetch having already been abandoned by a timeout and reissued) — never let a stale// answer land over whatever a fresher fetch already wrote.- if (currentGeneration(projectId) === gen) cache.set(projectId, { info, fetchedAt: Date.now() })+ if (currentGeneration(projectId) !== gen) return+ cache.set(projectId, { info, fetchedAt: Date.now() })+ // Same branch, same guard: the reactive mirror only ever reflects what the cache accepted.+ syncVisuals(projectId, info)}).catch(() => {// Fail open: leave whatever is cached (possibly nothing) alone.@@ -111,6 +170,7 @@ export function ensureProjectLaunchInfo(projectId: string): Promise<void> {* Called on `onTrustChanged` for the affected project, and after a settings-panel save. */export function invalidateProjectLaunchInfo(projectId: string): void {cache.delete(projectId)+ clearVisuals(projectId)generation.set(projectId, currentGeneration(projectId) + 1)inFlight.delete(projectId)}@@ -120,4 +180,5 @@ export function resetProjectLaunchInfoForTests(): void {cache.clear()inFlight.clear()generation.clear()+ useProjectVisuals.setState({ byProject: {} })}diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.tsindex b46117d1f..a8fb34a2d 100644--- a/src/renderer/terminal/terminal-config.test.ts+++ b/src/renderer/terminal/terminal-config.test.ts@@ -24,6 +24,7 @@ import {toXtermText,xtermScrollback,applyLiveOptions,+ mergeProjectVisuals,terminalLetterSpacing,terminalLineHeight,xtermOptionsFromSettings,@@ -908,3 +909,63 @@ describe('applyLiveOptions', () => {expect(term.options.theme).toBe(resolveTerminalTheme('nord').theme)})})++describe('mergeProjectVisuals (a project\'s own theme / font over the global settings)', () => {+ it('returns the base BY IDENTITY when the project overrides nothing', () => {+ const base = visual()+ expect(mergeProjectVisuals(base, undefined)).toBe(base)+ expect(mergeProjectVisuals(base, {})).toBe(base)+ })++ it('lets a project theme win over the global one', () => {+ const merged = mergeProjectVisuals(visual({ terminalTheme: 'nord' }), { theme: 'dracula' })+ expect(merged.terminalTheme).toBe('dracula')+ expect(xtermOptionsFromSettings(merged).theme).toBe(resolveTerminalTheme('dracula').theme)+ })++ it('lets a project font family win over the global one', () => {+ const merged = mergeProjectVisuals(visual({ fontFamily: 'Menlo' }), { fontFamily: 'Iosevka' })+ expect(merged.fontFamily).toBe('Iosevka')+ expect(xtermOptionsFromSettings(merged).fontFamily).toBe('Iosevka')+ })++ // The whole reason `isKnownTerminalThemeId` exists: `resolveTerminalTheme` is total, so passing an+ // unknown override straight through would repaint the project's terminals with the APP DEFAULT+ // rather than leaving the user's own global choice alone.+ it('falls back to the GLOBAL theme for an unknown id, not to the app default', () => {+ const merged = mergeProjectVisuals(visual({ terminalTheme: 'nord' }), { theme: 'bogus' })+ expect(merged.terminalTheme).toBe('nord')+ expect(xtermOptionsFromSettings(merged).theme).toBe(resolveTerminalTheme('nord').theme)+ expect(xtermOptionsFromSettings(merged).theme).not.toBe(+ resolveTerminalTheme('nodeterm-dark').theme+ )+ })++ it('ignores a blank font family rather than handing xterm an empty string', () => {+ const base = visual({ fontFamily: 'Menlo' })+ expect(mergeProjectVisuals(base, { fontFamily: '' })).toBe(base)+ expect(mergeProjectVisuals(base, { fontFamily: ' ' })).toBe(base)+ })++ it('overrides one value without disturbing the other twelve', () => {+ const base = visual({ fontSize: 15, cursorStyle: 'bar' })+ const merged = mergeProjectVisuals(base, { theme: 'nord' })+ expect(merged).toEqual({ ...base, terminalTheme: 'nord' })+ })++ // Live application rides the EXISTING machinery: nothing new re-fits, and a project font is a+ // cell-geometry change exactly like a global one (see the co-attach caveat on mergeProjectVisuals).+ it('feeds applyLiveOptions the same way a global change does', () => {+ const base = visual()+ const backing = xtermOptionsFromSettings(base) as unknown as Record<string, unknown>+ const term = { options: backing } as LiveOptionTarget+ expect(applyLiveOptions(term, mergeProjectVisuals(base, { theme: 'nord' }))).toEqual({+ metricsChanged: false,+ themeChanged: true+ })+ expect(applyLiveOptions(term, mergeProjectVisuals(base, { fontFamily: 'Iosevka' }))).toEqual({+ metricsChanged: true,+ themeChanged: true // back off `nord` — the project no longer sets a theme in this call+ })+ })+})diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.tsindex 7fb232edf..39ac9b5ec 100644--- a/src/renderer/terminal/terminal-config.ts+++ b/src/renderer/terminal/terminal-config.ts@@ -6,7 +6,7 @@ import type {TerminalCursorInactiveStyle,TerminalCursorStyle} from '@shared/types'-import { resolveTerminalTheme } from './themes'+import { isKnownTerminalThemeId, resolveTerminalTheme } from './themes'/*** Pure decisions behind the xterm instance in `TerminalNode` — extracted so they can be tested@@ -251,6 +251,58 @@ export const XTERM_VISUAL_KEYS = ['tmuxScrollback'] as const satisfies readonly (keyof XtermVisualSettings)[]+/**+ * The two appearance values a PROJECT may set for its own terminals (`terminal.theme` /+ * `terminal.fontFamily` in `.nodeterm/settings.json`, local-over-shared already applied).+ *+ * Deliberately UNGATED by the project trust store, unlike the same family's `shell`: neither value+ * can execute anything — the worst a hostile shared document achieves is an ugly terminal, which is+ * visible and one edit away from being undone. Gating them would put a consent dialog in front of a+ * colour.+ */+export interface ProjectVisualOverrides {+ theme?: string+ fontFamily?: string+}++/**+ * Layer a project's appearance overrides on top of this machine's global appearance settings.+ *+ * Returns `base` BY IDENTITY when nothing is overridden — the result is a `useMemo`/effect+ * dependency in `useXtermVisualSettings`, and a fresh object per render would re-run the live+ * re-option pass on every terminal for nothing.+ *+ * Two rules, both about failing back to the GLOBAL value rather than to the app default:+ * - an unknown theme id is ignored (see `isKnownTerminalThemeId`),+ * - an empty/blank `fontFamily` is ignored — handing xterm `''` yields the browser default font,+ * which is not what "this project sets no font" means.+ *+ * CO-ATTACH CAVEAT (the reason this merge is worth a comment at all): `fontFamily` is CELL GEOMETRY,+ * so a project-scoped font makes `applyLiveOptions` report `metricsChanged` and the caller re-fit —+ * and under co-attach (one pty, N subscribers) the pty runs at the SMALLEST subscriber's grid. A+ * project font therefore re-reports THIS viewer's grid to a pty that other viewers may share (a+ * modal card over the same session, another device attached to it), exactly as a global font change+ * already does. That is the existing machinery working as designed, not a new hazard — but it does+ * mean a per-project font is not visually private to that project's window. Nothing extra is done+ * here: the re-fit is precisely what keeps the pty from being clamped to a stale grid.+ */+export function mergeProjectVisuals(+ base: XtermVisualSettings,+ overrides: ProjectVisualOverrides | undefined+): XtermVisualSettings {+ const theme = isKnownTerminalThemeId(overrides?.theme) ? overrides!.theme! : undefined+ const fontFamily =+ typeof overrides?.fontFamily === 'string' && overrides.fontFamily.trim() !== ''+ ? overrides.fontFamily+ : undefined+ if (theme === undefined && fontFamily === undefined) return base+ return {+ ...base,+ ...(theme !== undefined ? { terminalTheme: theme } : {}),+ ...(fontFamily !== undefined ? { fontFamily } : {})+ }+}+/** The appearance-derived options, resolved and clamped. */export interface XtermVisualOptions {fontFamily: stringdiff --git a/src/renderer/terminal/themes.ts b/src/renderer/terminal/themes.tsindex 41e8ae671..b0dd8b132 100644--- a/src/renderer/terminal/themes.ts+++ b/src/renderer/terminal/themes.ts@@ -355,3 +355,17 @@ const BY_ID = new Map(TERMINAL_THEMES.map((t) => [t.id, t]))export function resolveTerminalTheme(id: string | undefined): TerminalTheme {return (id ? BY_ID.get(id) : undefined) ?? BY_ID.get(DEFAULT_TERMINAL_THEME_ID)!}++/**+ * Whether an id names a theme this build actually ships.+ *+ * `resolveTerminalTheme` is total, which is exactly right for the GLOBAL setting (there is nothing+ * behind it to fall back to) and exactly wrong for a per-project OVERRIDE: a project naming a theme+ * this build does not have must fall back to whatever the user's own global setting says, not to the+ * app default — silently repainting someone's terminals to `nodeterm-dark` because a teammate's+ * `.nodeterm/settings.json` mentions a theme from a newer version is a worse answer than ignoring+ * the override. So an override asks this FIRST and only then resolves.+ */+export function isKnownTerminalThemeId(id: string | undefined): boolean {+ return id !== undefined && BY_ID.has(id)+}diff --git a/src/renderer/terminal/useXtermVisualSettings.test.tsx b/src/renderer/terminal/useXtermVisualSettings.test.tsxnew file mode 100644index 000000000..455c35a0b--- /dev/null+++ b/src/renderer/terminal/useXtermVisualSettings.test.tsx@@ -0,0 +1,252 @@+// @vitest-environment jsdom+//+// Project-scoped terminal appearance, end to end through the hook: a project's `terminal.theme` /+// `terminal.fontFamily` reaching the terminals of THAT project (and no other), live.+//+// The pure merge is covered in terminal-config.test.ts. What is proved here is the seam the merge+// hangs off — the reactive mirror of the launch-info cache (`useProjectVisuals`) — and the two+// properties that make it safe to put in front of a canvas full of live terminals:+// - a project's terminals re-render when ITS values change, and other projects' do not,+// - nothing re-renders when an UNRELATED part of the launch-info answer moves (a launch command, a+// trust verdict), which is why the mirror carries the appearance slice alone.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { ProjectLaunchInfo, ResolvedProjectSettings } from '@shared/project-settings'+import {+ ensureProjectLaunchInfo,+ invalidateProjectLaunchInfo,+ resetProjectLaunchInfoForTests+} from '../state/projectLaunchInfo'+import { useSettings } from '../state/settings'+import { useXtermVisualSettings } from './useXtermVisualSettings'+import { xtermOptionsFromSettings } from './terminal-config'+import { resolveTerminalTheme } from './themes'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const info = (+ terminal: ResolvedProjectSettings['terminal'],+ agents: ResolvedProjectSettings['agents'] = {}+): ProjectLaunchInfo => ({+ resolved: { setup: {}, worktree: {}, agents, terminal },+ trusted: { agents: true, shell: true }+})++/** Stand in for the preload/bridge `projectSettings.launchInfo()` call — answers per project id. */+function mockLaunchInfo(byProject: Record<string, ProjectLaunchInfo | null>): void {+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ projectSettings: {+ launchInfo: vi.fn((projectId: string) => Promise.resolve(byProject[projectId] ?? null))+ }+ }+}++interface Probe {+ /** What the hook last answered. */+ theme: () => string+ font: () => string+ /** How many times the component rendered — the re-render assertions live on this. */+ renders: () => number+ unmount: () => void+}++/** Mount one component that consumes the hook for `projectId`, recording every render. */+function probe(projectId?: string): Probe {+ let renders = 0+ let last = { terminalTheme: '', fontFamily: '' }+ function Probed(): null {+ renders += 1+ const v = useXtermVisualSettings(projectId)+ last = { terminalTheme: v.terminalTheme, fontFamily: v.fontFamily }+ return null+ }+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root: Root = createRoot(host)+ act(() => root.render(<Probed />))+ return {+ theme: () => last.terminalTheme,+ font: () => last.fontFamily,+ renders: () => renders,+ unmount: () => {+ act(() => root.unmount())+ host.remove()+ }+ }+}++const GLOBAL = { terminalTheme: 'nord', fontFamily: 'Menlo' }+let mounted: Probe[] = []++beforeEach(() => {+ resetProjectLaunchInfoForTests()+ useSettings.setState((s) => ({ settings: { ...s.settings, ...GLOBAL } }))+})++afterEach(() => {+ for (const p of mounted) p.unmount()+ mounted = []+})++const mount = (projectId?: string): Probe => {+ const p = probe(projectId)+ mounted.push(p)+ return p+}++describe('useXtermVisualSettings — project-scoped appearance', () => {+ it('starts on the global settings and picks the project up when its info lands', async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'dracula', source: 'shared' } }) })+ const p = mount('p1')+ expect(p.theme()).toBe('nord') // nothing fetched yet — the global setting, not a blank+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ // The whole point of doing this live: the terminal that is ALREADY on screen repaints — the+ // hook re-rendered its consumer with the project's theme, which is what feeds applyLiveOptions.+ expect(p.theme()).toBe('dracula')+ expect(xtermOptionsFromSettings({ ...useSettings.getState().settings, terminalTheme: p.theme() })+ .theme).toBe(resolveTerminalTheme('dracula').theme)+ })++ it("leaves another project's terminals on the global theme", async () => {+ mockLaunchInfo({+ p1: info({ theme: { value: 'dracula', source: 'shared' } }),+ p2: info({})+ })+ const one = mount('p1')+ const two = mount('p2')+ await act(async () => {+ await Promise.all([ensureProjectLaunchInfo('p1'), ensureProjectLaunchInfo('p2')])+ })+ expect(one.theme()).toBe('dracula')+ expect(two.theme()).toBe('nord')+ })++ it('takes a LOCAL override the same as a shared one — appearance is not gated', async () => {+ mockLaunchInfo({+ p1: {+ ...info({ theme: { value: 'tokyo-night', source: 'local' } }),+ // Untrusted shared content: irrelevant here. `shell` is the gated field in this family;+ // a colour cannot execute anything.+ trusted: { agents: false, shell: false }+ }+ })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('tokyo-night')+ })++ it('falls back to the GLOBAL theme for an id this build does not know', async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'from-a-newer-version', source: 'shared' } }) })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('nord')+ expect(resolveTerminalTheme(p.theme()).id).toBe('nord')+ })++ it('overrides the font family, and only for that project', async () => {+ mockLaunchInfo({+ p1: info({ fontFamily: { value: 'Iosevka', source: 'shared' } }),+ p2: info({})+ })+ const one = mount('p1')+ const two = mount('p2')+ await act(async () => {+ await Promise.all([ensureProjectLaunchInfo('p1'), ensureProjectLaunchInfo('p2')])+ })+ expect(one.font()).toBe('Iosevka')+ expect(one.theme()).toBe('nord') // untouched by a font-only override+ expect(two.font()).toBe('Menlo')+ })++ it('gives a project-less terminal (the settings preview) the global settings', async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'dracula', source: 'shared' } }) })+ const p = mount(undefined)+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('nord')+ expect(p.font()).toBe('Menlo')+ })++ it('re-renders on nothing but the appearance slice of a launch-info answer', async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'dracula', source: 'shared' } }) })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ const afterTheme = p.renders()+ // A second answer that changes only the launch command and the trust verdict — a terminal has+ // no business repainting for either.+ mockLaunchInfo({+ p1: {+ ...info(+ { theme: { value: 'dracula', source: 'shared' } },+ { launchCmd: { value: 'nix develop -c claude', source: 'shared' } }+ ),+ trusted: { agents: false, shell: false }+ }+ })+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('dracula')+ // NOT ONE extra render: the mirror mirrors the appearance slice alone, and re-answering the+ // same two values must not touch the entry a canvas full of terminals is subscribed to.+ expect(p.renders()).toBe(afterTheme)+ })++ // The accepted cost of keeping the mirror in lockstep with the cache (see its doc comment): the+ // panel's save path invalidates and immediately re-warms, so the project's terminals show this+ // machine's global appearance for the length of one round trip. Asserted rather than left to be+ // discovered — it is the visible half of the design decision.+ it('falls back to global between an invalidate and the answer that follows it', async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'dracula', source: 'shared' } }) })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('dracula')+ act(() => invalidateProjectLaunchInfo('p1'))+ expect(p.theme()).toBe('nord')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ expect(p.theme()).toBe('dracula')+ })++ it('keeps following the global setting for a project that overrides nothing', async () => {+ mockLaunchInfo({ p1: info({}) })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ act(() => {+ // `setState`, not `update()`: the store's real setter also schedules a disk save through a+ // preload this test does not stand up. What is under test is the SUBSCRIPTION.+ useSettings.setState((s) => ({ settings: { ...s.settings, terminalTheme: 'gruvbox-dark' } }))+ })+ expect(p.theme()).toBe('gruvbox-dark')+ })++ it("lets the project's theme survive an unrelated global appearance edit", async () => {+ mockLaunchInfo({ p1: info({ theme: { value: 'dracula', source: 'shared' } }) })+ const p = mount('p1')+ await act(async () => {+ await ensureProjectLaunchInfo('p1')+ })+ act(() => {+ useSettings.setState((s) => ({+ settings: { ...s.settings, terminalTheme: 'one-dark', fontFamily: 'Fira Code' }+ }))+ })+ expect(p.theme()).toBe('dracula') // the project still wins+ expect(p.font()).toBe('Fira Code') // …and the un-overridden half follows the global edit+ })+})diff --git a/src/renderer/terminal/useXtermVisualSettings.ts b/src/renderer/terminal/useXtermVisualSettings.tsindex 98d9445df..834fb34a8 100644--- a/src/renderer/terminal/useXtermVisualSettings.ts+++ b/src/renderer/terminal/useXtermVisualSettings.ts@@ -1,9 +1,11 @@+import { useMemo } from 'react'import { useShallow } from 'zustand/react/shallow'import { useSettings } from '../state/settings'-import { XTERM_VISUAL_KEYS, type XtermVisualSettings } from './terminal-config'+import { useProjectVisuals } from '../state/projectLaunchInfo'+import { mergeProjectVisuals, XTERM_VISUAL_KEYS, type XtermVisualSettings } from './terminal-config'/**- * The appearance slice of Settings, as ONE subscription.+ * The appearance slice of Settings for ONE project's terminals, as two subscriptions.** 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@@ -15,13 +17,39 @@ import { XTERM_VISUAL_KEYS, type XtermVisualSettings } from './terminal-config'* 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.+ *+ * `projectId` layers that project's own `terminal.theme` / `terminal.fontFamily` over the global+ * pick (see `mergeProjectVisuals`). Omit it for a terminal that belongs to no project — the+ * settings-panel PREVIEW is the one such surface, and it must keep showing the GLOBAL settings+ * being edited rather than whichever project happens to be active behind the panel.+ *+ * The project half subscribes to `useProjectVisuals`, NOT to the launch-info cache as a whole: that+ * cache also carries launch commands, env and trust verdicts, and a terminal has no business+ * re-rendering when one of those moves. Shallow again, and over the two values only.+ *+ * SPEC DEVIATION, deliberate (Task 5): the spec said a project's appearance applies "when a terminal+ * is created", with existing terminals keeping theirs. There is no per-node appearance in this app —+ * every terminal renders from the live settings and re-options itself through `applyLiveOptions` —+ * so the honest implementation is live and project-scoped: changing a project's theme repaints that+ * project's terminals, including ones already open, and leaves every other project's alone.*/-export function useXtermVisualSettings(): XtermVisualSettings {- return useSettings(+export function useXtermVisualSettings(projectId?: string): XtermVisualSettings {+ const base = 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}))+ const overrides = useProjectVisuals(+ useShallow((s) => {+ const v = projectId ? s.byProject[projectId] : undefined+ // Normalised (never the stored object, never `undefined`) so the shallow comparison has a+ // stable shape to compare in every case — including a project whose entry is dropped.+ return { theme: v?.theme, fontFamily: v?.fontFamily }+ })+ )+ // Identity-stable while neither half changed: this value is the dependency the terminal+ // components' live re-option effects hang off.+ return useMemo(() => mergeProjectVisuals(base, overrides), [base, overrides])}