@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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.
@@ -0,0 +1,87 @@
1
+ /**
2
+ * bt-profile compare: prints before → after for two analyses of the same scenario — per phase (FPS, CPU ms/frame,
3
+ * busy, draws), per owner (ms/frame) and the functions whose time changed most — so a fix is kept or reverted on
4
+ * numbers, not impressions.
5
+ *
6
+ * Usage:
7
+ * node compare.mjs --before runs/baseline/cold/analysis.json --after runs/fix-1/cold/analysis.json [--focus "Name.fn,Other.fn"]
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ /**
13
+ * Reads `--name value` pairs from the command line.
14
+ * @param {string[]} argv - process.argv.slice(2)
15
+ * @returns {Record<string, string>} the parsed flags
16
+ */
17
+ function parseArguments(argv) {
18
+ const flags = {};
19
+ for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
20
+ return flags;
21
+ }
22
+
23
+ /** Formats a signed change. */
24
+ const signed = (value, digits = 1) => (value == null || Number.isNaN(value) ? " –" : `${value > 0 ? "+" : ""}${value.toFixed(digits)}`);
25
+
26
+ /** Total ms per frame of a function (inclusive) in a phase list, by display name. */
27
+ function inclusiveByName(lists) {
28
+ const map = new Map();
29
+ for (const entry of lists.inclusiveTop) map.set(entry.name, (map.get(entry.name) || 0) + (entry.msPerFrame || 0));
30
+ return map;
31
+ }
32
+
33
+ /** Entry point. */
34
+ function main() {
35
+ const flags = parseArguments(process.argv.slice(2));
36
+ const before = JSON.parse(fs.readFileSync(path.resolve(flags.before), "utf8"));
37
+ const after = JSON.parse(fs.readFileSync(path.resolve(flags.after), "utf8"));
38
+ const out = [];
39
+ const line = (text = "") => out.push(text);
40
+ line(`before: ${path.dirname(path.resolve(flags.before))} (${before.capture.capturedAt})`);
41
+ line(`after: ${path.dirname(path.resolve(flags.after))} (${after.capture.capturedAt})`);
42
+ line();
43
+ line("PHASE fps before → after CPU ms/frame before → after busy% draws");
44
+ for (const phase of after.phases) {
45
+ const previous = before.phases.find((candidate) => candidate.name === phase.name);
46
+ if (!previous) { line(` ${phase.name.padEnd(14)} (new phase)`); continue; }
47
+ const fps = `${String(previous.frames.fps).padStart(5)} → ${String(phase.frames.fps).padStart(5)} (${signed(phase.frames.fps - previous.frames.fps)})`;
48
+ const cpu = `${String(previous.frames.cpuMeanMs).padStart(6)} → ${String(phase.frames.cpuMeanMs).padStart(6)} (${signed(phase.frames.cpuMeanMs - previous.frames.cpuMeanMs, 2)})`;
49
+ line(` ${phase.name.padEnd(14)} ${fps.padEnd(26)} ${cpu.padEnd(31)} ${String(previous.busyPct).padStart(3)}→${String(phase.busyPct).padEnd(3)} ${previous.frames.draws}→${phase.frames.draws}`);
50
+ }
51
+ line();
52
+ line("OWNER ms/frame (whole run)");
53
+ const ownersBefore = new Map(before.overall.lists.owners.map((entry) => [entry.owner, entry.msPerFrame]));
54
+ for (const entry of after.overall.lists.owners) {
55
+ const previous = ownersBefore.get(entry.owner);
56
+ line(` ${entry.owner.padEnd(10)} ${String(previous ?? "–").padStart(8)} → ${String(entry.msPerFrame).padStart(8)} (${signed(previous != null ? entry.msPerFrame - previous : null, 3)})`);
57
+ }
58
+ line();
59
+ line("FUNCTIONS whose inclusive ms/frame changed most (whole run)");
60
+ const inclusiveBefore = inclusiveByName(before.overall.lists);
61
+ const inclusiveAfter = inclusiveByName(after.overall.lists);
62
+ const names = new Set([...inclusiveBefore.keys(), ...inclusiveAfter.keys()]);
63
+ const changes = [...names].map((name) => ({ name, before: inclusiveBefore.get(name) ?? 0, after: inclusiveAfter.get(name) ?? 0 }))
64
+ .map((entry) => ({ ...entry, change: entry.after - entry.before }))
65
+ .sort((a, b) => Math.abs(b.change) - Math.abs(a.change)).slice(0, 15);
66
+ for (const entry of changes) line(` ${signed(entry.change, 3).padStart(9)} ms/f ${entry.before.toFixed(3)} → ${entry.after.toFixed(3)} ${entry.name}`);
67
+ if (flags.focus) {
68
+ line();
69
+ line("FOCUS");
70
+ for (const name of flags.focus.split(",")) {
71
+ for (const phase of after.phases) {
72
+ const previous = before.phases.find((candidate) => candidate.name === phase.name);
73
+ const now = inclusiveByName(phase.lists).get(name);
74
+ const was = previous ? inclusiveByName(previous.lists).get(name) : null;
75
+ if (now == null && was == null) continue;
76
+ line(` ${name} [${phase.name}] ${was?.toFixed(3) ?? "–"} → ${now?.toFixed(3) ?? "–"} ms/frame`);
77
+ }
78
+ }
79
+ }
80
+ if (before.heap && after.heap) {
81
+ line();
82
+ line(`ALLOCATION ${before.heap.mbPerSecond} → ${after.heap.mbPerSecond} MB/s`);
83
+ }
84
+ process.stdout.write(out.join("\n") + "\n");
85
+ }
86
+
87
+ main();
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The in-page half of the bt-profile capture. `installProbe` is serialised into every document the profiled page
3
+ * opens (puppeteer `evaluateOnNewDocument`), so it must stay self-contained: no imports, no outer variables.
4
+ *
5
+ * It records, on `window.__btProfile`:
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;
8
+ * - counters sampled every half second: meshes, materials, textures, particle systems, compiled effects (shader
9
+ * programs / pipelines), JS heap;
10
+ * - long animation frames (LoAF) with their script attribution, when the browser supports them;
11
+ * - phase marks set by the scenario (`__btProfile.mark("countdown")`).
12
+ *
13
+ * Every time is an epoch time in milliseconds (`performance.timeOrigin + performance.now()`), so frames, marks and
14
+ * the CPU profile line up across page navigations.
15
+ */
16
+ export function installProbe() {
17
+ /** How often the scene counters are sampled, in milliseconds. */
18
+ const COUNTER_INTERVAL_MS = 500;
19
+ /** How often the probe looks for a new engine or scene, in milliseconds. */
20
+ const ATTACH_POLL_MS = 50;
21
+ /** Frames longer than this (ms) keep their full instrumentation breakdown in the spike list. */
22
+ const LONG_FRAME_MS = 50;
23
+
24
+ const epochNow = () => performance.timeOrigin + performance.now();
25
+ const state = {
26
+ frames: [],
27
+ counters: [],
28
+ marks: [],
29
+ longFrames: [],
30
+ loafs: [],
31
+ engineAttachedAt: null,
32
+ scenesSeen: 0,
33
+ };
34
+ window.__btProfile = state;
35
+
36
+ /** Records a named phase boundary (the scenario calls it: "intro", "countdown", "takeoff" …). */
37
+ state.mark = (name) => {
38
+ state.marks.push({ name, at: epochNow() });
39
+ return name;
40
+ };
41
+
42
+ const babylon = () => window.BABYLON || null;
43
+ const currentEngine = () => {
44
+ const library = babylon();
45
+ if (!library || !library.EngineStore) return null;
46
+ return library.EngineStore.LastCreatedEngine || null;
47
+ };
48
+ const currentScene = () => {
49
+ const library = babylon();
50
+ if (!library || !library.EngineStore) return null;
51
+ return library.EngineStore.LastCreatedScene || null;
52
+ };
53
+
54
+ let hookedEngine = null;
55
+ let hookedScene = null;
56
+ let instrumentation = null;
57
+ let frameBegin = 0;
58
+
59
+ /** Turns on every SceneInstrumentation timer this Babylon version has, for the scene now rendering. */
60
+ const instrumentScene = (scene) => {
61
+ const library = babylon();
62
+ if (!library.SceneInstrumentation) return;
63
+ if (instrumentation) {
64
+ try { instrumentation.dispose(); } catch { /* the old scene is already gone */ }
65
+ }
66
+ instrumentation = new library.SceneInstrumentation(scene);
67
+ for (const flag of ["captureFrameTime", "captureRenderTime", "captureRenderTargetsRenderTime", "captureActiveMeshesEvaluationTime",
68
+ "captureAnimationsTime", "capturePhysicsTime", "captureParticlesRenderTime", "captureCameraRenderTime", "captureInterFrameTime"]) {
69
+ try { instrumentation[flag] = true; } catch { /* timer not supported by this engine */ }
70
+ }
71
+ hookedScene = scene;
72
+ state.scenesSeen++;
73
+ };
74
+
75
+ const timer = (name) => {
76
+ const counter = instrumentation && instrumentation[name];
77
+ return counter && typeof counter.current === "number" ? counter.current : null;
78
+ };
79
+
80
+ const activeParticles = (scene) => {
81
+ let total = 0;
82
+ for (const system of scene.particleSystems || []) {
83
+ try { total += system.getActiveCount ? system.getActiveCount() : 0; } catch { /* a GPU system mid-dispose */ }
84
+ }
85
+ return total;
86
+ };
87
+
88
+ const onBeginFrame = () => { frameBegin = performance.now(); };
89
+ const onEndFrame = () => {
90
+ const end = performance.now();
91
+ const scene = hookedScene;
92
+ const engine = hookedEngine;
93
+ const drawCounter = engine && engine._drawCalls;
94
+ const frame = {
95
+ at: performance.timeOrigin + frameBegin,
96
+ cpuMs: +(end - frameBegin).toFixed(3),
97
+ draws: drawCounter && typeof drawCounter.current === "number" ? drawCounter.current : null,
98
+ activeMeshes: scene && scene.getActiveMeshes ? scene.getActiveMeshes().length : null,
99
+ particles: scene ? activeParticles(scene) : null,
100
+ renderMs: timer("renderTimeCounter"),
101
+ targetsMs: timer("renderTargetsRenderTimeCounter"),
102
+ evaluateMs: timer("activeMeshesEvaluationTimeCounter"),
103
+ animationsMs: timer("animationsTimeCounter"),
104
+ physicsMs: timer("physicsTimeCounter"),
105
+ particlesMs: timer("particlesRenderTimeCounter"),
106
+ };
107
+ state.frames.push(frame);
108
+ if (frame.cpuMs >= LONG_FRAME_MS) state.longFrames.push(frame);
109
+ };
110
+
111
+ /** Hooks the engine's frame observables once, and re-instruments whenever a new scene starts rendering. */
112
+ const attach = () => {
113
+ const engine = currentEngine();
114
+ if (engine && engine !== hookedEngine && engine.onBeginFrameObservable && engine.onEndFrameObservable) {
115
+ hookedEngine = engine;
116
+ engine.onBeginFrameObservable.add(onBeginFrame);
117
+ engine.onEndFrameObservable.add(onEndFrame);
118
+ state.engineAttachedAt = epochNow();
119
+ state.engine = engine.isWebGPU ? "WebGPU" : "WebGL" + (engine.webGLVersion || "");
120
+ }
121
+ const scene = currentScene();
122
+ if (scene && scene !== hookedScene && !scene.isDisposed) instrumentScene(scene);
123
+ };
124
+ setInterval(attach, ATTACH_POLL_MS);
125
+
126
+ /** Counts what the scene holds and how many shader programs / pipelines the engine has compiled so far. */
127
+ const sampleCounters = () => {
128
+ const engine = hookedEngine;
129
+ const scene = hookedScene;
130
+ const memory = performance.memory;
131
+ const entry = { at: epochNow(), heapMb: memory ? +(memory.usedJSHeapSize / 1048576).toFixed(1) : null };
132
+ if (engine) {
133
+ const compiled = engine._compiledEffects;
134
+ entry.compiledEffects = compiled ? Object.keys(compiled).length : null;
135
+ entry.textureCache = engine.getLoadedTexturesCache ? engine.getLoadedTexturesCache().length : null;
136
+ }
137
+ if (scene && !scene.isDisposed) {
138
+ entry.meshes = scene.meshes.length;
139
+ entry.materials = scene.materials.length;
140
+ entry.textures = scene.textures.length;
141
+ entry.particleSystems = (scene.particleSystems || []).length;
142
+ entry.animationGroups = (scene.animationGroups || []).length;
143
+ entry.skeletons = (scene.skeletons || []).length;
144
+ }
145
+ state.counters.push(entry);
146
+ };
147
+ setInterval(sampleCounters, COUNTER_INTERVAL_MS);
148
+
149
+ // Long Animation Frames name the script, function and invoker behind every frame over 50 ms.
150
+ try {
151
+ const observer = new PerformanceObserver((list) => {
152
+ for (const entry of list.getEntries()) {
153
+ state.loafs.push({
154
+ at: performance.timeOrigin + entry.startTime,
155
+ durationMs: +entry.duration.toFixed(1),
156
+ blockingMs: +(entry.blockingDuration || 0).toFixed(1),
157
+ renderMs: entry.renderStart ? +(entry.startTime + entry.duration - entry.renderStart).toFixed(1) : null,
158
+ scripts: (entry.scripts || []).slice(0, 6).map((script) => ({
159
+ invoker: script.invoker,
160
+ invokerType: script.invokerType,
161
+ sourceUrl: script.sourceURL,
162
+ sourceFunction: script.sourceFunctionName,
163
+ sourceChar: script.sourceCharPosition,
164
+ durationMs: +script.duration.toFixed(1),
165
+ forcedLayoutMs: +(script.forcedStyleAndLayoutDuration || 0).toFixed(1),
166
+ })),
167
+ });
168
+ }
169
+ });
170
+ observer.observe({ type: "long-animation-frame", buffered: true });
171
+ } catch {
172
+ // Long Animation Frames are Chrome 123+; the CPU profile still attributes the time without them.
173
+ }
174
+
175
+ /**
176
+ * Static census of the scene now rendering: what the GPU is asked to do each frame and what may be expensive.
177
+ * @returns {object|null} null before a scene exists
178
+ */
179
+ state.census = () => {
180
+ const scene = currentScene();
181
+ const engine = currentEngine();
182
+ if (!scene || !engine) return null;
183
+ const particleSystems = (scene.particleSystems || []).map((system) => ({
184
+ name: system.name,
185
+ className: system.getClassName ? system.getClassName() : "",
186
+ capacity: system.getCapacity ? system.getCapacity() : null,
187
+ emitRate: system.emitRate,
188
+ active: system.isStarted ? system.isStarted() : null,
189
+ activeCount: system.getActiveCount ? system.getActiveCount() : null,
190
+ emitter: system.emitter && system.emitter.name ? system.emitter.name : null,
191
+ }));
192
+ let adapter = "";
193
+ try { adapter = engine.getGlInfo ? JSON.stringify(engine.getGlInfo()) : ""; } catch { adapter = ""; }
194
+ return {
195
+ engine: engine.isWebGPU ? "WebGPU" : "WebGL" + (engine.webGLVersion || ""),
196
+ adapter,
197
+ hardwareScaling: engine.getHardwareScalingLevel(),
198
+ renderSize: [engine.getRenderWidth(), engine.getRenderHeight()],
199
+ devicePixelRatio: window.devicePixelRatio,
200
+ meshes: scene.meshes.length,
201
+ materials: scene.materials.length,
202
+ textures: scene.textures.length,
203
+ lights: scene.lights.length,
204
+ shadowGenerators: scene.lights.filter((light) => light.getShadowGenerator && light.getShadowGenerator()).length,
205
+ skeletons: (scene.skeletons || []).length,
206
+ animationGroups: (scene.animationGroups || []).length,
207
+ compiledEffects: engine._compiledEffects ? Object.keys(engine._compiledEffects).length : null,
208
+ particleSystems,
209
+ postProcesses: scene.activeCamera && scene.activeCamera._postProcesses ? scene.activeCamera._postProcesses.filter(Boolean).map((post) => post.name) : [],
210
+ physics: !!(scene.getPhysicsEngine && scene.getPhysicsEngine()),
211
+ };
212
+ };
213
+
214
+ /** Everything the probe recorded, for the capture script to save. */
215
+ state.dump = () => ({
216
+ engine: state.engine || null,
217
+ engineAttachedAt: state.engineAttachedAt,
218
+ scenesSeen: state.scenesSeen,
219
+ frames: state.frames,
220
+ counters: state.counters,
221
+ marks: state.marks,
222
+ loafs: state.loafs,
223
+ location: location.href,
224
+ });
225
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The live progress panel of a bt-profile dashboard: what the profile is doing right now, its stages, its fixes and
3
+ * the numbers so far — read from `data/progress.js` (written by `progress.mjs`) and refreshed while the run goes on.
4
+ *
5
+ * Used twice: `report.mjs` puts it at the top of the finished report, and `progress.mjs start` writes a live page
6
+ * around it when a slug has no report yet. A page opened from disk (`file://`) may load a neighbouring `<script src>`
7
+ * but not fetch a JSON file, so the data is a script that sets `window.PROFILE_PROGRESS`, re-loaded to check for
8
+ * changes. The panel takes the report's colours where they exist and falls back to its own on the live page.
9
+ */
10
+
11
+ /** Marks a page that carries the panel; `progress.mjs start` replaces a dashboard without it. */
12
+ export const PROGRESS_MARKER = "<!-- bt-profile progress panel -->";
13
+
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);
16
+ --btp-text: var(--text-primary, #f0efec); --btp-muted: var(--text-secondary, #c3c2b7); --btp-faint: var(--text-muted, #8f8e86);
17
+ --btp-good: var(--good, #3fae5a); --btp-active: var(--warning, #c98500); --btp-bad: var(--critical, #e66767); --btp-accent: var(--accent, #3987e5);
18
+ --btp-mono: var(--mono, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
19
+ margin: 18px 0 8px; display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr); color: var(--btp-text); }
20
+ .bt-progress:empty { display: none; }
21
+ .btp-card { background: var(--btp-surface); border: 1px solid var(--btp-line); border-radius: 10px; padding: 16px 18px; min-width: 0; }
22
+ .btp-kicker { font: 600 11px/1.5 var(--btp-mono); letter-spacing: 0.12em; text-transform: uppercase; color: var(--btp-faint); display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
23
+ .btp-kicker b { color: var(--btp-text); font-weight: 700; }
24
+ .btp-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--btp-active); animation: btp-pulse 1.6s ease-in-out infinite; }
25
+ @keyframes btp-pulse { 50% { opacity: 0.3; } }
26
+ @media (prefers-reduced-motion: reduce) { .btp-dot { animation: none; } }
27
+ .btp-now { border-left: 3px solid var(--btp-active); }
28
+ .btp-now.is-stale { border-left-color: var(--btp-bad); }
29
+ .btp-age { text-transform: none; letter-spacing: 0; font-weight: 500; }
30
+ .btp-now.is-stale .btp-age { color: var(--btp-bad); font-weight: 700; }
31
+ .btp-activity { margin: 8px 0 0; font-size: 17px; font-weight: 600; line-height: 1.4; overflow-wrap: anywhere; }
32
+ .btp-warning { margin: 10px 0 0; padding: 8px 12px; border-radius: 6px; background: color-mix(in srgb, var(--btp-bad) 14%, transparent); font-size: 13.5px; }
33
+ .btp-steps { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 4px; font-size: 13.5px; color: var(--btp-muted); }
34
+ .btp-steps li { display: grid; grid-template-columns: 48px minmax(0, 1fr); gap: 10px; overflow-wrap: anywhere; }
35
+ .btp-steps time { font: 600 12px/1.6 var(--btp-mono); color: var(--btp-faint); }
36
+ .btp-steps li:last-child { color: var(--btp-text); font-weight: 600; }
37
+ .btp-tag { padding: 1px 7px; border-radius: 5px; border: 1px solid var(--btp-line); font: 600 10.5px/1.5 var(--btp-mono); letter-spacing: 0.06em; text-transform: uppercase; }
38
+ .btp-tag.is-watchdog { color: var(--btp-active); border-color: color-mix(in srgb, var(--btp-active) 45%, transparent); }
39
+ .btp-stages { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; }
40
+ .btp-stage { min-width: 0; display: flex; flex-direction: column; }
41
+ .btp-bar { height: 8px; border-radius: 999px; background: var(--btp-line); overflow: hidden; }
42
+ .btp-fill { height: 100%; width: 0; border-radius: 999px; background: var(--btp-good); }
43
+ .btp-stage.is-done .btp-fill { width: 100%; }
44
+ .btp-stage.is-active .btp-fill { width: 50%; background: var(--btp-active); }
45
+ .btp-stage.is-skipped .btp-bar { background: repeating-linear-gradient(90deg, var(--btp-line) 0 6px, transparent 6px 10px); }
46
+ .btp-stage-label { flex: 1; margin-top: 7px; padding: 7px 9px; border: 1px solid var(--btp-line); border-radius: 8px; background: var(--btp-sunken); font: 500 11.5px/1.3 var(--btp-mono); color: var(--btp-muted); min-width: 0; }
47
+ .btp-stage.is-active .btp-stage-label { border-color: color-mix(in srgb, var(--btp-active) 45%, transparent); color: var(--btp-text); }
48
+ .btp-stage-name { display: block; font-weight: 700; color: var(--btp-text); }
49
+ .btp-stage-note { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; overflow-wrap: anywhere; margin-top: 2px; }
50
+ .btp-metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
51
+ .btp-metric { background: var(--btp-sunken); border: 1px solid var(--btp-line); border-radius: 8px; padding: 10px 12px; min-width: 0; }
52
+ .btp-metric-label { font: 600 10.5px/1.4 var(--btp-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--btp-faint); }
53
+ .btp-metric-value { margin-top: 4px; font-size: 20px; font-weight: 700; overflow-wrap: anywhere; }
54
+ .btp-metric-note { margin-top: 2px; font-size: 12.5px; color: var(--btp-muted); overflow-wrap: anywhere; }
55
+ .btp-table { width: 100%; table-layout: fixed; border-collapse: collapse; font-size: 13.5px; }
56
+ .btp-table th { text-align: left; padding: 6px 8px; font: 600 10.5px/1.4 var(--btp-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--btp-faint); border-bottom: 1px solid var(--btp-line); }
57
+ .btp-table td { padding: 8px; vertical-align: top; border-bottom: 1px solid var(--btp-line); overflow-wrap: anywhere; }
58
+ .btp-chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font: 700 11px/1.6 var(--btp-mono); text-transform: uppercase; letter-spacing: 0.04em; background: var(--btp-sunken); color: var(--btp-muted); }
59
+ .btp-chip.is-kept { color: var(--btp-good); background: color-mix(in srgb, var(--btp-good) 15%, transparent); }
60
+ .btp-chip.is-reverted, .btp-chip.is-failed { color: var(--btp-bad); background: color-mix(in srgb, var(--btp-bad) 14%, transparent); }
61
+ .btp-chip.is-trying, .btp-chip.is-measuring { color: var(--btp-active); background: color-mix(in srgb, var(--btp-active) 15%, transparent); }
62
+ .btp-section-title { margin: 0 0 10px; font: 700 11px/1.5 var(--btp-mono); letter-spacing: 0.12em; text-transform: uppercase; color: var(--btp-faint); }
63
+ .btp-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; font-size: 13.5px; max-height: 320px; overflow-y: auto; }
64
+ .btp-log li { display: grid; grid-template-columns: 52px minmax(0, 1fr); gap: 10px; overflow-wrap: anywhere; }
65
+ .btp-log time { font: 600 12px/1.6 var(--btp-mono); color: var(--btp-faint); }
66
+ .btp-done > summary { cursor: pointer; list-style: none; }
67
+ .btp-done > summary::-webkit-details-marker { display: none; }
68
+ .btp-done > summary::before { content: "▸ "; color: var(--btp-faint); }
69
+ .btp-done[open] > summary::before { content: "▾ "; }
70
+ .btp-done[open] > summary { margin-bottom: 14px; }
71
+ .btp-done-body { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr); }
72
+ .btp-summary { margin: 8px 0 0; color: var(--btp-muted); font-size: 14px; }
73
+ .btp-stopped { border-left: 3px solid var(--btp-bad); }
74
+ .btp-hint { margin: 0; color: var(--btp-muted); font-size: 14px; }
75
+ @media (max-width: 640px) {
76
+ .btp-table, .btp-table tbody, .btp-table tr, .btp-table td { display: block; width: 100%; }
77
+ .btp-table thead { display: none; }
78
+ .btp-table tr { padding: 8px 0; border-bottom: 1px solid var(--btp-line); }
79
+ .btp-table td { border: 0; padding: 2px 0; }
80
+ .btp-table td:empty { display: none; }
81
+ .btp-table td::before { content: attr(data-label); display: block; font: 600 10.5px/1.6 var(--btp-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--btp-faint); }
82
+ }
83
+ `;
84
+
85
+ export const PROGRESS_SCRIPT = String.raw`
86
+ (function () {
87
+ "use strict";
88
+ // How often the page checks the progress file while a run is going, and while it is not.
89
+ var RUNNING_CHECK_SECONDS = 10;
90
+ var IDLE_CHECK_SECONDS = 30;
91
+ // A run that has written nothing for this long is flagged on the page.
92
+ var STALE_MINUTES = 15;
93
+ var DATA_SOURCE = "data/progress.js";
94
+ var root = document.getElementById("bt-progress");
95
+ if (!root) return;
96
+ var lastFingerprint = null;
97
+ var sawRunning = false;
98
+
99
+ function esc(value) {
100
+ return String(value == null ? "" : value).replace(/[&<>"']/g, function (c) { return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]; });
101
+ }
102
+ function parseStamp(stamp) {
103
+ var m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(String(stamp || ""));
104
+ return m ? new Date(+m[1], m[2] - 1, +m[3], +m[4], +m[5]) : null;
105
+ }
106
+ function minutesSince(stamp) {
107
+ var at = parseStamp(stamp);
108
+ return at ? Math.max(0, Math.floor((Date.now() - at) / 60000)) : null;
109
+ }
110
+ function duration(minutes) {
111
+ if (minutes == null) return "";
112
+ return minutes >= 60 ? Math.floor(minutes / 60) + " h " + (minutes % 60) + " min" : minutes + " min";
113
+ }
114
+ function ago(stamp) {
115
+ var minutes = minutesSince(stamp);
116
+ return minutes == null ? "" : minutes < 1 ? "just now" : duration(minutes) + " ago";
117
+ }
118
+ function between(start, end) {
119
+ var a = parseStamp(start), b = parseStamp(end);
120
+ return a && b ? Math.max(0, Math.round((b - a) / 60000)) : null;
121
+ }
122
+ function list(value) { return Array.isArray(value) ? value : []; }
123
+
124
+ function renderStages(progress) {
125
+ return '<div class="btp-stages">' + list(progress.stages).map(function (stage) {
126
+ var times = stage.started ? esc(stage.started) + (stage.finished ? "–" + esc(stage.finished) : "") : "";
127
+ var note = stage.note || (stage.status === "skipped" ? "skipped" : times);
128
+ return '<div class="btp-stage is-' + esc(stage.status || "pending") + '" title="' + esc(stage.name + (stage.note ? " — " + stage.note : "") + (times ? " · " + times : "")) + '">' +
129
+ '<div class="btp-bar"><div class="btp-fill"></div></div>' +
130
+ '<div class="btp-stage-label"><span class="btp-stage-name">' + esc(stage.name) + '</span><span class="btp-stage-note">' + esc(note) + "</span></div></div>";
131
+ }).join("") + "</div>";
132
+ }
133
+
134
+ function renderMetrics(progress) {
135
+ var metrics = list(progress.metrics);
136
+ if (!metrics.length) return "";
137
+ return '<div class="btp-metrics">' + metrics.map(function (metric) {
138
+ return '<div class="btp-metric"><div class="btp-metric-label">' + esc(metric.label) + '</div><div class="btp-metric-value">' + esc(metric.value) + "</div>" +
139
+ (metric.note ? '<div class="btp-metric-note">' + esc(metric.note) + "</div>" : "") + "</div>";
140
+ }).join("") + "</div>";
141
+ }
142
+
143
+ function renderFixes(progress) {
144
+ var fixes = list(progress.fixes);
145
+ if (!fixes.length) return "";
146
+ var headings = ["Fix", "Status", "Before → after", "Note"];
147
+ return '<div class="btp-card"><h3 class="btp-section-title">Fixes · ' + fixes.filter(function (f) { return f.status === "kept"; }).length + " kept · " +
148
+ fixes.filter(function (f) { return f.status === "reverted"; }).length + ' reverted</h3><table class="btp-table"><colgroup><col style="width:34%"><col style="width:14%"><col style="width:22%"><col style="width:30%"></colgroup>' +
149
+ "<thead><tr>" + headings.map(function (h) { return "<th>" + h + "</th>"; }).join("") + "</tr></thead><tbody>" +
150
+ fixes.map(function (fix) {
151
+ var change = fix.before || fix.after ? esc(fix.before || "–") + " → " + esc(fix.after || "…") : "–";
152
+ return '<tr><td data-label="Fix"><b>' + esc(fix.id) + "</b> " + esc(fix.title) + '</td><td data-label="Status"><span class="btp-chip is-' + esc(fix.status) + '">' + esc(fix.status) +
153
+ '</span></td><td data-label="Before → after">' + change + '</td><td data-label="Note">' + esc(fix.note) + "</td></tr>";
154
+ }).join("") + "</tbody></table></div>";
155
+ }
156
+
157
+ function renderLog(progress, limit) {
158
+ var entries = list(progress.activity).slice().reverse();
159
+ if (!entries.length) return "";
160
+ return '<div class="btp-card"><h3 class="btp-section-title">Milestones</h3><ul class="btp-log">' +
161
+ entries.slice(0, limit || entries.length).map(function (entry) {
162
+ var clock = String(entry.at || "").slice(11, 16) || esc(entry.at);
163
+ return "<li><time>" + esc(clock) + "</time><span>" + esc(entry.text) + "</span></li>";
164
+ }).join("") + "</ul></div>";
165
+ }
166
+
167
+ function renderNow(progress) {
168
+ var now = progress.now || {};
169
+ var quiet = minutesSince(now.updatedAt);
170
+ var stale = quiet != null && quiet >= STALE_MINUTES;
171
+ var active = list(progress.stages).filter(function (s) { return s.status === "active"; })[0];
172
+ var steps = list(now.steps);
173
+ var elapsed = minutesSince(progress.startedAt);
174
+ return '<div class="btp-card btp-now' + (stale ? " is-stale" : "") + '">' +
175
+ '<div class="btp-kicker"><span class="btp-dot"></span><b>Profiling now</b>' + (active ? "<span>· " + esc(active.name) + "</span>" : "") +
176
+ (now.source === "watchdog" ? '<span class="btp-tag is-watchdog" title="Written by the watchdog because the agent has been quiet">watchdog</span>' : "") +
177
+ '<span class="btp-age" data-btp-age="' + esc(now.updatedAt) + '">' + esc(ago(now.updatedAt)) + "</span>" +
178
+ (elapsed != null ? "<span>· running " + esc(duration(elapsed)) + "</span>" : "") + "</div>" +
179
+ '<p class="btp-activity">' + esc(now.activity || "Starting…") + "</p>" +
180
+ (stale ? '<p class="btp-warning">Nothing written for ' + esc(duration(quiet)) + ". The run may be busy with a long capture, waiting, or stopped — check the session.</p>" : "") +
181
+ (steps.length ? '<ol class="btp-steps">' + steps.map(function (step) { return "<li><time>" + esc(step.at) + "</time><span>" + esc(step.text) + "</span></li>"; }).join("") + "</ol>" : "") +
182
+ "</div>";
183
+ }
184
+
185
+ function render(progress) {
186
+ var running = progress.status === "running";
187
+ var title = esc(progress.title || "Profile run");
188
+ if (running) {
189
+ sawRunning = true;
190
+ root.innerHTML = renderNow(progress) + '<div class="btp-card">' + renderStages(progress) + "</div>" + renderMetrics(progress) + renderFixes(progress) + renderLog(progress, 12);
191
+ return;
192
+ }
193
+ var stages = list(progress.stages);
194
+ var stoppedAt = stages.filter(function (s) { return s.status === "active"; })[0];
195
+ var fixes = list(progress.fixes);
196
+ var kept = fixes.filter(function (f) { return f.status === "kept"; }).length;
197
+ var reverted = fixes.filter(function (f) { return f.status === "reverted"; }).length;
198
+ var total = between(progress.startedAt, progress.finishedAt);
199
+ var headline = (progress.status === "done" ? "Profile finished" : progress.status === "failed" ? "Profile failed" : "Profile stopped") +
200
+ (progress.finishedAt ? " " + esc(progress.finishedAt) : "") + (total != null ? " · " + esc(duration(total)) : "") +
201
+ (fixes.length ? " · " + kept + " fix" + (kept === 1 ? "" : "es") + " kept, " + reverted + " reverted" : "");
202
+ var body = '<div class="btp-done-body"><div class="btp-card">' + renderStages(progress) + "</div>" + renderMetrics(progress) + renderFixes(progress) + renderLog(progress) + "</div>";
203
+ if (progress.status === "done") {
204
+ 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>";
206
+ } else {
207
+ 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;
209
+ }
210
+ }
211
+
212
+ function fingerprint(progress) { return JSON.stringify(progress); }
213
+
214
+ function load() {
215
+ var script = document.createElement("script");
216
+ script.src = DATA_SOURCE + "?check=" + Date.now();
217
+ script.onload = function () {
218
+ script.remove();
219
+ var progress = window.PROFILE_PROGRESS;
220
+ if (!progress || typeof progress !== "object") return schedule(IDLE_CHECK_SECONDS);
221
+ var print = fingerprint(progress);
222
+ if (print !== lastFingerprint) {
223
+ lastFingerprint = print;
224
+ // A run this page watched has ended: reload once, so the page shows the report it wrote.
225
+ if (sawRunning && progress.status !== "running") return setTimeout(function () { location.reload(); }, 3000);
226
+ try { render(progress); } catch (error) { root.innerHTML = '<div class="btp-card btp-stopped"><p class="btp-hint">The progress file could not be shown: ' + esc(error.message) + "</p></div>"; }
227
+ }
228
+ schedule(progress.status === "running" ? RUNNING_CHECK_SECONDS : IDLE_CHECK_SECONDS);
229
+ };
230
+ script.onerror = function () { script.remove(); schedule(IDLE_CHECK_SECONDS); };
231
+ document.head.appendChild(script);
232
+ }
233
+ function schedule(seconds) { setTimeout(load, seconds * 1000); }
234
+ // Ages move on between checks.
235
+ setInterval(function () {
236
+ document.querySelectorAll("[data-btp-age]").forEach(function (element) { element.textContent = ago(element.getAttribute("data-btp-age")); });
237
+ }, 30000);
238
+ load();
239
+ })();
240
+ `;
241
+
242
+ /** The panel's place in a page. */
243
+ export function progressMarkup() {
244
+ return `${PROGRESS_MARKER}\n<section class="bt-progress" id="bt-progress" aria-live="polite"></section>`;
245
+ }
246
+
247
+ /** The live page for a slug that has no report yet: the panel alone, until `report.mjs` writes the report. */
248
+ export function livePage({ title }) {
249
+ const safeTitle = String(title || "Profile").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" })[c]);
250
+ return `<!doctype html>
251
+ <html lang="en">
252
+ <head>
253
+ <meta charset="utf-8">
254
+ <meta name="viewport" content="width=device-width, initial-scale=1">
255
+ <title>${safeTitle}</title>
256
+ <style>
257
+ :root { color-scheme: dark; --surface-0: #111110; --surface-1: #1a1a19; --surface-3: #2d2d2a; --text-primary: #f0efec; --text-secondary: #c3c2b7; --text-muted: #8f8e86; }
258
+ @media (prefers-color-scheme: light) { :root { color-scheme: light; --surface-0: #f4f4f2; --surface-1: #fcfcfb; --surface-3: #e4e3df; --text-primary: #0b0b0b; --text-secondary: #52514e; --text-muted: #77766f; } }
259
+ body { margin: 0; background: var(--surface-0); color: var(--text-primary); font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif; }
260
+ main { max-width: 1100px; margin: 0 auto; padding: 28px 16px 60px; }
261
+ h1 { margin: 0; font-size: 24px; }
262
+ .lede { margin: 6px 0 0; color: var(--text-secondary); }
263
+ ${PROGRESS_STYLES}
264
+ </style>
265
+ </head>
266
+ <body>
267
+ <main>
268
+ <h1>${safeTitle}</h1>
269
+ <p class="lede">The performance report appears here when the profile finishes. Until then this page follows the run.</p>
270
+ ${progressMarkup()}
271
+ </main>
272
+ <script>${PROGRESS_SCRIPT}</script>
273
+ </body>
274
+ </html>`;
275
+ }