rob-revisited/ide/ui/js/profiler.js

654 lines
41 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Profiler: where a program spends its CPU time and its memory. Runs a run configuration under Xdebug's profiler through
// bin/jumphp (JUMPHP_PROFILE), reads the result in PHP (ide/src/Profile), and shows it: a flame graph first (click to zoom, search,
// icicle), the hot spots as bars (click: the file at that line), the memory over time (drag a range to filter the hot spots), the
// frame split of a game; the call tree, callers / callees and raw numbers when asked (Details). Runs are kept (var/profiles/) and
// compared; the editor's gutter shows the lines' cost. Claude profiles through the tools at the end of this file (agent.js).
import { backend } from './backend.js';
import { el, clear, icon, menu, dialog, notify, prefs, t, copyText, progressBar } from './ui.js';
import { monaco, pathOf } from './editor.js';
import * as F from './flame.js';
const SPACES = { app: 'Your code', engine: 'JumPHP engine', vendor: 'Libraries', php: 'PHP itself' };
const FRAME_BUDGET_MS = 1000 / 60;
const isDark = () => document.documentElement.dataset.theme !== 'light';
const when = (ts) => new Date(ts * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
const MODES = { cpu: 'CPU', memory: 'Memory', both: 'CPU and memory' };
export class ProfilerPanel {
constructor(app) {
this.app = app;
this.node = el('div.prof-view');
this.list = [];
this.profile = null; // the one shown (full)
this.compare = null; // {a, b, data} while two runs are compared
this.running = null; // {label, stage, ratio, runId}
this.details = prefs.get('profileDetails', false);
this.heat = prefs.get('profileHeat', true);
this.metric = 'v';
this.inverted = prefs.get('profileIcicle', false);
this.focus = [];
this.search = '';
this.range = null; // [fromSlice, toSlice]
this.selected = null; // a function name
this.expanded = new Set(['']);
this.sort = 'v';
this.hover = null;
this.decorations = new Map(); // model uri => ids
this.render();
backend.on('profile.progress', (p) => this.onProgress(p));
this.refreshList().then(() => { if (!this.profile && this.list[0]) this.open(this.list[0].id, { quiet: true }); });
monaco.editor.onDidCreateModel((model) => this.decorate(model));
new ResizeObserver(() => this.redrawCanvases()).observe(this.node);
}
title() { return 'Profiler'; }
actions() {
const has = !!this.profile && !this.running;
const b = (title, ico, fn, enabled = true, on = false) => el('button' + (on ? '.on' : ''), { title: t(title), disabled: !enabled, onclick: fn }, icon(ico));
return [
b('Profile…', 'profile', () => this.ask(), !this.running),
b('Previous runs, compare', 'refresh', (e) => this.historyMenu(e.currentTarget), this.list.length > 0),
b('Details: call tree, callers, files, numbers', 'structure', () => { this.details = !this.details; prefs.set('profileDetails', this.details); this.render(); this.app.refreshToolHeader('profile'); }, has, this.details),
b('Show the cost of each line in the editors', 'warning', () => { this.heat = !this.heat; prefs.set('profileHeat', this.heat); this.decorateAll(); this.app.refreshToolHeader('profile'); }, has, this.heat),
b('Copy a summary for an AI', 'copy', () => this.copySummary(), has),
b('Export for speedscope', 'download', () => this.exportSpeedscope(), has),
b('Delete this run', 'close', () => this.remove(), has),
];
}
shown() {
// a wide window: a flame graph wants width
if (!prefs.get('profileWide', false)) {
prefs.set('profileWide', true);
const root = document.documentElement;
const now = parseInt(getComputedStyle(root).getPropertyValue('--right-width'), 10) || 520;
const want = Math.min(Math.round(window.innerWidth * 0.55), 900);
if (now < want) root.style.setProperty('--right-width', `${want}px`);
}
this.redrawCanvases();
}
// data ---------------------------------------------------------------------------------------------------------
async refreshList() {
try { this.list = await backend.invoke('profile.list', {}); } catch { this.list = []; }
this.app.refreshToolHeader?.('profile');
}
async open(id, { quiet = false } = {}) {
try {
this.profile = await backend.invoke('profile.get', { id });
} catch (e) {
if (!quiet) notify(e.message, 'error', { title: t('Profiler') });
return null;
}
this.compare = null;
this.focus = [];
this.range = null;
this.selected = null;
this.search = '';
this.expanded = this.openChain(this.profile.flame.root);
this.render();
this.decorateAll();
this.app.refreshToolHeader?.('profile');
return this.profile;
}
/** The call tree opens along the heaviest path (while it still matters), so the first look shows where the time goes. */
openChain(root) {
const open = new Set(['']);
let node = root;
let id = '';
for (let depth = 0; depth < 8 && node.ch?.length; depth++) {
const i = node.ch.reduce((best, c, k) => (c.v > node.ch[best].v ? k : best), 0);
if (node.ch[i].v < root.v * 0.05) break;
id = `${id}/${i}`;
open.add(id);
node = node.ch[i];
}
return open;
}
async remove() {
if (!this.profile) return;
await backend.invoke('profile.delete', { id: this.profile.id }).catch(() => null);
await this.refreshList();
this.profile = null;
this.decorateAll();
if (this.list[0]) await this.open(this.list[0].id, { quiet: true }); else this.render();
this.app.refreshToolHeader('profile');
}
async copySummary() {
const r = await backend.invoke('profile.summary', { id: this.profile.id, n: 10 });
await copyText(r.markdown);
notify(t('Copied: paste it to an AI to optimise the hot spots'), 'success', { title: t('Profiler') });
}
async exportSpeedscope() {
const r = await backend.invoke('profile.export', { id: this.profile.id });
notify(t('Saved {path}: open it at speedscope.app', { path: r.path }), 'success', {
title: t('Profiler'), actions: [{ label: 'Show the file', action: () => this.app.editors.open(r.path) }, { label: 'Open speedscope.app', action: () => this.app.openUrl('https://www.speedscope.app') }] });
}
historyMenu(at) {
const items = this.list.map((p) => ({
label: `${p.label || p.id} · ${t(MODES[p.mode] || p.mode)} · ${F.formatMs(p.totalMs)} · ${when(p.created)}`, icon: 'profile',
checked: this.profile?.id === p.id, action: () => this.open(p.id),
}));
const compare = this.profile && this.list.length > 1 ? [
'-', { head: t('Compare this run with…') },
...this.list.filter((p) => p.id !== this.profile.id).map((p) => ({ label: `${p.label || p.id} · ${F.formatMs(p.totalMs)} · ${when(p.created)}`, icon: 'refresh', action: () => this.compareWith(p.id) })),
] : [];
menu([{ head: t('Previous runs') }, ...items, ...compare], at);
}
/** Two runs side by side: the older is "before", the newer "after". */
async compareWith(otherId) {
const [x, y] = [this.profile.id, otherId].sort();
try {
const data = await backend.invoke('profile.compare', { a: x, b: y, n: 12 });
this.compare = { data };
this.render();
} catch (e) { notify(e.message, 'error', { title: t('Profiler') }); }
}
// running ------------------------------------------------------------------------------------------------------
/** The dialog: what to measure, which run configuration, for how long. */
async ask(preset = {}) {
const runner = this.app.runner;
const configs = (runner?.configs || []).filter((c) => ['run', 'test', 'shot', 'tool'].includes(c.kind) && !/^(lint|update)$/.test(c.id) && !/^(install|pack|siteshot)/.test(c.id));
if (!configs.length) { notify(t('This project has nothing to profile.'), 'info', { title: t('Profiler') }); return null; }
let engines = [];
try { engines = await backend.invoke('profile.engines', {}); } catch { engines = [{ id: 'xdebug', label: 'Xdebug', cpu: null, memory: null }]; }
const saved = prefs.get('profileOptions:' + this.app.projectKey, {});
const o = { mode: 'both', durationKind: 'end', durationValue: 120, engine: 'xdebug', config: runner.selected, ...saved, ...preset };
if (!configs.some((c) => c.id === o.config)) o.config = configs[0].id;
const select = (options, value, onchange) => el('select.input', { onchange: (e) => onchange(e.target.value) },
...options.map(([v, label, disabled]) => el('option', { value: v, selected: v === value, disabled: !!disabled }, label)));
const number = el('input.input', { type: 'number', min: 1, value: o.durationValue, style: { width: '90px' }, oninput: (e) => { o.durationValue = Math.max(1, parseInt(e.target.value, 10) || 1); } });
const unit = el('span.pub-faint', {});
const sync = () => { number.hidden = o.durationKind === 'end'; unit.textContent = o.durationKind === 'end' ? '' : o.durationKind === 'frames' ? t('frames (60 = 1 second of game)') : t('seconds of game'); };
const note = el('div.pub-faint', { style: { marginTop: '8px' } });
const hint = () => {
const e = engines.find((x) => x.id === o.engine);
const why = e && (o.mode === 'cpu' ? e.cpu : e.memory || e.cpu);
note.textContent = why || (o.mode === 'cpu' ? t('The CPU profile alone: the least overhead.') : t('With the memory trace: slower to run (tens of times) and bigger to read, but you get memory over time.'));
};
const row = (label, control) => el('div.prof-ask-row', {}, el('label', {}, t(label)), control);
const body = el('div.prof-ask', {},
row('What', select([['cpu', t('CPU time')], ['memory', t('Memory')], ['both', t('CPU and memory')]], o.mode, (v) => { o.mode = v; hint(); })),
row('Program', select(configs.map((c) => [c.id, c.label]), o.config, (v) => { o.config = v; })),
row('Until', el('span.prof-ask-until', {},
select([['end', t('the program quits')], ['seconds', t('N seconds')], ['frames', t('N frames')]], o.durationKind, (v) => { o.durationKind = v; sync(); }), number, unit)),
row('Engine', select(engines.map((e) => [e.id, e.label + (e.cpu ? ' — ' + t('cannot profile') : ''), !!e.cpu && e.id !== 'xdebug']), o.engine, (v) => { o.engine = v; hint(); })),
note);
sync();
hint();
return new Promise((resolve) => {
dialog({ title: t('Profile'), body, onClose: () => resolve(null),
buttons: [{ label: t('Cancel') }, { label: t('Profile'), primary: true, action: async () => {
prefs.set('profileOptions:' + this.app.projectKey, { mode: o.mode, durationKind: o.durationKind, durationValue: o.durationValue, engine: o.engine, config: o.config });
resolve(this.profileConfig(configs.find((c) => c.id === o.config), o).catch((e) => { notify(e.message, 'error', { title: t('Profiler') }); return null; }));
} }] });
});
}
/** The program's profile has been asked for: runs it, reads the files, shows the result. Resolves with the profile. */
async profileConfig(config, o, env = {}) {
if (this.running) throw new Error(t('A profile is already running.'));
const supports = () => backend.invoke('jumphp.supports', { feature: 'JUMPHP_PROFILE' }).then((r) => r.ok, () => true);
if (!(await supports())) {
await this.app.updateJumphp({ ask: true, why: t('The profiler needs a newer JumPHP in this project: its bin/jumphp does not start the profiler yet.') });
if (!(await supports())) throw new Error(t('This project\'s bin/jumphp has no profiler (JUMPHP_PROFILE): update JumPHP in it, then Profile again.'));
}
const prep = await backend.invoke('profile.prepare', { mode: o.mode, engine: o.engine || 'xdebug', durationKind: o.durationKind, durationValue: o.durationValue, game: config.game });
if (!prefs.get('profilerImageSeen', false)) {
prefs.set('profilerImageSeen', true);
notify(t('The Xdebug image is built once, about a minute: the first profile waits for it.'), 'info', { title: t('Profiler') });
}
this.running = { label: config.label, stage: 'run', ratio: null, id: prep.id };
this.compare = null;
this.app.showTool('profile', true);
this.render();
this.app.refreshToolHeader('profile');
const task = this.app.task(t('Profiling {name}', { name: config.label }));
this.running.task = task;
const started = Date.now();
try {
// a CLI app's configuration runs in the Terminal: the profiler needs the plain run (its output is the Run window's)
const end = await this.app.runner.startAndWait({ ...config, terminal: false }, { ...env, ...prep.env });
if (!end) throw new Error(t('{name} could not start', { name: config.label }));
this.running.stage = 'read';
this.render();
const done = new Promise((resolve, reject) => {
const off1 = backend.on('profile.done', (p) => { if (p.id === prep.id) { off1?.(); off2?.(); resolve(p); } });
const off2 = backend.on('profile.failed', (p) => { if (p.id === prep.id) { off1?.(); off2?.(); reject(new Error(p.error)); } });
});
await backend.invoke('profile.parse', { id: prep.id, meta: {
label: config.label, mode: prep.mode, engine: o.engine || 'xdebug', wallSeconds: (Date.now() - started) / 1000, durationKind: o.durationKind, durationValue: o.durationValue,
strip: prep.strip, target: { key: config.id, label: config.label } } });
await done;
this.running = null;
task();
await this.refreshList();
const profile = await this.open(prep.id);
this.app.showTool('profile', true);
if (profile?.summary.truncated) notify(profile.summary.notes.join('\n'), 'info', { title: t('Profiler') });
return profile;
} catch (e) {
this.running = null;
task();
this.render();
this.app.refreshToolHeader('profile');
notify(e.message, 'error', { title: t('Profiler') });
throw e;
}
}
onProgress(p) {
if (!this.running || p.id !== this.running.id) return;
this.running.stage = 'read';
this.running.ratio = p.ratio;
this.running.sub = p.stage;
this.running.task?.update?.(null, p.ratio);
this.renderProgress();
}
/** Stop: the program while it runs, the reading of its profile after (a big trace takes a while) */
stopRun() {
if (this.running?.stage === 'read') backend.invoke('profile.cancel', { id: this.running.id }).catch(() => null);
else this.app.runner.stop();
}
// views --------------------------------------------------------------------------------------------------------
render() {
clear(this.node);
this.canvases = [];
for (const off of this.cleanups || []) off();
this.cleanups = [];
if (this.running) this.node.append(this.progressNode());
else if (this.compare) this.node.append(this.compareNode());
else if (this.profile) this.node.append(this.resultNode());
else this.node.append(this.emptyNode());
}
emptyNode() {
return el('div.prof-empty', {},
el('div.prof-empty-title', {}, t('Where do the time and the memory go?')),
el('p', {}, t('Run your game, app or tests under the profiler and see it: a flame graph, the hot spots, the memory over time.')),
el('button.btn.primary', { onclick: () => this.ask() }, t('Profile…')),
this.list.length ? el('p.pub-faint', {}, t('Previous runs are in the clock menu above.')) : null);
}
progressNode() {
this.progressHost = el('div.prof-progress');
this.renderProgress();
return el('div.prof-empty', {}, this.progressHost,
el('button.btn', { onclick: () => this.stopRun() }, t('Stop')));
}
renderProgress() {
if (!this.progressHost || !this.running) return;
const r = this.running;
clear(this.progressHost).append(
el('div.prof-empty-title', {}, r.stage === 'run' ? t('Running {name} under the profiler…', { name: r.label }) : t('Reading the profile…')),
progressBar(r.stage === 'run' ? null : r.ratio),
el('p.pub-faint', {}, r.stage === 'run' ? t('Close the program, or wait for it to end: the profile is read after it.') : (r.sub === 'memory' ? t('The memory trace') : t('The CPU profile'))));
}
resultNode() {
const p = this.profile;
const s = p.summary;
const chip = (label, value, tip) => el('div.prof-chip', { title: tip || '' }, el('span.prof-chip-v', {}, value), el('span.prof-chip-l', {}, t(label)));
const parts = [];
parts.push(el('div.prof-head', {},
el('div.prof-title', {}, p.label || p.id, el('span.pub-faint', {}, ` · ${t(MODES[p.mode] || p.mode)} · ${when(p.created)}`)),
el('div.prof-chips', {},
chip('CPU time', F.formatMs(s.totalMs), t('Total time in PHP functions of the run (without the memory trace\'s own cost when measured apart)')),
chip('Peak memory', s.peakBytes !== null ? F.formatBytes(s.peakBytes) : '–', s.peakBytes === null ? t('Not measured: profile the memory too') : ''),
chip('Allocated', F.formatBytes(s.allocBytes), t('What the functions kept allocated (net), summed')),
chip('Calls', F.formatCount(s.calls)),
chip('Functions', String(s.functions)),
...Object.entries(s.spaces).filter(([, v]) => v > 0).map(([k, v]) => el('div.prof-chip.space.ns-' + k, { title: t('Own time') }, el('span.prof-chip-v', {}, `${Math.round(100 * v / Math.max(1e-9, s.totalMs))}%`), el('span.prof-chip-l', {}, t(SPACES[k])))))));
if (s.notes?.length) parts.push(el('div.prof-notes', {}, ...s.notes.map((n) => el('div', {}, '⚠ ' + n))));
parts.push(this.flameNode());
if (p.timeline) parts.push(this.memoryNode());
parts.push(this.hotNode());
if (p.insight) parts.push(this.insightNode());
if (this.details) parts.push(this.detailsNode());
return el('div.prof-body', {}, ...parts);
}
section(title, ...children) { return el('section.prof-sec', {}, el('h4', {}, t(title)), ...children); }
// the flame graph
flameNode() {
const p = this.profile;
const root = p.flame.root;
const tip = el('div.prof-tip', { hidden: true });
const canvas = el('canvas.prof-flame');
const wrap = el('div.prof-flame-wrap', {}, canvas, tip);
const frame = el('div.prof-flame-frame', {}, wrap);
const search = el('input.input.small', { placeholder: t('Search a function or file…'), value: this.search, oninput: (e) => { this.search = e.target.value; draw(); } });
const metric = el('select.input.small', { onchange: (e) => { this.metric = e.target.value; this.focus = []; draw(); } },
el('option', { value: 'v', selected: this.metric === 'v' }, t('Size: time')), ...(p.timeline ? [el('option', { value: 'm', selected: this.metric === 'm' }, t('Size: memory'))] : []));
const crumbs = el('span.prof-crumbs');
let state = null;
let first = true;
const draw = () => {
const searchSet = F.searchNodes(root, this.search) || (this.selected ? F.searchNodes(root, this.selected) : null);
const before = frame.scrollTop;
state = F.drawFlame(canvas, root, { metric: this.metric, focus: this.focus, inverted: this.inverted, search: searchSet, hover: this.hover, dark: isDark() });
// a deep graph scrolls inside its frame: a flame starts at its base (the bottom), an icicle at its root
if (first) { first = false; frame.scrollTop = this.inverted ? 0 : frame.scrollHeight; } else frame.scrollTop = before;
clear(crumbs);
let node = root;
crumbs.append(el('a', { onclick: () => { this.focus = []; draw(); } }, t('whole run')));
this.focus.forEach((i, k) => { node = node.ch[i]; crumbs.append(' › ', el('a', { onclick: () => { this.focus = this.focus.slice(0, k + 1); draw(); } }, F.shortName(node.n))); });
};
canvas.addEventListener('mousemove', (e) => {
if (!state) return;
const r = canvas.getBoundingClientRect();
const hit = F.hitTest(state.layout, e.clientX - r.left, e.clientY - r.top, state.w, state.h, state.rowH, state.inverted);
const changed = (hit?.node || null) !== (this.hover?.node || null);
this.hover = hit;
canvas.style.cursor = hit ? 'pointer' : 'default';
if (!hit) { tip.hidden = true; if (changed) draw(); return; }
if (changed) draw();
const n = hit.node;
const total = state.layout.total;
const self = (n.v || 0) - (n.ch || []).reduce((a, c) => a + c.v, 0);
clear(tip).append(el('b', {}, n.n),
el('div', {}, `${F.formatMs(n.v)} (${(100 * (this.metric === 'm' ? Math.max(0, n.m) : n.v) / Math.max(1e-12, total)).toFixed(1)}%) · ${t('own')} ${F.formatMs(Math.max(0, self))}`),
el('div', {}, `${n.c} ${t('calls')} · ${F.formatBytes(n.m)} ${t('memory')}`),
n.f && n.f !== 'php:internal' ? el('div.pub-faint', {}, n.f + (n.l ? ':' + n.l : '')) : null);
tip.hidden = false;
const x = e.clientX - r.left + 14;
tip.style.left = `${Math.min(x, Math.max(0, wrap.clientWidth - 260))}px`;
tip.style.top = `${Math.max(0, e.clientY - r.top - (state.inverted ? -16 : 62))}px`;
});
canvas.addEventListener('mouseleave', () => { tip.hidden = true; if (this.hover) { this.hover = null; draw(); } });
canvas.addEventListener('click', (e) => {
if (!state) return;
const r = canvas.getBoundingClientRect();
const hit = F.hitTest(state.layout, e.clientX - r.left, e.clientY - r.top, state.w, state.h, state.rowH, state.inverted);
if (!hit) return;
if (e.detail >= 2 || e.altKey) this.pick(hit.node.n, hit.node.f, hit.node.l);
else if (hit.node.ch?.length) { this.focus = hit.path; this.hover = null; draw(); }
else this.pick(hit.node.n, hit.node.f, hit.node.l);
});
canvas.addEventListener('dblclick', (e) => { e.preventDefault(); });
this.canvases.push(draw);
const iciclebtn = el('button.btn.small' + (this.inverted ? '.on' : ''), { title: t('Icicle: the root on top'), onclick: (e) => { this.inverted = !this.inverted; prefs.set('profileIcicle', this.inverted); e.currentTarget.classList.toggle('on', this.inverted); draw(); } }, t('Icicle'));
setTimeout(draw, 0);
return this.section('Flame graph', el('div.prof-bar', {}, search, metric, iciclebtn, crumbs,
p.flame.source === 'edges' ? el('span.pub-faint', { title: t('The profile keeps who calls whom, not each call in order: this graph unfolds it. Profile the memory too for the real call tree.') }, t('from the call graph')) : null), frame,
el('div.prof-legend', {}, ...Object.entries(SPACES).map(([k, v]) => el('span.prof-legend-i', {}, el('i.sw.ns-' + k), t(v))), el('span.pub-faint', {}, t('Click a box to zoom, double click to open the code'))));
}
// memory over time: drag to filter the hot spots to a range
memoryNode() {
const p = this.profile;
const canvas = el('canvas.prof-mem');
const label = el('span.pub-faint', {});
const dur = p.timeline.duration;
let brush = this.range ? [this.range[0] / 100, (this.range[1] + 1) / 100] : null;
const draw = () => { F.drawMemory(canvas, p.timeline, { brush, dark: isDark() }); };
const setLabel = () => {
label.textContent = this.range ? `${t('Selected')}: ${(this.range[0] / 100 * dur).toFixed(2)}–${((this.range[1] + 1) / 100 * dur).toFixed(2)} s` : t('Drag over the chart to look at a part of the run');
};
let down = null;
const at = (e) => { const r = canvas.getBoundingClientRect(); return Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)); };
canvas.addEventListener('mousedown', (e) => { down = at(e); brush = [down, down]; draw(); });
const move = (e) => { if (down === null) return; brush = [down, at(e)]; draw(); };
const up = () => {
if (down === null) return;
down = null;
if (Math.abs(brush[1] - brush[0]) < 0.01) { brush = null; this.range = null; } else this.range = F.brushSlices(brush[0], brush[1], p.slices?.count || 100);
setLabel();
draw();
this.refreshHot();
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
this.cleanups.push(() => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); });
this.canvases.push(draw);
setLabel();
setTimeout(draw, 0);
return this.section('Memory over time', canvas, el('div.prof-bar', {}, label,
el('button.btn.small', { onclick: () => { this.range = null; brush = null; setLabel(); draw(); this.refreshHot(); } }, t('Clear')),
el('span.pub-faint', {}, t('(measured with the trace, which slows the program down)'))));
}
// hot spots
hotNode() {
this.hotHost = el('div.prof-hot');
this.fillHot();
return this.section('Hot spots', this.hotHost);
}
refreshHot() { if (this.hotHost) this.fillHot(); }
fillHot() {
const p = this.profile;
const total = Math.max(1e-9, p.summary.totalMs);
const info = new Map(p.functions.map((f) => [f.n, f]));
const ranged = this.range && p.slices ? F.rangeTotals(p.slices, this.range[0], this.range[1], 10) : null;
const fn = (name) => info.get(name) || { n: name, f: '', l: 0, ns: F.nodeSpace(name, '') };
const list = (title, rows, value, label, tipOf) => {
const max = Math.max(1e-9, ...rows.map(value));
return el('div.prof-hot-col', {}, el('h5', {}, title),
...(rows.length ? rows.map((r) => {
const f = fn(r.n);
const noFile = !f.f || f.f === 'php:internal';
return el('div.prof-row' + (this.selected === r.n ? '.sel' : ''), { title: tipOf(r), onclick: () => { this.pick(r.n, f.f, f.l); if (noFile) this.showSites(r.n); } },
el('div.prof-row-bar.ns-' + (f.ns || 'app'), { style: { width: `${Math.max(2, 100 * Math.abs(value(r)) / max)}%` } }),
el('span.prof-row-name', {}, F.shortName(r.n)), el('span.prof-row-val', {}, label(r)),
el('button.btn.small.prof-sites', { title: t('Where it is called from'), onclick: (e) => { e.stopPropagation(); this.showSites(r.n); } }, '↗'));
}) : [el('div.pub-faint', {}, t('Nothing'))]));
};
const byCalls = [...p.functions].sort((a, b) => b.calls - a.calls).slice(0, 10);
const bySelf = ranged ? ranged.time.map((r) => ({ n: r.n, self: r.ms })) : [...p.functions].sort((a, b) => b.self - a.self).slice(0, 10);
const byMem = ranged ? ranged.memory.map((r) => ({ n: r.n, mem: r.bytes })) : [...p.functions].filter((f) => f.mem > 0).sort((a, b) => b.mem - a.mem).slice(0, 10);
const suffix = ranged ? ` — ${t('selected range')}` : '';
clear(this.hotHost).append(
list(t('Most CPU (own time)') + suffix, bySelf, (r) => r.self, (r) => `${F.formatMs(r.self)} · ${(100 * r.self / (ranged ? Math.max(1e-9, ranged.ms) : total)).toFixed(1)}%`, (r) => `${r.n}\n${t('with calls')}: ${F.formatMs(fn(r.n).incl)}`),
list(t('Most memory allocated') + suffix, byMem, (r) => r.mem, (r) => F.formatBytes(r.mem), (r) => `${r.n}\n${t('with calls')}: ${F.formatBytes(fn(r.n).imem)}`),
list(t('Most called'), byCalls, (r) => r.calls, (r) => F.formatCount(r.calls) + '×', (r) => `${r.n}\n${F.formatMs(r.self)} ${t('own')}`));
}
// what a game's frame is made of
insightNode() {
const i = this.profile.insight;
const sp = i.split;
const pct = (v) => `${Math.max(0, 100 * v / Math.max(1e-9, sp.frameMs)).toFixed(1)}%`;
const seg = (cls, v, label) => el('div.prof-seg.seg-' + cls, { style: { width: pct(v) }, title: `${t(label)}: ${F.formatMs(v)}` }, v / sp.frameMs > 0.12 ? `${t(label)} ${F.formatMs(v)}` : '');
const kids = (title, list) => el('div.prof-hot-col', {}, el('h5', {}, title), ...(list.length ? list.map((c) => el('div.prof-row', { title: c.n, onclick: () => { const f = this.profile.functions.find((x) => x.n === c.n); this.pick(c.n, f?.f, f?.l); } },
el('div.prof-row-bar.ns-app', { style: { width: `${Math.max(2, 100 * c.ms / Math.max(1e-9, list[0].ms))}%` } }), el('span.prof-row-name', {}, F.shortName(c.n)), el('span.prof-row-val', {}, F.formatMs(c.ms)))) : [el('div.pub-faint', {}, t('Nothing'))]));
const fr = i.frames;
const budget = sp.frameMs / FRAME_BUDGET_MS;
const spark = fr?.series?.length ? el('div.prof-spark', { title: t('Time of each frame') }, ...(() => { const max = Math.max(...fr.series); return fr.series.map((v, k) => el('i', { style: { height: `${Math.max(3, 100 * v / max)}%` }, title: `${F.formatMs(v)}`, class: v > FRAME_BUDGET_MS ? 'over' : '' })); })()) : null;
return this.section('A frame of the game',
el('div.prof-frame', {}, seg('engine', sp.engineMs, 'Engine'), seg('update', sp.updateMs, 'Update'), seg('render', sp.renderMs, 'Render')),
el('div.prof-frame-info', {}, el('b', {}, `${F.formatMs(sp.frameMs)}`), ` ${t('per frame')} · ${Math.round(budget * 100)}% ${t('of the 60 FPS budget')} (${FRAME_BUDGET_MS.toFixed(1)} ms)`,
fr ? ` · ${t('about')} ${Math.round(fr.fps)} FPS ${t('if only this ran')} · p95 ${F.formatMs(fr.p95Ms)} · max ${F.formatMs(fr.maxMs)}` : ''),
spark,
fr?.slowest?.length ? el('div.prof-slow', {}, el('span.pub-faint', {}, t('Slowest frames') + ': '), ...fr.slowest.slice(0, 8).map((s) => el('span.prof-slow-i', {}, `#${s.frame} ${F.formatMs(s.ms)}`))) : null,
el('div.prof-hot', {}, kids(t('In the engine, per frame'), i.frameChildren.filter((c) => !/SceneManager->(update|render)$/.test(c.n))), kids(t('In update (your scenes)'), i.updateChildren), kids(t('In render (your scenes)'), i.renderChildren)));
}
// details: call tree, callers / callees, files, classes, numbers
detailsNode() {
const p = this.profile;
const parts = [];
// call tree
const total = Math.max(1e-9, p.flame.root.v);
const tree = el('table.prof-table');
const head = el('tr', {}, el('th', {}, t('Function')),
...[['c', 'Calls'], ['self', 'Own'], ['v', 'With calls'], ['m', 'Memory']].map(([k, label]) => el('th.num' + (this.sort === k ? '.on' : ''), { onclick: () => { this.sort = k; this.render(); }, title: t('Sort') }, t(label))));
tree.append(head);
const selfOf = (n) => Math.max(0, n.v - (n.ch || []).reduce((a, c) => a + c.v, 0));
const keyOf = (n, k) => (k === 'self' ? selfOf(n) : n[k]);
let rows = 0;
const walk = (n, depth, id) => {
if (rows++ > 600) return;
const open = this.expanded.has(id);
const has = n.ch?.length > 0;
tree.append(el('tr' + (this.selected === n.n ? '.sel' : ''), { onclick: () => this.pick(n.n, n.f, n.l) },
el('td', { style: { paddingLeft: `${depth * 14 + 4}px` } },
el('span.prof-caret', { onclick: (e) => { e.stopPropagation(); if (open) this.expanded.delete(id); else this.expanded.add(id); this.render(); } }, has ? (open ? '▾' : '▸') : ' '),
el('i.sw.ns-' + (F.nodeSpace(n.n, n.f || '') === 'root' ? 'php' : F.nodeSpace(n.n, n.f || ''))), F.shortName(n.n)),
el('td.num', {}, F.formatCount(n.c)), el('td.num', {}, `${F.formatMs(selfOf(n))}`), el('td.num', {}, `${F.formatMs(n.v)} · ${(100 * n.v / total).toFixed(1)}%`), el('td.num', {}, F.formatBytes(n.m))));
if (open && has) [...n.ch].sort((a, b) => keyOf(b, this.sort) - keyOf(a, this.sort)).forEach((c, i) => walk(c, depth + 1, `${id}/${n.ch.indexOf(c)}`));
};
walk(p.flame.root, 0, '');
parts.push(this.section('Call tree', el('div.prof-scroll', {}, tree), el('div.pub-faint', {}, t('Calls of the same function from the same place are merged.'))));
// callers / callees
if (this.selected) {
this.neighbours = this.neighbours?.name === this.selected ? this.neighbours : { name: this.selected, data: null };
const host = el('div.prof-hot');
parts.push(this.section('Callers and callees', el('div.prof-title', {}, this.selected), host));
backend.invoke('profile.neighbours', { id: p.id, name: this.selected }).then((nb) => {
const col = (title, list) => el('div.prof-hot-col', {}, el('h5', {}, title), ...(list.length ? list.map((c) => el('div.prof-row', { onclick: () => { const f = p.functions.find((x) => x.n === c.n); this.pick(c.n, f?.f, f?.l); }, title: c.n },
el('div.prof-row-bar.ns-app', { style: { width: `${Math.max(2, 100 * c.ms / Math.max(1e-9, list[0].ms))}%` } }), el('span.prof-row-name', {}, F.shortName(c.n)), el('span.prof-row-val', {}, `${F.formatMs(c.ms)} · ${F.formatCount(c.calls)}×`))) : [el('div.pub-faint', {}, t('Nothing'))]));
host.append(col(t('Called by'), nb.callers), col(t('Calls'), nb.callees));
}).catch(() => null);
}
// files
const files = new Map();
for (const f of p.functions) {
if (!f.f || f.f === 'php:internal') continue;
const e = files.get(f.f) || { f: f.f, self: 0, mem: 0, calls: 0 };
e.self += f.self; e.mem += Math.max(0, f.mem); e.calls += f.calls;
files.set(f.f, e);
}
const ft = el('table.prof-table', {}, el('tr', {}, el('th', {}, t('File')), el('th.num', {}, t('Calls')), el('th.num', {}, t('Own')), el('th.num', {}, t('Memory'))));
[...files.values()].sort((a, b) => b.self - a.self).slice(0, 25).forEach((e) => ft.append(el('tr', { onclick: () => this.pick('', e.f, 1) }, el('td', {}, e.f), el('td.num', {}, F.formatCount(e.calls)), el('td.num', {}, F.formatMs(e.self)), el('td.num', {}, F.formatBytes(e.mem)))));
parts.push(this.section('Files', el('div.prof-scroll', {}, ft)));
// classes
if (p.classes?.length) {
const ct = el('table.prof-table', {}, el('tr', {}, el('th', {}, t('Class')), el('th.num', {}, t('Calls')), el('th.num', {}, t('Own')), el('th.num', {}, t('Memory'))));
p.classes.slice(0, 25).forEach((c) => ct.append(el('tr', {}, el('td', {}, el('i.sw.ns-' + c.ns), c.n), el('td.num', {}, F.formatCount(c.calls)), el('td.num', {}, F.formatMs(c.self)), el('td.num', {}, F.formatBytes(c.mem)))));
parts.push(this.section('Classes (your scenes and entities show here)', el('div.prof-scroll', {}, ct)));
}
parts.push(this.section('Raw numbers', el('pre.prof-raw', {}, JSON.stringify({ id: p.id, engine: p.engine, mode: p.mode, duration: p.duration, summary: { ...p.summary, notes: undefined }, notes: p.summary.notes }, null, 1))));
return el('div.prof-details', {}, ...parts);
}
// comparing two runs
compareNode() {
const c = this.compare.data;
const s = c.summary;
const card = (label, row, fmt, lowerIsBetter = true) => {
const d = row[2];
const good = d === 0 ? '' : ((d < 0) === lowerIsBetter ? '.good' : '.bad');
return el('div.prof-chip.delta' + good, {}, el('span.prof-chip-v', {}, `${fmt(row[0])} → ${fmt(row[1])}`),
el('span.prof-chip-l', {}, `${t(label)}${row[3] !== null && row[3] !== undefined ? ` · ${row[3] > 0 ? '+' : ''}${row[3]}%` : ''}`));
};
const table = (title, rows, key, fmt) => rows.length ? this.section(title, el('table.prof-table', {},
el('tr', {}, el('th', {}, t('Function')), el('th.num', {}, t('Before')), el('th.num', {}, t('After')), el('th.num', {}, t('Change'))),
...rows.map((r) => {
const d = r[key][2];
return el('tr', { onclick: () => this.pick(r.n, r.f, r.l) }, el('td', { title: r.n }, F.shortName(r.n)), el('td.num', {}, fmt(r[key][0])), el('td.num', {}, fmt(r[key][1])),
el('td.num.' + (d < 0 ? 'good' : 'bad'), {}, (d > 0 ? '+' : '') + fmt(d)));
}))) : null;
return el('div.prof-body', {},
el('div.prof-head', {}, el('div.prof-title', {}, t('Comparison'), el('span.pub-faint', {}, ` · ${c.a.label || c.a.id} (${when(c.a.created)}) → ${c.b.label || c.b.id} (${when(c.b.created)})`)),
el('div.prof-chips', {}, card('CPU time', s.totalMs, F.formatMs), card('Allocated', s.allocBytes, F.formatBytes), s.peakBytes[2] !== null ? card('Peak memory', s.peakBytes, F.formatBytes) : null, card('Calls', s.calls, F.formatCount),
el('button.btn', { onclick: () => { this.compare = null; this.render(); } }, t('Back to the run')))),
table('Slower', c.slower, 'self', F.formatMs), table('Faster', c.faster, 'self', F.formatMs), table('Heavier', c.heavier, 'mem', F.formatBytes), table('Lighter', c.lighter, 'mem', F.formatBytes),
!c.slower.length && !c.faster.length && !c.heavier.length && !c.lighter.length ? el('div.prof-empty', {}, t('Nothing changed.')) : null);
}
// going to the code -------------------------------------------------------------------------------------------
/** A window listing the places of the code a function is called from (PHP's own functions have no file: this is where to find them). */
async showSites(name) {
const body = el('div.prof-sites-list', {}, el('div.pub-faint', {}, t('Loading…')));
const d = dialog({ title: `${t('Called from')} — ${F.shortName(name)}`, body, wide: true });
let sites = [];
try { sites = await backend.invoke('profile.sites', { id: this.profile.id, name }); } catch { sites = []; }
clear(body);
if (!sites.length) { body.append(el('div.pub-faint', {}, t('No call site was recorded for this function.'))); return; }
const table = el('table.prof-table', {}, el('tr', {}, el('th', {}, t('Where')), el('th', {}, t('Function')), el('th.num', {}, t('Calls')), el('th.num', {}, t('Time'))));
for (const s of sites) {
const here = s.file && s.file !== 'php:internal' ? `${s.file}${s.line ? ':' + s.line : ''}` : t('(no file)');
table.append(el('tr', { title: s.n, onclick: () => { if (s.file && s.file !== 'php:internal' && !s.file.startsWith('/')) { this.app.editors.open(s.file, s.line ? { line: s.line, endLine: s.line } : {}).catch(() => null); d?.close?.(); } } },
el('td', {}, here), el('td', {}, F.shortName(s.n)), el('td.num', {}, F.formatCount(s.calls)), el('td.num', {}, F.formatMs(s.ms))));
}
body.append(el('div.prof-scroll', {}, table), el('div.pub-faint', {}, t('Click a line to open it in the editor.')));
}
pick(name, file, line) {
this.selected = name || this.selected;
if (file && file !== 'php:internal' && !file.startsWith('/')) this.app.editors.open(file, line ? { line, endLine: line } : {}).catch(() => null);
if (this.profile && !this.compare) { this.refreshHot(); this.redrawCanvases(); if (this.details) this.render(); }
}
redrawCanvases() { for (const draw of this.canvases || []) draw(); }
// the cost of each line, in the editors' gutter ----------------------------------------------------------------
decorateAll() { for (const model of monaco.editor.getModels()) this.decorate(model); }
decorate(model) {
const key = model.uri.toString();
const old = this.decorations.get(key) || [];
const lines = this.heat && this.profile && !this.compare ? this.profile.lines?.[pathOf(model.uri)] : null;
if (!lines) { if (old.length) this.decorations.set(key, model.deltaDecorations(old, [])); return; }
// the colour is relative to the file's costliest line; lines under 0.2% of the run are noise and stay plain
const max = Math.max(...Object.values(lines).map((l) => l[0]));
const floor = this.profile.summary.totalMs * 0.002;
const last = model.getLineCount();
const next = [];
for (const [line, [ms, bytes]] of Object.entries(lines)) {
const n = Number(line);
const ratio = max > 0 ? Math.sqrt(ms / max) : 0;
if (n < 1 || n > last || ms < floor) continue;
const bucket = Math.min(5, Math.max(1, Math.ceil(ratio * 5)));
next.push({ range: new monaco.Range(n, 1, n, 1), options: { isWholeLine: true, className: `prof-heat-line h${bucket}`, linesDecorationsClassName: `prof-heat-gutter h${bucket}`,
hoverMessage: { value: `**${t('Profile')}**: ${F.formatMs(ms)}${bytes ? ` · ${F.formatBytes(bytes)}` : ''}` } } });
}
this.decorations.set(key, model.deltaDecorations(old, next));
}
}
// Claude's tools (agent.js adds them to AgentTools): profile, read, optimise, profile again ------------------------------
export const profileAgentTools = {
profiler() {
if (!this.app.profiler) throw new Error('no profiler here: it needs a JumPHP project run on this computer (bin/jumphp with Docker)');
return this.app.profiler;
},
async tool_profile_run(args) {
const profiler = this.profiler();
const { config, env } = this.resolveRun(args);
const mode = ['cpu', 'memory', 'both'].includes(args.mode) ? args.mode : 'both';
const durationKind = args.frames ? 'frames' : args.seconds ? 'seconds' : 'end';
const durationValue = args.frames || args.seconds || 0;
const profile = await profiler.profileConfig(config, { mode, engine: 'xdebug', durationKind, durationValue }, env);
if (!profile) throw new Error('no profile was made');
const md = await backend.invoke('profile.summary', { id: profile.id, n: 8 });
return { profile_id: profile.id, configuration: config.label, mode, notes: profile.summary.notes, summary: md.markdown };
},
async tool_profile_summary(args) {
this.profiler();
const id = args.id || 'latest';
if (args.format === 'json') return backend.invoke('profile.summary', { id, n: args.top || 10, format: 'json' });
const r = await backend.invoke('profile.summary', { id, n: args.top || 10 });
return { profile_id: r.id, summary: r.markdown };
},
async tool_profile_compare(args) {
this.profiler();
if (!args.a || !args.b) throw new Error('give the two profile ids (a = before, b = after)');
const r = await backend.invoke('profile.compare', { a: args.a, b: args.b, format: args.format === 'json' ? 'json' : 'markdown' });
return args.format === 'json' ? r : r.markdown;
},
};