File size: 3,061 Bytes
624a22c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 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 (`<prefix>:webgpu-trial`, `<prefix>: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; }
}