283 lines
16 KiB
JavaScript
283 lines
16 KiB
JavaScript
// A/B tests, the Cryo window's A/B tab (and Claude's ab_* tools): "Start" copies the PHP code of a game or app (A); the
|
||
// code is then changed as usual (B); the functions changed since are listed (ticked: the sections compared); "Test A"
|
||
// profiles the same run with the A version of the changed files (JUMPHP_AB_OVERLAY: the engine loads them instead of
|
||
// the game's own), "Test B" with the code as it is; the two profiles (CPU time, memory) are compared, the whole run and
|
||
// each section. PHP side: ide/src/Ab/AbTest.php, AbCommands.php; the profiles are the Profiler's (Xdebug).
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t } from './ui.js';
|
||
|
||
const kb = (n) => (n == null ? '–' : Math.abs(n) >= 1048576 ? (n / 1048576).toFixed(2) + ' MB' : Math.abs(n) >= 1024 ? (n / 1024).toFixed(1) + ' KB' : n + ' B');
|
||
const pct = (p) => (p == null ? '' : ` (${p > 0 ? '+' : ''}${p}%)`);
|
||
|
||
export class AbTab {
|
||
constructor(app, panel) {
|
||
this.app = app;
|
||
this.panel = panel;
|
||
this.module = prefs.get('abModule:' + app.projectKey, null);
|
||
this.state = null;
|
||
this.changes = null;
|
||
this.unticked = new Set();
|
||
this.frames = prefs.get('abFrames', 600);
|
||
this.scene = prefs.get('abScene:' + app.projectKey, '');
|
||
this.profiles = { a: null, b: null };
|
||
this.result = null;
|
||
this.busy = '';
|
||
this.aiTarget = prefs.get('abAiTarget', 'selection');
|
||
this.aiAgent = prefs.get('abAiAgent', 'claude');
|
||
this.aiAutoTest = prefs.get('abAiAutoTest', true);
|
||
this.aiWaiting = false;
|
||
}
|
||
|
||
modules() { return (this.app.project?.modules || []).filter((m) => m.dir); }
|
||
|
||
current() {
|
||
const all = this.modules();
|
||
return all.find((m) => m.id === this.module) || all[0] || null;
|
||
}
|
||
|
||
async refresh() {
|
||
const m = this.current();
|
||
if (!m) return;
|
||
try {
|
||
this.state = await backend.invoke('ab.state', { id: m.id });
|
||
this.changes = this.state.active ? await backend.invoke('ab.changes', { id: m.id }) : null;
|
||
} catch (e) { this.state = { active: false, error: String(e.message || e) }; }
|
||
this.panel.render();
|
||
}
|
||
|
||
render(body) {
|
||
const m = this.current();
|
||
if (!m) {
|
||
body.append(el('div.prof-empty', {}, el('div.prof-empty-title', {}, t('A/B test')), el('p', {}, t('This project has no game or app to test.'))));
|
||
return;
|
||
}
|
||
if (this.state === null) { this.refresh(); body.append(el('p.pub-faint', {}, t('Reading…'))); return; }
|
||
const pick = this.modules().length > 1 ? el('select', { onchange: (e) => { this.module = e.target.value; prefs.set('abModule:' + this.app.projectKey, this.module); this.state = null; this.result = null; this.panel.render(); } },
|
||
...this.modules().map((x) => el('option', { value: x.id, selected: x.id === m.id }, x.title || x.id))) : el('b', {}, m.title || m.id);
|
||
body.append(el('div.cryo-row', {}, pick));
|
||
if (!this.state.active) {
|
||
body.append(el('div.prof-empty', {},
|
||
el('div.prof-empty-title', {}, t('Is a change faster? Test A against B')),
|
||
el('p', {}, t('Start copies the code as it is now (A). Change it in the editor (B), then Test A and Test B run the same thing under the profiler: CPU time and memory compared, for the whole run and for each function you changed.')),
|
||
el('button.btn.primary', { disabled: !!this.busy, onclick: () => this.start() }, icon('fork'), t('Start an A/B test'))));
|
||
if (this.app.claude) body.append(this.aiNode());
|
||
return;
|
||
}
|
||
const when = new Date(this.state.started * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||
body.append(el('p.pub-faint', {}, t('A = the code of {dir} at {time} ({n} files). B = the code as it is now: change it in the editor.', { dir: this.state.module, time: when, n: this.state.files })));
|
||
// what changed: the sections
|
||
const box = el('div.cryo-detail', {}, el('div.cryo-row', {}, el('h5', {}, t('Changed since A')),
|
||
el('button', { title: t('Refresh'), onclick: () => this.refresh() }, icon('refresh'))));
|
||
if (!this.changes?.length) box.append(el('p.pub-faint', {}, t('Nothing changed yet: change the code of the game, then refresh.')));
|
||
for (const c of this.changes || []) {
|
||
box.append(el('div.ab-file', {}, el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.app.editors.open(c.file).catch(() => null); } }, c.file),
|
||
el('span.pub-faint', {}, ` ${t(c.status)}`)));
|
||
for (const s of c.sections) {
|
||
const key = s.name;
|
||
const outside = key.startsWith('(');
|
||
box.append(el('label.ab-section', {},
|
||
el('input', { type: 'checkbox', disabled: outside, checked: !outside && !this.unticked.has(key), onchange: (e) => { if (e.target.checked) this.unticked.delete(key); else this.unticked.add(key); } }),
|
||
el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.app.editors.open(c.file, { line: s.from, endLine: s.to }).catch(() => null); } }, key),
|
||
outside ? el('span.pub-faint', {}, ' ' + t('(counts in the whole run only)')) : null));
|
||
}
|
||
}
|
||
body.append(box);
|
||
if (this.app.claude) body.append(this.aiNode());
|
||
// the run
|
||
body.append(el('div.cryo-row', {},
|
||
el('label', {}, t('Frames'), ' ', el('input.cryo-num', { type: 'number', min: 30, max: 36000, step: 60, value: this.frames, onchange: (e) => { this.frames = Math.max(30, Number(e.target.value) || 600); prefs.set('abFrames', this.frames); } })),
|
||
el('label', {}, t('Scene'), ' ', el('input', { placeholder: t('its smoke scene'), value: this.scene, style: { width: '170px' }, onchange: (e) => { this.scene = e.target.value.trim(); prefs.set('abScene:' + this.app.projectKey, this.scene); } }))));
|
||
body.append(el('div.cryo-row', {},
|
||
el('button.btn', { disabled: !!this.busy, onclick: () => this.test('a') }, icon('play'), t('Test A')),
|
||
el('button.btn', { disabled: !!this.busy, onclick: () => this.test('b') }, icon('play'), t('Test B')),
|
||
el('button.btn.primary', { disabled: !!this.busy, onclick: () => this.both() }, icon('profile'), t('Test A then B')),
|
||
this.busy ? el('span.pub-faint', {}, this.busy) : null));
|
||
if (this.profiles.a || this.profiles.b) body.append(el('p.pub-faint', {}, `A: ${this.profiles.a ? '✓' : '–'} B: ${this.profiles.b ? '✓' : '–'}`));
|
||
if (this.result) body.append(this.resultNode());
|
||
body.append(el('div.cryo-row', {}, el('button.btn', { disabled: !!this.busy, onclick: () => this.stop() }, icon('close'), t('End the A/B test (the copy A is deleted, your code stays)'))));
|
||
}
|
||
|
||
/** "Improve it with the AI": Claude Code or OpenCode is asked to make a selection, a file or the project faster and lighter */
|
||
aiNode() {
|
||
const radio = (value, label) => el('label', {}, el('input', { type: 'radio', name: 'abAiTarget', checked: this.aiTarget === value,
|
||
onchange: () => { this.aiTarget = value; prefs.set('abAiTarget', value); } }), ' ', t(label));
|
||
const agent = el('select', { onchange: (e) => { this.aiAgent = e.target.value; prefs.set('abAiAgent', this.aiAgent); } },
|
||
el('option', { value: 'claude', selected: this.aiAgent === 'claude' }, 'Claude'), el('option', { value: 'opencode', selected: this.aiAgent === 'opencode' }, 'OpenCode'));
|
||
return el('div.cryo-detail', {}, el('h5', {}, t('Improve it with the AI')),
|
||
el('p.pub-faint', {}, t('The AI is asked to make the code faster and lighter without changing what it does; the code before is A (an A/B test starts if none is), its version is B.')),
|
||
el('div.cryo-row', {}, radio('selection', 'The selection in the editor'), radio('file', 'The file in the editor'), radio('project', 'The whole game / app')),
|
||
el('div.cryo-row', {}, agent,
|
||
el('label', {}, el('input', { type: 'checkbox', checked: this.aiAutoTest, onchange: (e) => { this.aiAutoTest = e.target.checked; prefs.set('abAiAutoTest', this.aiAutoTest); } }), ' ', t('Test A then B when it is done')),
|
||
el('button.btn.primary', { disabled: !!this.busy || this.aiWaiting, onclick: () => this.improve() }, icon('claude'), t(this.aiWaiting ? 'The AI is working…' : 'Ask the AI'))));
|
||
}
|
||
|
||
/** the request for the AI, from the editor's selection, its file or the module */
|
||
aiRequest() {
|
||
const m = this.current();
|
||
const goal = 'Make this code faster and lighter (CPU time and memory) without changing what it does: same behaviour, same public API, '
|
||
+ 'change only what is needed, keep the style of the project. When you are done, stop and say in two lines what you changed: '
|
||
+ 'the IDE then runs an A/B test (A = the code before your change, B = yours) and shows the CPU and memory difference.';
|
||
const group = this.app.editors?.focused;
|
||
const tab = this.app.editors?.activeTab();
|
||
if (this.aiTarget === 'selection') {
|
||
const ed = group?.editor;
|
||
const sel = ed?.getSelection();
|
||
if (!tab || !sel || sel.isEmpty()) throw new Error(t('Select the code to improve in the editor first.'));
|
||
return `${goal}\n\nIn ${tab.path} (lines ${sel.startLineNumber}-${sel.endLineNumber}):\n\`\`\`\n${ed.getModel().getValueInRange(sel)}\n\`\`\`\n`;
|
||
}
|
||
if (this.aiTarget === 'file') {
|
||
if (!tab) throw new Error(t('Open the file to improve in the editor first.'));
|
||
return `${goal}\n\nThe file: @${tab.path}`;
|
||
}
|
||
return `${goal}\n\nThe whole ${m.dir} (its PHP code in ${m.dir}/src): find what costs the most first (the IDE's profile_run / profile_summary tools profile its smoke scene), then improve that.`;
|
||
}
|
||
|
||
async improve() {
|
||
let request;
|
||
try { request = this.aiRequest(); } catch (e) { notify(String(e.message || e), 'warning', { title: t('Improve it with the AI') }); return; }
|
||
if (!this.state?.active) await this.start();
|
||
if (!this.state?.active) return;
|
||
const panel = this.app.claude;
|
||
if (panel.agent !== this.aiAgent) await panel.setAgent(this.aiAgent);
|
||
panel.ask(request);
|
||
const conv = panel.current();
|
||
if (!conv) return;
|
||
this.aiWaiting = true;
|
||
this.panel.render();
|
||
await conv.send();
|
||
// done when its run ends: then the changes are read again (and tested, if asked)
|
||
const started = Date.now();
|
||
while ((conv.run || Date.now() - started < 1500) && Date.now() - started < 3600_000) await new Promise((r) => setTimeout(r, 1000));
|
||
this.aiWaiting = false;
|
||
await this.refresh();
|
||
this.app.showTool('cryo', true);
|
||
this.panel.setTab('ab');
|
||
if (this.aiAutoTest && this.changes?.length) await this.both();
|
||
}
|
||
|
||
resultNode() {
|
||
const r = this.result;
|
||
const s = r.summary;
|
||
const box = el('div.cryo-detail', {}, el('h5', {}, t('A → B')));
|
||
const line = (label, v, fmt) => el('p', {}, el('b', {}, t(label) + ': '), `${fmt(v[0])} → ${fmt(v[1])}`, el('span', { class: v[2] > 0 ? 'ab-worse' : v[2] < 0 ? 'ab-better' : '' }, pct(v[3])));
|
||
box.append(line('Whole run, CPU', s.totalMs, (x) => `${Math.round(x * 10) / 10} ms`), line('Whole run, memory allocated', s.allocBytes, kb));
|
||
if (s.peakBytes?.[0] != null) box.append(line('Peak memory', s.peakBytes, kb));
|
||
const rows = r.sections.map((x) => [x.section + (x.ran ? '' : ' ' + t('(not run)')),
|
||
`${x.selfMs[0]} → ${x.selfMs[1]}${pct(x.selfMs[3])}`, `${x.inclMs[0]} → ${x.inclMs[1]}${pct(x.inclMs[3])}`, `${kb(x.memBytes[0])} → ${kb(x.memBytes[1])}${pct(x.memBytes[3])}`, `${x.calls[0]} → ${x.calls[1]}`]);
|
||
if (rows.length) box.append(this.panel.table(['Section', 'Own CPU ms', 'With calls ms', 'Memory', 'Calls'], rows));
|
||
box.append(el('p.pub-faint', {}, t('One run each: CPU times move a few % from run to run; compare big differences, or test again.')));
|
||
return box;
|
||
}
|
||
|
||
sections() {
|
||
return (this.changes || []).flatMap((c) => c.sections.map((s) => s.name)).filter((n) => !n.startsWith('(') && !this.unticked.has(n));
|
||
}
|
||
|
||
async start() {
|
||
const m = this.current();
|
||
this.busy = t('Copying…');
|
||
this.panel.render();
|
||
try { this.state = await backend.invoke('ab.start', { id: m.id, dir: m.dir }); this.changes = []; this.result = null; this.profiles = { a: null, b: null }; }
|
||
catch (e) { notify(String(e.message || e), 'error', { title: t('A/B test') }); }
|
||
this.busy = '';
|
||
this.panel.render();
|
||
}
|
||
|
||
async stop() {
|
||
const m = this.current();
|
||
await backend.invoke('ab.stop', { id: m.id }).catch(() => null);
|
||
this.state = { active: false };
|
||
this.changes = null; this.result = null; this.profiles = { a: null, b: null };
|
||
this.panel.render();
|
||
}
|
||
|
||
/** profiles one side; returns the profile */
|
||
async test(side) {
|
||
const m = this.current();
|
||
if (!this.app.profiler) throw new Error(t('The profiler is not available here.'));
|
||
this.busy = side === 'a' ? t('Testing A…') : t('Testing B…');
|
||
this.panel.render();
|
||
try {
|
||
const env = {};
|
||
if (side === 'a') env.JUMPHP_AB_OVERLAY = (await backend.invoke('ab.overlay', { id: m.id })).path;
|
||
if (this.scene) env.JUMPHP_SCENE = this.scene;
|
||
else {
|
||
// its self-playing demo (project.yaml smoke): the same play, A and B
|
||
const smoke = await backend.invoke('ab.smoke', { dir: m.dir }).catch(() => ({}));
|
||
if (smoke.scene) { env.JUMPHP_SCENE = smoke.scene; env.JUMPHP_SCENE_PARAMS = JSON.stringify(smoke.params || {}); }
|
||
}
|
||
const config = { id: 'adhoc', kind: 'shot', label: `A/B ${side.toUpperCase()}: ${m.id}`, command: ['bin/jumphp', 'shot', m.id, String(this.frames)] };
|
||
const profile = await this.app.profiler.profileConfig(config, { mode: 'both', engine: 'xdebug', durationKind: 'frames', durationValue: this.frames }, env);
|
||
if (!profile) throw new Error(t('no profile was made'));
|
||
this.profiles[side] = profile.id;
|
||
this.app.showTool('cryo', true);
|
||
if (this.profiles.a && this.profiles.b) await this.compare();
|
||
return profile;
|
||
} catch (e) {
|
||
notify(String(e.message || e), 'error', { title: t('A/B test') });
|
||
throw e;
|
||
} finally {
|
||
this.busy = '';
|
||
this.panel.render();
|
||
}
|
||
}
|
||
|
||
async both() {
|
||
await this.refresh();
|
||
try { await this.test('a'); await this.test('b'); } catch { /* told */ }
|
||
}
|
||
|
||
async compare() {
|
||
this.result = await backend.invoke('ab.compare', { a: this.profiles.a, b: this.profiles.b, sections: this.sections() });
|
||
this.panel.render();
|
||
return this.result;
|
||
}
|
||
}
|
||
|
||
// Claude's tools (agent.js): the same as the tab, for an autonomous A/B test
|
||
export const abAgentTools = {
|
||
abTab(args) {
|
||
const tab = this.app.cryo?.ab;
|
||
if (!tab) throw new Error('no A/B tests here: it needs a JumPHP project run on this computer (bin/jumphp with Docker)');
|
||
if (args.project) {
|
||
const m = tab.modules().find((x) => x.id === args.project);
|
||
if (!m) throw new Error(`no game or app "${args.project}": ${tab.modules().map((x) => x.id).join(', ')}`);
|
||
tab.module = m.id;
|
||
}
|
||
return tab;
|
||
},
|
||
async tool_ab_start(args) {
|
||
const tab = this.abTab(args);
|
||
await tab.start();
|
||
return tab.state;
|
||
},
|
||
async tool_ab_changes(args) {
|
||
const tab = this.abTab(args);
|
||
await tab.refresh();
|
||
if (!tab.state?.active) throw new Error('no A/B test started: ab_start first');
|
||
return tab.changes;
|
||
},
|
||
async tool_ab_run(args) {
|
||
const tab = this.abTab(args);
|
||
await tab.refresh();
|
||
if (!tab.state?.active) throw new Error('no A/B test started: ab_start first');
|
||
if (args.frames) tab.frames = Math.max(30, Number(args.frames));
|
||
if (args.scene !== undefined) tab.scene = String(args.scene || '');
|
||
if (Array.isArray(args.sections)) {
|
||
const keep = new Set(args.sections.map(String));
|
||
tab.unticked = new Set(tab.changes.flatMap((c) => c.sections.map((s) => s.name)).filter((n) => !keep.has(n)));
|
||
}
|
||
if (args.side === 'a' || args.side === 'b') {
|
||
const p = await tab.test(args.side);
|
||
return { side: args.side, profile_id: p.id, compared: !!tab.result, result: tab.result?.markdown };
|
||
}
|
||
await tab.test('a');
|
||
await tab.test('b');
|
||
return { sections: tab.sections(), result: tab.result?.markdown, json: { summary: tab.result?.summary, sections: tab.result?.sections } };
|
||
},
|
||
async tool_ab_stop(args) {
|
||
const tab = this.abTab(args);
|
||
await tab.stop();
|
||
return { stopped: true };
|
||
},
|
||
};
|