Merge remote-tracking branch 'origin/main' into Jinwoo-H/windows-update-survival
This commit is contained in:
@@ -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<string> {
|
||||
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<string> {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<string, CachedTranscript>()
|
||||
@@ -28,19 +31,36 @@ const cache = new Map<string, CachedTranscript>()
|
||||
// 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<number> {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<T>(platform: NodeJS.Platform, fn: () => Promise<T>): Promise<T> {
|
||||
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<void> {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
+28
-17
@@ -3,6 +3,9 @@ import { execFile } from 'node:child_process'
|
||||
let cachedFonts: string[] | null = null
|
||||
let fontsPromise: Promise<string[]> | 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<string[]> {
|
||||
if (cachedFonts) {
|
||||
@@ -43,23 +46,26 @@ function loadSystemFontFamilies(): Promise<string[]> {
|
||||
}
|
||||
|
||||
function listMacFonts(): Promise<string[]> {
|
||||
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<string[]> {
|
||||
@@ -95,7 +101,12 @@ $fonts.Families | ForEach-Object { $_.Name }
|
||||
)
|
||||
}
|
||||
|
||||
function execFileText(command: string, args: string[], maxBuffer: number): Promise<string> {
|
||||
function execFileText(
|
||||
command: string,
|
||||
args: string[],
|
||||
maxBuffer: number,
|
||||
timeoutMs = SYSTEM_FONT_LIST_TIMEOUT_MS
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
let timer: ReturnType<typeof setTimeout> | 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()
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
@@ -129,7 +129,10 @@ function createWarpThemesStub() {
|
||||
|
||||
async function renderAppearancePane(
|
||||
settings: GlobalSettings,
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void = vi.fn()
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void = vi.fn(),
|
||||
options: {
|
||||
onRequestFontSuggestions?: () => void
|
||||
} = {}
|
||||
): Promise<HTMLDivElement> {
|
||||
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<HTMLInputElement>('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'))
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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<string[]>(
|
||||
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<HTMLDivElement | null>(null)
|
||||
const searchInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const terminalFontsLoadedRef = useRef(false)
|
||||
const installedFontsLoadedRef = useRef(false)
|
||||
const installedFontsLoadPromiseRef = useRef<Promise<void> | null>(null)
|
||||
const settingsMountedRef = useRef(true)
|
||||
const pendingNavSectionRef = useRef<string | null>(null)
|
||||
const pendingScrollTargetRef = useRef<string | null>(null)
|
||||
const pendingSubsectionScrollFrameRef = useRef<number | null>(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<void> => {
|
||||
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}
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
|
||||
@@ -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 (
|
||||
<FontAutocomplete
|
||||
value={value}
|
||||
suggestions={['Geist', 'JetBrains Mono']}
|
||||
onChange={setValue}
|
||||
onRequestSuggestions={requestSuggestions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />)
|
||||
})
|
||||
|
||||
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 <FontAutocomplete value={value} suggestions={suggestions} onChange={setValue} />
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />)
|
||||
})
|
||||
|
||||
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 <FontAutocomplete value={value} suggestions={suggestions} onChange={setValue} />
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />)
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
getInput().focus()
|
||||
})
|
||||
|
||||
expect(getOptionLabels()).toHaveLength(FONT_SUGGESTION_RENDER_LIMIT)
|
||||
expect(getOptionLabels().at(-1)).toBe('Zed Mono')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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({
|
||||
}}
|
||||
>
|
||||
<ScrollArea
|
||||
className={visibleSuggestions.length > 8 ? 'h-64' : undefined}
|
||||
className={renderedSuggestions.length > 8 ? 'h-64' : undefined}
|
||||
style={popoverAvailableHeightStyle}
|
||||
viewportProps={{ style: popoverAvailableHeightStyle }}
|
||||
>
|
||||
<div id={listboxId} role="listbox" className="p-1">
|
||||
{visibleSuggestions.length > 0 ? (
|
||||
visibleSuggestions.map((font, index) => (
|
||||
renderedSuggestions.map(({ font, sourceIndex }) => (
|
||||
<button
|
||||
key={font}
|
||||
type="button"
|
||||
id={`${listboxId}-option-${index}`}
|
||||
id={`${listboxId}-option-${sourceIndex}`}
|
||||
role="option"
|
||||
aria-selected={index === highlightedIndex}
|
||||
aria-selected={sourceIndex === highlightedIndex}
|
||||
ref={(element) => {
|
||||
if (element && index === highlightedIndex) {
|
||||
if (element && sourceIndex === highlightedIndex) {
|
||||
element.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onMouseEnter={() => setHighlightedIndex(index)}
|
||||
onMouseEnter={() => setHighlightedIndex(sourceIndex)}
|
||||
onClick={() => commitValue(font)}
|
||||
className={`flex w-full items-center justify-between rounded-sm px-3 py-2 text-left text-sm transition-colors ${
|
||||
index === highlightedIndex
|
||||
sourceIndex === highlightedIndex
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'hover:bg-muted/60'
|
||||
}`}
|
||||
|
||||
@@ -44,6 +44,7 @@ type TerminalAppearanceSectionProps = {
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void
|
||||
systemPrefersDark: boolean
|
||||
terminalFontSuggestions: string[]
|
||||
onRequestFontSuggestions?: () => void
|
||||
ghostty: UseGhosttyImportReturn
|
||||
warpThemes: UseWarpThemeImportReturn
|
||||
forceVisiblePrimary?: boolean
|
||||
@@ -74,6 +75,7 @@ export function TerminalAppearanceSection({
|
||||
updateSettings,
|
||||
systemPrefersDark,
|
||||
terminalFontSuggestions,
|
||||
onRequestFontSuggestions,
|
||||
ghostty,
|
||||
warpThemes,
|
||||
forceVisiblePrimary = false
|
||||
@@ -225,6 +227,7 @@ export function TerminalAppearanceSection({
|
||||
<FontAutocomplete
|
||||
value={settings.terminalFontFamily}
|
||||
suggestions={terminalFontSuggestions}
|
||||
onRequestSuggestions={onRequestFontSuggestions}
|
||||
onChange={(value) => updateSettings({ terminalFontFamily: value })}
|
||||
onPreviewFontFamily={setPreviewFontFamily}
|
||||
/>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { TerminalThemeOption } from '@/lib/terminal-theme'
|
||||
import {
|
||||
FONT_SUGGESTION_RENDER_LIMIT,
|
||||
SETTINGS_FORM_OPTION_QUERY_MAX_BYTES,
|
||||
filterFontSuggestions,
|
||||
filterTerminalThemeOptions,
|
||||
getRenderedFontSuggestions,
|
||||
isSettingsFormOptionQueryTooLarge
|
||||
} from './settings-form-option-filter'
|
||||
|
||||
@@ -86,4 +88,37 @@ describe('settings-form-option-filter', () => {
|
||||
expect(filterTerminalThemeOptions([createThemeOption('Solarized Dark')], query)).toEqual([])
|
||||
expect(filterFontSuggestions(['Fira Code'], query)).toEqual([])
|
||||
})
|
||||
|
||||
it('caps rendered font suggestions without changing the searchable source list', () => {
|
||||
const suggestions = Array.from(
|
||||
{ length: FONT_SUGGESTION_RENDER_LIMIT + 40 },
|
||||
(_value, index) => `System Font ${index}`
|
||||
)
|
||||
|
||||
const rendered = getRenderedFontSuggestions(suggestions, 0)
|
||||
|
||||
expect(rendered).toHaveLength(FONT_SUGGESTION_RENDER_LIMIT)
|
||||
expect(rendered.map((option) => option.font)).not.toContain(
|
||||
`System Font ${FONT_SUGGESTION_RENDER_LIMIT + 39}`
|
||||
)
|
||||
expect(
|
||||
filterFontSuggestions(suggestions, `System Font ${FONT_SUGGESTION_RENDER_LIMIT + 39}`)
|
||||
).toEqual([`System Font ${FONT_SUGGESTION_RENDER_LIMIT + 39}`])
|
||||
})
|
||||
|
||||
it('keeps a highlighted late font visible inside the render cap', () => {
|
||||
const lateFontIndex = FONT_SUGGESTION_RENDER_LIMIT + 12
|
||||
const suggestions = Array.from(
|
||||
{ length: lateFontIndex + 1 },
|
||||
(_value, index) => `System Font ${index}`
|
||||
)
|
||||
|
||||
const rendered = getRenderedFontSuggestions(suggestions, lateFontIndex)
|
||||
|
||||
expect(rendered).toHaveLength(FONT_SUGGESTION_RENDER_LIMIT)
|
||||
expect(rendered.at(-1)).toEqual({
|
||||
font: `System Font ${lateFontIndex}`,
|
||||
sourceIndex: lateFontIndex
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,12 @@ import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard
|
||||
import type { TerminalThemeOption } from '@/lib/terminal-theme'
|
||||
|
||||
export const SETTINGS_FORM_OPTION_QUERY_MAX_BYTES = 2 * 1024
|
||||
export const FONT_SUGGESTION_RENDER_LIMIT = 320
|
||||
|
||||
export type RenderedFontSuggestion = {
|
||||
font: string
|
||||
sourceIndex: number
|
||||
}
|
||||
|
||||
export function isSettingsFormOptionQueryTooLarge(
|
||||
query: string,
|
||||
@@ -55,3 +61,20 @@ export function filterFontSuggestions(suggestions: readonly string[], query: str
|
||||
}
|
||||
return [...startsWith, ...includes]
|
||||
}
|
||||
|
||||
export function getRenderedFontSuggestions(
|
||||
suggestions: readonly string[],
|
||||
highlightedIndex: number,
|
||||
limit = FONT_SUGGESTION_RENDER_LIMIT
|
||||
): RenderedFontSuggestion[] {
|
||||
const cappedLength = Math.min(suggestions.length, limit)
|
||||
if (cappedLength <= 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const sourceIndexes = Array.from({ length: cappedLength }, (_value, index) => index)
|
||||
if (highlightedIndex >= cappedLength && highlightedIndex < suggestions.length) {
|
||||
sourceIndexes[cappedLength - 1] = highlightedIndex
|
||||
}
|
||||
return sourceIndexes.map((sourceIndex) => ({ font: suggestions[sourceIndex] ?? '', sourceIndex }))
|
||||
}
|
||||
|
||||
@@ -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 */
|
||||
}
|
||||
|
||||
@@ -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<typeof vi.fn>
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1840,7 +1840,9 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
for (const id of worktreeIdSet) {
|
||||
for (const tab of s.tabsByWorktree[id] ?? []) {
|
||||
doomedTabIds.add(tab.id)
|
||||
for (const ptyId of s.ptyIdsByTabId[tab.id] ?? []) {
|
||||
// Null-tolerant like the omit* helpers below: some callers pass partial
|
||||
// state that omits this slice; the production store always inits it to {}.
|
||||
for (const ptyId of s.ptyIdsByTabId?.[tab.id] ?? []) {
|
||||
doomedPtyIds.add(ptyId)
|
||||
}
|
||||
// Why: a removed worktree's panes are gone for good, so drop their
|
||||
|
||||
@@ -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<void> {
|
||||
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<RenderProbeResult> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user