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

476 lines
27 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 Cryo window: ext-cryo (built into JumPHP's PHP) from the IDE. Three tabs:
// - Live: a program run with memory metrics (JUMPHP_CRYO_METRICS, engine/src/Cryo/LiveMetrics.php) shows its memory over time,
// its live objects and its classes; "Snapshot" writes its object graph into var/cryo/;
// - Files: the project's snapshots (.cryo), freeze files (.cryf) and series (.cryom), opened (what retains memory, leaks
// found by heuristics, duplicates) and two snapshots compared (what grew);
// - Sandbox: PHP code run in an isolated Cryo\Sandbox (timeout, memory limit): a crash or an endless loop never touches the IDE.
// - Hot patch & console (cryo-hot.js): the running game's methods / constants replaced, PHP run inside it with completions.
// The PHP side: ide/src/Cryo/CryoCommands.php + cryo-tool.php (run in the desktop runtime). Claude: cryo_* tools at the end.
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, confirm } from './ui.js';
import { AbTab, abAgentTools } from './ab.js';
import { HotTab, hotAgentTools } from './cryo-hot.js';
export const CRYO_PORT = 47830;
const kb = (n) => (n == null ? '–' : Math.abs(n) >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : Math.abs(n) >= 1024 ? (n / 1024).toFixed(1) + ' KB' : n + ' B');
const signed = (n, f = kb) => (n > 0 ? '+' : '') + f(n);
const isDark = () => document.documentElement.dataset.theme !== 'light';
export class CryoPanel {
constructor(app) {
this.app = app;
this.node = el('div.cryo-view');
this.tab = prefs.get('cryoTab', 'live');
this.live = { points: [], since: 0, metrics: null, error: null, polling: false };
this.files = [];
this.opened = null; // {path, data}
this.marked = []; // snapshots chosen to compare
this.diff = null;
this.why = null; // {what, data} the paths that keep an object alive
this.savepoints = [];
this.sandbox = { code: prefs.get('cryoSandboxCode', '<?php\n$a = [];\nfor ($i = 0; $i < 1000; $i++) $a[] = str_repeat("x", 100);\necho count($a), " strings\\n";\nreturn memory_get_usage();\n'),
timeout: 5, memory: '64M', result: null, busy: false };
this.support = { cryo: true, live: true };
this.ab = new AbTab(app, this);
this.hot = new HotTab(this);
this.render();
this.refreshSavepoints();
this.supportChecked = backend.invoke('cryo.support', {}).then((r) => { this.support = r; this.render(); }).catch(() => null);
setInterval(() => this.poll(), 1000);
}
title() { return 'Cryo'; }
/** env added to the runs made with "Run with memory metrics" on (run.js) */
runEnv() { return prefs.get('cryoLive', false) ? { JUMPHP_CRYO_METRICS: String(CRYO_PORT) } : {}; }
actions() {
const b = (title, ico, fn, on = false) => el('button' + (on ? '.on' : ''), { title: t(title), onclick: fn }, icon(ico));
return [
b('Run with memory metrics (the next runs serve ext-cryo\'s metrics to this window)', 'profile', () => {
prefs.set('cryoLive', !prefs.get('cryoLive', false));
notify(t(prefs.get('cryoLive', false) ? 'The next runs serve their memory metrics to the Cryo window.' : 'Memory metrics off for the next runs.'), 'info');
this.app.refreshToolHeader('cryo');
}, prefs.get('cryoLive', false)),
b('Refresh', 'refresh', () => this.refresh()),
b('Reset: everything the Cryo window made is deleted', 'trash', () => this.reset()),
];
}
shown() { if (this.tab === 'files') this.refreshFiles(); }
setTab(tab) { this.tab = tab; prefs.set('cryoTab', tab); if (tab === 'files') this.refreshFiles(); this.render(); }
refresh() { if (this.tab === 'files') this.refreshFiles(); else this.render(); }
render() {
clear(this.node);
const tabs = [['live', 'Live'], ['files', 'Files'], ['sandbox', 'Sandbox'], ['hot', 'Hot patch & console'], ['ab', 'A/B']];
this.node.append(el('div.cryo-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label)))));
this.body = el('div.cryo-body');
this.node.append(this.body);
if (!this.support.cryo) {
this.body.append(el('div.prof-empty', {},
el('div.prof-empty-title', {}, t('ext-cryo is not in this project\'s runtime')),
el('p', {}, t('This project\'s JumPHP is older than 0.5.57: its desktop runtime (Docker) is built without ext-cryo. Update JumPHP: the runtime is rebuilt with it.')),
this.updateButton()));
return;
}
if (this.tab === 'live') this.renderLive();
else if (this.tab === 'files') this.renderFiles();
else if (this.tab === 'ab') this.ab.render(this.body);
else if (this.tab === 'hot') this.hot.render(this.body);
else this.renderSandbox();
}
updateButton() {
return el('button.btn.primary', { onclick: async () => {
await this.app.updateJumphp?.({ ask: true, why: 'Cryo' });
this.support = await backend.invoke('cryo.support', {}).catch(() => this.support);
this.render();
} }, t('Update JumPHP…'));
}
// Live -------------------------------------------------------------------------------------------------------
async poll() {
if (this.tab !== 'live' || this.live.polling || !this.node.isConnected) return;
this.live.polling = true;
try {
const r = await backend.invoke('cryo.live', { since: this.live.since });
this.live.error = null;
this.live.metrics = r.metrics;
const samples = r.series?.samples || [];
if (samples.length) {
for (const s of samples) this.live.points.push({ time: s.time, memory: s.memory, objects: s.objects_alive ?? null });
this.live.since = (samples[samples.length - 1].seq ?? this.live.since) + 1;
} else if (r.metrics) {
this.live.points.push({ time: r.metrics.time ?? Date.now() / 1000, memory: r.metrics.memory, objects: r.metrics.objects_alive });
}
if (this.live.pid && r.metrics?.pid && r.metrics.pid !== this.live.pid) { this.live.points = this.live.points.slice(-samples.length || -1); }
this.live.pid = r.metrics?.pid;
if (this.live.points.length > 1200) this.live.points.splice(0, this.live.points.length - 1200);
} catch (e) {
if (!this.live.error) this.live.since = 0;
this.live.error = String(e.message || e);
} finally {
this.live.polling = false;
}
if (this.tab === 'live') this.renderLive();
}
renderLive() {
if (!this.body) return;
clear(this.body);
const m = this.live.metrics;
if (!this.support.live) {
this.body.append(el('div.prof-empty', {},
el('div.prof-empty-title', {}, t('Memory of a running program')),
el('p', {}, t('This project\'s JumPHP ({version}) is too old for live memory metrics and save points: they need JumPHP 0.5.68. Files and Sandbox work already.', { version: this.support.version || '?' })),
this.updateButton()));
return;
}
if (this.live.error || !m) {
this.body.append(el('div.prof-empty', {},
el('div.prof-empty-title', {}, t('Memory of a running program')),
el('p', {}, prefs.get('cryoLive', false)
? t('Run your game or app (Run): while it runs, its memory, its live objects and its classes show here.')
: t('Turn on "Run with memory metrics", then run your game or app: its memory shows here while it runs.')),
prefs.get('cryoLive', false) ? null : el('button.btn.primary', { onclick: () => { prefs.set('cryoLive', true); this.app.refreshToolHeader('cryo'); this.renderLive(); } }, t('Run with memory metrics')),
this.live.points.length ? el('p.pub-faint', {}, t('The program ended.')) : null));
if (this.live.points.length > 1) this.body.append(this.chart());
this.body.append(this.savepointsNode(false));
return;
}
const stat = (label, value) => el('div.cryo-stat', {}, el('b', {}, value), el('span', {}, t(label)));
this.body.append(
el('div.cryo-stats', {}, stat('Memory', kb(m.memory)), stat('Peak', kb(m.memory_peak)), stat('Live objects', String(m.objects_alive ?? '–')),
stat('GC runs', String(m.gc_runs ?? '–')), stat('RSS', kb(m.memory_rss))),
this.chart(),
el('div.cryo-row', {},
el('button.btn.primary', { onclick: () => this.snapshot() }, icon('camera'), t('Snapshot')),
el('span.pub-faint', {}, t('The object graph of the running program, written into var/cryo/ and opened.'))));
const classes = m.class_counts && Object.entries(m.class_counts);
this.body.append(this.savepointsNode(true));
if (classes?.length) this.body.append(el('h5', {}, t('Live objects per class')), this.table(['Class', 'Objects'], classes.slice(0, 20).map(([c, n]) => [c, String(n)])));
}
// development save points: the playing scene frozen (Freeze), a run that starts from it (Resume here) --------------
async refreshSavepoints() {
try { this.savepoints = await backend.invoke('cryo.savepoints', {}); } catch (e) { this.savepoints = []; }
if (this.tab === 'live') this.renderLive();
}
savepointsNode(running) {
const box = el('div.cryo-detail', {}, el('h5', {}, t('Save points')),
el('p.pub-faint', {}, t('Freeze here: the whole program is frozen (every object, timers, the level, the player...), whatever the game; Resume here starts it again exactly there. If the code changed since (or the game uses OpenGL), the scene alone is resumed (hotState() of a HotReloadable scene, else its plain properties).')));
if (running) box.append(el('div.cryo-row', {}, el('button.btn', { onclick: () => this.freeze() }, icon('snowflake'), t('Freeze here'))));
for (const sp of this.savepoints) {
box.append(el('div.cryo-file', {},
el('span', { title: sp.path }, `${sp.name} · ${String(sp.scene || '').split('\\').pop()}${sp.game ? ' · ' + sp.game : ''}`),
sp.process ? el('span.cryo-badge', { title: t('The whole program is in it: it resumes exactly where it was.') }, t('whole program'))
: el('span.cryo-badge.scene', { title: sp.processWhyNot || '' }, t('scene only')),
sp.error ? el('span.cryo-error', {}, sp.error) : el('button.btn', { onclick: () => this.resume(sp) }, icon('play'), t('Resume here')),
el('button', { title: t('Delete'), onclick: async () => { await backend.invoke('cryo.savepoint.delete', { name: sp.name }); this.refreshSavepoints(); } }, icon('close'))));
}
return box;
}
async freeze() {
try {
const r = await backend.invoke('cryo.freeze', {});
notify(t('Frozen: {scene} ({path})', { scene: String(r.scene || '').split('\\').pop(), path: r.path })
+ (r.process ? '' : ' — ' + t('scene only: {why}', { why: r.processWhyNot || '?' })), r.process ? 'info' : 'warning');
} catch (e) { notify(String(e.message || e), 'error', { title: t('Freeze here') }); }
this.refreshSavepoints();
}
async resume(sp) {
if (!sp.game) return notify(t('This save point does not say which game it belongs to.'), 'error');
await this.app.runner.start({ id: 'adhoc', kind: 'run', label: `${sp.game}: ${t('resume')} ${sp.name}`, command: ['bin/jumphp', 'run', sp.game] },
{ ...this.runEnv(), JUMPHP_CRYO_THAW: sp.path });
}
chart() {
const canvas = el('canvas.cryo-chart');
requestAnimationFrame(() => {
const pts = this.live.points;
const w = canvas.clientWidth || 300, h = 110, dpr = window.devicePixelRatio || 1;
canvas.width = w * dpr; canvas.height = h * dpr;
const g = canvas.getContext('2d');
g.scale(dpr, dpr);
if (pts.length < 2) return;
const max = Math.max(...pts.map((p) => p.memory || 0)) * 1.1 || 1;
const t0 = pts[0].time, t1 = pts[pts.length - 1].time || t0 + 1;
g.strokeStyle = isDark() ? '#3a3f4b' : '#dde1e6';
for (let i = 1; i < 4; i++) { g.beginPath(); g.moveTo(0, (h * i) / 4); g.lineTo(w, (h * i) / 4); g.stroke(); }
g.strokeStyle = '#4c9aff'; g.lineWidth = 1.5; g.beginPath();
pts.forEach((p, i) => { const x = ((p.time - t0) / Math.max(0.001, t1 - t0)) * w, y = h - ((p.memory || 0) / max) * h; if (i) g.lineTo(x, y); else g.moveTo(x, y); });
g.stroke();
g.fillStyle = isDark() ? '#aab' : '#556';
g.font = '11px sans-serif';
g.fillText(kb(max / 1.1), 4, 12);
g.fillText(`${Math.round(t1 - t0)} s`, w - 34, h - 4);
});
return canvas;
}
async snapshot() {
try {
const r = await backend.invoke('cryo.snapshot', {});
notify(t('Snapshot written: {path}', { path: r.path }), 'info');
await this.openFile(r.path);
} catch (e) { notify(String(e.message || e), 'error', { title: t('Snapshot') }); }
}
// Files ------------------------------------------------------------------------------------------------------
async reset() {
if (!(await confirm(t('Reset Cryo?'), t('Deleted: the save points, the snapshots taken from Live, the A/B test and its copy (var/cryo, var/ab). Your code and Cryo files elsewhere in the project stay.'), { ok: t('Reset'), danger: true }))) return;
try {
const r = await backend.invoke('cryo.reset', {});
prefs.set('cryoLive', false);
this.live = { points: [], since: 0, metrics: null, error: null, polling: false };
this.opened = null; this.diff = null; this.why = null; this.marked = [];
this.sandbox.result = null;
this.ab.state = null; this.ab.changes = null; this.ab.result = null; this.ab.profiles = { a: null, b: null };
this.savepoints = [];
notify(t('Cryo reset: {n} file(s) deleted.', { n: r.removed }), 'info');
} catch (e) { notify(String(e.message || e), 'error', { title: t('Reset') }); }
this.app.refreshToolHeader('cryo');
this.refreshFiles();
this.render();
}
async deleteFile(path) {
if (!(await confirm(t('Delete {path}?', { path }), t('The file is deleted from the disk (a save point: its other files too).'), { ok: t('Delete'), danger: true }))) return;
try {
await backend.invoke('cryo.file.delete', { path });
this.marked = this.marked.filter((p) => p !== path);
if (this.opened?.path === path) this.opened = null;
if (this.diff && (this.diff.a === path || this.diff.b === path)) this.diff = null;
this.refreshSavepoints();
} catch (e) { notify(String(e.message || e), 'error', { title: t('Delete') }); }
this.refreshFiles();
}
async refreshFiles() {
try { this.files = await backend.invoke('cryo.files', {}); } catch (e) { this.files = []; }
if (this.tab === 'files') this.renderFiles();
}
async openFile(path) {
this.app.showTool?.('cryo');
this.tab = 'files'; prefs.set('cryoTab', 'files');
this.diff = null;
this.why = null;
this.opened = { path, data: null, busy: true };
this.render();
try { this.opened.data = await backend.invoke('cryo.inspect', { path }); } catch (e) { this.opened.error = String(e.message || e); }
this.opened.busy = false;
this.refreshFiles();
}
async compare() {
const [a, b] = this.marked;
this.opened = null;
this.diff = { a, b, data: null, busy: true };
this.renderFiles();
try { this.diff.data = await backend.invoke('cryo.diff', { a, b }); } catch (e) { this.diff.error = String(e.message || e); }
this.diff.busy = false;
this.renderFiles();
}
renderFiles() {
if (!this.body) return;
clear(this.body);
if (!this.files.length && !this.opened) {
this.body.append(el('div.prof-empty', {}, el('div.prof-empty-title', {}, t('No Cryo file in this project')),
el('p', {}, t('Snapshots (.cryo: cryo_snapshot() or Live > Snapshot), freeze files (.cryf: cryo_freeze()) and series (.cryom: cryo_metrics_sample()) show here.'))));
return;
}
const list = el('div.cryo-files');
for (const f of this.files) {
const snap = /\.cryo$/i.test(f.path);
const box = snap ? el('input', { type: 'checkbox', title: t('Compare'), checked: this.marked.includes(f.path), onchange: (e) => {
this.marked = e.target.checked ? [...this.marked.filter((p) => p !== f.path), f.path].slice(-2) : this.marked.filter((p) => p !== f.path);
this.renderFiles();
} }) : el('span.cryo-nobox');
list.append(el('div.cryo-file' + (this.opened?.path === f.path ? '.on' : ''), {}, box,
el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.openFile(f.path); } }, f.path), el('span.pub-faint', {}, kb(f.bytes)),
el('button.cryo-del', { title: t('Delete'), onclick: () => this.deleteFile(f.path) }, icon('trash'))));
}
this.body.append(list);
if (this.marked.length === 2) this.body.append(el('div.cryo-row', {}, el('button.btn', { onclick: () => this.compare() }, t('Compare the two snapshots')),
el('span.pub-faint', {}, `${this.marked[0]} → ${this.marked[1]}`)));
if (this.diff) this.body.append(this.diffNode());
else if (this.opened) this.body.append(this.openedNode());
}
openedNode() {
const o = this.opened;
const box = el('div.cryo-detail', {}, el('h4', {}, o.path));
if (o.busy) return box.append(el('p.pub-faint', {}, t('Reading…'))), box;
if (o.error) return box.append(el('p.cryo-error', {}, o.error)), box;
const d = o.data;
if (d.kind === 'series') {
this.live.points = (d.samples || []).map((s) => ({ time: s.time, memory: s.memory }));
box.append(el('p', {}, t('{n} samples every {ms} ms', { n: d.samples?.length || 0, ms: d.info?.interval_ms ?? '?' })), this.chart());
if (d.info?.marks?.length) box.append(this.table(['Mark', 'Time'], d.info.marks.map((m) => [m.label ?? String(m), String(m.time ?? '')])));
return box;
}
if (d.kind === 'savepoint') {
box.append(el('p', {}, t('Save point of {scene}', { scene: d.scene || '?' }), d.meta?.game ? ` · ${d.meta.game}` : ''),
d.meta?.game ? el('div.cryo-row', {}, el('button.btn.primary', { onclick: () => this.resume({ ...d.meta, path: o.path }) }, icon('play'), t('Resume here'))) : null,
el('pre.cryo-out', {}, JSON.stringify({ params: d.params, state: d.state }, null, 2)));
return box;
}
if (d.kind === 'freeze') {
box.append(el('p', {}, d.valid ? t('Valid: it can be thawed by this PHP with these sources.') : t('Not thawable here: {why}', { why: d.why || t('other PHP or changed sources') })));
box.append(this.table(['Field', 'Value'], Object.entries(d.info || {}).map(([k, v]) => [k, typeof v === 'object' ? JSON.stringify(v) : String(v)])));
return box;
}
const i = d.info || {};
box.append(el('p', {}, t('{objects} objects, {nodes} nodes, {bytes} reachable', { objects: i.objects ?? '?', nodes: i.nodes ?? '?', bytes: kb(i.bytes) })));
if (this.why && this.why.path === o.path) box.append(this.whyNode());
if (d.heuristics?.length) {
box.append(el('h5', {}, t('Suspicious')));
for (const h of d.heuristics.slice(0, 8)) box.append(el('div.cryo-warn', {}, el('b', {}, h.kind), ' ', h.message, h.site ? el('span.pub-faint', {}, ` — ${h.site}`) : null));
}
if (d.top?.length) box.append(el('h5', {}, t('What retains memory (per class)')), this.table(['Class', 'Objects', 'Bytes', 'Retained'], d.top.map((r) => [this.whyLink(r.class, r.class), String(r.count), kb(r.bytes), kb(r.retained)])));
if (d.sites?.length && d.sites.some((s) => s.site && s.site !== '(unknown)')) box.append(el('h5', {}, t('Allocation sites')), this.table(['Site', 'Objects', 'Bytes'], d.sites.map((r) => [this.siteLink(r.site), String(r.count), kb(r.bytes)])));
if (d.dominators?.length) box.append(el('h5', {}, t('Biggest retainers')), this.table(['Node', 'Type', 'Self', 'Retained'], d.dominators.slice(0, 10).map((r) => [this.whyLink('#' + r.node, '#' + r.node), r.class || r.type, kb(r.self), kb(r.retained)])));
if (d.dupes?.length) box.append(el('h5', {}, t('Duplicates')), this.table(['Type', 'Copies', 'Wasted'], d.dupes.map((r) => [r.type + ` (${r.length})`, String(r.count), kb(r.wasted)])));
if (d.orphans?.length) box.append(el('h5', {}, t('Kept by uncollected cycles')), this.table(['Node', 'Class', 'Size'], d.orphans.map((r) => ['#' + r.node, r.class || r.type, kb(r.size)])));
return box;
}
diffNode() {
const df = this.diff;
const box = el('div.cryo-detail', {}, el('h4', {}, `${df.a} → ${df.b}`));
if (df.busy) return box.append(el('p.pub-faint', {}, t('Comparing…'))), box;
if (df.error) return box.append(el('p.cryo-error', {}, df.error)), box;
const d = df.data;
box.append(el('p', {}, t('Memory {bytes}, objects {count}', { bytes: signed(d.bytes_delta), count: signed(d.count_delta, String) })));
box.append(this.table(['Class', 'Objects', 'Bytes'], d.classes.filter((r) => r.count_delta || r.bytes_delta).map((r) => [r.class, signed(r.count_delta, String), signed(r.bytes_delta)])));
if (d.sites?.length) box.append(el('h5', {}, t('Allocation sites that keep growing')),
this.table(['Site', 'Survivors', 'Hooked by', ''], d.sites.map((r) => [this.siteLink(r.site), String(r.survivors), r.hooked_by ? this.siteLink(r.hooked_by) : '–',
el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.explain(r.site); } }, t('Explain'))])));
if (df.explained) box.append(this.explainNode(df.explained));
return box;
}
whyLink(label, what) {
return el('a', { href: '#', title: t('Why is it alive?'), onclick: (e) => { e.preventDefault(); this.askWhy(what); } }, label);
}
async askWhy(what) {
const path = this.opened?.path;
this.why = { path, what, busy: true };
this.renderFiles();
try { this.why.data = await backend.invoke('cryo.why', { path, what }); } catch (e) { this.why.error = String(e.message || e); }
this.why.busy = false;
this.renderFiles();
}
whyNode() {
const w = this.why;
const box = el('div.cryo-why', {}, el('h5', {}, t('Why is {what} alive?', { what: w.what })));
if (w.busy) return box.append(el('p.pub-faint', {}, t('Reading…'))), box;
if (w.error) return box.append(el('p.cryo-error', {}, w.error)), box;
const n = w.data.node;
box.append(el('p', {}, `#${n.node} ${n.class || n.type} · ${kb(n.size)}`, n.site ? el('span', {}, ' · ', this.siteLink(n.site)) : null));
if (!w.data.paths.length) box.append(el('p.pub-faint', {}, t('No path from a root: it is kept only by a cycle (or it is about to be freed).')));
for (const path of w.data.paths) {
box.append(el('div.cryo-path', {}, ...path.map((step, i) => el('span', {}, i ? ' → ' : '', el('b', {}, i ? step.name : `${step.kind} ${step.name}`),
step.class ? el('span.pub-faint', {}, ` (${step.class.split('\\').pop()})`) : null))));
}
if (n.in?.length) box.append(el('p.pub-faint', {}, t('Held by: {list}', { list: n.in.map((x) => `${x.name} (#${x.node})`).join(', ') })));
return box;
}
async explain(site) {
const df = this.diff;
df.explained = { site, busy: true };
this.renderFiles();
try { df.explained = (await backend.invoke('cryo.explain', { site, files: [df.a, df.b] })).explain || { site, error: t('Nothing known about this site.') }; } catch (e) { df.explained = { site, error: String(e.message || e) }; }
this.renderFiles();
}
explainNode(x) {
const box = el('div.cryo-why', {}, el('h5', {}, x.site));
if (x.busy) return box.append(el('p.pub-faint', {}, t('Reading…'))), box;
if (x.error) return box.append(el('p.cryo-error', {}, x.error)), box;
const code = (lines) => el('pre.cryo-out', {}, Object.entries(lines || {}).map(([n, l]) => `${n} ${l}`).join('\n'));
if (x.code) box.append(el('p', {}, t('Where they are made')), code(x.code));
if (x.hooked_by) box.append(el('p', {}, t('What keeps them:'), ' ', this.siteLink(x.hooked_by)), code(x.hook_code));
for (const p of x.paths || []) box.append(el('div.cryo-path', {}, `${p.count} × `, ...p.path.map((step, i) => el('span', {}, i ? ' → ' : '', el('b', {}, step.name)))));
return box;
}
/** "file:line function" -> a link to that line (paths of the runtime, /workspace/..., are the project's) */
siteLink(site) {
const m = /^(\/workspace\/)?(.+?):(\d+)/.exec(String(site || ''));
if (!m) return String(site || '–');
return el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.app.editors.open(m[2], { line: Number(m[3]), endLine: Number(m[3]) }).catch(() => null); } }, String(site).replace('/workspace/', ''));
}
table(head, rows) {
return el('table.cryo-table', {}, el('thead', {}, el('tr', {}, ...head.map((h) => el('th', {}, t(h))))),
el('tbody', {}, ...rows.map((r) => el('tr', {}, ...r.map((c) => el('td', {}, c))))));
}
// Sandbox ----------------------------------------------------------------------------------------------------
renderSandbox() {
const s = this.sandbox;
const code = el('textarea.cryo-code', { spellcheck: false, value: s.code, oninput: (e) => { s.code = e.target.value; prefs.set('cryoSandboxCode', s.code); } });
code.value = s.code;
code.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); this.runSandbox(); } });
this.body.append(
el('p.pub-faint', {}, t('PHP run in an isolated Cryo\\Sandbox: a fatal error, an endless loop or too much memory stops the sandbox, never the IDE. Ctrl+Enter runs it.')),
code,
el('div.cryo-row', {},
el('button.btn.primary', { disabled: s.busy, onclick: () => this.runSandbox() }, icon('play'), t(s.busy ? 'Running…' : 'Run')),
el('label', {}, t('Timeout (s)'), ' ', el('input.cryo-num', { type: 'number', min: 0.1, max: 60, step: 0.5, value: s.timeout, onchange: (e) => { s.timeout = Number(e.target.value) || 5; } })),
el('label', {}, t('Memory'), ' ', el('input.cryo-num', { value: s.memory, onchange: (e) => { s.memory = e.target.value || '64M'; } }))));
const r = s.result;
if (r?.error) this.body.append(el('p.cryo-error', {}, r.error));
else if (r) {
this.body.append(el('div.cryo-detail', {},
r.failed ? el('p.cryo-error', {}, r.failed) : el('p', {}, t('Returned'), ' ', el('code', {}, r.result)),
r.output ? el('pre.cryo-out', {}, r.output) : null,
el('p.pub-faint', {}, t('{ms} ms · sandbox memory {memory} · limits {timeout} s, {limit}', { ms: r.ms, memory: kb(r.status?.memory), timeout: r.timeout, limit: r.memory_limit }))));
}
}
async runSandbox() {
const s = this.sandbox;
if (s.busy) return;
s.busy = true; this.render();
try { s.result = await backend.invoke('cryo.sandbox', { code: s.code, timeout: s.timeout, memory: s.memory }); } catch (e) { s.result = { error: String(e.message || e) }; }
s.busy = false;
if (this.tab === 'sandbox') this.render();
}
}
// Claude's tools (agent.js): the same as the window
export const cryoAgentTools = {
...abAgentTools,
...hotAgentTools,
cryo() {
if (!this.app.cryo) throw new Error('no Cryo window here: it needs a JumPHP project run on this computer (bin/jumphp with Docker)');
return this.app.cryo;
},
async tool_cryo_inspect(args) { this.cryo(); return backend.invoke('cryo.inspect', { path: args.path }); },
async tool_cryo_why(args) { this.cryo(); return backend.invoke('cryo.why', { path: args.path, what: args.what }); },
async tool_cryo_freeze(args) { this.cryo(); return backend.invoke('cryo.freeze', { name: args.name || '' }); },
async tool_cryo_diff(args) { this.cryo(); return backend.invoke('cryo.diff', { a: args.a, b: args.b }); },
async tool_cryo_sandbox(args) { this.cryo(); return backend.invoke('cryo.sandbox', { code: args.code, timeout: args.timeout || 5, memory: args.memory_limit || '64M' }); },
async tool_cryo_live(args) {
this.cryo();
if (args.snapshot) { const r = await backend.invoke('cryo.snapshot', {}); this.app.cryo.openFile(r.path); return r; }
return (await backend.invoke('cryo.live', { since: 0 })).metrics;
},
};