@babylonjs-toolkit/agent 1.1.68 → 1.1.76

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.
@@ -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>
@@ -17,14 +17,22 @@
17
17
  * Usage (from `.agents/profile/<slug>/data`, whose profile.config.json supplies the defaults for --url and --scenario):
18
18
  * node ../../.tools/profile.mjs --out runs/baseline [--url http://localhost:5173/play] [--scenario scenario.mjs]
19
19
  * [--seconds 150] [--dpr 2] [--width 1600] [--height 900] [--headed true] [--interval 250] [--warm true]
20
- * [--trace true] [--uncapped true] [--heap false] [--snapshots true] [--filmstrip-interval 1] [--autoplay gesture] [--args key=value,key2=value2]
20
+ * [--trace true] [--uncapped true] [--heap false] [--snapshots true] [--filmstrip-interval 1] [--autoplay gesture] [--watch true]
21
+ * [--gpu-cold true] [--args key=value,key2=value2]
22
+ *
23
+ * `--gpu-cold true` makes every fragment shader unique to the load, so the GPU compiles every pipeline as on a first visit
24
+ * (a fresh Chrome profile alone does not: macOS keeps compiled Metal pipelines in a system cache outside it).
25
+ *
26
+ * A scenario that fails or runs past --seconds still ends the capture: every step after it has a time limit, and the run
27
+ * folder gets `shots/failed.png` plus the page's address, title and console errors in the log.
21
28
  */
22
29
  import fs from "node:fs";
23
30
  import os from "node:os";
24
31
  import path from "node:path";
25
32
  import { pathToFileURL } from "node:url";
26
33
  import puppeteer from "puppeteer-core";
27
- import { installProbe } from "./lib/probe.mjs";
34
+ import { installProbe, installGpuCold } from "./lib/probe.mjs";
35
+ import { findChrome } from "./lib/chrome.mjs";
28
36
 
29
37
  /** Default sampling interval of the CPU profiler, in microseconds (DevTools uses 100–1000). */
30
38
  const DEFAULT_SAMPLING_INTERVAL_US = 250;
@@ -70,29 +78,29 @@ function parseScenarioArguments(text) {
70
78
  return options;
71
79
  }
72
80
 
81
+ /** Pauses for the given number of seconds. */
82
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
83
+
73
84
  /**
74
- * Finds a Chrome or Chromium executable: CHROME_PATH, the usual install locations, then puppeteer's own cache.
75
- * @returns {string} absolute path of the browser executable
76
- * @throws {Error} when no browser can be found
85
+ * Waits for a DevTools call at most `seconds`. The browser has no per-call timeout (a scenario may wait minutes), so every
86
+ * step after the scenario uses this: a stuck page must never keep the capture from finishing.
87
+ * @returns {Promise<*>} the call's result, or `fallback` when it fails or takes too long
77
88
  */
78
- function findChrome() {
79
- const candidates = [
80
- process.env.CHROME_PATH,
81
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
82
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
83
- "/usr/bin/google-chrome",
84
- "/usr/bin/chromium",
85
- "/usr/bin/chromium-browser",
86
- "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
87
- "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
88
- ].filter(Boolean);
89
- const found = candidates.find((candidate) => fs.existsSync(candidate));
90
- if (found) return found;
91
- throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
89
+ async function limit(promise, seconds, fallback, log, what) {
90
+ let timer;
91
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(limit.TIMED_OUT), seconds * 1000); });
92
+ try {
93
+ const result = await Promise.race([promise, timeout]);
94
+ if (result === limit.TIMED_OUT) { log(`${what}: no answer within ${seconds} s — skipped`); return fallback; }
95
+ return result;
96
+ } catch (error) {
97
+ log(`${what}: ${String(error && error.message ? error.message : error).split("\n")[0]}`);
98
+ return fallback;
99
+ } finally {
100
+ clearTimeout(timer);
101
+ }
92
102
  }
93
-
94
- /** Pauses for the given number of seconds. */
95
- const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
103
+ limit.TIMED_OUT = Symbol("timed out");
96
104
 
