@babylonjs-toolkit/agent 1.1.68 → 1.1.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -208,7 +208,7 @@ function frameStats(frames, from, to) {
208
208
  const intervals = [];
209
209
  for (let i = 1; i < inside.length; i++) intervals.push(inside[i].at - inside[i - 1].at);
210
210
  const sortedIntervals = [...intervals].sort((first, second) => first - second);
211
- const cpu = inside.map((frame) => frame.cpuMs).sort((first, second) => first - second);
211
+ const cpu = inside.map((frame) => frame.cpuMs).filter((value) => typeof value === "number").sort((first, second) => first - second);
212
212
  const seconds = (inside[inside.length - 1].at - inside[0].at) / 1000;
213
213
  const mean = (key) => {
214
214
  const values = inside.map((frame) => frame[key]).filter((value) => typeof value === "number");
@@ -221,8 +221,8 @@ function frameStats(frames, from, to) {
221
221
  intervalP95Ms: round(percentile(sortedIntervals, 0.95)),
222
222
  worstIntervalMs: round(sortedIntervals[sortedIntervals.length - 1]),
223
223
  slowFrames: intervals.filter((interval) => interval > FRAME_BUDGET_MS * 1.5).length,
224
- cpuMeanMs: round(cpu.reduce((sum, value) => sum + value, 0) / cpu.length, 2),
225
- cpuP95Ms: round(percentile(cpu, 0.95), 2),
224
+ cpuMeanMs: cpu.length ? round(cpu.reduce((sum, value) => sum + value, 0) / cpu.length, 2) : null,
225
+ cpuP95Ms: cpu.length ? round(percentile(cpu, 0.95), 2) : null,
226
226
  draws: round(mean("draws"), 0),
227
227
  activeMeshes: round(mean("activeMeshes"), 0),
228
228
  particles: round(mean("particles"), 0),
@@ -369,15 +369,46 @@ function excerpt(symbolizer, file, line, hot) {
369
369
  return { file, from, to, rows };
370
370
  }
371
371
 
372
- /** The worst frames of the run, each with the functions and owners that filled it. */
373
- function worstFrames(frames, prepared, info, phases, top) {
374
- const candidates = frames.map((frame, index) => ({ ...frame, intervalMs: index > 0 ? frame.at - frames[index - 1].at : null }));
375
- const worst = [...candidates].sort((a, b) => b.cpuMs - a.cpuMs).slice(0, top);
372
+ /** Counts the shader modules and pipelines / programs the page created inside a window. */
373
+ function compilesIn(gpuCompiles, from, to) {
374
+ let pipelines = 0;
375
+ let shaderModules = 0;
376
+ for (const entry of gpuCompiles || []) {
377
+ if (entry.at < from || entry.at >= to) continue;
378
+ if (entry.kind === "shaderModule") shaderModules++;
379
+ else pipelines++;
380
+ }
381
+ return { pipelines, shaderModules };
382
+ }
383
+
384
+ /**
385
+ * The worst frames of the run, each with the functions and owners that filled it. A frame is bad for one of two reasons:
386
+ * its own CPU work (`kind: "cpu"`), or a long gap before it while the main thread mostly waited (`kind: "wait"`) — the GPU
387
+ * process compiling pipelines, a GPU-bound frame, the browser's own work. A wait never shows in CPU time, so both rank.
388
+ */
389
+ function worstFrames(frames, prepared, info, phases, gpuCompiles, top) {
390
+ const candidates = frames.map((frame, index) => {
391
+ const previous = index > 0 ? frames[index - 1] : null;
392
+ const intervalMs = previous ? frame.at - previous.at : null;
393
+ const timed = typeof frame.cpuMs === "number";
394
+ // The gap before this frame, minus the CPU work of the frame that opened it, is time the main thread did not draw.
395
+ const waitMs = intervalMs == null ? 0 : intervalMs - (previous && typeof previous.cpuMs === "number" ? previous.cpuMs : 0);
396
+ const cpuCost = timed ? frame.cpuMs : 0;
397
+ const waits = !timed || waitMs > cpuCost;
398
+ return {
399
+ ...frame, intervalMs, kind: timed ? (waits ? "wait" : "cpu") : "gap", cost: waits ? (intervalMs ?? 0) : cpuCost,
400
+ from: waits ? frame.at - (intervalMs ?? 0) : frame.at, to: waits ? frame.at : frame.at + cpuCost,
401
+ };
402
+ });
403
+ const worst = [...candidates].sort((a, b) => b.cost - a.cost).slice(0, top);
376
404
  return worst.map((frame) => {
377
- const aggregate = aggregateWindow(prepared, info, frame.at, frame.at + frame.cpuMs);
405
+ const aggregate = aggregateWindow(prepared, info, frame.from, frame.to);
378
406
  const phase = phases.find((candidate) => frame.at >= candidate.from && frame.at < candidate.to);
407
+ // Pipelines created just before a wait (up to 2 s) are what the GPU process may still be compiling during it.
408
+ const compiles = compilesIn(gpuCompiles, frame.from - 2000, frame.to);
379
409
  return {
380
- at: frame.at, cpuMs: round(frame.cpuMs), intervalMs: round(frame.intervalMs), phase: phase ? phase.name : null,
410
+ at: frame.at, cpuMs: round(frame.cpuMs), intervalMs: round(frame.intervalMs), kind: frame.kind, phase: phase ? phase.name : null,
411
+ scriptMs: round(aggregate.busyMs), pipelinesNear: compiles.pipelines, shaderModulesNear: compiles.shaderModules,
381
412
  draws: frame.draws, particles: frame.particles,
382
413
  top: [...aggregate.self].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([key, ms]) => ({ name: aggregate.symbols.get(key).name, owner: aggregate.symbols.get(key).owner, ms: round(ms) })),
383
414
  yours: [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, 3).map((blame) => ({ name: blame.symbol.name, file: blame.symbol.file, line: blame.symbol.line, ms: round(blame.totalMs) })),
@@ -444,10 +475,18 @@ function signals(analysis) {
444
475
  if (ownerPct("gc") >= 5) notes.push(`Garbage collection takes ${ownerPct("gc")}% of busy time — look at the allocation list (heap.yoursTop) for per-frame garbage.`);
445
476
  if (ownerPct("shader") >= 5) notes.push(`GLSL → WGSL shader translation takes ${ownerPct("shader")}% of busy time — new material / particle shader variants are being compiled on the main thread.`);
446
477
  for (const phase of analysis.phases) {
447
- if (phase.frames.fps != null && phase.frames.fps < 45 && phase.durationSeconds >= 1) {
448
- const lead = phase.lists.inclusiveTop.find((entry) => !entry.shell && entry.owner !== "program");
449
- notes.push(`Phase "${phase.name}" runs at ${phase.frames.fps} FPS (CPU ${phase.frames.cpuMeanMs} ms/frame, main thread ${phase.busyPct}% busy)${phase.lists.yoursTop[0] ? `; your heaviest code: ${phase.lists.yoursTop[0].name} (${phase.lists.yoursTop[0].msPerFrame} ms/frame)` : ""}${lead ? `; heaviest stack entry: ${lead.name}` : ""}.`);
450
- }
478
+ if (phase.beforeFirstFrame || phase.frames.fps == null || phase.frames.fps >= 45 || phase.durationSeconds < 1) continue;
479
+ const lead = phase.lists.inclusiveTop.find((entry) => !entry.shell && entry.owner !== "program");
480
+ const cpu = phase.frames.cpuMeanMs != null ? `CPU ${phase.frames.cpuMeanMs} ms/frame, ` : "";
481
+ const rate = phase.frames.frames < 2 ? `draws ${phase.frames.frames} frame(s) in ${phase.durationSeconds} s` : `runs at ${phase.frames.fps} FPS`;
482
+ notes.push(`Phase "${phase.name}" ${rate} (${cpu}main thread ${phase.busyPct}% busy)${phase.lists.yoursTop[0] ? `; your heaviest code: ${phase.lists.yoursTop[0].name} (${phase.lists.yoursTop[0].msPerFrame != null ? `${phase.lists.yoursTop[0].msPerFrame} ms/frame` : `${phase.lists.yoursTop[0].ms} ms`})` : ""}${lead ? `; heaviest stack entry: ${lead.name}` : ""}.`);
483
+ }
484
+ // The first-visit stutter signature: long frames the main thread spent waiting, right after new pipelines were created.
485
+ const waits = analysis.worstFrames.filter((frame) => frame.kind === "wait" && frame.intervalMs >= 250 && frame.scriptMs < frame.intervalMs * 0.25);
486
+ if (waits.length) {
487
+ const withCompiles = waits.filter((frame) => frame.pipelinesNear > 0);
488
+ notes.push(`${waits.length} frame(s) of ${waits.map((frame) => `${frame.intervalMs} ms at ${frame.t}s`).slice(0, 4).join(", ")} were spent waiting, not running script (main thread ${waits.map((frame) => frame.scriptMs).slice(0, 4).join(" / ")} ms)` +
489
+ (withCompiles.length ? ` — ${withCompiles.length} of them right after new GPU pipelines / programs were created: the GPU process compiling shaders.${analysis.gpuCold ? " This capture was GPU-cold (--gpu-cold), as on a first visit." : " A later visit may hide it (shader caches): confirm with --gpu-cold true."}` : ` — GPU-bound frames or browser work; check draws and the GPU timers.`));
451
490
  }
452
491
  const shaderBuckets = analysis.timeline.filter((bucket) => bucket.newShaders > 0);
453
492
  if (shaderBuckets.length) {
@@ -534,11 +573,19 @@ function printSummary(analysis) {
534
573
  for (const phase of analysis.phases) {
535
574
  line(` ${phase.name.padEnd(14)} ${String(phase.durationSeconds + "s").padStart(6)} ${String(phase.frames.fps ?? "-").padStart(5)} fps p95 ${String(phase.frames.intervalP95Ms ?? "-").padStart(6)} ms cpu ${String(phase.frames.cpuMeanMs ?? "-").padStart(6)} ms/frame busy ${String(phase.busyPct).padStart(3)}% particles ${phase.frames.particles ?? "-"} draws ${phase.frames.draws ?? "-"}`);
536
575
  line(` owners: ${phase.lists.owners.slice(0, 6).map((entry) => `${entry.owner} ${entry.pctBusy}%`).join(" · ")}`);
537
- line(` yours: ${phase.lists.yoursTop.slice(0, 3).map((entry) => `${entry.name} ${entry.msPerFrame}ms/f`).join(" · ") || "-"}`);
576
+ line(` yours: ${phase.lists.yoursTop.slice(0, 3).map((entry) => (entry.msPerFrame != null ? `${entry.name} ${entry.msPerFrame}ms/f` : `${entry.name} ${entry.ms}ms`)).join(" · ") || "-"}`);
577
+ if (phase.gpuCompiles && (phase.gpuCompiles.pipelines || phase.gpuCompiles.shaderModules)) line(` gpu: ${phase.gpuCompiles.pipelines} pipelines / programs, ${phase.gpuCompiles.shaderModules} shader modules created`);
538
578
  if (phase.heap) line(` alloc: ${phase.heap.mbPerSecond} MB/s · ${phase.heap.selfTop.slice(0, 3).map((entry) => `${entry.name} ${entry.mbPerSecond}MB/s`).join(" · ")}`);
539
579
  line(` hot: ${phase.lists.inclusiveTop.filter((entry) => entry.owner !== "program" && !entry.shell).slice(0, 5).map((entry) => `${entry.name} ${entry.pctBusy}%`).join(" · ")}`);
540
580
  }
541
581
  line();
582
+ line("WORST FRAMES — cpu: the frame's own work · wait: a gap the main thread mostly waited through (GPU, browser)");
583
+ for (const frame of analysis.worstFrames.slice(0, 8)) {
584
+ const cost = frame.kind === "cpu" ? `${frame.cpuMs} ms cpu` : `${frame.intervalMs} ms ${frame.kind}`;
585
+ line(` ${String(frame.t + "s").padStart(8)} ${cost.padEnd(16)} ${String(frame.phase || "-").padEnd(14)} script ${frame.scriptMs} ms · ${frame.pipelinesNear} pipelines near · ${frame.top.slice(0, 2).map((entry) => `${entry.name} ${entry.ms}`).join(", ") || "-"}`);
586
+ }
587
+ if (analysis.gpuCold) line(` (--gpu-cold: ${analysis.gpuCold.tagged} fragment shaders made unique, so every pipeline compiled as on a first visit)`);
588
+ line();
542
589
  line("YOUR CODE — time spent, including the library work it triggers (whole run)");
543
590
  for (const entry of analysis.overall.lists.yoursTop.slice(0, 15)) {
544
591
  line(` ${String(entry.ms).padStart(8)} ms ${String(entry.pctBusy).padStart(5)}% ${entry.name} ${shortFile(entry.file)}:${entry.line} [own ${entry.ownCodeMs} ms; ${entry.callees.slice(0, 3).map((callee) => `${callee.name} ${callee.ms}`).join(", ")}]`);
@@ -603,6 +650,9 @@ function main() {
603
650
  startSeconds: round((phase.from - startMs) / 1000, 1),
604
651
  durationSeconds: round((phase.to - phase.from) / 1000, 1),
605
652
  busyPct: round((aggregate.busyMs / Math.max(aggregate.totalMs, 1e-6)) * 100, 0),
653
+ // A phase over before the first frame (the page loading) has no frame rate to judge — it is load time.
654
+ beforeFirstFrame: frames.length === 0 || phase.to <= frames[0].at,
655
+ gpuCompiles: compilesIn(probe.gpuCompiles, phase.from, phase.to),
606
656
  frames: stats,
607
657
  lists: topLists(aggregate, stats.frames, Math.min(top, 15), symbolizer.labels),
608
658
  };
@@ -638,7 +688,9 @@ function main() {
638
688
  phases: phaseResults,
639
689
  timeline: buildTimeline(prepared, info, frames, probe.counters, startMs, endMs),
640
690
  marks: probe.marks.map((mark) => ({ name: mark.name, t: round((mark.at - startMs) / 1000, 2) })),
641
- worstFrames: worstFrames(frames, prepared, info, phases, 15).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })),
691
+ worstFrames: worstFrames(frames, prepared, info, phases, probe.gpuCompiles, 15).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })),
692
+ gpuCompiles: (probe.gpuCompiles || []).map((entry) => ({ kind: entry.kind, t: round((entry.at - startMs) / 1000, 2) })),
693
+ gpuCold: capture.gpuCold || null,
642
694
  hotLines: lines,
643
695
  excerpts: [...excerptsFor.values()],
644
696
  heap: analyzeHeap(heapProfiles.map((entry) => entry.profile), symbolizer, (endMs - startMs) / 1000, top),
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Finds the Chrome (or Chromium) executable that bt-profile drives: the capture (profile.mjs) and the report's PDF
3
+ * (report.mjs). CHROME_PATH wins; otherwise the usual install locations on macOS, Linux and Windows.
4
+ */
5
+ import fs from "node:fs";
6
+
7
+ /** @returns {string} the path of a Chrome or Chromium executable */
8
+ export function findChrome() {
9
+ const candidates = [
10
+ process.env.CHROME_PATH,
11
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
12
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
13
+ "/usr/bin/google-chrome",
14
+ "/usr/bin/chromium",
15
+ "/usr/bin/chromium-browser",
16
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
17
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
18
+ ].filter(Boolean);
19
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
20
+ if (found) return found;
21
+ throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
22
+ }
@@ -4,10 +4,12 @@
4
4
  *
5
5
  * It records, on `window.__btProfile`:
6
6
  * - one entry per rendered Babylon frame: begin time, CPU work (begin → end of the engine frame), draw calls, active
7
- * meshes and particles, and the SceneInstrumentation timers the engine exposes;
7
+ * meshes and particles, and the SceneInstrumentation timers the engine exposes — or, on a page with no Babylon engine,
8
+ * one entry per browser frame (requestAnimationFrame: time only, `frameSource: "raf"`);
8
9
  * - counters sampled every half second: meshes, materials, textures, particle systems, compiled effects (shader
9
10
  * programs / pipelines), JS heap;
10
11
  * - long animation frames (LoAF) with their script attribution, when the browser supports them;
12
+ * - every shader module / pipeline (WebGPU) and program (WebGL) the page creates, with its time (`gpuCompiles`);
11
13
  * - phase marks set by the scenario (`__btProfile.mark("countdown")`).
12
14
  *
13
15
  * Every time is an epoch time in milliseconds (`performance.timeOrigin + performance.now()`), so frames, marks and
@@ -20,6 +22,8 @@ export function installProbe() {
20
22
  const ATTACH_POLL_MS = 50;
21
23
  /** Frames longer than this (ms) keep their full instrumentation breakdown in the spike list. */
22
24
  const LONG_FRAME_MS = 50;
25
+ /** Most shader / pipeline creations kept (a run creates tens to a few thousand). */
26
+ const MAX_GPU_COMPILES = 20000;
23
27
 
24
28
  const epochNow = () => performance.timeOrigin + performance.now();
25
29
  const state = {
@@ -30,6 +34,7 @@ export function installProbe() {
30
34
  loafs: [],
31
35
  engineAttachedAt: null,
32
36
  scenesSeen: 0,
37
+ rafFrames: [],
33
38
  };
34
39
  window.__btProfile = state;
35
40
 
@@ -123,6 +128,17 @@ export function installProbe() {
123
128
  };
124
129
  setInterval(attach, ATTACH_POLL_MS);
125
130
 
131
+ // Any web app: until a Babylon engine is found, the browser's own frames (requestAnimationFrame) are timed, so a page
132
+ // with no Babylon at all still gets FPS, frame gaps and the timeline. They are used only when no engine ever attaches.
133
+ let rafPrevious = null;
134
+ const onAnimationFrame = (now) => {
135
+ if (hookedEngine != null) return;
136
+ if (rafPrevious != null) state.rafFrames.push({ at: performance.timeOrigin + now, cpuMs: null });
137
+ rafPrevious = now;
138
+ requestAnimationFrame(onAnimationFrame);
139
+ };
140
+ requestAnimationFrame(onAnimationFrame);
141
+
126
142
  /** Counts what the scene holds and how many shader programs / pipelines the engine has compiled so far. */
127
143
  const sampleCounters = () => {
128
144
  const engine = hookedEngine;
@@ -146,6 +162,27 @@ export function installProbe() {
146
162
  };
147
163
  setInterval(sampleCounters, COUNTER_INTERVAL_MS);
148
164
 
165
+ // GPU work the main thread does not see: every shader module, render / compute pipeline (WebGPU) and linked program
166
+ // (WebGL) the page creates, with its time. A frame gap with little script in it right after a burst of these is the GPU
167
+ // process compiling pipelines — the classic first-visit stutter (the browser's shader caches hide it on later visits).
168
+ state.gpuCompiles = [];
169
+ const recordCompile = (kind) => { if (state.gpuCompiles.length < MAX_GPU_COMPILES) state.gpuCompiles.push({ at: epochNow(), kind }); };
170
+ const wrapCompile = (prototype, method, kind) => {
171
+ if (!prototype || typeof prototype[method] !== "function") return;
172
+ const original = prototype[method];
173
+ prototype[method] = function (...args) { recordCompile(kind); return original.apply(this, args); };
174
+ };
175
+ if (typeof GPUDevice !== "undefined") {
176
+ wrapCompile(GPUDevice.prototype, "createShaderModule", "shaderModule");
177
+ wrapCompile(GPUDevice.prototype, "createRenderPipeline", "renderPipeline");
178
+ wrapCompile(GPUDevice.prototype, "createRenderPipelineAsync", "renderPipeline");
179
+ wrapCompile(GPUDevice.prototype, "createComputePipeline", "computePipeline");
180
+ wrapCompile(GPUDevice.prototype, "createComputePipelineAsync", "computePipeline");
181
+ }
182
+ for (const name of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
183
+ if (typeof window[name] !== "undefined") wrapCompile(window[name].prototype, "linkProgram", "program");
184
+ }
185
+
149
186
  // Long Animation Frames name the script, function and invoker behind every frame over 50 ms.
150
187
  try {
151
188
  const observer = new PerformanceObserver((list) => {
@@ -216,10 +253,88 @@ export function installProbe() {
216
253
  engine: state.engine || null,
217
254
  engineAttachedAt: state.engineAttachedAt,
218
255
  scenesSeen: state.scenesSeen,
219
- frames: state.frames,
256
+ frameSource: state.engine ? "babylon" : "raf",
257
+ frames: state.engine ? state.frames : state.rafFrames,
220
258
  counters: state.counters,
221
259
  marks: state.marks,
222
260
  loafs: state.loafs,
261
+ gpuCompiles: state.gpuCompiles,
262
+ gpuCold: window.__btGpuCold || null,
223
263
  location: location.href,
224
264
  });
225
265
  }
266
+
267
+ /**
268
+ * `--gpu-cold true`: makes every fragment shader unique to this page load, so the GPU process cannot reuse a pipeline
269
+ * compiled on an earlier visit. A fresh Chrome profile only makes the browser cold — on macOS the compiled Metal pipelines
270
+ * live in a system cache outside it, so without this only the first capture after a shader change is a true first visit.
271
+ * Each fragment shader gets a branch that is never taken but cannot be folded away (it compares the pixel position with a
272
+ * random bound), so it renders exactly the same. Nothing on disk is touched. Serialised into every document like
273
+ * `installProbe`, so it must stay self-contained.
274
+ */
275
+ export function installGpuCold() {
276
+ const bound = (1000000 + Math.floor(Math.random() * 1000000)) + 0.123;
277
+ const stats = { bound, tagged: 0, untagged: 0 };
278
+ window.__btGpuCold = stats;
279
+
280
+ /** WGSL: finds the @fragment entry point and the name of its pixel position, and opens its body with the branch. */
281
+ const tagWgsl = (code) => {
282
+ const head = /@fragment\s+fn\s+\w+\s*\(/.exec(code);
283
+ if (!head) return null;
284
+ // The parameter list holds attributes with their own parentheses (@location(0)): find its matching ")".
285
+ const open = head.index + head[0].length;
286
+ let depth = 1;
287
+ let close = open;
288
+ for (; close < code.length && depth > 0; close++) {
289
+ if (code[close] === "(") depth++;
290
+ else if (code[close] === ")") depth--;
291
+ }
292
+ close--; // the matching ")"
293
+ const body = code.indexOf("{", close);
294
+ if (depth !== 0 || body < 0) return null;
295
+ const parameters = code.slice(open, close);
296
+ const at = body + 1;
297
+ let position = null;
298
+ const direct = /@builtin\s*\(\s*position\s*\)\s*(\w+)\s*:/.exec(parameters);
299
+ if (direct) position = direct[1];
300
+ else {
301
+ for (const typed of parameters.matchAll(/(?:^|,)\s*(\w+)\s*:\s*(\w+)\s*(?=,|$)/g)) {
302
+ const struct = new RegExp(`struct\\s+${typed[2]}\\s*\\{([^}]*)\\}`).exec(code);
303
+ const field = struct && /@builtin\s*\(\s*position\s*\)\s*(\w+)\s*:/.exec(struct[1]);
304
+ if (field) { position = `${typed[1]}.${field[1]}`; break; }
305
+ }
306
+ }
307
+ if (position) return `${code.slice(0, at)}\n if (${position}.x < -${bound}) { discard; }${code.slice(at)}`;
308
+ // No pixel position among the inputs (a blit, a mip-map pass): add one — a builtin input never shifts the vertex
309
+ // stage's @location interface.
310
+ const kept = parameters.replace(/,\s*$/, "");
311
+ const signature = `${kept}${kept.trim() ? ", " : ""}@builtin(position) btGpuColdPosition : vec4<f32>`;
312
+ return `${code.slice(0, open)}${signature}${code.slice(close, at)}\n if (btGpuColdPosition.x < -${bound}) { discard; }${code.slice(at)}`;
313
+ };
314
+ if (typeof GPUDevice !== "undefined") {
315
+ const createShaderModule = GPUDevice.prototype.createShaderModule;
316
+ GPUDevice.prototype.createShaderModule = function (descriptor) {
317
+ const code = descriptor && typeof descriptor.code === "string" ? descriptor.code : null;
318
+ if (code == null || !code.includes("@fragment")) return createShaderModule.call(this, descriptor);
319
+ const tagged = tagWgsl(code);
320
+ if (tagged == null) { stats.untagged++; return createShaderModule.call(this, descriptor); }
321
+ stats.tagged++;
322
+ return createShaderModule.call(this, { ...descriptor, code: tagged });
323
+ };
324
+ }
325
+ // GLSL (WebGL): a fragment shader's main() opens with the same never-taken branch on gl_FragCoord.
326
+ for (const name of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
327
+ if (typeof window[name] === "undefined") continue;
328
+ const shaderSource = window[name].prototype.shaderSource;
329
+ window[name].prototype.shaderSource = function (shader, source) {
330
+ let fragment = false;
331
+ try { fragment = this.getShaderParameter(shader, this.SHADER_TYPE) === this.FRAGMENT_SHADER; } catch { /* not a shader */ }
332
+ const main = fragment && typeof source === "string" ? /void\s+main\s*\(\s*(void)?\s*\)\s*\{/.exec(source) : null;
333
+ if (!fragment) return shaderSource.call(this, shader, source);
334
+ if (!main) { stats.untagged++; return shaderSource.call(this, shader, source); }
335
+ stats.tagged++;
336
+ const at = main.index + main[0].length;
337
+ return shaderSource.call(this, shader, `${source.slice(0, at)}\n if (gl_FragCoord.x < -${bound}) discard;${source.slice(at)}`);
338
+ };
339
+ }
340
+ }
@@ -12,7 +12,7 @@
12
12
  export const PROGRESS_MARKER = "<!-- bt-profile progress panel -->";
13
13
 
14
14
  export const PROGRESS_STYLES = `
15
- .bt-progress { --btp-surface: var(--surface-1, #1a1a19); --btp-sunken: var(--surface-0, #111110); --btp-line: var(--surface-3, #2d2d2a);
15
+ .bt-progress, .btp-toolbar { --btp-surface: var(--surface-1, #1a1a19); --btp-sunken: var(--surface-0, #111110); --btp-line: var(--surface-3, #2d2d2a);
16
16
  --btp-text: var(--text-primary, #f0efec); --btp-muted: var(--text-secondary, #c3c2b7); --btp-faint: var(--text-muted, #8f8e86);
17
17
  --btp-good: var(--good, #3fae5a); --btp-active: var(--warning, #c98500); --btp-bad: var(--critical, #e66767); --btp-accent: var(--accent, #3987e5);
18
18
  --btp-mono: var(--mono, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
@@ -23,6 +23,23 @@ export const PROGRESS_STYLES = `
23
23
  .btp-kicker b { color: var(--btp-text); font-weight: 700; }
24
24
  .btp-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--btp-active); animation: btp-pulse 1.6s ease-in-out infinite; }
25
25
  @keyframes btp-pulse { 50% { opacity: 0.3; } }
26
+ .btp-next { display: grid; gap: 6px; margin: 10px 0; }
27
+ .btp-next-row { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-size: 13px; color: var(--btp-muted); }
28
+ .btp-next-row code { font: 600 12px/1.4 var(--btp-mono); color: var(--btp-text); background: var(--btp-sunken); border: 1px solid var(--btp-line); border-radius: 6px; padding: 3px 8px; overflow-wrap: anywhere; }
29
+ .btp-copy { font: 600 11px/1 var(--btp-mono); color: var(--btp-muted); background: transparent; border: 1px solid var(--btp-line); border-radius: 999px; padding: 4px 10px; cursor: pointer; }
30
+ .btp-copy:hover { color: var(--btp-text); border-color: var(--btp-active); }
31
+ @media screen {
32
+ html.btp-running main > :not(header):not(h1):not(.lede):not(.btp-toolbar):not(#bt-progress):not(footer):not(script):not(style) { display: none !important; }
33
+ html.btp-running #print, html.btp-running #pdf { display: none !important; }
34
+ }
35
+ .btp-pending-report { margin: 4px 0 0; color: var(--btp-muted); font-size: 13px; }
36
+ footer.generated-by { margin-top: 64px; padding-top: 20px; border-top: 1px solid var(--surface-3, #2d2d2a); color: var(--text-muted, #8f8e86); font-size: 12.5px; }
37
+ footer.generated-by a { color: inherit; }
38
+ .btp-toolbar[hidden] { display: none !important; }
39
+ .btp-toolbar { display: flex; justify-content: flex-end; margin: 0 0 8px; }
40
+ .btp-live-toggle { display: inline-flex; gap: 8px; align-items: center; padding: 6px 12px; border: 1px solid var(--btp-line); border-radius: 999px; background: var(--btp-surface); color: var(--btp-muted); font: 600 12px/1 var(--btp-mono); cursor: pointer; white-space: nowrap; }
41
+ .btp-live-toggle[aria-pressed="true"] { color: var(--btp-active); border-color: var(--btp-active); }
42
+ .btp-live-toggle[aria-pressed="true"]::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--btp-active); animation: btp-pulse 1.6s ease-in-out infinite; }
26
43
  @media (prefers-reduced-motion: reduce) { .btp-dot { animation: none; } }
27
44
  .btp-now { border-left: 3px solid var(--btp-active); }
28
45
  .btp-now.is-stale { border-left-color: var(--btp-bad); }
@@ -89,13 +106,63 @@ export const PROGRESS_SCRIPT = String.raw`
89
106
  var RUNNING_CHECK_SECONDS = 10;
90
107
  var IDLE_CHECK_SECONDS = 30;
91
108
  // A run that has written nothing for this long is flagged on the page.
92
- var STALE_MINUTES = 15;
109
+ var STALE_MINUTES = 10;
93
110
  var DATA_SOURCE = "data/progress.js";
94
111
  var root = document.getElementById("bt-progress");
95
112
  if (!root) return;
96
113
  var lastFingerprint = null;
97
114
  var sawRunning = false;
98
115
 
116
+ // While a run is going the page shows its progress only; the report (charts, findings, tables) appears when it ends.
117
+ // The last known state is remembered per page, so a reload during a run does not flash the previous report.
118
+ var STATE_KEY = "bt-profile:" + location.pathname + ":running";
119
+ function setRunning(running) {
120
+ document.documentElement.classList.toggle("btp-running", running);
121
+ try { sessionStorage.setItem(STATE_KEY, running ? "1" : "0"); } catch (error) { /* private window */ }
122
+ }
123
+ try { if (sessionStorage.getItem(STATE_KEY) === "1") document.documentElement.classList.add("btp-running"); } catch (error) { /* private window */ }
124
+
125
+ // Auto-update on / off (as on the bt-execute dashboard): remembered per page; off pauses the checks until turned on.
126
+ var LIVE_KEY = "bt-profile:" + location.pathname + ":live";
127
+ // The button is hidden for now (the page always auto-updates); set to true to show it again.
128
+ var SHOW_LIVE_TOGGLE = false;
129
+ function readLive() { try { return localStorage.getItem(LIVE_KEY) !== "off"; } catch (error) { return true; } }
130
+ function writeLive(on) { try { localStorage.setItem(LIVE_KEY, on ? "on" : "off"); } catch (error) { /* private window: this visit only */ } }
131
+ var liveEnabled = SHOW_LIVE_TOGGLE ? readLive() : true;
132
+ var toolbar = document.createElement("div");
133
+ toolbar.className = "btp-toolbar";
134
+ toolbar.innerHTML = '<button class="btp-live-toggle" id="btp-live-toggle" type="button"></button>';
135
+ toolbar.hidden = !SHOW_LIVE_TOGGLE;
136
+ root.parentNode.insertBefore(toolbar, root);
137
+ var toggle = toolbar.querySelector("button");
138
+ function showToggle() {
139
+ toggle.setAttribute("aria-pressed", String(liveEnabled));
140
+ toggle.textContent = "Auto-update " + (liveEnabled ? "on" : "off");
141
+ toggle.title = liveEnabled ? "Checks the run's progress every " + RUNNING_CHECK_SECONDS + " s and refreshes when it changes" : "Paused — click to check the run's progress again";
142
+ }
143
+ root.addEventListener("click", function (event) {
144
+ var button = event.target.closest ? event.target.closest(".btp-copy") : null;
145
+ if (!button) return;
146
+ var text = button.getAttribute("data-copy");
147
+ var done = function () { button.textContent = "Copied"; setTimeout(function () { button.textContent = "Copy"; }, 1500); };
148
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text); done(); });
149
+ else { fallbackCopy(text); done(); }
150
+ });
151
+ function fallbackCopy(text) {
152
+ var area = document.createElement("textarea");
153
+ area.value = text; area.style.position = "fixed"; area.style.opacity = "0";
154
+ document.body.appendChild(area); area.select();
155
+ try { document.execCommand("copy"); } catch (error) { /* the command stays visible to copy by hand */ }
156
+ area.remove();
157
+ }
158
+ toggle.addEventListener("click", function () {
159
+ liveEnabled = !liveEnabled;
160
+ writeLive(liveEnabled);
161
+ showToggle();
162
+ if (liveEnabled) load();
163
+ });
164
+ showToggle();
165
+
99
166
  function esc(value) {
100
167
  return String(value == null ? "" : value).replace(/[&<>"']/g, function (c) { return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]; });
101
168
  }
@@ -182,12 +249,25 @@ export const PROGRESS_SCRIPT = String.raw`
182
249
  "</div>";
183
250
  }
184
251
 
252
+ /** The commands that act on this run (type them in Claude Code): stop it while it runs, resume or restart it after. */
253
+ function renderNext(progress) {
254
+ var slug = progress.slug || "";
255
+ var command = function (name) { return "/bt-profile --" + name + (slug ? ":" + slug : ""); };
256
+ var rows = progress.status === "running" ? [["Stop this run", command("stop")]]
257
+ : progress.status === "done" ? [["Profile it again from a fresh baseline", command("restart")]]
258
+ : [["Continue where it stopped", command("resume")], ["Start over from a fresh baseline", command("restart")]];
259
+ return '<div class="btp-next">' + rows.map(function (row) {
260
+ return '<div class="btp-next-row"><span>' + esc(row[0]) + "</span><code>" + esc(row[1]) + '</code><button type="button" class="btp-copy" data-copy="' + esc(row[1]) + '">Copy</button></div>';
261
+ }).join("") + "</div>";
262
+ }
263
+
185
264
  function render(progress) {
186
265
  var running = progress.status === "running";
266
+ setRunning(running);
187
267
  var title = esc(progress.title || "Profile run");
188
268
  if (running) {
189
269
  sawRunning = true;
190
- root.innerHTML = renderNow(progress) + '<div class="btp-card">' + renderStages(progress) + "</div>" + renderMetrics(progress) + renderFixes(progress) + renderLog(progress, 12);
270
+ root.innerHTML = renderNow(progress) + '<p class="btp-pending-report">The full report — findings, charts and tables — appears here when the profile finishes.</p>' + renderNext(progress) + '<div class="btp-card">' + renderStages(progress) + "</div>" + renderMetrics(progress) + renderFixes(progress) + renderLog(progress, 12);
191
271
  return;
192
272
  }
193
273
  var stages = list(progress.stages);
@@ -202,22 +282,23 @@ export const PROGRESS_SCRIPT = String.raw`
202
282
  var body = '<div class="btp-done-body"><div class="btp-card">' + renderStages(progress) + "</div>" + renderMetrics(progress) + renderFixes(progress) + renderLog(progress) + "</div>";
203
283
  if (progress.status === "done") {
204
284
  root.innerHTML = '<details class="btp-card btp-done"><summary class="btp-kicker"><b>How this profile ran</b><span>' + headline + "</span></summary>" +
205
- (progress.summary ? '<p class="btp-summary">' + esc(progress.summary) + "</p>" : "") + body + "</details>";
285
+ (progress.summary ? '<p class="btp-summary">' + esc(progress.summary) + "</p>" : "") + renderNext(progress) + body + "</details>";
206
286
  } else {
207
287
  root.innerHTML = '<div class="btp-card btp-stopped"><div class="btp-kicker"><b>' + title + "</b><span>" + headline + "</span></div>" +
208
- '<p class="btp-activity">' + esc(progress.summary || (stoppedAt ? "It ended during " + stoppedAt.name + "." : "It ended before the report was written.")) + "</p></div>" + body;
288
+ '<p class="btp-activity">' + esc(progress.summary || (stoppedAt ? "It ended during " + stoppedAt.name + "." : "It ended before the report was written.")) + "</p>" + renderNext(progress) + "</div>" + body;
209
289
  }
210
290
  }
211
291
 
212
292
  function fingerprint(progress) { return JSON.stringify(progress); }
213
293
 
214
294
  function load() {
295
+ if (!liveEnabled && lastFingerprint != null) return; // paused: the click that turns it on loads again
215
296
  var script = document.createElement("script");
216
297
  script.src = DATA_SOURCE + "?check=" + Date.now();
217
298
  script.onload = function () {
218
299
  script.remove();
219
300
  var progress = window.PROFILE_PROGRESS;
220
- if (!progress || typeof progress !== "object") return schedule(IDLE_CHECK_SECONDS);
301
+ if (!progress || typeof progress !== "object") { setRunning(false); return schedule(IDLE_CHECK_SECONDS); }
221
302
  var print = fingerprint(progress);
222
303
  if (print !== lastFingerprint) {
223
304
  lastFingerprint = print;
@@ -227,7 +308,7 @@ export const PROGRESS_SCRIPT = String.raw`
227
308
  }
228
309
  schedule(progress.status === "running" ? RUNNING_CHECK_SECONDS : IDLE_CHECK_SECONDS);
229
310
  };
230
- script.onerror = function () { script.remove(); schedule(IDLE_CHECK_SECONDS); };
311
+ script.onerror = function () { script.remove(); setRunning(false); schedule(IDLE_CHECK_SECONDS); };
231
312
  document.head.appendChild(script);
232
313
  }
233
314
  function schedule(seconds) { setTimeout(load, seconds * 1000); }
@@ -244,6 +325,20 @@ export function progressMarkup() {
244
325
  return `${PROGRESS_MARKER}\n<section class="bt-progress" id="bt-progress" aria-live="polite"></section>`;
245
326
  }
246
327
 
328
+ /**
329
+ * An existing report (written before the panel existed) with the live panel added — its charts, tables and findings all
330
+ * kept: the panel's styles go into <head>, the panel to the top of <main> (else <body>), its script before </body>.
331
+ * @returns {string|null} the report with the panel, or null when the HTML has no place for it
332
+ */
333
+ export function withProgressPanel(html) {
334
+ const mainOpen = html.match(/<main[^>]*>/i) || html.match(/<body[^>]*>/i);
335
+ if (!mainOpen || !/<\/head>/i.test(html) || !/<\/body>/i.test(html)) return null;
336
+ return html
337
+ .replace(/<\/head>/i, `<style>${PROGRESS_STYLES}</style>\n</head>`)
338
+ .replace(mainOpen[0], `${mainOpen[0]}\n${progressMarkup()}`)
339
+ .replace(/<\/body>(?![\s\S]*<\/body>)/i, `<script>${PROGRESS_SCRIPT}</script>\n</body>`);
340
+ }
341
+
247
342
  /** The live page for a slug that has no report yet: the panel alone, until `report.mjs` writes the report. */
248
343
  export function livePage({ title }) {
249
344
  const safeTitle = String(title || "Profile").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" })[c]);
@@ -268,6 +363,7 @@ ${PROGRESS_STYLES}
268
363
  <h1>${safeTitle}</h1>
269
364
  <p class="lede">The performance report appears here when the profile finishes. Until then this page follows the run.</p>
270
365
  ${progressMarkup()}
366
+ <footer class="generated-by">Generated by the <a href="https://www.npmjs.com/package/@babylonjs-toolkit/agent" target="_blank" rel="noopener noreferrer">Babylon Toolkit Desktop Agent</a></footer>
271
367
  </main>
272
368
  <script>${PROGRESS_SCRIPT}</script>
273
369
  </body>