// WebGPU first, without letting one crash repeat. A WebGPU run that takes the tab down (iOS ended an iPhone // tab in our phone tests) can't be caught, so a marker goes into storage right before WebGPU starts and comes out once the first // real sentence was spoken. A page that finds the marker still there knows the last try died: this device stays on the CPU // until reset. const read = (key) => { try { return localStorage.getItem(key); } catch { return null; } }; const write = (key, value) => { try { if (value === null) localStorage.removeItem(key); else localStorage.setItem(key, value); } catch { /* no storage (a private window): WebGPU is tried every time */ } }; /** prefix names the keys (`:webgpu-trial`, `:webgpu-off`); onCrash hears once about a try that died. */ export function gpuTrial(prefix, onCrash) { const TRIAL = `${prefix}:webgpu-trial`, OFF = `${prefix}:webgpu-off`; const page = Math.random().toString(36).slice(2, 10), lock = (id) => `${prefix}:webgpu-page:${id}`; let mine = false, startedAt = ""; // The marker names its page, which holds a Web Lock for its life: another open tab still trying is no crash. const left = read(TRIAL); const checked = left === null ? Promise.resolve() : (navigator.locks?.query() ?? Promise.resolve({ held: [] })) .then(({ held }) => { const [id, since] = left.split(" "); if (held?.some((e) => e.name === lock(id ?? ""))) return; if (read(TRIAL) !== left) return; write(TRIAL, null); write(OFF, since ?? new Date().toISOString()); onCrash?.(since ?? ""); }).catch(() => {}); const lift = () => { if (read(TRIAL)?.startsWith(`${page} `)) write(TRIAL, null); }; const end = () => { if (mine) lift(); mine = false; }; addEventListener("pagehide", end); // a reload or leaving is no crash // iOS ends background tabs without a pagehide: hidden, the try steps aside; back in front, it is marked again document.addEventListener("visibilitychange", () => { if (!mine) return; if (document.visibilityState === "hidden") lift(); else write(TRIAL, `${page} ${startedAt}`); }); return { /** resolves once a marker left by an earlier page was judged */ ready: () => checked, allowed: () => read(OFF) === null && (left === null || read(TRIAL) !== left), begin() { mine = true; startedAt = new Date().toISOString(); if (document.visibilityState !== "hidden") write(TRIAL, `${page} ${startedAt}`); navigator.locks?.request(lock(page), () => new Promise(() => {})); }, passed: end, reset() { write(OFF, null); write(TRIAL, null); }, benched: () => read(OFF) !== null, }; } /** What the device offers before a model is tried on it: navigator.gpu, an adapter, and a device that opens. */ export async function webGpuWorks() { if (!navigator.gpu) return false; try { const adapter = await navigator.gpu.requestAdapter(); if (!adapter) return false; const device = await adapter.requestDevice(); device.destroy?.(); return true; } catch { return false; } }