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 +} 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 }) => (