import { mkdtempSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { DesktopConfigStore, normalizeGpuMode, parseLaunchArgs, readPreReadyGpuHandoff, readPreReadyGpuMode, } from '../src/main/config' import { buildGpuHandoffArgs, canAutoSwitchGpu, chooseStartupGpuTarget, createSustainedLowFpsTracker, createVramHysteresisTracker, detectIntegratedGpuFromRegistryOutput, isGpuProcessCrash, parseNvidiaSmiCsv, resolveChromiumGpuSwitches, stripGpuOverrideArgs, VRAM_LOW_THRESHOLD_MIB, VRAM_RECOVER_THRESHOLD_MIB, } from '../src/main/gpu-policy' import { computeSplashCanvasSize } from '../src/preload/splash' let tempRoot = '' beforeAll(() => { tempRoot = mkdtempSync(path.join(os.tmpdir(), 'planet-gpu-policy-test-')) }) afterAll(() => { if (tempRoot) { rmSync(tempRoot, { recursive: true, force: true }) } }) describe('chromium GPU switch policy and splash pixel budget', () => { test('win32 hardware mode avoids risky zero-copy and forced GPU switches by default', () => { const switches = resolveChromiumGpuSwitches({ platform: 'win32', headlessSmoke: false, softwareGl: false, }) const names = switches.map((entry) => entry.name) expect(names).not.toContain('enable-zero-copy') expect(names).not.toContain('enable-gpu-rasterization') expect(names).not.toContain('force_high_performance_gpu') expect(names).not.toContain('force_low_power_gpu') expect(names).toContain('disable-renderer-backgrounding') expect(names).not.toContain('ozone-platform-hint') }) test('low-power and high-performance targets emit matching Chromium GPU preference switches without enable-zero-copy', () => { const igpuSwitches = resolveChromiumGpuSwitches({ platform: 'win32', headlessSmoke: false, target: 'low-power', }) expect(igpuSwitches).toEqual([ { name: 'force_low_power_gpu' }, { name: 'disable-renderer-backgrounding' }, ]) const dgpuSwitches = resolveChromiumGpuSwitches({ platform: 'win32', headlessSmoke: false, target: 'high-performance', }) expect(dgpuSwitches).toEqual([ { name: 'force_high_performance_gpu' }, { name: 'disable-renderer-backgrounding' }, ]) }) test('linux hardware mode adds ozone auto hint without enable-zero-copy', () => { const switches = resolveChromiumGpuSwitches({ platform: 'linux', headlessSmoke: false, softwareGl: false, }) expect(switches).toEqual([ { name: 'disable-renderer-backgrounding' }, { name: 'ozone-platform-hint', value: 'auto' }, ]) }) test('headless smoke, explicit software-gl, and target=software select SwiftShader safely', () => { for (const flags of [ { headlessSmoke: true, softwareGl: false }, { headlessSmoke: false, softwareGl: true }, { headlessSmoke: false, target: 'software' as const }, ]) { const switches = resolveChromiumGpuSwitches({ platform: 'win32', ...flags }) expect(switches).toEqual([ { name: 'disable-gpu' }, { name: 'use-gl', value: 'angle' }, { name: 'use-angle', value: 'swiftshader' }, { name: 'enable-unsafe-swiftshader' }, ]) } }) test('isGpuProcessCrash detects unexpected GPU exits and ignores clean exits', () => { expect(isGpuProcessCrash({ type: 'GPU', reason: 'crashed' })).toBe(true) expect(isGpuProcessCrash({ type: 'GPU', reason: 'killed' })).toBe(true) expect(isGpuProcessCrash({ type: 'GPU', reason: 'clean-exit' })).toBe(false) expect(isGpuProcessCrash({ type: 'Utility', reason: 'crashed' })).toBe(false) expect(isGpuProcessCrash(null)).toBe(false) }) test('computeSplashCanvasSize preserves 1080p clarity while capping 4K splash buffers', () => { expect(computeSplashCanvasSize(1920, 1080, 1)).toEqual({ dpr: 1, width: 1920, height: 1080, }) const qhdScaled4k = computeSplashCanvasSize(2560, 1440, 1.5) expect(qhdScaled4k.dpr).toBeLessThan(1.5) expect(qhdScaled4k.width * qhdScaled4k.height).toBeLessThanOrEqual(1920 * 1080) const native4k = computeSplashCanvasSize(3840, 2160, 1) expect(native4k.dpr).toBe(0.75) expect(native4k.width).toBe(2880) expect(native4k.height).toBe(1620) }) }) describe('adaptive VRAM probing, GPU decision, and hysteresis', () => { test('parseNvidiaSmiCsv parses single and multi-line CSV while skipping invalid rows', () => { expect( parseNvidiaSmiCsv('NVIDIA GeForce RTX 5070 Ti, 14651, 1345, 16303\n'), ).toEqual({ gpuName: 'NVIDIA GeForce RTX 5070 Ti', usedMiB: 14651, freeMiB: 1345, totalMiB: 16303, }) expect( parseNvidiaSmiCsv( '\n[N/A], [N/A], [N/A], [N/A]\nNVIDIA GeForce RTX 4090, 4096 MiB, 20480 MiB, 24576 MiB\n', ), ).toEqual({ gpuName: 'NVIDIA GeForce RTX 4090', usedMiB: 4096, freeMiB: 20480, totalMiB: 24576, }) expect(parseNvidiaSmiCsv('')).toBeNull() expect(parseNvidiaSmiCsv('Failed to initialize NVML')).toBeNull() }) test('detectIntegratedGpuFromRegistryOutput distinguishes iGPU from single-GPU and virtual adapters', () => { expect( detectIntegratedGpuFromRegistryOutput(` HKEY_LOCAL_MACHINE\\...\\0000 DriverDesc REG_SZ Intel(R) Graphics HKEY_LOCAL_MACHINE\\...\\0001 DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti `), ).toBe(true) expect( detectIntegratedGpuFromRegistryOutput(` DriverDesc REG_SZ AMD Radeon(TM) Graphics DriverDesc REG_SZ NVIDIA GeForce RTX 4060 Laptop GPU `), ).toBe(true) expect( detectIntegratedGpuFromRegistryOutput(` DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti DriverDesc REG_SZ Microsoft Basic Display Adapter DriverDesc REG_SZ Parsec Virtual Display Adapter `), ).toBe(false) expect( detectIntegratedGpuFromRegistryOutput(` DriverDesc REG_SZ Intel(R) Arc(TM) A770 Graphics DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti `), ).toBe(false) }) test('chooseStartupGpuTarget handles low VRAM auto offload, recovery, explicit modes, and smoke', () => { const lowVramSample = { gpuName: 'NVIDIA GeForce RTX 5070 Ti', usedMiB: 14651, freeMiB: 1345, totalMiB: 16303, } const healthyVramSample = { gpuName: 'NVIDIA GeForce RTX 5070 Ti', usedMiB: 4000, freeMiB: 8000, totalMiB: 16303, } expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'auto', vramSample: lowVramSample, hasIntegratedGpu: true, }), ).toEqual({ target: 'low-power', requestedMode: 'auto', reason: 'low-vram-igpu', vramSample: lowVramSample, hasIntegratedGpu: true, }) expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'auto', vramSample: lowVramSample, hasIntegratedGpu: false, }), ).toEqual({ target: 'software', requestedMode: 'auto', reason: 'low-vram-software', vramSample: lowVramSample, hasIntegratedGpu: false, }) expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'auto', vramSample: healthyVramSample, hasIntegratedGpu: true, }), ).toEqual({ target: 'default', requestedMode: 'auto', reason: 'normal-gpu', vramSample: healthyVramSample, hasIntegratedGpu: true, }) expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'high-performance', vramSample: lowVramSample, hasIntegratedGpu: true, }).reason, ).toBe('user-high-performance') expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'low-power', vramSample: healthyVramSample, hasIntegratedGpu: true, }).target, ).toBe('low-power') expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: true, requestedMode: 'high-performance', vramSample: healthyVramSample, hasIntegratedGpu: true, }), ).toMatchObject({ target: 'software', reason: 'headless-smoke' }) }) test('createVramHysteresisTracker enforces consecutive readings and deadband', () => { const lowSample = { gpuName: 'RTX 5070 Ti', usedMiB: 14500, freeMiB: 1500, totalMiB: 16303 } const midSample = { gpuName: 'RTX 5070 Ti', usedMiB: 13000, freeMiB: 3000, totalMiB: 16303 } const highSample = { gpuName: 'RTX 5070 Ti', usedMiB: 11000, freeMiB: VRAM_RECOVER_THRESHOLD_MIB, totalMiB: 16303 } const igpuTracker = createVramHysteresisTracker({ activeTarget: 'low-power', hasIntegratedGpu: true, }) expect(igpuTracker.observe(midSample)).toBeNull() expect(igpuTracker.observe(highSample)).toBeNull() expect(igpuTracker.observe(midSample)).toBeNull() // streak reset expect(igpuTracker.observe(highSample)).toBeNull() expect(igpuTracker.observe(highSample)).toEqual({ kind: 'switch-to-discrete', sample: highSample, }) const dgpuWithIgpu = createVramHysteresisTracker({ activeTarget: 'default', hasIntegratedGpu: true, }) expect(dgpuWithIgpu.observe(midSample)).toBeNull() expect(dgpuWithIgpu.observe({ ...lowSample, freeMiB: VRAM_LOW_THRESHOLD_MIB - 1 })).toBeNull() expect(dgpuWithIgpu.observe(null)).toBeNull() // missing reading resets streak expect(dgpuWithIgpu.observe(lowSample)).toBeNull() expect(dgpuWithIgpu.observe(lowSample)).toEqual({ kind: 'switch-to-low-power', sample: lowSample, }) const dgpuNoIgpu = createVramHysteresisTracker({ activeTarget: 'high-performance', hasIntegratedGpu: false, }) expect(dgpuNoIgpu.observe(lowSample)).toBeNull() expect(dgpuNoIgpu.observe(lowSample)).toEqual({ kind: 'switch-to-software', sample: lowSample, }) }) test('stripGpuOverrideArgs removes CLI GPU override flags cleanly', () => { expect( stripGpuOverrideArgs([ '--fullscreen', '--software-gl', '--gpu-mode=low-power', '--gpu-mode', 'high-performance', '--low-power-gpu', '--high-performance-gpu', 'planet-earth://open', ]), ).toEqual(['--fullscreen', 'planet-earth://open']) }) test('gpuMode config normalization, CLI flags, persistence, and readPreReadyGpuMode precedence work', () => { expect(normalizeGpuMode('AUTO')).toBe('auto') expect(normalizeGpuMode('igpu')).toBe('low-power') expect(normalizeGpuMode('discrete')).toBe('high-performance') expect(normalizeGpuMode('cpu')).toBe('software') expect(normalizeGpuMode('unknown', 'low-power')).toBe('low-power') expect(parseLaunchArgs(['--low-power-gpu']).flags.gpuModeOverride).toBe('low-power') expect(parseLaunchArgs(['--high-performance-gpu']).flags.gpuModeOverride).toBe('high-performance') expect(parseLaunchArgs(['--software-gl']).flags.gpuModeOverride).toBe('software') expect(parseLaunchArgs(['--gpu-mode', 'igpu']).flags.gpuModeOverride).toBe('low-power') const userDataDir = path.join(tempRoot, 'gpu-user-data') const exeDir = path.join(tempRoot, 'gpu-exe-dir') const store = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} }) expect(store.get().gpuMode).toBe('auto') store.updateEndpoints({ backendUrl: 'https://rclaw.test' }) store.updateGpuMode('low-power') expect( readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: {} }), ).toBe('low-power') expect( readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: { PLANET_GPU_MODE: 'high-performance' } }), ).toBe('high-performance') expect( readPreReadyGpuMode({ userDataDir, exeDir, argv: ['--software-gl'], env: { PLANET_GPU_MODE: 'high-performance' }, }), ).toBe('software') const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} }) expect(reloaded.get().gpuMode).toBe('low-power') expect(reloaded.get().backendUrl).toBe('https://rclaw.test') }) test('createSustainedLowFpsTracker ignores brief dips and triggers after 5s below 20 FPS with cooldown', () => { const tracker = createSustainedLowFpsTracker() let now = 0 expect(tracker.onFrame(now)).toBeNull() // Simulate 10 FPS (100ms frame delta) for 4 seconds -> not yet 5s sustained for (let sec = 0; sec < 4; sec += 1) { for (let f = 0; f < 10; f += 1) { now += 100 expect(tracker.onFrame(now)).toBeNull() } } // Recover above 20 FPS -> resets low streak for (let f = 0; f < 30; f += 1) { now += 35 expect(tracker.onFrame(now)).toBeNull() } // Now sustain 10 FPS for 5 full seconds -> triggers on 5th second let trigger: { avgFps: number; sustainedMs: number } | null = null for (let sec = 0; sec < 5; sec += 1) { for (let f = 0; f < 10; f += 1) { now += 100 const res = tracker.onFrame(now) if (res) trigger = res } } expect(trigger).not.toBeNull() expect(trigger!.avgFps).toBeGreaterThanOrEqual(9.5) expect(trigger!.avgFps).toBeLessThan(11) expect(trigger!.sustainedMs).toBeGreaterThanOrEqual(5000) // Within 15s report cooldown -> suppressed even if slow again for (let sec = 0; sec < 5; sec += 1) { for (let f = 0; f < 10; f += 1) { now += 100 expect(tracker.onFrame(now)).toBeNull() } } // Reset clears accumulated low duration cleanly tracker.reset() now += 20_000 expect(tracker.onFrame(now)).toBeNull() for (let sec = 0; sec < 4; sec += 1) { for (let f = 0; f < 10; f += 1) { now += 100 expect(tracker.onFrame(now)).toBeNull() } } }) test('canAutoSwitchGpu, handoff target decision, and handoff CLI args preserve state across relaunch', () => { expect(canAutoSwitchGpu(null, 10_000)).toBe(true) expect(canAutoSwitchGpu(10_000, 40_000)).toBe(false) expect(canAutoSwitchGpu(10_000, 55_000)).toBe(true) expect( chooseStartupGpuTarget({ platform: 'win32', headlessSmoke: false, requestedMode: 'auto', handoffTarget: 'low-power', vramSample: null, hasIntegratedGpu: true, }), ).toMatchObject({ target: 'low-power', reason: 'gpu-handoff' }) const args = buildGpuHandoffArgs( ['--fullscreen', '--gpu-handoff', '--gpu-handoff-target=low-power', 'planet-earth://open'], 'default', ) expect(args).toEqual([ '--fullscreen', 'planet-earth://open', '--gpu-handoff', '--gpu-handoff-target=default', ]) expect(readPreReadyGpuHandoff(args)).toEqual({ gpuHandoff: true, gpuHandoffTarget: 'default', }) expect(stripGpuOverrideArgs(args)).toEqual(['--fullscreen', 'planet-earth://open']) }) })