97
105
  /**
98
106
  * Runs the sync marker in the page: a named function that busy-waits a few milliseconds. Its first sample in the CPU
@@ -191,9 +199,10 @@ function createScenarioContext(page, targetUrl, shotsDir, options, log, snapshot
191
199
  /** Waits until a page function returns truthy (polls every 100 ms). */
192
200
  waitFor: (pageFunction, { timeout = 600000, polling = 100, args = [] } = {}) =>
193
201
  page.waitForFunction(pageFunction, { timeout, polling }, ...args),
194
- /** Waits until the Babylon engine has rendered at least `count` frames. */
202
+ /** Waits until the page has rendered at least `count` frames (Babylon frames on a Babylon page, else browser frames). */
195
203
  waitForFrames: (count = 10, timeout = 600000) =>
196
- page.waitForFunction((minimum) => window.__btProfile && window.__btProfile.frames.length >= minimum, { timeout, polling: 100 }, count),
204
+ // Babylon frames on a Babylon page; the browser's own frames on any other page
205
+ page.waitForFunction((minimum) => window.__btProfile && (window.BABYLON ? window.__btProfile.frames.length : window.__btProfile.rafFrames.length) >= minimum, { timeout, polling: 100 }, count),
197
206
  evaluate: (pageFunction, ...args) => page.evaluate(pageFunction, ...args),
198
207
  keyDown: (key) => page.keyboard.down(key),
199
208
  keyUp: (key) => page.keyboard.up(key),
@@ -365,6 +374,11 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
365
374
  // Document loads only: a router's history.pushState / replaceState is a same-document "navigation" and is not a reload.
366
375
  page.on("domcontentloaded", () => navigations.push({ at: Date.now(), url: page.url() }));
367
376
  page.on("pageerror", (error) => consoleErrors.push({ type: "pageerror", text: String(error).slice(0, 600) }));
377
+ // A document that fails to load (a bad response, a decoding error) shows a white page and no console line of its own.
378
+ page.on("requestfailed", (request) => {
379
+ if (request.resourceType() === "document" || request.resourceType() === "script") consoleErrors.push({ type: "requestfailed", text: `${request.resourceType()} ${request.url().slice(0, 300)} — ${request.failure() ? request.failure().errorText : "failed"}` });
380
+ });
381
+ if (flags["gpu-cold"] === "true") await page.evaluateOnNewDocument(installGpuCold);
368
382
  await page.evaluateOnNewDocument(installProbe);
369
383
 
370
384
  // Start on a same-origin document so the renderer process (and the V8 isolate the profiler is attached to)
@@ -412,24 +426,35 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
412
426
  log(`scenario failed: ${scenarioError.split("\n")[0]}`);
413
427
  }
414
428
  if (timedOut) log(`scenario still running after --seconds ${maxSeconds}; stopping the capture there`);
415
- await context.mark("end").catch(() => {});
429
+ // From here on the page may be stuck (a failed load, a hung game): every call has a time limit.
430
+ await limit(context.mark("end"), 10, null, log, "mark end");
416
431
 
417
- const filmstrip = stopFilmstrip ? await stopFilmstrip() : [];
418
- const { profile } = await session.send("Profiler.stop");
432
+ const filmstrip = stopFilmstrip ? await limit(stopFilmstrip(), 15, [], log, "filmstrip") : [];
433
+ const stopped = await limit(session.send("Profiler.stop"), 120, null, log, "CPU profile");
434
+ const profile = stopped ? stopped.profile : { nodes: [], samples: [], timeDeltas: [], startTime: 0, endTime: 0 };
419
435
  fs.writeFileSync(path.join(runDir, "cpu.cpuprofile"), JSON.stringify(profile));
