From 86f404ef53c1d3f9299668ce0c400d92cc1a5654 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 6 Jul 2026 19:08:42 -0700 Subject: [PATCH 1/3] perf(native-chat): byte-cap the transcript read-cache to bound RSS (GB-scale leak) (#7625) --- .../native-chat/transcript-read-cache.test.ts | 76 ++++++++++++++++++- src/main/native-chat/transcript-read-cache.ts | 42 ++++++++-- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/src/main/native-chat/transcript-read-cache.test.ts b/src/main/native-chat/transcript-read-cache.test.ts index df5b310fc..6f0fc39ac 100644 --- a/src/main/native-chat/transcript-read-cache.test.ts +++ b/src/main/native-chat/transcript-read-cache.test.ts @@ -20,7 +20,8 @@ vi.mock('./transcript-reader', async (importOriginal) => { import { isTextBlock } from '../../shared/native-chat-types' import { clearNativeChatTranscriptCache, - readNativeChatTranscriptCached + readNativeChatTranscriptCached, + setNativeChatTranscriptCacheMaxBytesForTests } from './transcript-read-cache' let tempRoots: string[] = [] @@ -46,8 +47,26 @@ async function seedSession(sessionId: string, turns: number): Promise { return filePath } +// Writes a transcript file at an explicit path whose on-disk size is ~`bytes` +// (padded via one big user message), returning the path. Read it back by passing +// the path as `transcriptPath` so resolution doesn't depend on process.env.HOME. +async function seedBigFile(name: string, bytes: number): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-cache-bytes-')) + tempRoots.push(root) + const filePath = join(root, `${name}.jsonl`) + const record = { + type: 'user', + uuid: `u-${name}`, + timestamp: '2026-06-01T10:00:00.000Z', + message: { role: 'user', content: 'x'.repeat(Math.max(1, bytes)) } + } + await writeFile(filePath, jsonLines([record])) + return filePath +} + beforeEach(() => { clearNativeChatTranscriptCache() + setNativeChatTranscriptCacheMaxBytesForTests() readSpy.mockClear() }) @@ -148,4 +167,59 @@ describe('readNativeChatTranscriptCached', () => { // Distinct files must not share a cached parse object. expect(c).not.toBe(a) }) + + // Why: each cached entry is a FULL unwindowed transcript parse; heavy agent + // sessions are tens of MB, so the count-only cap let 50 entries retain multiple + // GB in the one process serving desktop + every paired client. The byte budget + // evicts the oldest large entries while always keeping the most-recent. + it('evicts the oldest entry once total cached bytes exceed the budget', async () => { + // ~4 KB per file, budget 9 KB → holds 2, a third read evicts the oldest. + setNativeChatTranscriptCacheMaxBytesForTests(9 * 1024) + const fileA = await seedBigFile('big-a', 4 * 1024) + const fileB = await seedBigFile('big-b', 4 * 1024) + const fileC = await seedBigFile('big-c', 4 * 1024) + + await readNativeChatTranscriptCached('claude', 'sa', fileA) // spy 1 + await readNativeChatTranscriptCached('claude', 'sb', fileB) // spy 2 + await readNativeChatTranscriptCached('claude', 'sc', fileC) // spy 3, evicts A + expect(readSpy).toHaveBeenCalledTimes(3) + + // C is the most-recent → still cached (no re-read). + await readNativeChatTranscriptCached('claude', 'sc', fileC) + expect(readSpy).toHaveBeenCalledTimes(3) + + // A was evicted by the byte cap → this re-reads (and evicts B in turn). + await readNativeChatTranscriptCached('claude', 'sa', fileA) + expect(readSpy).toHaveBeenCalledTimes(4) + + // B is now evicted → also re-reads. + await readNativeChatTranscriptCached('claude', 'sb', fileB) + expect(readSpy).toHaveBeenCalledTimes(5) + }) + + it('keeps a single active transcript larger than the whole budget cached', async () => { + // A lone entry over budget must NOT be dropped, else every read re-parses. + setNativeChatTranscriptCacheMaxBytesForTests(1024) + const big = await seedBigFile('huge', 8 * 1024) + await readNativeChatTranscriptCached('claude', 'huge', big) + await readNativeChatTranscriptCached('claude', 'huge', big) + expect(readSpy).toHaveBeenCalledTimes(1) + }) + + it('does not evict small entries under the default budget (no regression for typical use)', async () => { + const files = await Promise.all([ + seedBigFile('s1', 512), + seedBigFile('s2', 512), + seedBigFile('s3', 512) + ]) + for (const [i, file] of files.entries()) { + await readNativeChatTranscriptCached('claude', `sess-${i}`, file) + } + expect(readSpy).toHaveBeenCalledTimes(3) + // Re-read all three: every one is still cached (byte budget never triggered). + for (const [i, file] of files.entries()) { + await readNativeChatTranscriptCached('claude', `sess-${i}`, file) + } + expect(readSpy).toHaveBeenCalledTimes(3) + }) }) diff --git a/src/main/native-chat/transcript-read-cache.ts b/src/main/native-chat/transcript-read-cache.ts index b62a1a114..9f4df5bde 100644 --- a/src/main/native-chat/transcript-read-cache.ts +++ b/src/main/native-chat/transcript-read-cache.ts @@ -21,6 +21,9 @@ type CachedTranscript = { result: ReadTranscriptResult /** mtime of the resolved file when cached; a newer mtime invalidates it. */ mtimeMs: number + /** On-disk byte size of the resolved file — a cheap, monotonic proxy for this + * entry's parsed memory footprint, used to bound the cache by total bytes. */ + bytes: number } const cache = new Map() @@ -28,19 +31,36 @@ const cache = new Map() // Why: cap the cache so a long-lived process browsing many sessions can't grow // it unbounded. Map preserves insertion order, so evicting the first key drops // the oldest entry (a simple LRU once re-inserts bump recency; see setCached). -// Entry-count cap is fine for v1; a byte-aware cap is the follow-up if profiling -// shows RSS pressure now that one process serves many remote clients. const MAX_CACHE_ENTRIES = 50 +// Why: a heavy Claude/Codex coding session's JSONL is routinely tens of MB (tool +// results embed whole file contents, command output, and diffs), and each cached +// entry is the full unwindowed parse. The count cap alone let 50 such entries +// retain multiple GB in the one process that now serves desktop + every paired +// web/mobile client. Bound total cached file bytes too; we always keep the most- +// recent entry (see setCached) so an active transcript is never re-parsed on +// every read, which caps the regression to extra re-parses only past this budget. +const MAX_CACHE_BYTES = 128 * 1024 * 1024 +// Overridable only from tests so the byte-eviction path can be exercised without +// writing hundreds of MB of fixtures; production always uses MAX_CACHE_BYTES. +let maxCacheBytes = MAX_CACHE_BYTES function setCached(key: string, value: CachedTranscript): void { // Re-insert moves the key to the most-recent position for LRU eviction. cache.delete(key) cache.set(key, value) - while (cache.size > MAX_CACHE_ENTRIES) { + let totalBytes = 0 + for (const entry of cache.values()) { + totalBytes += entry.bytes + } + // Evict oldest until within BOTH caps, but never drop the most-recent entry + // (cache.size > 1): a single active transcript larger than the whole budget + // must stay cached or every read would re-parse the full file. + while (cache.size > 1 && (cache.size > MAX_CACHE_ENTRIES || totalBytes > maxCacheBytes)) { const oldest = cache.keys().next().value if (oldest === undefined) { break } + totalBytes -= cache.get(oldest)?.bytes ?? 0 cache.delete(oldest) } } @@ -49,11 +69,12 @@ function cacheKey(agent: AgentType, filePath: string): string { return `${agent}:${filePath}` } -async function fileMtimeMs(filePath: string): Promise { +async function fileStat(filePath: string): Promise<{ mtimeMs: number; bytes: number }> { try { - return (await stat(filePath)).mtimeMs + const stats = await stat(filePath) + return { mtimeMs: stats.mtimeMs, bytes: stats.size } } catch { - return Number.NaN + return { mtimeMs: Number.NaN, bytes: 0 } } } @@ -74,7 +95,7 @@ export async function readNativeChatTranscriptCached( } const key = cacheKey(agent, filePath) - const mtimeMs = await fileMtimeMs(filePath) + const { mtimeMs, bytes } = await fileStat(filePath) const cached = cache.get(key) if (cached && Number.isFinite(mtimeMs) && cached.mtimeMs === mtimeMs) { // Bump recency so a frequently-read session survives eviction. @@ -84,7 +105,7 @@ export async function readNativeChatTranscriptCached( const result = await readNativeChatTranscript(agent, sessionId, { filePath }) if (Number.isFinite(mtimeMs)) { - setCached(key, { result, mtimeMs }) + setCached(key, { result, mtimeMs, bytes }) } return result } @@ -93,3 +114,8 @@ export async function readNativeChatTranscriptCached( export function clearNativeChatTranscriptCache(): void { cache.clear() } + +/** Test-only: override the byte budget (pass no arg to restore the default). */ +export function setNativeChatTranscriptCacheMaxBytesForTests(bytes?: number): void { + maxCacheBytes = bytes ?? MAX_CACHE_BYTES +} From a6cbd3102a6fd589b74e0b7b809f154c1197c143 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 6 Jul 2026 20:17:35 -0700 Subject: [PATCH 2/3] fix(terminal): repaint revealed panes stuck behind xterm's paused-render gate (#7614) Co-authored-by: Orca --- .../lib/pane-manager/pane-webgl-renderer.ts | 14 +- .../terminal-render-pause-release.test.ts | 87 ++++++ .../terminal-render-pause-release.ts | 73 +++++ ...erminal-reveal-paused-render-repro.spec.ts | 268 ++++++++++++++++++ 4 files changed, 439 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts create mode 100644 tests/e2e/terminal-reveal-paused-render-repro.spec.ts diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts index d7c80e762..e0ca80580 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts @@ -1,5 +1,6 @@ import { WebglAddon } from '@xterm/addon-webgl' import type { ManagedPaneInternal } from './pane-manager-types' +import { forceRepaintThroughRenderPause } from './terminal-render-pause-release' import { getTerminalWebglAutoDecision, resetTerminalWebglAutoDecision @@ -126,9 +127,16 @@ export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { // context-loss event. Clearing the atlas preserves GPU rendering and forces // a fresh paint when the pane becomes visible/focused again. pane.webglAddon?.clearTextureAtlas() - // Why: refresh even without a WebGL addon so recovery never silently - // no-ops — a DOM-rendered pane can hold stale pixels after reveal too. - pane.terminal.refresh(0, pane.terminal.rows - 1) + // Why: on reveal xterm's IntersectionObserver can still report the pane as + // not intersecting, so a plain refresh() is swallowed by RenderService's + // paused-render gate and the cleared model never repaints (stale bottom rows + // until a drag-select forces a redraw). Force the paused render through + // first; only fall back to refresh() when the terminal was not gated. + if (!forceRepaintThroughRenderPause(pane.terminal)) { + // Why: refresh even without a WebGL addon so recovery never silently + // no-ops — a DOM-rendered pane can hold stale pixels after reveal too. + pane.terminal.refresh(0, pane.terminal.rows - 1) + } } catch { /* ignore — pane may have been disposed in the meantime */ } diff --git a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts new file mode 100644 index 000000000..e3d846774 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it, vi } from 'vitest' +import { forceRepaintThroughRenderPause } from './terminal-render-pause-release' + +type FakeRenderService = { + _isPaused?: boolean + _needsFullRefresh?: boolean + refreshRows?: ReturnType +} + +function createTerminal(options: { + rows?: number + renderService?: FakeRenderService | null + withoutCore?: boolean +}): unknown { + const { rows = 24, renderService, withoutCore } = options + if (withoutCore) { + return { rows } + } + return { + rows, + _core: { _renderService: renderService ?? null } + } +} + +describe('forceRepaintThroughRenderPause', () => { + it('drives a synchronous full-viewport render and clears the pause latches when paused', () => { + const refreshRows = vi.fn() + const renderService: FakeRenderService = { + _isPaused: true, + _needsFullRefresh: true, + refreshRows + } + const terminal = createTerminal({ rows: 30, renderService }) + + expect(forceRepaintThroughRenderPause(terminal)).toBe(true) + expect(refreshRows).toHaveBeenCalledWith(0, 29, true) + expect(renderService._isPaused).toBe(false) + expect(renderService._needsFullRefresh).toBe(false) + }) + + it('leaves the terminal untouched and returns false when not paused', () => { + const refreshRows = vi.fn() + const renderService: FakeRenderService = { + _isPaused: false, + _needsFullRefresh: false, + refreshRows + } + const terminal = createTerminal({ renderService }) + + expect(forceRepaintThroughRenderPause(terminal)).toBe(false) + expect(refreshRows).not.toHaveBeenCalled() + }) + + it('returns false when the render service internals are unavailable', () => { + expect(forceRepaintThroughRenderPause(createTerminal({ withoutCore: true }))).toBe(false) + expect(forceRepaintThroughRenderPause(createTerminal({ renderService: null }))).toBe(false) + expect(forceRepaintThroughRenderPause(createTerminal({ renderService: {} }))).toBe(false) + expect(forceRepaintThroughRenderPause(null)).toBe(false) + }) + + it('returns false without rendering when the row count is invalid', () => { + const refreshRows = vi.fn() + const terminal = createTerminal({ + rows: 0, + renderService: { _isPaused: true, refreshRows } + }) + + expect(forceRepaintThroughRenderPause(terminal)).toBe(false) + expect(refreshRows).not.toHaveBeenCalled() + }) + + it('returns false when the forced render throws (disposed mid-frame)', () => { + const renderService: FakeRenderService = { + _isPaused: true, + _needsFullRefresh: true, + refreshRows: vi.fn(() => { + throw new Error('terminal disposed') + }) + } + const terminal = createTerminal({ renderService }) + + expect(forceRepaintThroughRenderPause(terminal)).toBe(false) + // Latch is still cleared — the observer reasserts authority on its next + // callback, and we must not leave a half-serviced full-refresh queued. + expect(renderService._isPaused).toBe(false) + }) +}) diff --git a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts new file mode 100644 index 000000000..88b53129d --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts @@ -0,0 +1,73 @@ +/** + * Forces a full synchronous repaint through xterm's RenderService even when its + * IntersectionObserver still reports the screen element as not intersecting. + * + * Why: on tab/worktree reveal the pane is DOM-visible but xterm's own + * observer callback can lag a frame (worse under load), leaving + * `RenderService._isPaused === true`. While paused, `refreshRows` early-returns + * and only latches `_needsFullRefresh`, so the reveal-repaint's + * `terminal.refresh()` is swallowed — the freshly-cleared render model never + * repaints and the canvas keeps compositing stale rows (classic "bottom rows + * missing until you drag-select" symptom). We can't wait for the observer, so + * we clear the latch and drive one synchronous full render ourselves; the + * observer reasserts authority naturally on its next callback. + * + * All access is behind typeof guards: an xterm upgrade that renames these + * internals degrades to a no-op (callers keep their existing refresh path), it + * never throws into a render frame. + */ + +type MaybePausableRenderService = { + _isPaused?: boolean + _needsFullRefresh?: boolean + refreshRows?: (start: number, end: number, sync?: boolean) => void +} + +type PausableRenderService = MaybePausableRenderService & { + refreshRows: (start: number, end: number, sync?: boolean) => void +} + +type TerminalWithRenderService = { + rows?: number + _core?: { + _renderService?: MaybePausableRenderService + } +} + +function getRenderService(terminal: unknown): PausableRenderService | null { + const service = (terminal as TerminalWithRenderService | null)?._core?._renderService + return service && typeof service.refreshRows === 'function' + ? (service as PausableRenderService) + : null +} + +/** + * If xterm's renderer is paused (observer hasn't caught up to the reveal), + * clear the pause latch and force a synchronous full-viewport repaint. + * Returns true when it drove the render, false when it left the terminal + * untouched (not paused, or internals unavailable) so the caller can fall back + * to its normal `terminal.refresh()`. + */ +export function forceRepaintThroughRenderPause(terminal: unknown): boolean { + const service = getRenderService(terminal) + if (!service || service._isPaused !== true) { + return false + } + + const rows = (terminal as TerminalWithRenderService).rows + if (typeof rows !== 'number' || rows < 1) { + return false + } + + // Why: leave the latch as if the pending full refresh was serviced — we are + // about to service it — so the observer's next callback doesn't queue a + // redundant second full repaint. + service._isPaused = false + service._needsFullRefresh = false + try { + service.refreshRows(0, rows - 1, true) + return true + } catch { + return false + } +} diff --git a/tests/e2e/terminal-reveal-paused-render-repro.spec.ts b/tests/e2e/terminal-reveal-paused-render-repro.spec.ts new file mode 100644 index 000000000..5b280037d --- /dev/null +++ b/tests/e2e/terminal-reveal-paused-render-repro.spec.ts @@ -0,0 +1,268 @@ +import type { Page } from '@stablyai/playwright-test' +import { test, expect } from './helpers/orca-app' +import { getActiveTabId, waitForSessionReady } from './helpers/store' +import { + execInTerminal, + waitForActivePanePtyId, + waitForActiveTerminalManager, + waitForTerminalOutput +} from './helpers/terminal' +import { captureStableTabScreenshot } from './terminal-tab-screenshot' +import { compareTerminalScreenshots } from './terminal-screenshot-diff' + +/** + * Reproduction for the "missing bottom rows on reveal, recover on drag-select" + * bug (PR #7614). The mechanism is xterm's RenderService gating refreshRows() on + * its IntersectionObserver: while `_isPaused` is true (the observer can lag a + * frame behind a just-revealed pane, worse under load), refresh() early-returns + * and only latches `_needsFullRefresh`. The reveal-repaint's terminal.refresh() + * is then swallowed and the freshly-cleared render model never repaints. + * + * This spec drives the REAL production reveal path (manager.resetWebglTextureAtlases + * -> resetWebglTextureAtlas -> forceRepaintThroughRenderPause) against a real + * xterm Terminal + RenderService. It: + * 1. proves the bug: while paused, a plain refresh() renders nothing; + * 2. proves the fix: the real reveal repaint forces a full-viewport render + * through the paused gate and clears the pause latch; + * 3. confirms recovery at the pixel level. + * + * The paused state is set deterministically rather than raced, because headless + * Electron does not reliably reproduce the observer-lag timing (documented for + * this bug class). The gate we force is the exact one the field bug hits. + */ + +const BOTTOM_MARKER = 'REVEAL_PAUSED_RENDER_BOTTOM_MARKER' + +type RenderProbeResult = { + paused: boolean + renderedRanges: [number, number][] + rows: number +} + +type RevealRenderDebug = { + installProbe: () => boolean + setPaused: (paused: boolean) => boolean + dirtyModelLikeReveal: () => boolean + plainRefresh: () => void + runRealRevealRepaint: () => void + read: () => RenderProbeResult +} + +type RevealProbeWindow = Window & { + __revealRenderProbe?: RevealRenderDebug +} + +/** + * Installs an in-page probe that instruments the active pane's REAL xterm + * RenderService. Everything here runs against production objects; the only + * test-only code is the recording wrapper around `_renderRows` and the manual + * flip of `_isPaused` that stands in for the observer-lag race. + */ +async function installRevealRenderProbe(page: Page, tabId: string): Promise { + await page.evaluate((tabId) => { + const manager = window.__paneManagers?.get(tabId) + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null + if (!manager || !pane) { + throw new Error('No active pane for reveal render probe') + } + + type PausableRenderService = { + _isPaused?: boolean + _needsFullRefresh?: boolean + _renderRows?: (start: number, end: number) => void + __revealProbeRanges?: [number, number][] + __revealProbeInstalled?: boolean + } + type TerminalInternals = { + rows?: number + _core?: { _renderService?: PausableRenderService } + buffer?: { active?: { getLine?: (y: number) => unknown } } + refresh?: (start: number, end: number) => void + } + + const terminal = pane.terminal as unknown as TerminalInternals + const service = terminal._core?._renderService + if (!service || typeof service._renderRows !== 'function') { + throw new Error('Real RenderService._renderRows unavailable — cannot probe') + } + + const debug: RevealRenderDebug = { + installProbe: () => { + if (service.__revealProbeInstalled) { + service.__revealProbeRanges = [] + return true + } + service.__revealProbeRanges = [] + const original = service._renderRows!.bind(service) + service._renderRows = (start: number, end: number): void => { + service.__revealProbeRanges!.push([start, end]) + original(start, end) + } + service.__revealProbeInstalled = true + return true + }, + setPaused: (paused: boolean) => { + service._isPaused = paused + return service._isPaused === paused + }, + dirtyModelLikeReveal: () => { + // Why: reveal clears the WebGL render model so a full rebuild is forced. + // clearTextureAtlas() routes through RenderService and, crucially, also + // requests a redraw — which is exactly what the paused gate then eats. + const withAtlas = pane as unknown as { + webglAddon?: { clearTextureAtlas?: () => void } + } + withAtlas.webglAddon?.clearTextureAtlas?.() + return true + }, + plainRefresh: () => { + const rows = terminal.rows ?? 0 + terminal.refresh?.(0, Math.max(0, rows - 1)) + }, + runRealRevealRepaint: () => { + // The real production reveal path — contains the fix under test. + manager.resetWebglTextureAtlases() + }, + read: () => ({ + paused: service._isPaused === true, + renderedRanges: (service.__revealProbeRanges ?? []).slice(), + rows: terminal.rows ?? 0 + }) + } + + ;(window as RevealProbeWindow).__revealRenderProbe = debug + }, tabId) +} + +async function probeRead(page: Page): Promise { + return page.evaluate(() => { + const probe = (window as RevealProbeWindow).__revealRenderProbe + if (!probe) { + throw new Error('Reveal render probe not installed') + } + return probe.read() + }) +} + +async function probeCall( + page: Page, + method: + | 'installProbe' + | 'setPaused' + | 'dirtyModelLikeReveal' + | 'plainRefresh' + | 'runRealRevealRepaint', + paused?: boolean +): Promise { + await page.evaluate( + ({ method, paused }) => { + const probe = (window as RevealProbeWindow).__revealRenderProbe + if (!probe) { + throw new Error('Reveal render probe not installed') + } + if (method === 'setPaused') { + probe.setPaused(paused ?? false) + return + } + ;(probe[method] as () => void)() + }, + { method, paused } + ) +} + +async function forceWebglOn(page: Page, tabId: string): Promise { + await page.evaluate((id) => { + const state = window.__store?.getState() + if (state?.settings) { + window.__store?.setState({ + settings: { ...state.settings, terminalGpuAcceleration: 'on' } + }) + } + window.__paneManagers?.get(id)?.setTerminalGpuAcceleration?.('on') + }, tabId) +} + +test.describe('terminal reveal paused-render recovery', () => { + test("reveal repaint forces a render through xterm's paused gate", async ({ orcaPage }) => { + // Why: __store / __paneManagers live on the main Orca renderer window + // (orcaPage), not Playwright's default first page. + const page = orcaPage + await waitForSessionReady(page) + await waitForActiveTerminalManager(page) + const tabId = (await getActiveTabId(page))! + const ptyId = await waitForActivePanePtyId(page) + + await forceWebglOn(page, tabId) + + // Fill the viewport down to the bottom so a swallowed repaint is observable + // both in the render ranges and on-screen. + await execInTerminal( + page, + ptyId, + `for i in $(seq 1 40); do echo "line $i ${BOTTOM_MARKER}_$i"; done` + ) + await waitForTerminalOutput(page, `${BOTTOM_MARKER}_40`) + // Clear-screen + reprint so the marker sits on the real bottom rows. + await execInTerminal( + page, + ptyId, + `clear; printf '%s\\n' "$(seq 1 30)"; echo "${BOTTOM_MARKER}_FINAL"` + ) + await waitForTerminalOutput(page, `${BOTTOM_MARKER}_FINAL`) + + const revealed = await captureStableTabScreenshot(page, tabId) + + await installRevealRenderProbe(page, tabId) + await probeCall(page, 'installProbe') + + // ---- Control: prove the bug. This sequence (clearTextureAtlas + refresh) + // is byte-for-byte the PRE-FIX resetWebglTextureAtlas on origin/main, so it + // faithfully replays the old reveal path. While paused, it renders nothing. + await probeCall(page, 'setPaused', true) + await probeCall(page, 'dirtyModelLikeReveal') + await probeCall(page, 'plainRefresh') + // Give any (non-existent) queued render a frame to land. + await page.waitForTimeout(80) + const afterPlainRefresh = await probeRead(page) + + expect(afterPlainRefresh.paused, 'terminal is in the paused-render state').toBe(true) + expect( + afterPlainRefresh.renderedRanges, + 'BUG REPRODUCED: while paused, plain refresh() is swallowed by the gate — no render fires' + ).toHaveLength(0) + + // ---- Fix: the real reveal repaint must force a full render through the gate. + await probeCall(page, 'setPaused', true) + await probeCall(page, 'dirtyModelLikeReveal') + await probeCall(page, 'runRealRevealRepaint') + await page.waitForTimeout(80) + const afterRealReveal = await probeRead(page) + + expect( + afterRealReveal.renderedRanges.length, + 'FIX: reveal repaint drove at least one render despite the paused gate' + ).toBeGreaterThan(0) + + const fullViewportRender = afterRealReveal.renderedRanges.some( + ([start, end]) => start === 0 && end >= afterRealReveal.rows - 1 + ) + expect( + fullViewportRender, + 'FIX: reveal repaint rendered the FULL viewport (0..rows-1), not a partial range' + ).toBe(true) + + expect( + afterRealReveal.paused, + 'FIX: pause latch is cleared so the observer can reassert authority cleanly' + ).toBe(false) + + // ---- Pixel-level confirmation: the surface still shows the correct content + // after being driven through the paused gate (no stale/blank bottom rows). + const afterFix = await captureStableTabScreenshot(page, tabId) + const diff = compareTerminalScreenshots(revealed, afterFix) + expect( + diff.matches, + `recovered surface matches the revealed content (diffRatio=${diff.diffRatio})` + ).toBe(true) + }) +}) From 98d850aebae9f9e87ab20add8fd9cb53f33101a0 Mon Sep 17 00:00:00 2001 From: gatsby74 <166927047+gatsby74@users.noreply.github.com> Date: Tue, 7 Jul 2026 05:21:58 +0200 Subject: [PATCH 3/3] fix(settings): keep full installed font list (#7581) * fix(settings): keep full installed font list * fix(settings): bound font picker rendering * Fix redundant font queries and handle partial state in worktree purge - Latch the loaded state even when the returned font list is empty, preventing font-less systems from reissuing font listing calls on every picker interaction. - Add null-tolerance for `ptyIdsByTabId` when building worktree purge state to support callers that pass partial AppState. --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> --- src/main/system-fonts.test.ts | 57 ++++++++++++- src/main/system-fonts.ts | 45 ++++++---- .../settings/AppearanceInterfaceSection.tsx | 3 + .../settings/AppearancePane.test.tsx | 25 +++++- .../components/settings/AppearancePane.tsx | 4 + .../src/components/settings/Settings.tsx | 78 ++++++++++-------- .../settings/SettingsConstants.test.ts | 14 ++++ .../components/settings/SettingsConstants.ts | 11 ++- ...ngsFormControls.font-autocomplete.test.tsx | 82 +++++++++++++++++++ .../settings/SettingsFormControls.tsx | 31 +++++-- .../settings/TerminalAppearanceSection.tsx | 3 + .../settings-form-option-filter.test.ts | 35 ++++++++ .../settings/settings-form-option-filter.ts | 23 ++++++ src/renderer/src/store/slices/worktrees.ts | 4 +- 14 files changed, 353 insertions(+), 62 deletions(-) create mode 100644 src/renderer/src/components/settings/SettingsConstants.test.ts diff --git a/src/main/system-fonts.test.ts b/src/main/system-fonts.test.ts index 3f63d8930..c6c5e0e42 100644 --- a/src/main/system-fonts.test.ts +++ b/src/main/system-fonts.test.ts @@ -9,16 +9,56 @@ vi.mock('child_process', () => ({ execFile: execFileMock })) -function expectedFallbackFont(): string { - if (process.platform === 'darwin') { +function expectedFallbackFont(platform = process.platform): string { + if (platform === 'darwin') { return 'SF Mono' } - if (process.platform === 'win32') { + if (platform === 'win32') { return 'Cascadia Mono' } return 'JetBrains Mono' } +async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): Promise { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return await fn() + } finally { + Object.defineProperty(process, 'platform', { + configurable: true, + value: originalPlatform + }) + } +} + +async function expectFontCommandTimeout( + platform: NodeJS.Platform, + timeoutMs: number +): Promise { + await withPlatform(platform, async () => { + vi.useFakeTimers() + execFileMock.mockReturnValue({ kill: killMock }) + + const { listSystemFontFamilies } = await import('./system-fonts') + const fontsPromise = listSystemFontFamilies() + let resolvedFonts: string[] | null = null + fontsPromise.then((fonts) => { + resolvedFonts = fonts + }) + + await vi.advanceTimersByTimeAsync(timeoutMs - 1) + + expect(resolvedFonts).toBeNull() + expect(killMock).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + await expect(fontsPromise).resolves.toContain(expectedFallbackFont(platform)) + expect(killMock).toHaveBeenCalledOnce() + }) +} + describe('listSystemFontFamilies', () => { afterEach(() => { vi.useRealTimers() @@ -44,4 +84,15 @@ describe('listSystemFontFamilies', () => { expect(resolvedFonts).toContain(expectedFallbackFont()) expect(killMock).toHaveBeenCalledOnce() }) + + it('uses the longer timeout for macOS profiler scans', async () => { + await expectFontCommandTimeout('darwin', 45_000) + }) + + it.each([ + ['linux' as NodeJS.Platform, 15_000], + ['win32' as NodeJS.Platform, 15_000] + ])('keeps the %s font command timeout short', async (platform, timeoutMs) => { + await expectFontCommandTimeout(platform, timeoutMs) + }) }) diff --git a/src/main/system-fonts.ts b/src/main/system-fonts.ts index afe142562..15ff9c28b 100644 --- a/src/main/system-fonts.ts +++ b/src/main/system-fonts.ts @@ -3,6 +3,9 @@ import { execFile } from 'node:child_process' let cachedFonts: string[] | null = null let fontsPromise: Promise | null = null const SYSTEM_FONT_LIST_TIMEOUT_MS = 15_000 +// Why: large macOS font catalogs can make system_profiler exceed 15s even +// when it is healthy; keep the longer wait scoped to that slow command. +const MAC_SYSTEM_FONT_LIST_TIMEOUT_MS = 45_000 export async function listSystemFontFamilies(): Promise { if (cachedFonts) { @@ -43,23 +46,26 @@ function loadSystemFontFamilies(): Promise { } function listMacFonts(): Promise { - return execFileText('system_profiler', ['SPFontsDataType', '-json'], 32 * 1024 * 1024).then( - (output) => { - const parsed = JSON.parse(output) as { - SPFontsDataType?: { - typefaces?: { - family?: string - }[] + return execFileText( + 'system_profiler', + ['SPFontsDataType', '-json'], + 32 * 1024 * 1024, + MAC_SYSTEM_FONT_LIST_TIMEOUT_MS + ).then((output) => { + const parsed = JSON.parse(output) as { + SPFontsDataType?: { + typefaces?: { + family?: string }[] - } - - return uniqueSorted( - (parsed.SPFontsDataType ?? []).flatMap((font) => - (font.typefaces ?? []).map((typeface) => typeface.family) - ) - ) + }[] } - ) + + return uniqueSorted( + (parsed.SPFontsDataType ?? []).flatMap((font) => + (font.typefaces ?? []).map((typeface) => typeface.family) + ) + ) + }) } function listLinuxFonts(): Promise { @@ -95,7 +101,12 @@ $fonts.Families | ForEach-Object { $_.Name } ) } -function execFileText(command: string, args: string[], maxBuffer: number): Promise { +function execFileText( + command: string, + args: string[], + maxBuffer: number, + timeoutMs = SYSTEM_FONT_LIST_TIMEOUT_MS +): Promise { return new Promise((resolve, reject) => { let settled = false let timer: ReturnType | undefined @@ -123,7 +134,7 @@ function execFileText(command: string, args: string[], maxBuffer: number): Promi // should fall back instead of keeping settings IPC pending forever. child.kill() reject(new Error(`Timed out listing system fonts with ${command}`)) - }, SYSTEM_FONT_LIST_TIMEOUT_MS) + }, timeoutMs) if (typeof timer === 'object' && 'unref' in timer) { timer.unref() } diff --git a/src/renderer/src/components/settings/AppearanceInterfaceSection.tsx b/src/renderer/src/components/settings/AppearanceInterfaceSection.tsx index 0f691a072..31afc7d68 100644 --- a/src/renderer/src/components/settings/AppearanceInterfaceSection.tsx +++ b/src/renderer/src/components/settings/AppearanceInterfaceSection.tsx @@ -38,6 +38,7 @@ type AppearanceInterfaceSectionProps = { applyTheme: (theme: 'system' | 'dark' | 'light') => void fontSuggestions: string[] isDesktopWindows: boolean + onRequestFontSuggestions?: () => void forceVisiblePrimary?: boolean } @@ -47,6 +48,7 @@ export function AppearanceInterfaceSection({ applyTheme, fontSuggestions, isDesktopWindows, + onRequestFontSuggestions, forceVisiblePrimary = false }: AppearanceInterfaceSectionProps): React.JSX.Element { const searchQuery = useAppStore((state) => state.settingsSearchQuery) @@ -142,6 +144,7 @@ export function AppearanceInterfaceSection({ value={settings.appFontFamily} suggestions={fontSuggestions} placeholder={DEFAULT_APP_FONT_FAMILY} + onRequestSuggestions={onRequestFontSuggestions} onChange={(value) => updateSettings({ appFontFamily: value.trim() || DEFAULT_APP_FONT_FAMILY }) } diff --git a/src/renderer/src/components/settings/AppearancePane.test.tsx b/src/renderer/src/components/settings/AppearancePane.test.tsx index 714844932..5fe949cea 100644 --- a/src/renderer/src/components/settings/AppearancePane.test.tsx +++ b/src/renderer/src/components/settings/AppearancePane.test.tsx @@ -129,7 +129,10 @@ function createWarpThemesStub() { async function renderAppearancePane( settings: GlobalSettings, - updateSettings: (updates: Partial) => void = vi.fn() + updateSettings: (updates: Partial) => void = vi.fn(), + options: { + onRequestFontSuggestions?: () => void + } = {} ): Promise { const container = document.createElement('div') document.body.appendChild(container) @@ -146,6 +149,7 @@ async function renderAppearancePane( applyTheme={vi.fn()} fontSuggestions={[]} terminalFontSuggestions={[]} + onRequestFontSuggestions={options.onRequestFontSuggestions} systemPrefersDark={false} ghostty={createGhosttyStub() as never} warpThemes={createWarpThemesStub() as never} @@ -296,6 +300,25 @@ describe('AppearancePane', () => { expect(container.textContent).not.toContain('Code & Markdown') }) + it('requests installed font suggestions only after the IDE font picker is used', async () => { + mocks.state.settingsSearchQuery = '' + const requestFontSuggestions = vi.fn() + const container = await renderAppearancePane(getDefaultSettings('/tmp'), vi.fn(), { + onRequestFontSuggestions: requestFontSuggestions + }) + + expect(requestFontSuggestions).not.toHaveBeenCalled() + + const input = container.querySelector('input[role="combobox"]') + expect(input).not.toBeNull() + + await act(async () => { + input?.focus() + }) + + expect(requestFontSuggestions).toHaveBeenCalledOnce() + }) + it('keeps the app icon control at the bottom of the pane, after the section rows', async () => { mocks.state.settingsSearchQuery = '' const container = await renderAppearancePane(getDefaultSettings('/tmp')) diff --git a/src/renderer/src/components/settings/AppearancePane.tsx b/src/renderer/src/components/settings/AppearancePane.tsx index f7a2dd52c..927926215 100644 --- a/src/renderer/src/components/settings/AppearancePane.tsx +++ b/src/renderer/src/components/settings/AppearancePane.tsx @@ -45,6 +45,7 @@ type AppearancePaneProps = { applyTheme: (theme: 'system' | 'dark' | 'light') => void fontSuggestions: string[] terminalFontSuggestions: string[] + onRequestFontSuggestions?: () => void systemPrefersDark: boolean ghostty: UseGhosttyImportReturn warpThemes: UseWarpThemeImportReturn @@ -68,6 +69,7 @@ export function AppearancePane({ applyTheme, fontSuggestions, terminalFontSuggestions, + onRequestFontSuggestions, systemPrefersDark, ghostty, warpThemes @@ -179,6 +181,7 @@ export function AppearancePane({ updateSettings={updateSettings} applyTheme={applyTheme} fontSuggestions={fontSuggestions} + onRequestFontSuggestions={onRequestFontSuggestions} isDesktopWindows={isDesktopWindows} forceVisiblePrimary={interfaceLabelMatches} /> @@ -205,6 +208,7 @@ export function AppearancePane({ updateSettings={updateSettings} systemPrefersDark={systemPrefersDark} terminalFontSuggestions={terminalFontSuggestions} + onRequestFontSuggestions={onRequestFontSuggestions} ghostty={ghostty} warpThemes={warpThemes} forceVisiblePrimary={terminalLabelMatches} diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index 92c4a35b2..bfe82c9d7 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -23,7 +23,11 @@ import { useSystemPrefersDark } from '@/components/terminal-pane/use-system-pref import { isMacUserAgent, isWindowsUserAgent } from '@/components/terminal-pane/pane-helpers' import { applyDocumentTheme } from '@/lib/document-theme' import { useConfirmationDialog } from '@/components/confirmation-dialog' -import { SCROLLBACK_PRESETS_ROWS, getFallbackTerminalFonts } from './SettingsConstants' +import { + SCROLLBACK_PRESETS_ROWS, + getFallbackTerminalFonts, + mergeFontSuggestions +} from './SettingsConstants' import { DEFAULT_APP_FONT_FAMILY, getDefaultVoiceSettings } from '../../../../shared/constants' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { GeneralPane } from './GeneralPane' @@ -313,7 +317,7 @@ function Settings(): React.JSX.Element { const ghostty = useGhosttyImport(updateSettings, settings) const warpThemes = useWarpThemeImport(updateSettings, settings) const [fontSuggestions, setFontSuggestions] = useState( - Array.from(new Set([DEFAULT_APP_FONT_FAMILY, ...getFallbackTerminalFonts()])) + mergeFontSuggestions([], getFallbackTerminalFonts()) ) const terminalFontSuggestions = useMemo( () => fontSuggestions.filter((font) => font !== DEFAULT_APP_FONT_FAMILY), @@ -336,7 +340,9 @@ function Settings(): React.JSX.Element { const [hiddenExperimentalUnlocked, setHiddenExperimentalUnlocked] = useState(false) const contentScrollRef = useRef(null) const searchInputRef = useRef(null) - const terminalFontsLoadedRef = useRef(false) + const installedFontsLoadedRef = useRef(false) + const installedFontsLoadPromiseRef = useRef | null>(null) + const settingsMountedRef = useRef(true) const pendingNavSectionRef = useRef(null) const pendingScrollTargetRef = useRef(null) const pendingSubsectionScrollFrameRef = useRef(null) @@ -394,6 +400,42 @@ function Settings(): React.JSX.Element { cancelPendingSettingsSubsectionScrollFrame(pendingSubsectionScrollFrameRef) }, []) + useEffect(() => { + // Why: React dev StrictMode replays mount effects; async font requests + // should still commit while the Settings view is actually mounted. + settingsMountedRef.current = true + return () => { + settingsMountedRef.current = false + } + }, []) + + const requestFontSuggestions = useCallback((): void => { + if (installedFontsLoadedRef.current || installedFontsLoadPromiseRef.current) { + return + } + + installedFontsLoadPromiseRef.current = window.api.settings + .listFonts() + .then((fonts) => { + if (!settingsMountedRef.current) { + return + } + // Latch after the first successful attempt even when empty, so a font-less + // system doesn't reissue listFonts() on every picker interaction. + installedFontsLoadedRef.current = true + if (fonts.length === 0) { + return + } + setFontSuggestions((prev) => mergeFontSuggestions(fonts, prev)) + }) + .catch(() => { + // Fall back to curated cross-platform suggestions. + }) + .finally(() => { + installedFontsLoadPromiseRef.current = null + }) + }, []) + // Pure "discard and leave?" prompt — no side effects. Why separate from the // discard helper below: the window-close guard must ask without clearing the // drafts, since a later guard/handler can still cancel the close. @@ -754,35 +796,6 @@ function Settings(): React.JSX.Element { setMountedSectionIds(neededSectionIds) } - useEffect(() => { - if (!neededSectionIds.has('appearance') && !neededSectionIds.has('terminal')) { - return - } - if (terminalFontsLoadedRef.current) { - return - } - - let stale = false - const loadFontSuggestions = async (): Promise => { - try { - const fonts = await window.api.settings.listFonts() - if (stale || fonts.length === 0) { - return - } - terminalFontsLoadedRef.current = true - setFontSuggestions((prev) => - Array.from(new Set([DEFAULT_APP_FONT_FAMILY, ...fonts, ...prev])).slice(0, 320) - ) - } catch { - // Fall back to curated cross-platform suggestions. - } - } - void loadFontSuggestions() - return () => { - stale = true - } - }, [neededSectionIds]) - const neededRepoIds = useMemo( () => deriveNeededRepoIds(repos, neededSectionIds), [neededSectionIds, repos] @@ -1410,6 +1423,7 @@ function Settings(): React.JSX.Element { applyTheme={applyTheme} fontSuggestions={fontSuggestions} terminalFontSuggestions={terminalFontSuggestions} + onRequestFontSuggestions={requestFontSuggestions} systemPrefersDark={systemPrefersDark} ghostty={ghostty} warpThemes={warpThemes} diff --git a/src/renderer/src/components/settings/SettingsConstants.test.ts b/src/renderer/src/components/settings/SettingsConstants.test.ts new file mode 100644 index 000000000..468767967 --- /dev/null +++ b/src/renderer/src/components/settings/SettingsConstants.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { DEFAULT_APP_FONT_FAMILY } from '../../../../shared/constants' +import { mergeFontSuggestions } from './SettingsConstants' + +describe('mergeFontSuggestions', () => { + it('keeps installed fonts beyond the old hydration cutoff', () => { + const systemFonts = Array.from({ length: 350 }, (_value, index) => `System Font ${index}`) + const suggestions = mergeFontSuggestions(systemFonts, ['JetBrains Mono']) + + expect(suggestions).toContain(DEFAULT_APP_FONT_FAMILY) + expect(suggestions).toContain('System Font 349') + expect(suggestions).toContain('JetBrains Mono') + }) +}) diff --git a/src/renderer/src/components/settings/SettingsConstants.ts b/src/renderer/src/components/settings/SettingsConstants.ts index 47fb0ba28..2c49121d3 100644 --- a/src/renderer/src/components/settings/SettingsConstants.ts +++ b/src/renderer/src/components/settings/SettingsConstants.ts @@ -1,5 +1,5 @@ import type { OrcaHooks } from '../../../../shared/types' -import { getDefaultRepoHookSettings } from '../../../../shared/constants' +import { DEFAULT_APP_FONT_FAMILY, getDefaultRepoHookSettings } from '../../../../shared/constants' import { DESKTOP_TERMINAL_SCROLLBACK_ROW_PRESETS } from '../../../../shared/terminal-scrollback-policy' export type HookName = keyof OrcaHooks['scripts'] @@ -14,6 +14,15 @@ export function zoomLevelToPercent(level: number): number { return Math.round(100 * Math.pow(1.2, level)) } +export function mergeFontSuggestions( + systemFonts: readonly string[], + previousFonts: readonly string[] +): string[] { + // Why: picker rendering can be capped later, but the source list must keep + // every installed font searchable/selectable. + return Array.from(new Set([DEFAULT_APP_FONT_FAMILY, ...systemFonts, ...previousFonts])) +} + export function getFallbackTerminalFonts(): string[] { const nav = typeof navigator !== 'undefined' diff --git a/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx b/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx index 62412f2e2..4e5e3a8f2 100644 --- a/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx +++ b/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx @@ -4,6 +4,7 @@ import { act, useState, type ReactNode } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { FontAutocomplete } from './SettingsFormControls' +import { FONT_SUGGESTION_RENDER_LIMIT } from './settings-form-option-filter' vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, defaultValue: string) => defaultValue @@ -186,4 +187,85 @@ describe('FontAutocomplete', () => { expect(getOptionLabels()).toEqual(['JetBrains Mono']) }) + + it('requests installed suggestions only after the picker is used', async () => { + const requestSuggestions = vi.fn() + + function Harness(): ReactNode { + const [value, setValue] = useState('Geist') + return ( + + ) + } + + await act(async () => { + root.render() + }) + + expect(requestSuggestions).not.toHaveBeenCalled() + + await act(async () => { + getInput().focus() + }) + + expect(requestSuggestions).toHaveBeenCalledOnce() + }) + + it('searches suggestions past the previous 320 font cutoff', async () => { + const suggestions = [ + ...Array.from({ length: 350 }, (_value, index) => `System Font ${index}`), + 'Zed Mono' + ] + + function Harness(): ReactNode { + const [value, setValue] = useState('System Font 0') + return + } + + await act(async () => { + root.render() + }) + + const input = getInput() + + await act(async () => { + input.focus() + }) + expect(getOptionLabels()).toHaveLength(FONT_SUGGESTION_RENDER_LIMIT) + expect(getOptionLabels()).not.toContain('Zed Mono') + + await typeIntoInput(input, 'Zed') + + expect(getOptionLabels()).toEqual(['Zed Mono']) + }) + + it('renders the selected late-list font even when the full list is capped', async () => { + const suggestions = [ + ...Array.from({ length: FONT_SUGGESTION_RENDER_LIMIT + 30 }, (_value, index) => { + return `System Font ${index}` + }), + 'Zed Mono' + ] + + function Harness(): ReactNode { + const [value, setValue] = useState('Zed Mono') + return + } + + await act(async () => { + root.render() + }) + + await act(async () => { + getInput().focus() + }) + + expect(getOptionLabels()).toHaveLength(FONT_SUGGESTION_RENDER_LIMIT) + expect(getOptionLabels().at(-1)).toBe('Zed Mono') + }) }) diff --git a/src/renderer/src/components/settings/SettingsFormControls.tsx b/src/renderer/src/components/settings/SettingsFormControls.tsx index a8b5bbdef..146e0000f 100644 --- a/src/renderer/src/components/settings/SettingsFormControls.tsx +++ b/src/renderer/src/components/settings/SettingsFormControls.tsx @@ -13,6 +13,7 @@ import { MAX_THEME_RESULTS } from './SettingsConstants' import { filterFontSuggestions, filterTerminalThemeOptions, + getRenderedFontSuggestions, isSettingsFormOptionQueryTooLarge } from './settings-form-option-filter' import { cn } from '@/lib/utils' @@ -286,6 +287,7 @@ type FontAutocompleteProps = { suggestions: string[] onChange: (value: string) => void placeholder?: string + onRequestSuggestions?: () => void /** Fires with whichever option the user is currently highlighting in the * dropdown (via mouse hover or keyboard arrow), or null when nothing is * highlighted / the dropdown is closed. Lets a consumer show a live @@ -588,6 +590,7 @@ export function FontAutocomplete({ suggestions, onChange, placeholder = 'SF Mono', + onRequestSuggestions, onPreviewFontFamily }: FontAutocompleteProps): React.JSX.Element { const [query, setQuery] = useState(value) @@ -619,8 +622,15 @@ export function FontAutocomplete({ } } + const requestSuggestions = useCallback((): void => { + onRequestSuggestions?.() + }, [onRequestSuggestions]) + const handleOpenChange = (nextOpen: boolean): void => { setOpen(nextOpen) + if (nextOpen) { + requestSuggestions() + } if (!nextOpen) { setIsFilteringQuery(false) } @@ -636,6 +646,10 @@ export function FontAutocomplete({ // still reveal every installed font instead of only fonts sharing that name. const visibleSuggestions = !isFilteringQuery && normalizedQuery === normalizedValue ? suggestions : filteredSuggestions + const renderedSuggestions = useMemo( + () => getRenderedFontSuggestions(visibleSuggestions, highlightedIndex), + [visibleSuggestions, highlightedIndex] + ) // Why: sync the highlighted index during render rather than via useEffect so // the correct item is highlighted on the very first paint after open/filter @@ -699,12 +713,14 @@ export function FontAutocomplete({ value={query} onChange={(e) => { const next = e.target.value + requestSuggestions() setQuery(next) setIsFilteringQuery(true) onChange(next) setOpen(true) }} onFocus={() => { + requestSuggestions() setIsFilteringQuery(false) setOpen(true) }} @@ -795,6 +811,7 @@ export function FontAutocomplete({ setIsFilteringQuery(false) } if (nextOpen) { + requestSuggestions() focusInput() } }} @@ -831,29 +848,29 @@ export function FontAutocomplete({ }} > 8 ? 'h-64' : undefined} + className={renderedSuggestions.length > 8 ? 'h-64' : undefined} style={popoverAvailableHeightStyle} viewportProps={{ style: popoverAvailableHeightStyle }} >
{visibleSuggestions.length > 0 ? ( - visibleSuggestions.map((font, index) => ( + renderedSuggestions.map(({ font, sourceIndex }) => (