@babylonjs-toolkit/agent 1.1.66 → 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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-design/SKILL.md +7 -0
- package/skills/bt-design/templates/3d-hero-scroll/hero-scroll.js +27 -9
- package/skills/bt-execute/SKILL.md +4 -4
- package/skills/bt-execute/templates/dashboard/dashboard.html +96 -21
- package/skills/bt-execute/templates/dashboard/data-schema.md +4 -3
- package/skills/bt-gauntlet/references/critic-rubrics.md +1 -0
- package/skills/bt-plan/SKILL.md +1 -1
- package/skills/bt-profile/SKILL.md +318 -0
- package/skills/bt-profile/scripts/analyze.mjs +735 -0
- package/skills/bt-profile/scripts/compare.mjs +87 -0
- package/skills/bt-profile/scripts/lib/chrome.mjs +22 -0
- package/skills/bt-profile/scripts/lib/probe.mjs +340 -0
- package/skills/bt-profile/scripts/lib/progress-panel.mjs +371 -0
- package/skills/bt-profile/scripts/lib/symbolize.mjs +356 -0
- package/skills/bt-profile/scripts/package.json +10 -0
- package/skills/bt-profile/scripts/profile.mjs +566 -0
- package/skills/bt-profile/scripts/progress.mjs +516 -0
- package/skills/bt-profile/scripts/report.mjs +803 -0
- package/skills/bt-profile/templates/census.template.mjs +76 -0
- package/skills/bt-profile/templates/scenario.template.mjs +78 -0
- package/skills/bt-prototype/SKILL.md +1 -1
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bt-profile capture: opens a Babylon Toolkit web game in a real Chrome (GPU on, fresh profile = cold shader and HTTP
|
|
3
|
+
* caches), runs a scenario (a small module that drives the game: open the page, wait for phases, hold keys, mark
|
|
4
|
+
* phases, take screenshots), and records everything needed to name the code behind every slow frame:
|
|
5
|
+
*
|
|
6
|
+
* - a V8 sampling CPU profile of the whole scenario (`cpu.cpuprofile`, opens in DevTools too);
|
|
7
|
+
* - a sampling allocation profile that includes collected objects (`heap.heapprofile`) — who feeds the GC;
|
|
8
|
+
* - the in-page probe's per-frame CPU work, Babylon timers, scene counters, phase marks and long animation frames;
|
|
9
|
+
* - the source text and source map of every script the profile hit (`scripts/`), so analysis can map minified or
|
|
10
|
+
* transformed positions back to original files offline;
|
|
11
|
+
* - optional: a full DevTools performance trace (`--trace true`), and a second, warm load in the same browser
|
|
12
|
+
* (`--warm true`) to separate first-use costs (shader compiles, decoding) from steady per-frame work;
|
|
13
|
+
* - optional (`--snapshots true`): the scenario's phase screenshots plus a filmstrip — about one small frame per
|
|
14
|
+
* second from Chrome's screencast, timed on the same clock as the frames. Off by default: a full-size screenshot
|
|
15
|
+
* stalls the game for a moment and would show up in the very profile it is meant to explain.
|
|
16
|
+
*
|
|
17
|
+
* Usage (from `.agents/profile/<slug>/data`, whose profile.config.json supplies the defaults for --url and --scenario):
|
|
18
|
+
* node ../../.tools/profile.mjs --out runs/baseline [--url http://localhost:5173/play] [--scenario scenario.mjs]
|
|
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] [--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.
|
|
28
|
+
*/
|
|
29
|
+
import fs from "node:fs";
|
|
30
|
+
import os from "node:os";
|
|
31
|
+
import path from "node:path";
|
|
32
|
+
import { pathToFileURL } from "node:url";
|
|
33
|
+
import puppeteer from "puppeteer-core";
|
|
34
|
+
import { installProbe, installGpuCold } from "./lib/probe.mjs";
|
|
35
|
+
import { findChrome } from "./lib/chrome.mjs";
|
|
36
|
+
|
|
37
|
+
/** Default sampling interval of the CPU profiler, in microseconds (DevTools uses 100–1000). */
|
|
38
|
+
const DEFAULT_SAMPLING_INTERVAL_US = 250;
|
|
39
|
+
/** Console lines a dev server's client prints when it hot-patches or reloads the page (Vite, webpack, Parcel, Next). */
|
|
40
|
+
const DEV_SERVER_UPDATE = /^\[vite\] (hot updated|page reload|.*full reload)|^\[HMR\]|^\[webpack-dev-server\].*(reload|updated)|^\[parcel\].*(updated|reload)|^\[Fast Refresh\]/i;
|
|
41
|
+
/** Allocation sampling interval, in bytes: one sample per this many bytes allocated, on average. */
|
|
42
|
+
const HEAP_SAMPLING_INTERVAL_BYTES = 32768;
|
|
43
|
+
/** Hard ceiling on one scenario run, in seconds, so a stuck scenario never hangs the capture. */
|
|
44
|
+
const DEFAULT_MAX_SECONDS = 240;
|
|
45
|
+
/** Name of the busy-wait function that ties CPU-profile timestamps to page epoch time. */
|
|
46
|
+
const SYNC_MARKER_NAME = "__btProfileSyncMarker";
|
|
47
|
+
/** How long the sync marker busy-waits, in milliseconds — long enough to be sampled many times. */
|
|
48
|
+
const SYNC_MARKER_MS = 4;
|
|
49
|
+
/** Trace categories DevTools' Performance panel records, so `trace.json` opens there with a flame chart. */
|
|
50
|
+
const TRACE_CATEGORIES = [
|
|
51
|
+
"-*", "devtools.timeline", "disabled-by-default-devtools.timeline", "disabled-by-default-devtools.timeline.frame",
|
|
52
|
+
"v8.execute", "blink.user_timing", "loading", "latencyInfo", "disabled-by-default-v8.cpu_profiler", "v8", "gpu",
|
|
53
|
+
"disabled-by-default-devtools.timeline.stack",
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Reads `--name value` pairs from the command line.
|
|
58
|
+
* @param {string[]} argv - process.argv.slice(2)
|
|
59
|
+
* @returns {Record<string, string>} the parsed flags
|
|
60
|
+
*/
|
|
61
|
+
function parseArguments(argv) {
|
|
62
|
+
const flags = {};
|
|
63
|
+
for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
|
|
64
|
+
return flags;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Parses `key=value,key2=value2` into an object of strings, for scenario options.
|
|
69
|
+
* @param {string|undefined} text - the raw `--args` value
|
|
70
|
+
* @returns {Record<string, string>} the options
|
|
71
|
+
*/
|
|
72
|
+
function parseScenarioArguments(text) {
|
|
73
|
+
const options = {};
|
|
74
|
+
for (const pair of (text || "").split(",").filter(Boolean)) {
|
|
75
|
+
const [key, ...rest] = pair.split("=");
|
|
76
|
+
options[key.trim()] = rest.join("=").trim();
|
|
77
|
+
}
|
|
78
|
+
return options;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Pauses for the given number of seconds. */
|
|
82
|
+
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
83
|
+
|
|
84
|
+
/**
|
|
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
|
|
88
|
+
*/
|
|
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
|
+
}
|
|
102
|
+
}
|
|
103
|
+
limit.TIMED_OUT = Symbol("timed out");
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Runs the sync marker in the page: a named function that busy-waits a few milliseconds. Its first sample in the CPU
|
|
107
|
+
* profile and the epoch time it returns pin the profile's clock to the page's clock.
|
|
108
|
+
* @param {import("puppeteer-core").Page} page - the profiled page
|
|
109
|
+
* @returns {Promise<number>} epoch milliseconds at which the marker started
|
|
110
|
+
*/
|
|
111
|
+
async function runSyncMarker(page) {
|
|
112
|
+
return page.evaluate(`(function ${SYNC_MARKER_NAME}() {
|
|
113
|
+
const startedAt = performance.timeOrigin + performance.now();
|
|
114
|
+
const until = performance.now() + ${SYNC_MARKER_MS};
|
|
115
|
+
let spins = 0;
|
|
116
|
+
while (performance.now() < until) spins++;
|
|
117
|
+
return startedAt;
|
|
118
|
+
})()`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Loads the scenario module. A scenario exports `meta` ({ name, description }) and `async run(context)`.
|
|
123
|
+
* @param {string|undefined} scenarioPath - path of the scenario module, or undefined for the built-in idle scenario
|
|
124
|
+
* @returns {Promise<{meta: object, run: Function}>} the scenario
|
|
125
|
+
*/
|
|
126
|
+
async function loadScenario(scenarioPath) {
|
|
127
|
+
if (!scenarioPath) {
|
|
128
|
+
return {
|
|
129
|
+
meta: { name: "idle", description: "Opens the URL and records for --idle seconds (default 60) after the first frame." },
|
|
130
|
+
run: async (context) => {
|
|
131
|
+
await context.open();
|
|
132
|
+
await context.waitForFrames();
|
|
133
|
+
context.mark("running");
|
|
134
|
+
await context.sleep(Number(context.options.idle || 60));
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const module = await import(pathToFileURL(path.resolve(scenarioPath)).href);
|
|
139
|
+
if (typeof module.run !== "function") throw new Error(`Scenario ${scenarioPath} must export an async run(context) function.`);
|
|
140
|
+
return { meta: module.meta || { name: path.basename(scenarioPath, path.extname(scenarioPath)) }, run: module.run };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Says whether the game restarted under the capture without the scenario asking: a document load after the first
|
|
145
|
+
* open() with no open() since the previous load, or the dev server hot-patching the page.
|
|
146
|
+
* @returns {{reason: string, unexpectedNavigations: object[], devServerUpdates: object[], scenesSeen: number}|null}
|
|
147
|
+
*/
|
|
148
|
+
function disturbance(context, navigations, devServerUpdates, probe) {
|
|
149
|
+
const opens = context.openTimes;
|
|
150
|
+
const unexpectedNavigations = [];
|
|
151
|
+
let previousLoad = opens.length ? opens[0] : Infinity;
|
|
152
|
+
for (const navigation of navigations) {
|
|
153
|
+
if (navigation.at < previousLoad) continue; // the start page, or the first load the scenario asked for
|
|
154
|
+
if (!opens.some((at) => at >= previousLoad && at <= navigation.at)) unexpectedNavigations.push(navigation);
|
|
155
|
+
previousLoad = navigation.at;
|
|
156
|
+
}
|
|
157
|
+
if (unexpectedNavigations.length === 0 && devServerUpdates.length === 0) return null;
|
|
158
|
+
const parts = [];
|
|
159
|
+
if (unexpectedNavigations.length) parts.push(`${unexpectedNavigations.length} page reload(s) the scenario did not ask for`);
|
|
160
|
+
if (devServerUpdates.length) parts.push(`${devServerUpdates.length} dev-server update(s) (${devServerUpdates[0].text})`);
|
|
161
|
+
return { reason: parts.join(", "), unexpectedNavigations, devServerUpdates: devServerUpdates.slice(0, 40), scenesSeen: probe ? probe.scenesSeen : null };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Builds the object a scenario drives the game through.
|
|
166
|
+
* @returns {object} the scenario context
|
|
167
|
+
*/
|
|
168
|
+
function createScenarioContext(page, targetUrl, shotsDir, options, log, snapshots, onMark) {
|
|
169
|
+
const nodeMarks = [];
|
|
170
|
+
const context = {
|
|
171
|
+
nodeMarks,
|
|
172
|
+
/** When the scenario asked for a navigation (a document load no open() asked for is a dev-server reload). */
|
|
173
|
+
openTimes: [],
|
|
174
|
+
page,
|
|
175
|
+
options,
|
|
176
|
+
url: targetUrl,
|
|
177
|
+
log,
|
|
178
|
+
sleep,
|
|
179
|
+
/** Navigates to the target URL (or another URL / path on the same origin). */
|
|
180
|
+
open: async (urlOrPath) => {
|
|
181
|
+
const destination = urlOrPath ? new URL(urlOrPath, targetUrl).href : targetUrl;
|
|
182
|
+
log(`open ${destination}`);
|
|
183
|
+
context.openTimes.push(Date.now());
|
|
184
|
+
await page.goto(destination, { waitUntil: "domcontentloaded", timeout: 600000 });
|
|
185
|
+
},
|
|
186
|
+
/**
|
|
187
|
+
* Says the next page load is the scenario's own doing (a click on a link or button that navigates), so the
|
|
188
|
+
* capture does not report it as a dev-server reload. Call it just before the click.
|
|
189
|
+
*/
|
|
190
|
+
expectNavigation: () => { context.openTimes.push(Date.now()); },
|
|
191
|
+
/** Records a phase boundary in the page's clock. */
|
|
192
|
+
mark: async (name) => {
|
|
193
|
+
log(`mark ${name}`);
|
|
194
|
+
// Kept on this side too: a mark sent while a navigation commits can miss the page's recorder.
|
|
195
|
+
nodeMarks.push({ name, at: Date.now() });
|
|
196
|
+
await page.evaluate((markName) => window.__btProfile && window.__btProfile.mark(markName), name);
|
|
197
|
+
if (onMark) await onMark(name);
|
|
198
|
+
},
|
|
199
|
+
/** Waits until a page function returns truthy (polls every 100 ms). */
|
|
200
|
+
waitFor: (pageFunction, { timeout = 600000, polling = 100, args = [] } = {}) =>
|
|
201
|
+
page.waitForFunction(pageFunction, { timeout, polling }, ...args),
|
|
202
|
+
/** Waits until the page has rendered at least `count` frames (Babylon frames on a Babylon page, else browser frames). */
|
|
203
|
+
waitForFrames: (count = 10, timeout = 600000) =>
|
|
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),
|
|
206
|
+
evaluate: (pageFunction, ...args) => page.evaluate(pageFunction, ...args),
|
|
207
|
+
keyDown: (key) => page.keyboard.down(key),
|
|
208
|
+
keyUp: (key) => page.keyboard.up(key),
|
|
209
|
+
press: (key) => page.keyboard.press(key),
|
|
210
|
+
/** Saves a screenshot under shots/<name>.png — only with --snapshots true; otherwise a no-op returning null. */
|
|
211
|
+
shot: async (name) => {
|
|
212
|
+
if (!snapshots) return null;
|
|
213
|
+
const file = path.join(shotsDir, `${name}.png`);
|
|
214
|
+
await page.screenshot({ path: file });
|
|
215
|
+
log(`shot ${path.basename(file)}`);
|
|
216
|
+
return file;
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
return context;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Fetches a script's source map: inline `data:` URLs are decoded, anything else is fetched relative to the script.
|
|
224
|
+
* @returns {Promise<string|null>} the source map JSON text, or null when there is none or it cannot be fetched
|
|
225
|
+
*/
|
|
226
|
+
async function fetchSourceMap(scriptUrl, sourceMapUrl) {
|
|
227
|
+
if (!sourceMapUrl) return null;
|
|
228
|
+
try {
|
|
229
|
+
if (sourceMapUrl.startsWith("data:")) {
|
|
230
|
+
const comma = sourceMapUrl.indexOf(",");
|
|
231
|
+
const header = sourceMapUrl.slice(0, comma);
|
|
232
|
+
const body = sourceMapUrl.slice(comma + 1);
|
|
233
|
+
return header.includes(";base64") ? Buffer.from(body, "base64").toString("utf8") : decodeURIComponent(body);
|
|
234
|
+
}
|
|
235
|
+
const absolute = new URL(sourceMapUrl, scriptUrl).href;
|
|
236
|
+
const response = await fetch(absolute);
|
|
237
|
+
return response.ok ? await response.text() : null;
|
|
238
|
+
} catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Saves the source and source map of every script the CPU profile sampled. Enabling the debugger after the profile
|
|
245
|
+
* stops replays `scriptParsed` for every live script, so the profiled run itself never ran with the debugger on.
|
|
246
|
+
* @returns {Promise<object[]>} the script index written to scripts/index.json
|
|
247
|
+
*/
|
|
248
|
+
async function saveProfiledScripts(session, profile, scriptsDir) {
|
|
249
|
+
const sampledIds = new Set(profile.nodes.map((node) => node.callFrame.scriptId).filter((id) => id && id !== "0"));
|
|
250
|
+
const parsed = new Map();
|
|
251
|
+
session.on("Debugger.scriptParsed", (event) => parsed.set(event.scriptId, event));
|
|
252
|
+
await session.send("Debugger.enable");
|
|
253
|
+
await sleep(1);
|
|
254
|
+
const index = [];
|
|
255
|
+
for (const scriptId of sampledIds) {
|
|
256
|
+
const info = parsed.get(scriptId);
|
|
257
|
+
const entry = { scriptId, url: info ? info.url : "", sourceMapUrl: info ? info.sourceMapURL || "" : "", hasSource: false, hasMap: false };
|
|
258
|
+
try {
|
|
259
|
+
const { scriptSource } = await session.send("Debugger.getScriptSource", { scriptId });
|
|
260
|
+
fs.writeFileSync(path.join(scriptsDir, `${scriptId}.js`), scriptSource);
|
|
261
|
+
entry.hasSource = true;
|
|
262
|
+
if (!entry.sourceMapUrl) {
|
|
263
|
+
const inline = scriptSource.match(/\/\/[#@] sourceMappingURL=([^\s'"]+)\s*$/);
|
|
264
|
+
if (inline) entry.sourceMapUrl = inline[1];
|
|
265
|
+
}
|
|
266
|
+
} catch {
|
|
267
|
+
// Wasm modules and scripts from a navigated-away document have no retrievable source.
|
|
268
|
+
}
|
|
269
|
+
const mapText = entry.url ? await fetchSourceMap(entry.url, entry.sourceMapUrl) : null;
|
|
270
|
+
if (mapText) {
|
|
271
|
+
fs.writeFileSync(path.join(scriptsDir, `${scriptId}.map.json`), mapText);
|
|
272
|
+
entry.hasMap = true;
|
|
273
|
+
}
|
|
274
|
+
index.push(entry);
|
|
275
|
+
}
|
|
276
|
+
await session.send("Debugger.disable");
|
|
277
|
+
fs.writeFileSync(path.join(scriptsDir, "index.json"), JSON.stringify(index, null, 1));
|
|
278
|
+
return index;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Starts the allocation sampler, including objects the GC already collected, so short-lived per-frame garbage counts.
|
|
283
|
+
* Older Chrome versions reject the include flags; the sampler then reports only objects still alive at the end.
|
|
284
|
+
* @returns {Promise<boolean>} true when collected objects are included
|
|
285
|
+
*/
|
|
286
|
+
async function startHeapSampling(session) {
|
|
287
|
+
await session.send("HeapProfiler.enable");
|
|
288
|
+
try {
|
|
289
|
+
await session.send("HeapProfiler.startSampling", {
|
|
290
|
+
samplingInterval: HEAP_SAMPLING_INTERVAL_BYTES, includeObjectsCollectedByMajorGC: true, includeObjectsCollectedByMinorGC: true,
|
|
291
|
+
});
|
|
292
|
+
return true;
|
|
293
|
+
} catch {
|
|
294
|
+
await session.send("HeapProfiler.startSampling", { samplingInterval: HEAP_SAMPLING_INTERVAL_BYTES });
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Records a DevTools trace into trace.json (streamed, it can be large).
|
|
301
|
+
* @returns {Promise<() => Promise<void>>} a function that stops the trace and writes the file
|
|
302
|
+
*/
|
|
303
|
+
async function startTrace(session, traceFile) {
|
|
304
|
+
await session.send("Tracing.start", { traceConfig: { includedCategories: TRACE_CATEGORIES.filter((category) => category !== "-*"), excludedCategories: ["*"] }, transferMode: "ReturnAsStream" });
|
|
305
|
+
return async () => {
|
|
306
|
+
const complete = new Promise((resolve) => session.once("Tracing.tracingComplete", resolve));
|
|
307
|
+
await session.send("Tracing.end");
|
|
308
|
+
const { stream } = await complete;
|
|
309
|
+
const output = fs.createWriteStream(traceFile);
|
|
310
|
+
for (;;) {
|
|
311
|
+
const chunk = await session.send("IO.read", { handle: stream });
|
|
312
|
+
output.write(chunk.base64Encoded ? Buffer.from(chunk.data, "base64") : chunk.data);
|
|
313
|
+
if (chunk.eof) break;
|
|
314
|
+
}
|
|
315
|
+
await session.send("IO.close", { handle: stream });
|
|
316
|
+
await new Promise((resolve) => output.end(resolve));
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Records a filmstrip with Chrome's screencast: the compositor hands over frames it already produced, encoded off
|
|
322
|
+
* the page's main thread, and every `intervalSeconds` one is kept as a small JPEG under filmstrip/.
|
|
323
|
+
* @returns {Promise<() => Promise<object[]>>} a function that stops the screencast and returns [{ at, file }]
|
|
324
|
+
*/
|
|
325
|
+
async function startFilmstrip(session, runDir, intervalSeconds) {
|
|
326
|
+
const filmstripDir = path.join(runDir, "filmstrip");
|
|
327
|
+
fs.mkdirSync(filmstripDir, { recursive: true });
|
|
328
|
+
const frames = [];
|
|
329
|
+
let lastKeptAt = 0;
|
|
330
|
+
const onFrame = (event) => {
|
|
331
|
+
session.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
|
|
332
|
+
const at = event.metadata.timestamp * 1000;
|
|
333
|
+
if (at - lastKeptAt < intervalSeconds * 1000) return;
|
|
334
|
+
lastKeptAt = at;
|
|
335
|
+
const file = `${String(frames.length).padStart(4, "0")}.jpg`;
|
|
336
|
+
fs.writeFileSync(path.join(filmstripDir, file), Buffer.from(event.data, "base64"));
|
|
337
|
+
frames.push({ at, file: `filmstrip/${file}` });
|
|
338
|
+
};
|
|
339
|
+
session.on("Page.screencastFrame", onFrame);
|
|
340
|
+
await session.send("Page.startScreencast", { format: "jpeg", quality: 55, maxWidth: 480, maxHeight: 270, everyNthFrame: 4 });
|
|
341
|
+
return async () => {
|
|
342
|
+
await session.send("Page.stopScreencast").catch(() => {});
|
|
343
|
+
session.off("Page.screencastFrame", onFrame);
|
|
344
|
+
fs.writeFileSync(path.join(runDir, "filmstrip.json"), JSON.stringify(frames));
|
|
345
|
+
return frames;
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Runs the scenario once in a new page of the given browser and writes the whole capture into runDir.
|
|
351
|
+
* @returns {Promise<object>} the capture summary (also written to capture.json)
|
|
352
|
+
*/
|
|
353
|
+
async function captureOnce(browser, flags, scenario, runDir, label) {
|
|
354
|
+
const shotsDir = path.join(runDir, "shots");
|
|
355
|
+
const scriptsDir = path.join(runDir, "scripts");
|
|
356
|
+
fs.mkdirSync(shotsDir, { recursive: true });
|
|
357
|
+
fs.mkdirSync(scriptsDir, { recursive: true });
|
|
358
|
+
const log = (message) => process.stderr.write(`[bt-profile ${label} +${((Date.now() - startedAt) / 1000).toFixed(1)}s] ${message}\n`);
|
|
359
|
+
const startedAt = Date.now();
|
|
360
|
+
const targetUrl = flags.url;
|
|
361
|
+
const deviceScaleFactor = Number(flags.dpr || 2);
|
|
362
|
+
const page = await browser.newPage();
|
|
363
|
+
await page.setViewport({ width: Number(flags.width || 1600), height: Number(flags.height || 900), deviceScaleFactor });
|
|
364
|
+
const consoleErrors = [];
|
|
365
|
+
// A dev server that watches files reloads or hot-patches the game when anyone edits the project (another agent session,
|
|
366
|
+
// an editor's save): the scene restarts mid-capture and the numbers are worthless. Both are recorded and flagged.
|
|
367
|
+
const devServerUpdates = [];
|
|
368
|
+
const navigations = [];
|
|
369
|
+
page.on("console", (message) => {
|
|
370
|
+
const text = message.text();
|
|
371
|
+
if (DEV_SERVER_UPDATE.test(text)) devServerUpdates.push({ at: Date.now(), text: text.slice(0, 200) });
|
|
372
|
+
if (message.type() === "error" || message.type() === "warning") consoleErrors.push({ type: message.type(), text: text.slice(0, 600) });
|
|
373
|
+
});
|
|
374
|
+
// Document loads only: a router's history.pushState / replaceState is a same-document "navigation" and is not a reload.
|
|
375
|
+
page.on("domcontentloaded", () => navigations.push({ at: Date.now(), url: page.url() }));
|
|
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);
|
|
382
|
+
await page.evaluateOnNewDocument(installProbe);
|
|
383
|
+
|
|
384
|
+
// Start on a same-origin document so the renderer process (and the V8 isolate the profiler is attached to)
|
|
385
|
+
// stays the same when the scenario navigates to the game.
|
|
386
|
+
const origin = new URL(targetUrl).origin;
|
|
387
|
+
await page.goto(`${origin}/favicon.ico`, { waitUntil: "load" }).catch(() => page.goto("about:blank"));
|
|
388
|
+
|
|
389
|
+
const session = await page.createCDPSession();
|
|
390
|
+
await session.send("Profiler.enable");
|
|
391
|
+
await session.send("Profiler.setSamplingInterval", { interval: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US) });
|
|
392
|
+
const heapEnabled = flags.heap !== "false";
|
|
393
|
+
const heapIncludesCollected = heapEnabled ? await startHeapSampling(session) : false;
|
|
394
|
+
const stopTrace = flags.trace === "true" ? await startTrace(session, path.join(runDir, "trace.json")) : null;
|
|
395
|
+
await session.send("Profiler.start");
|
|
396
|
+
const syncEpochMs = await runSyncMarker(page);
|
|
397
|
+
const snapshots = flags.snapshots === "true";
|
|
398
|
+
const stopFilmstrip = snapshots ? await startFilmstrip(session, runDir, Number(flags["filmstrip-interval"] || 1)) : null;
|
|
399
|
+
|
|
400
|
+
// The allocation sampler has no timestamps, so it is restarted at every phase mark: one profile per phase
|
|
401
|
+
// (heap/<index>-<phase>.heapprofile) separates load-time buffers from per-frame garbage.
|
|
402
|
+
const heapDir = path.join(runDir, "heap");
|
|
403
|
+
if (heapEnabled) fs.mkdirSync(heapDir, { recursive: true });
|
|
404
|
+
let heapPhase = "start";
|
|
405
|
+
let heapIndex = 0;
|
|
406
|
+
const rotateHeap = async (nextPhase) => {
|
|
407
|
+
if (!heapEnabled) return;
|
|
408
|
+
const { profile: phaseProfile } = await session.send("HeapProfiler.stopSampling");
|
|
409
|
+
const safeName = heapPhase.replace(/[^\w+.-]+/g, "_");
|
|
410
|
+
fs.writeFileSync(path.join(heapDir, `${String(heapIndex).padStart(2, "0")}-${safeName}.heapprofile`), JSON.stringify(phaseProfile));
|
|
411
|
+
heapIndex++;
|
|
412
|
+
heapPhase = nextPhase;
|
|
413
|
+
if (nextPhase !== "end") await startHeapSampling(session);
|
|
414
|
+
};
|
|
415
|
+
const context = createScenarioContext(page, targetUrl, shotsDir, parseScenarioArguments(flags.args), log, snapshots, rotateHeap);
|
|
416
|
+
const maxSeconds = Number(flags.seconds || DEFAULT_MAX_SECONDS);
|
|
417
|
+
let scenarioError = null;
|
|
418
|
+
let timedOut = false;
|
|
419
|
+
try {
|
|
420
|
+
await Promise.race([
|
|
421
|
+
scenario.run(context),
|
|
422
|
+
sleep(maxSeconds).then(() => { timedOut = true; }),
|
|
423
|
+
]);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
scenarioError = String(error && error.stack ? error.stack : error);
|
|
426
|
+
log(`scenario failed: ${scenarioError.split("\n")[0]}`);
|
|
427
|
+
}
|
|
428
|
+
if (timedOut) log(`scenario still running after --seconds ${maxSeconds}; stopping the capture there`);
|
|
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");
|
|
431
|
+
|
|
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 };
|
|
435
|
+
fs.writeFileSync(path.join(runDir, "cpu.cpuprofile"), JSON.stringify(profile));
|
|
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");
|
|
439
|
+
if (probe) {
|
|
440
|
+
const recorded = new Set(probe.marks.map((mark) => mark.name));
|
|
441
|
+
for (const mark of context.nodeMarks) if (!recorded.has(mark.name)) probe.marks.push({ ...mark, fromNode: true });
|
|
442
|
+
probe.marks.sort((first, second) => first.at - second.at);
|
|
443
|
+
}
|
|
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");
|
|
458
|
+
|
|
459
|
+
const capture = {
|
|
460
|
+
label,
|
|
461
|
+
url: targetUrl,
|
|
462
|
+
scenario: scenario.meta,
|
|
463
|
+
scenarioOptions: context.options,
|
|
464
|
+
scenarioError,
|
|
465
|
+
timedOut,
|
|
466
|
+
capturedAt: new Date().toISOString(),
|
|
467
|
+
browser: await browser.version(),
|
|
468
|
+
platform: `${os.platform()} ${os.release()} ${os.arch()}`,
|
|
469
|
+
viewport: { width: Number(flags.width || 1600), height: Number(flags.height || 900), deviceScaleFactor },
|
|
470
|
+
samplingIntervalUs: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US),
|
|
471
|
+
heapIncludesCollected,
|
|
472
|
+
snapshots,
|
|
473
|
+
gpuCold: flags["gpu-cold"] === "true" ? (probe && probe.gpuCold) || { tagged: 0, untagged: 0 } : null,
|
|
474
|
+
filmstripFrames: filmstrip.length,
|
|
475
|
+
sync: { markerName: SYNC_MARKER_NAME, epochMs: syncEpochMs },
|
|
476
|
+
census,
|
|
477
|
+
probe,
|
|
478
|
+
scripts: scripts.length,
|
|
479
|
+
consoleErrors: consoleErrors.slice(0, 60),
|
|
480
|
+
disturbed: disturbance(context, navigations, devServerUpdates, probe),
|
|
481
|
+
wallSeconds: +((Date.now() - startedAt) / 1000).toFixed(1),
|
|
482
|
+
};
|
|
483
|
+
fs.writeFileSync(path.join(runDir, "capture.json"), JSON.stringify(capture));
|
|
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)`);
|
|
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}`);
|
|
488
|
+
return capture;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Entry point: launches Chrome, runs the cold capture and, with --warm true, a warm one in the same browser.
|
|
493
|
+
*/
|
|
494
|
+
async function main() {
|
|
495
|
+
const flags = parseArguments(process.argv.slice(2));
|
|
496
|
+
// The slug's config (in the working folder, `.agents/profile/<slug>/data`) supplies the URL and scenario by default.
|
|
497
|
+
const configPath = path.resolve("profile.config.json");
|
|
498
|
+
const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, "utf8")) : {};
|
|
499
|
+
if (!flags.url && config.url) flags.url = config.url;
|
|
500
|
+
if (!flags.scenario && config.scenario) flags.scenario = config.scenario;
|
|
501
|
+
if (!flags.url) throw new Error("Pass --url <game URL>, e.g. --url http://localhost:5173/play");
|
|
502
|
+
if (!flags.out) throw new Error("Pass --out <run folder>");
|
|
503
|
+
const runDir = path.resolve(flags.out);
|
|
504
|
+
fs.mkdirSync(runDir, { recursive: true });
|
|
505
|
+
const scenario = await loadScenario(flags.scenario);
|
|
506
|
+
const width = Number(flags.width || 1600);
|
|
507
|
+
const height = Number(flags.height || 900);
|
|
508
|
+
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "bt-profile-chrome-"));
|
|
509
|
+
const args = [
|
|
510
|
+
"--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist", "--enable-unsafe-webgpu",
|
|
511
|
+
"--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
|
|
512
|
+
"--enable-precise-memory-info", `--window-size=${width},${height}`,
|
|
513
|
+
];
|
|
514
|
+
// Audio: by default it may start without a user gesture, so it starts during the load. `--autoplay gesture` keeps a real
|
|
515
|
+
// browser's rule — audio stays locked until the first key or click — when the slow moment may be the audio unlock itself.
|
|
516
|
+
if (flags.autoplay !== "gesture") args.push("--autoplay-policy=no-user-gesture-required");
|
|
517
|
+
if (flags.uncapped === "true") args.push("--disable-frame-rate-limit", "--disable-gpu-vsync");
|
|
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,
|
|
521
|
+
executablePath: findChrome(),
|
|
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",
|
|
524
|
+
defaultViewport: null,
|
|
525
|
+
userDataDir,
|
|
526
|
+
args,
|
|
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
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
const cold = await captureOnce(browser, flags, scenario, path.join(runDir, "cold"), "cold");
|
|
546
|
+
const summary = { runDir, cold: path.join(runDir, "cold") };
|
|
547
|
+
if (flags.warm === "true") {
|
|
548
|
+
await captureOnce(browser, flags, scenario, path.join(runDir, "warm"), "warm");
|
|
549
|
+
summary.warm = path.join(runDir, "warm");
|
|
550
|
+
}
|
|
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");
|
|
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");
|
|
554
|
+
fs.writeFileSync(path.join(runDir, "run.json"), JSON.stringify({ ...summary, flags, scenario: scenario.meta }, null, 2));
|
|
555
|
+
process.stdout.write(JSON.stringify(summary) + "\n");
|
|
556
|
+
} finally {
|
|
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();
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
main().catch((error) => {
|
|
564
|
+
process.stderr.write(String(error && error.stack ? error.stack : error) + "\n");
|
|
565
|
+
process.exit(1);
|
|
566
|
+
});
|