420
- if (heapEnabled && heapPhase !== "end") await rotateHeap("end");
421
- if (stopTrace) await stopTrace();
422
- const probe = await page.evaluate(() => (window.__btProfile ? window.__btProfile.dump() : null));
436
+ if (heapEnabled && heapPhase !== "end") await limit(rotateHeap("end"), 60, null, log, "allocation profile");
437
+ if (stopTrace) await limit(stopTrace(), 180, null, log, "trace");
438
+ const probe = await limit(page.evaluate(() => (window.__btProfile ? window.__btProfile.dump() : null)), 30, null, log, "probe");
423
439
  if (probe) {
424
440
  const recorded = new Set(probe.marks.map((mark) => mark.name));
425
441
  for (const mark of context.nodeMarks) if (!recorded.has(mark.name)) probe.marks.push({ ...mark, fromNode: true });
426
442
  probe.marks.sort((first, second) => first.at - second.at);
427
443
  }
428
- const census = await page.evaluate(() => (window.__btProfile ? window.__btProfile.census() : null)).catch(() => null);
429
- if (snapshots) await page.screenshot({ path: path.join(shotsDir, "end.png") }).catch(() => {});
430
- const scripts = await saveProfiledScripts(session, profile, scriptsDir);
431
- await session.detach();
432
- await page.close();
444
+ const census = await limit(page.evaluate(() => (window.__btProfile ? window.__btProfile.census() : null)), 20, null, log, "census");
445
+ if (snapshots) await limit(page.screenshot({ path: path.join(shotsDir, "end.png") }), 20, null, log, "end screenshot");
446
+ // A failed or overrun scenario leaves the evidence behind: what the page showed, where it was, what it complained about.
447
+ if (scenarioError || timedOut) {
448
+ const failedShot = path.join(shotsDir, "failed.png");
449
+ const shot = await limit(page.screenshot({ path: failedShot }), 20, null, log, "failure screenshot");
450
+ const where = await limit(page.evaluate(() => ({ url: location.href, title: document.title, text: (document.body ? document.body.innerText : "").trim().slice(0, 300) })), 10, null, log, "page state");
451
+ log(`failure evidence: ${shot ? "shots/failed.png" : "no screenshot"} · page ${where ? `${where.url} "${where.title}" · text: ${JSON.stringify(where.text) || "(none)"}` : "not answering"}`);
452
+ for (const entry of consoleErrors.slice(-12)) log(` console ${entry.type}: ${entry.text.split("\n")[0].slice(0, 240)}`);
453
+ if (consoleErrors.length === 0) log(" console: no errors or warnings");
454
+ }
455
+ const scripts = stopped ? await limit(saveProfiledScripts(session, profile, scriptsDir), 300, [], log, "saving scripts") : [];
456
+ await limit(session.detach(), 10, null, log, "detach");
457
+ await limit(page.close(), 15, null, log, "closing the page");
433
458
 
434
459
  const capture = {
435
460
  label,
@@ -445,6 +470,7 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
445
470
  samplingIntervalUs: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US),
446
471
  heapIncludesCollected,
447
472
  snapshots,
473
+ gpuCold: flags["gpu-cold"] === "true" ? (probe && probe.gpuCold) || { tagged: 0, untagged: 0 } : null,
448
474
  filmstripFrames: filmstrip.length,
449
475
  sync: { markerName: SYNC_MARKER_NAME, epochMs: syncEpochMs },
450
476
  census,
@@ -456,7 +482,9 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
456
482
  };
457
483
  fs.writeFileSync(path.join(runDir, "capture.json"), JSON.stringify(capture));
458
484
  if (capture.disturbed) log(`WARNING: ${capture.disturbed.reason} — this capture is not comparable; profile a server with file watching off (SKILL.md › Other sessions)`);
459
- log(`done: ${probe ? probe.frames.length : 0} frames, ${profile.samples.length} CPU samples, ${scripts.length} scripts, engine ${probe && probe.engine}`);
485
+ if (capture.gpuCold) log(`gpu-cold: ${capture.gpuCold.tagged} fragment shader(s) made unique${capture.gpuCold.untagged ? `, ${capture.gpuCold.untagged} left as they were (no fragment entry found)` : ""}`);
486
+ const compiles = probe && probe.gpuCompiles ? probe.gpuCompiles.filter((entry) => entry.kind !== "shaderModule").length : 0;
487
+ log(`done: ${probe ? probe.frames.length : 0} frames, ${profile.samples.length} CPU samples, ${scripts.length} scripts, ${compiles} pipelines / programs created, engine ${probe && probe.engine}`);
460
488
  return capture;
