From 1dd21478d3502b8feafd512f6af370d24e509d59 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:41:52 -0600 Subject: [PATCH 01/22] docs: plan for issue 11 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- ...-11-07-issue-11-on-demand-gpu-benchmark.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md diff --git a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md new file mode 100644 index 0000000..e779891 --- /dev/null +++ b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md @@ -0,0 +1,67 @@ +# Plan: GPU compute benchmark runs a 64 MB dispatch every second indefinitely (issue #11) + +Risk tier: High. Not a forced-High area, but it raises three tiers: stateful UI with a new interactive control (not fully provable in jsdom), it alters existing behavior (continuous readout becomes on-demand), and it is async GPU lifecycle code (run, cancel, unmount, visibility). About six files change. + +Domain skills: +- superpowers:test-driven-development: invoke. +- vercel-react-best-practices: invoke (hook state, effect cleanup, stable callbacks, no work in render). +- chrome-devtools-mcp:a11y-debugging: invoke for the live drive (button name, focus ring, target size, live region). If the chrome-devtools MCP fails (locked profile), use Playwright via `npx playwright` with the cached Chromium instead. +- frontend-design: not applicable because the control must follow the existing HUD styling of the GPU panel; no new visual direction. +- dataviz, django, fastapi, expo, payments, email: not applicable because none of that is touched. + +## Acceptance criteria + +1. No GPU work on mount: rendering the map (and `useGPUCompute`) calls neither `navigator.gpu.requestAdapter`, `requestDevice`, `createBuffer`, nor `queue.submit`. Nothing is allocated until the user activates the "Run benchmark" control. +2. The GPU info panel's COMPUTE item contains a native `` that ignores clicks while running. +- `src/components/GPUInfoPanel.test.jsx`: add tests (button present/absent, name, click and keyboard activation via user-event, aria-disabled while running and no call, live region). Existing tests unchanged; they render without the new prop, so the prop must be optional. +- `src/components/MapView.jsx`: pass `benchmark={{ supported, running, onRun: run }}` from `useGPUCompute()`; memoize it. +- `src/index.css`: `.gpu-bench-btn` (pointer-events: auto; min-width and min-height 24px; background none; 1px `--border-active` border; `color: var(--accent)`; font inherit; cursor pointer), `.gpu-bench-btn:hover`, `.gpu-bench-btn:focus-visible` (2px solid `--accent`, offset 2px), `.gpu-bench-btn[aria-disabled='true']` (`color: var(--text-dim)`, cursor default). Only add `color:` rules you also add to `TEXT_PAIRS`. +- `src/styles.test.js`: add the new `color:` selectors to `TEXT_PAIRS` (bg `overMap`) and a 24x24 target-size assertion for `.gpu-bench-btn`. +- `README.md`: GPU info panel bullet and the Known limitations line about the benchmark. + +## Order of work + +1. Pure helpers (`median`, `formatThroughput`) with tests. +2. Hook tests red, then the hook: no work on mount; sequential dispatches; destroy after; hidden before and mid-run; overlap guard; unmount mid-run; no adapter; failure path. +3. Panel tests red, then the panel and MapView wiring. +4. CSS and the styles test table. +5. README. +6. Gate, then the live drive. + +## Risks + +- A stuck `running` state (a promise that never settles) would leave the button permanently disabled. Mitigation: never destroy the device on hide while awaiting; `finally` always clears. +- Layout: the 24px button grows the wide panel's height. It is bottom-right at `bottom: 40px`; check it still clears the layer panel and attribution at 1440x900. +- `.gpu-info-panel` has `pointer-events: none`; forgetting `pointer-events: auto` on the button makes it unclickable with a mouse while still passing keyboard tests. +- Existing `GPUInfoPanel` tests render without `benchmark`; the prop must default safely. + +## Proof + +- AC1, 3, 5, 6, 7, 8, 10: `src/hooks/useGPUCompute.test.js` with mocked `navigator.gpu`: no calls on mount; 5 submits, each only after the previous `onSubmittedWorkDone` resolves (submit count checked while a deferred is pending); `buffer.destroy` and `device.destroy` called after completion, after stop, and after a throw; hidden before run means `requestAdapter` not called; hidden mid-run stops at the next dispatch and shows `Stopped`; second `run()` during a run does not request a second adapter; unmount mid-run destroys and further deferred resolution submits nothing; null adapter gives `supported: false` and `--`. +- AC4: helper tests (`median`, `formatThroughput`) and a full-run test asserting the `~X.X GB/s est.` value. +- AC2, 7, 9, 10: `src/components/GPUInfoPanel.test.jsx`. +- AC11: `src/styles.test.js` table and target size; existing suite unchanged. +- Live drive (build + `npm run preview`, Playwright or chrome-devtools): headless Chromium has no WebGPU, so (a) confirm the no-WebGPU state: no button, COMPUTE `--`; (b) inject a mock `navigator.gpu` with an init script and drive a run by Tab plus Enter and by mouse click: `Running...`, then `~X GB/s est.`, aria-disabled while running, focus ring visible, button box at least 24x24; (c) edge paths with the mock: hide the tab mid-run (override `visibilityState` and dispatch `visibilitychange`) shows `Stopped`; double activation runs once; (d) measure layout at 375x812, 768x1024, 1440x900 per AC11, including the button's box at 1440 and its absence at 768 and 375. If the user's real Chrome (claude-in-chrome) has WebGPU, try a real run and record the number. From 60c17ab40217bab96afc371176737a58232068a4 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:44:02 -0600 Subject: [PATCH 02/22] fix: make the GPU compute benchmark an on-demand 5-dispatch run (#11) useGPUCompute no longer allocates or dispatches on mount. run() requests a device, performs 5 sequential dispatches, reports the median as an estimate, and destroys the buffer and device afterwards. Runs do not overlap, stop when the tab is hidden, and clean up on unmount. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/hooks/useGPUCompute.js | 181 +++++++++++++-------- src/hooks/useGPUCompute.test.js | 273 +++++++++++++++++++++++++++++++- 2 files changed, 386 insertions(+), 68 deletions(-) diff --git a/src/hooks/useGPUCompute.js b/src/hooks/useGPUCompute.js index 821dbae..6029099 100644 --- a/src/hooks/useGPUCompute.js +++ b/src/hooks/useGPUCompute.js @@ -1,8 +1,12 @@ -import { useState, useEffect } from 'react' +import { useState, useEffect, useRef, useCallback } from 'react' const COUNT = 65535 * 256 // 16,776,960 floats ~64MB, exactly 65535 workgroups const WORKGROUP_SIZE = 256 const WORKGROUPS = COUNT / WORKGROUP_SIZE // 65535 +// 128MB traffic per dispatch: 64MB read + 64MB write +const BYTES_PER_DISPATCH_GB = 0.128 + +export const BENCHMARK_DISPATCHES = 5 const SHADER = ` @group(0) @binding(0) var data: array; @@ -16,75 +20,122 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } ` +export function median(values) { + const sorted = [...values].sort((a, b) => a - b) + const mid = Math.floor(sorted.length / 2) + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2 +} + +// CPU-timed, so it includes submit and callback latency: an estimate. +export function formatThroughput(seconds) { + return `~${(BYTES_PER_DISPATCH_GB / seconds).toFixed(1)} GB/s est.` +} + +function isHidden() { + return document.visibilityState === 'hidden' +} + export function useGPUCompute() { - const [state, setState] = useState({ throughput: '--', supported: false }) + const [state, setState] = useState(() => ({ + throughput: '--', + supported: Boolean(navigator.gpu), + running: false, + })) + + const activeRef = useRef(false) + const stopRef = useRef(false) + const mountedRef = useRef(false) + const resourcesRef = useRef({ buffer: null, device: null }) + + const release = useCallback(() => { + const res = resourcesRef.current + res.buffer?.destroy() + res.device?.destroy() + res.buffer = null + res.device = null + }, []) useEffect(() => { - if (!navigator.gpu) return - - let intervalId = null - let device = null - let buf = null - - async function init() { - try { - const adapter = await navigator.gpu.requestAdapter() - if (!adapter) return - - device = await adapter.requestDevice() - - buf = device.createBuffer({ - size: COUNT * 4, - usage: GPUBufferUsage.STORAGE, - mappedAtCreation: true, - }) - new Float32Array(buf.getMappedRange()).fill(1.0) - buf.unmap() - - const module = device.createShaderModule({ code: SHADER }) - const pipeline = device.createComputePipeline({ - layout: 'auto', - compute: { module, entryPoint: 'main' }, - }) - const bindGroup = device.createBindGroup({ - layout: pipeline.getBindGroupLayout(0), - entries: [{ binding: 0, resource: { buffer: buf } }], - }) - - setState({ throughput: '...', supported: true }) - - intervalId = setInterval(async () => { - try { - const t0 = performance.now() - const encoder = device.createCommandEncoder() - const pass = encoder.beginComputePass() - pass.setPipeline(pipeline) - pass.setBindGroup(0, bindGroup) - pass.dispatchWorkgroups(WORKGROUPS) - pass.end() - device.queue.submit([encoder.finish()]) - await device.queue.onSubmittedWorkDone() - const elapsed = (performance.now() - t0) / 1000 - // 128MB traffic per dispatch: 64MB read + 64MB write - const gbps = (0.128 / elapsed).toFixed(1) - setState({ throughput: `${gbps} GB/s`, supported: true }) - } catch { - setState({ throughput: '--', supported: false }) - } - }, 1000) - } catch { - setState({ throughput: '--', supported: false }) - } + mountedRef.current = true + return () => { + mountedRef.current = false + stopRef.current = true + release() } + }, [release]) - init() + const run = useCallback(async () => { + if (activeRef.current || !navigator.gpu || isHidden()) return + activeRef.current = true + stopRef.current = false - return () => { - if (intervalId) clearInterval(intervalId) - buf?.destroy() - device?.destroy() + const update = (next) => { + if (mountedRef.current) setState((s) => ({ ...s, ...next })) } - }, []) + const onVisibility = () => { + if (isHidden()) stopRef.current = true + } + document.addEventListener('visibilitychange', onVisibility) + update({ running: true, throughput: 'Running...' }) + + const res = resourcesRef.current + try { + const adapter = await navigator.gpu.requestAdapter() + if (!adapter) { + update({ supported: false, throughput: '--' }) + return + } + + res.device = await adapter.requestDevice() + const device = res.device + + res.buffer = device.createBuffer({ + size: COUNT * 4, + usage: GPUBufferUsage.STORAGE, + mappedAtCreation: true, + }) + new Float32Array(res.buffer.getMappedRange()).fill(1.0) + res.buffer.unmap() + + const module = device.createShaderModule({ code: SHADER }) + const pipeline = device.createComputePipeline({ + layout: 'auto', + compute: { module, entryPoint: 'main' }, + }) + const bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [{ binding: 0, resource: { buffer: res.buffer } }], + }) - return state -} \ No newline at end of file + const timings = [] + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + if (stopRef.current) break + const t0 = performance.now() + const encoder = device.createCommandEncoder() + const pass = encoder.beginComputePass() + pass.setPipeline(pipeline) + pass.setBindGroup(0, bindGroup) + pass.dispatchWorkgroups(WORKGROUPS) + pass.end() + device.queue.submit([encoder.finish()]) + await device.queue.onSubmittedWorkDone() + timings.push((performance.now() - t0) / 1000) + } + + if (stopRef.current || timings.length < BENCHMARK_DISPATCHES) { + update({ throughput: 'Stopped' }) + } else { + update({ throughput: formatThroughput(median(timings)) }) + } + } catch { + update({ throughput: 'Failed' }) + } finally { + document.removeEventListener('visibilitychange', onVisibility) + release() + activeRef.current = false + update({ running: false }) + } + }, [release]) + + return { ...state, run } +} diff --git a/src/hooks/useGPUCompute.test.js b/src/hooks/useGPUCompute.test.js index dfba79c..a9ef187 100644 --- a/src/hooks/useGPUCompute.test.js +++ b/src/hooks/useGPUCompute.test.js @@ -1,6 +1,6 @@ -import { describe, it, expect } from 'vitest' -import { renderHook } from '@testing-library/react' -import { useGPUCompute } from './useGPUCompute.js' +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute, median, formatThroughput, BENCHMARK_DISPATCHES } from './useGPUCompute.js' describe('useGPUCompute', () => { it('returns supported: false and throughput: "--" when navigator.gpu is undefined', () => { @@ -10,3 +10,270 @@ describe('useGPUCompute', () => { expect(result.current.throughput).toBe('--') }) }) + +describe('median', () => { + it('returns the middle value of an odd-length list', () => { + expect(median([5, 1, 3, 2, 4])).toBe(3) + }) + + it('returns the mean of the two middle values of an even-length list', () => { + expect(median([4, 1, 3, 2])).toBe(2.5) + }) + + it('does not reorder its input', () => { + const values = [3, 1, 2] + median(values) + expect(values).toEqual([3, 1, 2]) + }) +}) + +describe('formatThroughput', () => { + it('formats 128 MB over the elapsed seconds as an estimate in GB/s', () => { + expect(formatThroughput(0.1)).toBe('~1.3 GB/s est.') + expect(formatThroughput(0.001)).toBe('~128.0 GB/s est.') + }) +}) + +// ─── Mocked WebGPU ─── + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +function installGPU({ adapter = true, failPipeline = false } = {}) { + const pending = [] + const buffer = { + getMappedRange: vi.fn(() => new ArrayBuffer(16)), + unmap: vi.fn(), + destroy: vi.fn(), + } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + return d.promise + }), + } + const pass = { + setPipeline: vi.fn(), + setBindGroup: vi.fn(), + dispatchWorkgroups: vi.fn(), + end: vi.fn(), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => { + if (failPipeline) throw new Error('pipeline failed') + return { getBindGroupLayout: () => ({}) } + }), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ + beginComputePass: () => pass, + finish: () => ({}), + })), + destroy: vi.fn(), + } + const gpuAdapter = { requestDevice: vi.fn(async () => device) } + const gpu = { requestAdapter: vi.fn(async () => (adapter ? gpuAdapter : null)) } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() +}) + +async function resolveDispatch(mock, k) { + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1)) + await waitFor(() => expect(mock.pending.length).toBe(k + 1)) + await act(async () => { + mock.pending[k].resolve() + }) +} + +describe('useGPUCompute with WebGPU', () => { + it('does no GPU work on mount', () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(mock.gpuAdapter.requestDevice).not.toHaveBeenCalled() + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(result.current.supported).toBe(true) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('runs the dispatches strictly in sequence and reports the estimate', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + expect(result.current.running).toBe(true) + expect(result.current.throughput).toBe('Running...') + + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1)) + // The next dispatch must wait for this one to finish. + await act(async () => {}) + expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1) + await act(async () => { + mock.pending[k].resolve() + }) + } + await act(async () => { + await done + }) + + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(mock.gpuAdapter.requestDevice).toHaveBeenCalledTimes(1) + expect(mock.device.createBuffer).toHaveBeenCalledTimes(1) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toMatch(/^~\d+\.\d GB\/s est\.$/) + }) + + it('schedules nothing after a run', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) await resolveDispatch(mock, k) + await act(async () => { + await done + }) + await act(async () => { + await new Promise((r) => setTimeout(r, 1100)) + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + }) + + it('does nothing when activated while the document is hidden', async () => { + const mock = installGPU() + setVisibility('hidden') + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('stops before the next dispatch when the tab is hidden mid-run', async () => { + const mock = installGPU() + setVisibility('visible') + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(1)) + setVisibility('hidden') + act(() => { + document.dispatchEvent(new Event('visibilitychange')) + }) + await act(async () => { + mock.pending[0].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(1) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('ignores activation while a run is in progress', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await act(async () => { + await result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) await resolveDispatch(mock, k) + await act(async () => { + await done + }) + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + }) + + it('keeps run stable across renders', async () => { + installGPU() + const { result, rerender } = renderHook(() => useGPUCompute()) + const first = result.current.run + rerender() + expect(result.current.run).toBe(first) + }) + + it('stops and destroys on unmount mid-run without updating state', async () => { + const mock = installGPU() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { result, unmount } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(1)) + unmount() + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + await act(async () => { + mock.pending[0].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(1) + expect(errorSpy).not.toHaveBeenCalled() + errorSpy.mockRestore() + }) + + it('reports unsupported when requestAdapter returns null', async () => { + const mock = installGPU({ adapter: false }) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(result.current.supported).toBe(false) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('shows Failed and destroys what it allocated when a run throws', async () => { + const mock = installGPU({ failPipeline: true }) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(result.current.supported).toBe(true) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) +}) From 5c6d86dd2b47a3781cfff3994ebdd31f7f01f282 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:44:36 -0600 Subject: [PATCH 03/22] feat: add a keyboard accessible RUN control for the compute benchmark (#11) The COMPUTE item gets a native button (accessible name "Run compute benchmark") that is aria-disabled while a run is in progress, and the COMPUTE value becomes a polite live region. MapView wires it to useGPUCompute. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/components/GPUInfoPanel.jsx | 23 ++++++++- src/components/GPUInfoPanel.test.jsx | 73 +++++++++++++++++++++++++++- src/components/MapView.jsx | 10 +++- 3 files changed, 101 insertions(+), 5 deletions(-) diff --git a/src/components/GPUInfoPanel.jsx b/src/components/GPUInfoPanel.jsx index 1da9b43..3d25d88 100644 --- a/src/components/GPUInfoPanel.jsx +++ b/src/components/GPUInfoPanel.jsx @@ -30,7 +30,23 @@ function Sparkline({ history }) { ) } -export function GPUInfoPanel({ capabilities }) { +const NO_BENCHMARK = { supported: false, running: false, onRun: undefined } + +function BenchmarkButton({ running, onRun }) { + return ( + + ) +} + +export function GPUInfoPanel({ capabilities, benchmark = NO_BENCHMARK }) { const { tier, adapterInfo, activePointCount, frameTime, frameHistory, gpuThroughput, heatmapComputeMs } = capabilities const deviceLabel = @@ -67,7 +83,10 @@ export function GPUInfoPanel({ capabilities }) { | COMPUTE - {gpuThroughput} + {gpuThroughput} + {benchmark.supported ? ( + + ) : null} | diff --git a/src/components/GPUInfoPanel.test.jsx b/src/components/GPUInfoPanel.test.jsx index e057758..0d69668 100644 --- a/src/components/GPUInfoPanel.test.jsx +++ b/src/components/GPUInfoPanel.test.jsx @@ -1,6 +1,7 @@ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' import { render, screen } from '@testing-library/react' import { GPUInfoPanel } from './GPUInfoPanel.jsx' +import userEvent from '@testing-library/user-event' const base = { tier: 'webgpu', @@ -90,3 +91,73 @@ describe('GPUInfoPanel secondary stats', () => { expect(visible).toEqual(['RENDER', '|', 'PTS', '|', 'FRAME']) }) }) + +describe('GPUInfoPanel benchmark control', () => { + const bench = (over = {}) => ({ supported: true, running: false, onRun: vi.fn(), ...over }) + + it('has no RUN button when the benchmark prop is omitted', () => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + }) + + it('has no RUN button when the benchmark is unsupported', () => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + expect(screen.getByText('COMPUTE').closest('.gpu-info-item')).toHaveTextContent('--') + }) + + it('renders a native RUN button inside the COMPUTE item when supported', () => { + render() + const button = screen.getByRole('button', { name: 'Run compute benchmark' }) + expect(button.tagName).toBe('BUTTON') + expect(button).toHaveAttribute('type', 'button') + expect(button).toHaveTextContent('RUN') + expect(button).toHaveClass('gpu-bench-btn') + expect(button.closest('.gpu-info-item')).toBe(screen.getByText('COMPUTE').closest('.gpu-info-item')) + }) + + it('runs on click', async () => { + const b = bench() + render() + await userEvent.click(screen.getByRole('button', { name: 'Run compute benchmark' })) + expect(b.onRun).toHaveBeenCalledTimes(1) + }) + + it('is reachable with Tab and runs on Enter and on Space', async () => { + const user = userEvent.setup() + const b = bench() + render() + await user.tab() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).toHaveFocus() + await user.keyboard('{Enter}') + expect(b.onRun).toHaveBeenCalledTimes(1) + await user.keyboard(' ') + expect(b.onRun).toHaveBeenCalledTimes(2) + }) + + it('is aria-disabled, still focusable, and ignores activation while running', async () => { + const user = userEvent.setup() + const b = bench({ running: true }) + render() + const button = screen.getByRole('button', { name: 'Run compute benchmark' }) + expect(button).toHaveAttribute('aria-disabled', 'true') + expect(button).not.toBeDisabled() + await user.tab() + expect(button).toHaveFocus() + await user.keyboard('{Enter}') + await user.click(button) + expect(b.onRun).not.toHaveBeenCalled() + }) + + it('has no aria-disabled when idle', () => { + render() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).not.toHaveAttribute('aria-disabled') + }) + + it('announces the COMPUTE value through a polite live region', () => { + render() + const value = screen.getByText('~1.3 GB/s est.') + expect(value).toHaveAttribute('aria-live', 'polite') + expect(value).not.toContainElement(screen.getByRole('button', { name: 'Run compute benchmark' })) + }) +}) diff --git a/src/components/MapView.jsx b/src/components/MapView.jsx index b653d80..97c9581 100644 --- a/src/components/MapView.jsx +++ b/src/components/MapView.jsx @@ -46,7 +46,8 @@ export function MapView({ layerData, heatmapComputeMs }) { const { viewport, setViewport, layerVisibility, setSelectedFeature } = useMapStore() const gpuBase = useGPUCapabilities() const { frameTime, frameHistory } = useFrameTime() - const { throughput: gpuThroughput } = useGPUCompute() + const { throughput: gpuThroughput, supported: benchSupported, running: benchRunning, run: runBenchmark } = + useGPUCompute() const activePointCount = (layerVisibility.airports ? (layerData.airports?.length ?? 0) : 0) + @@ -58,6 +59,11 @@ export function MapView({ layerData, heatmapComputeMs }) { [gpuBase, activePointCount, frameTime, frameHistory, gpuThroughput, heatmapComputeMs] ) + const benchmark = useMemo( + () => ({ supported: benchSupported, running: benchRunning, onRun: runBenchmark }), + [benchSupported, benchRunning, runBenchmark] + ) + const onFeatureClick = useCallback( (feature) => setSelectedFeature(feature), [setSelectedFeature] @@ -79,7 +85,7 @@ export function MapView({ layerData, heatmapComputeMs }) {
- +
) } \ No newline at end of file From a3c0196594ab1feea03f72cdae995acc3a3700e9 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:44:56 -0600 Subject: [PATCH 04/22] style: style the compute benchmark RUN button and cover it in the contrast table (#11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/index.css | 29 +++++++++++++++++++++++++++++ src/styles.test.js | 8 ++++++++ 2 files changed, 37 insertions(+) diff --git a/src/index.css b/src/index.css index dca8cff..b3801ea 100644 --- a/src/index.css +++ b/src/index.css @@ -641,6 +641,35 @@ body::before { color: var(--text-dim); } +/* The panel ignores pointer input so it never blocks the map; the button opts back in. */ +.gpu-bench-btn { + pointer-events: auto; + min-width: 24px; + min-height: 24px; + padding: 0 6px; + background: none; + border: 1px solid var(--border-active); + color: var(--accent); + font: inherit; + letter-spacing: inherit; + cursor: pointer; +} + +.gpu-bench-btn:hover { + border-color: var(--accent); +} + +.gpu-bench-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.gpu-bench-btn[aria-disabled='true'] { + color: var(--text-dim); + border-color: var(--border); + cursor: default; +} + /* ─── RESPONSIVE ─── */ @media (max-width: 1024px) { diff --git a/src/styles.test.js b/src/styles.test.js index 106856a..d33be0c 100644 --- a/src/styles.test.js +++ b/src/styles.test.js @@ -161,6 +161,8 @@ const TEXT_PAIRS = [ { selector: '.gpu-info-val.warn', bg: 'overMap' }, { selector: '.gpu-info-val.err', bg: 'overMap' }, { selector: '.gpu-info-sep', bg: 'overMap' }, + { selector: '.gpu-bench-btn', bg: 'overMap' }, + { selector: ".gpu-bench-btn[aria-disabled='true']", bg: 'overMap' }, ] function textRatio({ selector, bg, fg }) { @@ -262,6 +264,12 @@ describe('target size (WCAG 2.5.8, 24x24)', () => { expect(px(d.height)).toBeGreaterThanOrEqual(24) }) + it('compute benchmark RUN button is at least 24x24', () => { + const d = rule('.gpu-bench-btn') + expect(px(d['min-width'])).toBeGreaterThanOrEqual(24) + expect(px(d['min-height'])).toBeGreaterThanOrEqual(24) + }) + it('stress slider input is at least 24px tall', () => { expect(px(rule('.stress-slider').height)).toBeGreaterThanOrEqual(24) }) From 7e27de2929ef40b56f0612cf077d193e03a330d5 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:45:03 -0600 Subject: [PATCH 05/22] docs: describe the on-demand compute benchmark in the README (#11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5760948..cd6ca82 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Built with React 19, Vite, MapLibre GL (through `react-map-gl`), deck.gl (`@deck - **Sea ports layer:** the bundled ports GeoJSON, drawn as green points. Click a point to see its properties. - **Heatmap layer (WebGPU only):** a two-pass compute shader bins airport positions into a 1024 x 512 grid and colorizes it into a bitmap overlay. It runs once, after the airports load. The layer toggle appears only after that compute succeeds, so it is hidden while airports load, when WebGPU is unavailable, and when the airports fetch or the compute fails. - **Stress test:** a slider from 0 to 5,000,000 points in steps of 100,000. Points are generated on the main thread 150 ms after the slider stops moving, then drawn as a deck.gl binary attribute layer. -- **GPU info panel:** adapter name, render tier (`WebGPU`, `WebGL Fallback`, or `Detecting...`), active point count, frame time with a 60-frame sparkline, compute throughput (a 64 MB storage buffer read and written once per second, reported in GB/s), and heatmap compute time. At 1024px wide or less it shows only the render tier, active point count, and frame time. On small screens (see below) it is hidden while a feature popup is open. +- **GPU info panel:** adapter name, render tier (`WebGPU`, `WebGL Fallback`, or `Detecting...`), active point count, frame time with a 60-frame sparkline, an on-demand compute benchmark (press `RUN` next to COMPUTE: 5 sequential dispatches over a 64 MB storage buffer, reported as the median in GB/s, labelled `est.` because it is CPU timed; the buffer and device are freed when the run ends, and the run stops if the tab is hidden), and heatmap compute time. At 1024px wide or less it shows only the render tier, active point count, and frame time. On small screens (see below) it is hidden while a feature popup is open. - **Small screens** (640px wide or less, or up to 1024px wide and 500px tall or less): the layer panel starts collapsed behind a "Sensor layers" button, the header drops the coordinates and status, and the feature popup opens as a bottom sheet. ## Requirements @@ -75,5 +75,5 @@ public/data/ports.geojson bundled ports data - The basemap needs CARTO to be reachable; offline, only the overlays draw. - The heatmap runs once per page load from the first non-empty airports list and does not update afterwards. - Stress points are generated on the main thread. Large counts (millions of points) briefly block the UI once the slider settles. -- The COMPUTE throughput benchmark keeps a 64 MB GPU buffer allocated and dispatches every second for as long as the map is mounted. +- The COMPUTE benchmark is CPU timed (submit to `onSubmittedWorkDone`), so it includes driver and callback latency and reads lower than the real memory bandwidth. The `RUN` control is hidden at 1024px wide or less along with the rest of COMPUTE. - Unit tests run in jsdom, which has no WebGL or WebGPU. GPU code paths are covered by mocks and pure helpers only; check rendering in a real browser. From d33cb816f04549030988b52d414d2811ad26766f Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:48:18 -0600 Subject: [PATCH 06/22] test: add failing test for RUN shown when requestAdapter returns null (#11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- .../GPUInfoPanel.benchmarkTier.test.jsx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/components/GPUInfoPanel.benchmarkTier.test.jsx diff --git a/src/components/GPUInfoPanel.benchmarkTier.test.jsx b/src/components/GPUInfoPanel.benchmarkTier.test.jsx new file mode 100644 index 0000000..0fb7111 --- /dev/null +++ b/src/components/GPUInfoPanel.benchmarkTier.test.jsx @@ -0,0 +1,28 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { GPUInfoPanel } from './GPUInfoPanel.jsx' + +// Browsers can expose navigator.gpu while requestAdapter() returns null +// (headless Chromium does). useGPUCapabilities reports that as 'no-webgpu', +// and the RUN control must stay hidden then (issue #11, AC10). +const base = { + adapterInfo: {}, + activePointCount: 0, + frameTime: 16, + frameHistory: [], + gpuThroughput: '--', +} +const benchmark = { supported: true, running: false, onRun: vi.fn() } + +describe('GPUInfoPanel RUN control and the detected tier', () => { + it.each(['no-webgpu', 'unknown'])('hides the RUN button when the tier is %s', (tier) => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + expect(screen.getByText('COMPUTE').closest('.gpu-info-item')).toHaveTextContent('--') + }) + + it('shows the RUN button when the tier is webgpu', () => { + render() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).toBeInTheDocument() + }) +}) From 443985db39d01aca42c8226080bd17d608661cd7 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 19:48:40 -0600 Subject: [PATCH 07/22] fix: hide the RUN control unless the detected tier is WebGPU (#11) Browsers can expose navigator.gpu while requestAdapter() returns null. The benchmark hook may not probe an adapter on mount, so the panel uses the tier from useGPUCapabilities. The plan's AC1 and AC10 are updated to match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md | 8 ++++---- src/components/GPUInfoPanel.jsx | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md index e779891..85805fe 100644 --- a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md +++ b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md @@ -11,7 +11,7 @@ Domain skills: ## Acceptance criteria -1. No GPU work on mount: rendering the map (and `useGPUCompute`) calls neither `navigator.gpu.requestAdapter`, `requestDevice`, `createBuffer`, nor `queue.submit`. Nothing is allocated until the user activates the "Run benchmark" control. +1. No benchmark GPU work on mount: `useGPUCompute` calls neither `navigator.gpu.requestAdapter`, `requestDevice`, `createBuffer`, nor `queue.submit`. Nothing is allocated for the benchmark until the user activates the "Run benchmark" control. (The map's existing `useGPUCapabilities` adapter probe and the one-shot `useGPUHeatmap` run are unchanged and out of scope.) 2. The GPU info panel's COMPUTE item contains a native `` that ignores clicks while running. +- `src/components/GPUInfoPanel.jsx`: new props `benchmark = { supported, running, onRun }` (separate from `capabilities`). COMPUTE value gets `aria-live="polite"`; when `benchmark.supported` and the tier is `webgpu` render `` that ignores clicks while running. - `src/components/GPUInfoPanel.test.jsx`: add tests (button present/absent, name, click and keyboard activation via user-event, aria-disabled while running and no call, live region). Existing tests unchanged; they render without the new prop, so the prop must be optional. - `src/components/MapView.jsx`: pass `benchmark={{ supported, running, onRun: run }}` from `useGPUCompute()`; memoize it. - `src/index.css`: `.gpu-bench-btn` (pointer-events: auto; min-width and min-height 24px; background none; 1px `--border-active` border; `color: var(--accent)`; font inherit; cursor pointer), `.gpu-bench-btn:hover`, `.gpu-bench-btn:focus-visible` (2px solid `--accent`, offset 2px), `.gpu-bench-btn[aria-disabled='true']` (`color: var(--text-dim)`, cursor default). Only add `color:` rules you also add to `TEXT_PAIRS`. @@ -62,6 +62,6 @@ Domain skills: - AC1, 3, 5, 6, 7, 8, 10: `src/hooks/useGPUCompute.test.js` with mocked `navigator.gpu`: no calls on mount; 5 submits, each only after the previous `onSubmittedWorkDone` resolves (submit count checked while a deferred is pending); `buffer.destroy` and `device.destroy` called after completion, after stop, and after a throw; hidden before run means `requestAdapter` not called; hidden mid-run stops at the next dispatch and shows `Stopped`; second `run()` during a run does not request a second adapter; unmount mid-run destroys and further deferred resolution submits nothing; null adapter gives `supported: false` and `--`. - AC4: helper tests (`median`, `formatThroughput`) and a full-run test asserting the `~X.X GB/s est.` value. -- AC2, 7, 9, 10: `src/components/GPUInfoPanel.test.jsx`. +- AC2, 7, 9, 10: `src/components/GPUInfoPanel.test.jsx`; the tier gate in AC10 (found in the live drive) in `src/components/GPUInfoPanel.benchmarkTier.test.jsx`. - AC11: `src/styles.test.js` table and target size; existing suite unchanged. - Live drive (build + `npm run preview`, Playwright or chrome-devtools): headless Chromium has no WebGPU, so (a) confirm the no-WebGPU state: no button, COMPUTE `--`; (b) inject a mock `navigator.gpu` with an init script and drive a run by Tab plus Enter and by mouse click: `Running...`, then `~X GB/s est.`, aria-disabled while running, focus ring visible, button box at least 24x24; (c) edge paths with the mock: hide the tab mid-run (override `visibilityState` and dispatch `visibilitychange`) shows `Stopped`; double activation runs once; (d) measure layout at 375x812, 768x1024, 1440x900 per AC11, including the button's box at 1440 and its absence at 768 and 375. If the user's real Chrome (claude-in-chrome) has WebGPU, try a real run and record the number. diff --git a/src/components/GPUInfoPanel.jsx b/src/components/GPUInfoPanel.jsx index 3d25d88..733b33d 100644 --- a/src/components/GPUInfoPanel.jsx +++ b/src/components/GPUInfoPanel.jsx @@ -84,7 +84,8 @@ export function GPUInfoPanel({ capabilities, benchmark = NO_BENCHMARK }) { COMPUTE {gpuThroughput} - {benchmark.supported ? ( + {/* navigator.gpu can exist with no adapter, so also require the detected tier. */} + {benchmark.supported && isWebGPU ? ( ) : null} From 0c12766f2b60dbfe25d24c0e8987271269ca8a34 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 20:01:28 -0600 Subject: [PATCH 08/22] test: drop the vacuous console.error check and model error scopes and device loss in the GPU mock (#11) The console.error spy cannot detect a state update after unmount in React 19, so the unmount test no longer claims to. The mock device gains pushErrorScope, popErrorScope (resolving null), and a never-settling lost promise. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/hooks/useGPUCompute.test.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/hooks/useGPUCompute.test.js b/src/hooks/useGPUCompute.test.js index a9ef187..46c0b1a 100644 --- a/src/hooks/useGPUCompute.test.js +++ b/src/hooks/useGPUCompute.test.js @@ -79,6 +79,9 @@ function installGPU({ adapter = true, failPipeline = false } = {}) { finish: () => ({}), })), destroy: vi.fn(), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => null), + lost: new Promise(() => {}), } const gpuAdapter = { requestDevice: vi.fn(async () => device) } const gpu = { requestAdapter: vi.fn(async () => (adapter ? gpuAdapter : null)) } @@ -230,9 +233,8 @@ describe('useGPUCompute with WebGPU', () => { expect(result.current.run).toBe(first) }) - it('stops and destroys on unmount mid-run without updating state', async () => { + it('stops and destroys on unmount mid-run', async () => { const mock = installGPU() - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) const { result, unmount } = renderHook(() => useGPUCompute()) let done act(() => { @@ -247,8 +249,6 @@ describe('useGPUCompute with WebGPU', () => { await done }) expect(mock.queue.submit).toHaveBeenCalledTimes(1) - expect(errorSpy).not.toHaveBeenCalled() - errorSpy.mockRestore() }) it('reports unsupported when requestAdapter returns null', async () => { From 38abf459b7785d57fe0aa63cdf0b05ad99dc5131 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 20:01:53 -0600 Subject: [PATCH 09/22] test: add failing test for allocation after a stop during GPU setup (#11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/hooks/useGPUCompute.setupStop.test.js | 147 ++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 src/hooks/useGPUCompute.setupStop.test.js diff --git a/src/hooks/useGPUCompute.setupStop.test.js b/src/hooks/useGPUCompute.setupStop.test.js new file mode 100644 index 0000000..763b583 --- /dev/null +++ b/src/hooks/useGPUCompute.setupStop.test.js @@ -0,0 +1,147 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute } from './useGPUCompute.js' + +// Issue #11: a stop (hidden tab or unmount) during adapter or device setup must +// bail before the 64 MB buffer is allocated, and run() after unmount does nothing. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +function hide() { + setVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute stop during setup', () => { + it('stops before allocating when hidden while requestAdapter is pending', async () => { + const mock = installGPU({ holdAdapter: true }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpu.requestAdapter).toHaveBeenCalled()) + act(() => hide()) + await act(async () => { + mock.adapterGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + if (mock.gpuAdapter.requestDevice.mock.calls.length) expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('stops before allocating and destroys the device when hidden while requestDevice is pending', async () => { + const mock = installGPU({ holdDevice: true }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpuAdapter.requestDevice).toHaveBeenCalled()) + act(() => hide()) + await act(async () => { + mock.deviceGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('does not allocate and destroys the device when unmounted while requestDevice is pending', async () => { + const mock = installGPU({ holdDevice: true }) + const { result, unmount } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpuAdapter.requestDevice).toHaveBeenCalled()) + unmount() + await act(async () => { + mock.deviceGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + }) + + it('does nothing when run() is called after unmount', async () => { + const mock = installGPU() + const { result, unmount } = renderHook(() => useGPUCompute()) + const run = result.current.run + unmount() + await act(async () => { + await run() + }) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(mock.device.createBuffer).not.toHaveBeenCalled() + }) +}) From bd03e4ae9fb6aaa47772811a490e73e04ca25df4 Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 20:02:25 -0600 Subject: [PATCH 10/22] fix: bail before allocating when the benchmark is stopped during setup (#11) A hidden tab or unmount while requestAdapter() or requestDevice() is pending now ends the run before the 64 MB buffer is allocated, and a device that arrives late is destroyed. run() after unmount does nothing. The plan's AC6, AC8, and Proof are updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- ...2026-11-07-issue-11-on-demand-gpu-benchmark.md | 6 +++--- src/hooks/useGPUCompute.js | 15 +++++++++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md index 85805fe..fbad1f5 100644 --- a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md +++ b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md @@ -16,9 +16,9 @@ Domain skills: 3. A run requests one adapter and one device, allocates the 64 MB storage buffer once, then performs exactly `BENCHMARK_DISPATCHES` (5) dispatches strictly in sequence: dispatch k+1 is not submitted until `queue.onSubmittedWorkDone()` for dispatch k has resolved. No `setInterval`; nothing is scheduled after the run. 4. A run that completes shows the median of the 5 timings as `~X.X GB/s est.` (128 MB traffic per dispatch, CPU timed, so labelled as an estimate). 5. After every run, completed, stopped, or failed, `buffer.destroy()` and `device.destroy()` are called, so the 64 MB buffer and the device are held only for the run's duration. -6. No GPU work while the tab is hidden: activating the control while `document.visibilityState === 'hidden'` does nothing; if the tab becomes hidden mid-run, no further dispatch is submitted (the one in flight is allowed to finish), the resources are destroyed, and COMPUTE shows `Stopped`. +6. No GPU work while the tab is hidden: activating the control while `document.visibilityState === 'hidden'` does nothing; if the tab becomes hidden mid-run, no further dispatch is submitted (the one in flight is allowed to finish), the resources are destroyed, and COMPUTE shows `Stopped`. This includes setup: hidden while `requestAdapter()` or `requestDevice()` is pending means the run bails right after that await, before the buffer is allocated, destroys a device that arrives late, and shows `Stopped`. 7. Runs never overlap: activating the control while a run is in progress does nothing. While running, the button has `aria-disabled="true"` (not `disabled`, so focus is not lost) and COMPUTE shows `Running...`. -8. Unmount mid-run: the run stops before its next dispatch, the buffer and device are destroyed, and no React state update happens after unmount. +8. Unmount mid-run: the run stops before its next dispatch (or, during setup, before the buffer is allocated), the buffer and device are destroyed (a device that arrives after unmount is destroyed when it arrives), and state setters are skipped after unmount (mounted ref). `run()` called after unmount does nothing. 9. Results are announced: the COMPUTE value is a polite live region (`aria-live="polite"`), so `Running...`, the result, `Stopped`, and `Failed` are read by screen readers. 10. When WebGPU is unavailable (`navigator.gpu` undefined, or `requestAdapter()` returns null), the button is absent and COMPUTE shows `--`, as today. Because `useGPUCompute` may not probe an adapter on mount (AC1), the panel also requires the RENDER tier from `useGPUCapabilities` to be `webgpu` before it shows the button, so a browser that exposes `navigator.gpu` with no adapter (headless Chromium does) never shows it; the button is also hidden while the tier is `unknown`. A run that throws for any other reason shows `Failed` and destroys whatever it allocated; the button stays so the user can retry. 11. Prior work preserved: all existing tests pass unchanged. At 1024px wide or less the panel still shows only RENDER, PTS, FRAME (the button lives inside the secondary COMPUTE item and hides with it). At 375x812, 768x1024, and 1440x900: header elements do not overlap pairwise; `.app-header`, `.layer-panel`, `.gpu-info-panel`, and an open `.feature-popup` stay inside the viewport; popup and GPU panel do not overlap at 768. Every new `color:` rule is in `src/styles.test.js`'s `TEXT_PAIRS` and passes 4.5:1. @@ -60,7 +60,7 @@ Domain skills: ## Proof -- AC1, 3, 5, 6, 7, 8, 10: `src/hooks/useGPUCompute.test.js` with mocked `navigator.gpu`: no calls on mount; 5 submits, each only after the previous `onSubmittedWorkDone` resolves (submit count checked while a deferred is pending); `buffer.destroy` and `device.destroy` called after completion, after stop, and after a throw; hidden before run means `requestAdapter` not called; hidden mid-run stops at the next dispatch and shows `Stopped`; second `run()` during a run does not request a second adapter; unmount mid-run destroys and further deferred resolution submits nothing; null adapter gives `supported: false` and `--`. +- AC1, 3, 5, 6, 7, 8, 10: `src/hooks/useGPUCompute.test.js` with mocked `navigator.gpu`: no calls on mount; 5 submits, each only after the previous `onSubmittedWorkDone` resolves (submit count checked while a deferred is pending); `buffer.destroy` and `device.destroy` called after completion, after stop, and after a throw; hidden before run means `requestAdapter` not called; hidden mid-run stops at the next dispatch and shows `Stopped`; second `run()` during a run does not request a second adapter; unmount mid-run destroys and further deferred resolution submits nothing (React 19 does not warn on a state update after unmount, so the mounted-ref guard is reviewed, not asserted); `src/hooks/useGPUCompute.setupStop.test.js`: hidden during pending `requestAdapter` or `requestDevice`, and unmount during pending `requestDevice`, never call `createBuffer` and destroy a late device, and `run()` after unmount requests no adapter; null adapter gives `supported: false` and `--`. - AC4: helper tests (`median`, `formatThroughput`) and a full-run test asserting the `~X.X GB/s est.` value. - AC2, 7, 9, 10: `src/components/GPUInfoPanel.test.jsx`; the tier gate in AC10 (found in the live drive) in `src/components/GPUInfoPanel.benchmarkTier.test.jsx`. - AC11: `src/styles.test.js` table and target size; existing suite unchanged. diff --git a/src/hooks/useGPUCompute.js b/src/hooks/useGPUCompute.js index 6029099..0ad184e 100644 --- a/src/hooks/useGPUCompute.js +++ b/src/hooks/useGPUCompute.js @@ -65,9 +65,10 @@ export function useGPUCompute() { }, [release]) const run = useCallback(async () => { - if (activeRef.current || !navigator.gpu || isHidden()) return + if (activeRef.current || !mountedRef.current || !navigator.gpu || isHidden()) return activeRef.current = true stopRef.current = false + const stopped = () => stopRef.current || !mountedRef.current const update = (next) => { if (mountedRef.current) setState((s) => ({ ...s, ...next })) @@ -81,12 +82,22 @@ export function useGPUCompute() { const res = resourcesRef.current try { const adapter = await navigator.gpu.requestAdapter() + if (stopped()) { + update({ throughput: 'Stopped' }) + return + } if (!adapter) { update({ supported: false, throughput: '--' }) return } + // Assigned before the stop check so a device that arrives after a stop + // is still destroyed in finally. res.device = await adapter.requestDevice() + if (stopped()) { + update({ throughput: 'Stopped' }) + return + } const device = res.device res.buffer = device.createBuffer({ @@ -109,7 +120,7 @@ export function useGPUCompute() { const timings = [] for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { - if (stopRef.current) break + if (stopped()) break const t0 = performance.now() const encoder = device.createCommandEncoder() const pass = encoder.beginComputePass() From 224a89ed036f2257996893b2adf8329c9946fb3c Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 20:02:42 -0600 Subject: [PATCH 11/22] test: add failing test for Infinity GB/s when timings are 0 (#11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- src/hooks/useGPUCompute.tooFast.test.js | 94 +++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/hooks/useGPUCompute.tooFast.test.js diff --git a/src/hooks/useGPUCompute.tooFast.test.js b/src/hooks/useGPUCompute.tooFast.test.js new file mode 100644 index 0000000..568ebfe --- /dev/null +++ b/src/hooks/useGPUCompute.tooFast.test.js @@ -0,0 +1,94 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act } from '@testing-library/react' +import { useGPUCompute, formatThroughput } from './useGPUCompute.js' + +// Issue #11: a coarse performance.now() can make the median 0, which must not +// render as Infinity GB/s. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +function hide() { + setVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('formatThroughput with a non-positive or non-finite time', () => { + it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])('returns Too fast for %s seconds', (seconds) => { + expect(formatThroughput(seconds)).toBe('Too fast') + }) +}) + +describe('useGPUCompute with zero timings', () => { + it('shows Too fast when every dispatch times as 0', async () => { + const mock = installGPU() + vi.spyOn(performance, 'now').mockReturnValue(1000) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(5) + expect(result.current.throughput).toBe('Too fast') + }) +}) From 76eab1c4fe1f5c9dc1bb10a1d3ef169250ddaaee Mon Sep 17 00:00:00 2001 From: Brad Stricherz Date: Sat, 7 Nov 2026 20:03:01 -0600 Subject: [PATCH 12/22] fix: show Too fast instead of Infinity GB/s when the median time is 0 (#11) The plan's AC4 and Proof are updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AELE7jB1i3uqqrHu3SjJjf --- docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md | 4 ++-- src/hooks/useGPUCompute.js | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md index fbad1f5..9590f6b 100644 --- a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md +++ b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md @@ -14,7 +14,7 @@ Domain skills: 1. No benchmark GPU work on mount: `useGPUCompute` calls neither `navigator.gpu.requestAdapter`, `requestDevice`, `createBuffer`, nor `queue.submit`. Nothing is allocated for the benchmark until the user activates the "Run benchmark" control. (The map's existing `useGPUCapabilities` adapter probe and the one-shot `useGPUHeatmap` run are unchanged and out of scope.) 2. The GPU info panel's COMPUTE item contains a native `