461
489
  }
462
490
 
@@ -488,12 +516,31 @@ async function main() {
488
516
  if (flags.autoplay !== "gesture") args.push("--autoplay-policy=no-user-gesture-required");
489
517
  if (flags.uncapped === "true") args.push("--disable-frame-rate-limit", "--disable-gpu-vsync");
490
518
  const browser = await puppeteer.launch({
519
+ // No 180 s cap on one DevTools call: a scenario may wait minutes (a slow load, a user who drives the run).
520
+ protocolTimeout: 0,
491
521
  executablePath: findChrome(),
492
- headless: flags.headed === "true" ? false : "new",
522
+ // --watch true (or --headed true): a visible window the user can watch while the profile runs
523
+ headless: (flags.headed === "true" || flags.watch === "true") ? false : "new",
493
524
  defaultViewport: null,
494
525
  userDataDir,
495
526
  args,
496
527
  });
528
+ // The lock names this capture's process and its Chrome, so `progress.mjs stop` (/bt-profile --stop) can end both. It
529
+ // lives in the slug's data folder (the working folder of every capture), and goes when the capture ends.
530
+ const lockPath = fs.existsSync("profile.config.json") ? path.resolve("capture.lock.json") : path.join(runDir, "capture.lock.json");
531
+ const browserProcess = typeof browser.process === "function" ? browser.process() : null;
532
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: process.pid, browserPid: browserProcess ? browserProcess.pid : null, out: runDir, startedAt: new Date().toISOString() }, null, 2));
533
+ const removeLock = () => { try { fs.rmSync(lockPath, { force: true }); } catch { /* already gone */ } };
534
+ process.on("exit", removeLock);
535
+ const removeProfile = () => { try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch { /* Chrome still letting go */ } };
536
+ for (const signal of ["SIGTERM", "SIGINT"]) {
537
+ process.on(signal, () => {
538
+ removeLock();
539
+ try { browser.process()?.kill("SIGKILL"); } catch { /* gone */ }
540
+ removeProfile();
541
+ process.exit(130);
542
+ });
543
+ }
497
544
  try {
498
545
  const cold = await captureOnce(browser, flags, scenario, path.join(runDir, "cold"), "cold");
499
546
  const summary = { runDir, cold: path.join(runDir, "cold") };
@@ -501,13 +548,15 @@ async function main() {
501
548
  await captureOnce(browser, flags, scenario, path.join(runDir, "warm"), "warm");
502
549
  summary.warm = path.join(runDir, "warm");
503
550
  }
504
- if (cold.probe && cold.probe.engine == null) process.stderr.write("WARNING: the probe never found a Babylon engine (window.BABYLON.EngineStore). Frame data is empty.\n");
551
+ if (cold.scenarioError || cold.timedOut) process.stderr.write("WARNING: the scenario did not finish — this capture shows the failure, not the moment; see the failure evidence above.\n");
552
+ else if (cold.probe && cold.probe.engine == null) process.stderr.write("note: no Babylon engine on this page — frames are browser frames (requestAnimationFrame): FPS and frame gaps, no draw calls or engine timers.\n");
505
553
  if (cold.census && /swiftshader|llvmpipe|software/i.test(cold.census.adapter || "")) process.stderr.write("WARNING: Chrome rendered with a software adapter — GPU numbers are not representative.\n");
506
554
  fs.writeFileSync(path.join(runDir, "run.json"), JSON.stringify({ ...summary, flags, scenario: scenario.meta }, null, 2));
507
555
  process.stdout.write(JSON.stringify(summary) + "\n");
508
556
  } finally {
509
- await browser.close();
510
- fs.rmSync(userDataDir, { recursive: true, force: true });
557
+ const closed = await limit(browser.close(), 20, null, (message) => process.stderr.write(`[bt-profile] ${message}\n`), "closing Chrome");
558
+ if (closed === null) try { browser.process()?.kill("SIGKILL"); } catch { /* gone */ }
559
+ removeProfile();
511
560
  }
512
561
  }
513
562