glitchless-playtest 0.4.0 → 0.5.0

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 CHANGED
@@ -217,8 +217,19 @@ const result = await playtest({ saveAs: 'baseline' }); // later: playtest({ comp
217
217
  const check = await gameCheck({ url: 'https://someone.itch.io/their-game', server, apiKey }); // → { report, dm, share, files }
218
218
  ```
219
219
 
220
+ Both take a `signal` (an AbortSignal, from 0.5.0) to stop part-way: the browser closes, the build and anything it
221
+ started (a launcher's children too) are killed, or Studio's play test stops; nothing is saved, and the promise rejects
222
+ with the signal's reason.
223
+
224
+ ```js
225
+ const stop = new AbortController();
226
+ const running = playtest({ signal: stop.signal });
227
+ stop.abort(); // the run stops at once
228
+ ```
229
+
220
230
  The [glitchless-mcp](https://www.npmjs.com/package/glitchless-mcp) server exposes the same thing to
221
- coding agents as the `glitchless_playtest` tool, and a game check as its `check_url`.
231
+ coding agents as the `glitchless_playtest` tool, and a game check as its `check_url`. From glitchless-mcp
232
+ 0.23.0, a client that takes MCP tasks runs it as one, and cancelling the task stops the run.
222
233
 
223
234
  ## License
224
235
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glitchless-playtest",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Playtest bots for game observability: your game's autoplay bot plays a Unity, Godot, Unreal or GameMaker build, a Roblox game in Roblox Studio, or a web game (Three.js, Phaser, Babylon.js, PlayCanvas) in Chrome, on the current code and on a saved baseline, and Glitchless flags what got slower or started breaking.",
5
5
  "keywords": [
6
6
  "playtesting",
package/src/check.js CHANGED
@@ -23,6 +23,7 @@ import { checkInitScript } from './check-page.js';
23
23
  import { resolveGame, robotsCheck, refusal, CHECK_UA_SUFFIX } from './check-site.js';
24
24
  import { PROFILES, explore, aiPlayer, profileWords, AI_MODEL } from './check-bot.js';
25
25
  import { checkReport, checkDm, checkDashboard, CHECK_PAGE } from './check-report.js';
26
+ import { onStop, stopped, checkStop, pause } from './stop.js';
26
27
 
27
28
  const HERE = path.dirname(fileURLToPath(import.meta.url));
28
29
  // Seconds of play per profile by default; the phone plays two thirds as long. A check never plays past MAX_PLAY_S.
@@ -52,8 +53,10 @@ export function slugify(s) {
52
53
  * @param {string[]} [o.profiles] 'desktop', 'phone' or both (default both)
53
54
  * @param {boolean} [o.ai] let a Claude model pick the inputs (needs ANTHROPIC_API_KEY and @anthropic-ai/sdk)
54
55
  * @param {string} [o.outDir] where the report and screenshots go (default .glitchless/checks/<game>-<time>)
56
+ * @param {AbortSignal} [o.signal] stops the check part-way: the browser closes, nothing more is made in Glitchless
57
+ * (no dashboard, banner or share link), and it ends with the signal's reason
55
58
  */
56
- export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'http://localhost:7777', apiKey = process.env.GLITCHLESS_API_KEY || '', name, seconds = CHECK_SECONDS, profiles = ['desktop', 'phone'], ai = false, aiModel, headed = false, channel = 'chrome', adapters = true, outDir, cwd = process.cwd(), share = true, log = () => {} } = {}) {
59
+ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'http://localhost:7777', apiKey = process.env.GLITCHLESS_API_KEY || '', name, seconds = CHECK_SECONDS, profiles = ['desktop', 'phone'], ai = false, aiModel, headed = false, channel = 'chrome', adapters = true, outDir, cwd = process.cwd(), share = true, log = () => {}, signal } = {}) {
57
60
  if (!url) throw new Error('A game check needs the game\'s address (url).');
58
61
  const base = String(server).replace(/\/$/, '');
59
62
  const want = profiles.filter((p) => PROFILES[p]);
@@ -69,6 +72,7 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
69
72
  log(`Could not launch ${channel} (${err.message.split('\n')[0]}); using Playwright's Chromium.`);
70
73
  return launch(undefined);
71
74
  });
75
+ const forget = onStop(signal, () => browser.close().catch(() => {}));
72
76
  try {
73
77
  // The browser's own User-Agent, with the check named at its end, so a site can tell this visit apart.
74
78
  const probe = await browser.newPage();
@@ -83,6 +87,7 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
83
87
  const gameName = String(name || target.title || new URL(target.page_url).hostname).trim().slice(0, 80);
84
88
  log(`Game check: ${gameName} (${target.play_url})`);
85
89
 
90
+ checkStop(signal);
86
91
  const dest = await checkDestination({ base, apiKey, name: gameName, log });
87
92
  const sdk = await sdkScript(base, cwd);
88
93
  const version = `check-${new Date().toISOString().slice(0, 10)}`;
@@ -94,6 +99,7 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
94
99
  const runs = [];
95
100
  let landscape = target.size ? target.size.width > target.size.height * 1.1 : null;
96
101
  for (const p of want) {
102
+ checkStop(signal);
97
103
  const profile = { ...PROFILES[p] };
98
104
  if (p === 'desktop' && target.size) profile.viewport = { width: target.size.width, height: target.size.height };
99
105
  if (p === 'phone' && landscape) profile.viewport = { width: profile.viewport.height, height: profile.viewport.width };
@@ -107,13 +113,15 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
107
113
  if (landscape == null && run.page?.canvas) landscape = run.page.canvas.width > run.page.canvas.height * 1.1;
108
114
  }
109
115
 
116
+ checkStop(signal);
110
117
  const ids = runs.map((r) => r.session_id).filter(Boolean);
111
118
  const read = readerFor(base, apiKey, dest);
112
119
  let summary = null;
113
120
  let findings = [];
114
121
  if (ids.length) {
115
122
  log(`reading what Glitchless made of ${ids.length} run(s) …`);
116
- summary = await waitForSummary(read, dest.service, ids, started, { log, timeoutMs: dest.cloud ? 180_000 : 30_000 }).catch((err) => {
123
+ summary = await waitForSummary(read, dest.service, ids, started, { log, timeoutMs: dest.cloud ? 180_000 : 30_000, signal }).catch((err) => {
124
+ checkStop(signal);
117
125
  notes.push(`Glitchless's summary of the runs couldn't be read: ${err.message}`);
118
126
  return null;
119
127
  });
@@ -141,18 +149,22 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
141
149
 
142
150
  // The game's dashboard, a picture of it as the board's banner, and an unlisted link to the check's page: only when
143
151
  // what the bots measured reached Glitchless, or the board and its link would show nothing.
152
+ checkStop(signal);
144
153
  if (ids.length && !summary?.runs?.length) notes.push(`No dashboard or share link: ${summary ? 'nothing the bots measured reached Glitchless' : "Glitchless's summary of the runs couldn't be read"}, so they would show nothing.`);
145
154
  if (summary?.runs?.length) {
146
155
  const pages = checkDashboard(result);
156
+ checkStop(signal);
147
157
  await write(base, apiKey, dest, 'PUT', `/v1/dashboard?service=${encodeURIComponent(dest.service)}`, { pages })
148
158
  .then(() => (result.dashboard = { pages: pages.map((p) => p.title) }))
149
159
  .catch((err) => notes.push(`The dashboard wasn't saved: ${err.message}`));
150
160
  const picture = runs.find((r) => r.profile === 'desktop')?.shots?.find((s) => /playing/.test(s)) || runs.flatMap((r) => r.shots || []).find((s) => /playing|end/.test(s));
151
161
  if (picture && fs.statSync(picture).size <= 300_000) {
162
+ checkStop(signal);
152
163
  await upload(base, apiKey, dest, `/v1/brand/banner?service=${encodeURIComponent(dest.service)}`, fs.readFileSync(picture), 'image/jpeg').catch((err) => notes.push(`The board's banner wasn't set: ${err.message}`));
153
164
  }
154
165
  result.dashboard_url = dest.dashboard ? `${dest.dashboard}#/${CHECK_PAGE}` : `${base}/?service=${encodeURIComponent(dest.service)}#/${CHECK_PAGE}`;
155
166
  if (share && dest.cloud) {
167
+ checkStop(signal);
156
168
  result.share = await shareLink(base, apiKey, dest, { from: started - 60_000, to: Date.now() + 120_000 }).catch((err) => {
157
169
  notes.push(`No share link: ${err.message}`);
158
170
  return null;
@@ -160,6 +172,7 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
160
172
  } else if (share) notes.push('No share link: share links are a Glitchless Cloud feature (sign in with a workspace key, gl_ws_…). The dashboard is on this server.');
161
173
  }
162
174
 
175
+ checkStop(signal);
163
176
  result.report = checkReport(result);
164
177
  result.dm = checkDm(result);
165
178
  const files = { report: path.join(dir, 'report.md'), dm: path.join(dir, 'message.txt'), json: path.join(dir, 'check.json') };
@@ -168,7 +181,10 @@ export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'h
168
181
  fs.writeFileSync(files.json, `${JSON.stringify({ ...result, report: undefined, dm: undefined }, null, 2)}\n`);
169
182
  result.files = { ...files, shots: runs.flatMap((r) => r.shots || []) };
170
183
  return result;
184
+ } catch (err) {
185
+ throw stopped(signal, err);
171
186
  } finally {
187
+ forget();
172
188
  await browser.close();
173
189
  }
174
190
  }
@@ -480,10 +496,11 @@ async function upload(base, apiKey, dest, p, bytes, type) {
480
496
  }
481
497
 
482
498
  // The summary of the check's sessions, once each has ended (Glitchless Cloud's lake can take a minute or two).
483
- async function waitForSummary(read, service, ids, started, { log, timeoutMs }) {
499
+ async function waitForSummary(read, service, ids, started, { log, timeoutMs, signal }) {
484
500
  const deadline = Date.now() + timeoutMs;
485
501
  let last = null;
486
502
  while (true) {
503
+ checkStop(signal);
487
504
  const body = await read('playtest', { service, sessions: ids.join(','), from: started - 60_000, to: Date.now() + 60_000 });
488
505
  last = body.summary;
489
506
  const ended = new Set((last?.runs || []).filter((r) => r.ended).map((r) => r.session_id));
@@ -492,7 +509,7 @@ async function waitForSummary(read, service, ids, started, { log, timeoutMs }) {
492
509
  log(` ${ids.filter((id) => !ended.has(id)).length} run(s) not complete in Glitchless yet; using what arrived`);
493
510
  return last;
494
511
  }
495
- await new Promise((r) => setTimeout(r, 3000));
512
+ await pause(3000, signal);
496
513
  }
497
514
  }
498
515
 
package/src/engine.js CHANGED
@@ -7,8 +7,9 @@
7
7
  import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
- import { spawn } from 'node:child_process';
10
+ import { spawn, execFileSync } from 'node:child_process';
11
11
  import { gitInfo } from './run.js';
12
+ import { onStop, checkStop } from './stop.js';
12
13
 
13
14
  // How each engine takes flags, how long to wait before measuring, and how to give a game an autoplay mode.
14
15
  // Unreal and GameMaker games read single-dash flags; the Glitchless SDKs in them take either.
@@ -166,12 +167,53 @@ export function engineScenario(sc, engine, cfg) {
166
167
  const label = (sc) => sc.name || [...paramFlags(sc.params), ...(sc.args || [])].join(' ') || 'run';
167
168
  const tail = (text, n = 15) => String(text || '').trimEnd().split(/\r?\n/).slice(-n).join('\n');
168
169
 
169
- // Runs one build to the end, or kills it at the time cap.
170
- function runBuild(argv, { cwd, timeoutMs }) {
170
+ // The processes a build started, and theirs (a launcher script, Unreal's .sh or its Win64 bootstrap, a .bat, npm run):
171
+ // on macOS and Linux every descendant of pid, read from ps, deepest first. → [pid, …], without pid itself.
172
+ function descendants(pid) {
173
+ try {
174
+ const kids = new Map();
175
+ for (const line of execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8' }).split('\n')) {
176
+ const [p, pp] = line.trim().split(/\s+/).map(Number);
177
+ if (p && pp) kids.set(pp, [...(kids.get(pp) || []), p]);
178
+ }
179
+ const out = [];
180
+ const walk = (p) => (kids.get(p) || []).forEach((c) => (walk(c), out.push(c)));
181
+ walk(pid);
182
+ return out;
183
+ } catch {
184
+ return [];
185
+ }
186
+ }
187
+
188
+ // Ends a build and everything it started: on Windows with taskkill /T /F; elsewhere SIGTERM to the build and its
189
+ // descendants, then SIGKILL to what's left 5 seconds later. A build doesn't get a process group of its own, so Ctrl-C
190
+ // in the terminal running glitchless-playtest still reaches it.
191
+ function killTree(child) {
192
+ if (process.platform === 'win32') {
193
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on('error', () => child.kill());
194
+ return;
195
+ }
196
+ const signalAll = (sig, pids) => {
197
+ for (const p of pids) {
198
+ try {
199
+ process.kill(p, sig);
200
+ } catch {}
201
+ }
202
+ };
203
+ const tree = [...descendants(child.pid), child.pid];
204
+ signalAll('SIGTERM', tree);
205
+ setTimeout(() => signalAll('SIGKILL', [...new Set([...tree, ...descendants(child.pid)])]), 5000).unref();
206
+ }
207
+
208
+ // Runs one build to the end, or kills it (and what it started) at the time cap or once signal fires. Once killed, it
209
+ // settles when the build has exited, even if something it started still holds its output open.
210
+ function runBuild(argv, { cwd, timeoutMs, signal }) {
171
211
  return new Promise((resolve, reject) => {
172
212
  const t0 = Date.now();
173
213
  let output = '';
174
214
  let timedOut = false;
215
+ let killed = false;
216
+ let settled = false;
175
217
  const child = spawn(argv[0], argv.slice(1), { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
176
218
  const keep = (d) => {
177
219
  output += d;
@@ -179,19 +221,38 @@ function runBuild(argv, { cwd, timeoutMs }) {
179
221
  };
180
222
  child.stdout.on('data', keep);
181
223
  child.stderr.on('data', keep);
224
+ const kill = () => {
225
+ if (killed) return;
226
+ killed = true;
227
+ killTree(child);
228
+ };
182
229
  const timer = setTimeout(() => {
183
230
  timedOut = true;
184
- child.kill('SIGTERM');
185
- setTimeout(() => child.kill('SIGKILL'), 5000).unref();
231
+ kill();
186
232
  }, timeoutMs);
233
+ const forget = onStop(signal, kill);
234
+ const finish = (code, killedBy) => {
235
+ if (settled) return;
236
+ settled = true;
237
+ clearTimeout(timer);
238
+ forget();
239
+ resolve({ code, signal: killedBy, output, timedOut, seconds: Math.round((Date.now() - t0) / 1000) });
240
+ };
187
241
  child.on('error', (err) => {
242
+ settled = true;
188
243
  clearTimeout(timer);
244
+ forget();
189
245
  reject(err.code === 'ENOENT' ? new Error(`Could not start ${argv[0]}: no such program. Set "command" in glitchless.playtest.json to the exported build, or to the engine's command line with the project path (for Godot: ["godot", "--path", "."]).`) : err);
190
246
  });
191
- child.on('close', (code, signal) => {
192
- clearTimeout(timer);
193
- resolve({ code, signal, output, timedOut, seconds: Math.round((Date.now() - t0) / 1000) });
247
+ child.on('exit', (code, killedBy) => {
248
+ if (!killed) return;
249
+ setTimeout(() => {
250
+ child.stdout.destroy();
251
+ child.stderr.destroy();
252
+ finish(code, killedBy);
253
+ }, 2000);
194
254
  });
255
+ child.on('close', finish);
195
256
  });
196
257
  }
197
258
 
@@ -205,7 +266,7 @@ function readIfNew(file, since) {
205
266
  }
206
267
 
207
268
  /** Plays every scenario with the build, one at a time. */
208
- export async function runEngineScenarios(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {} } = {}) {
269
+ export async function runEngineScenarios(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {}, signal } = {}) {
209
270
  const root = cfg.root || process.cwd();
210
271
  const base = resolveCommand(command, root);
211
272
  const engine = cfg.engine || detectEngine(base);
@@ -216,12 +277,14 @@ export async function runEngineScenarios(cfg, { command = cfg.command, scenarios
216
277
  const results = [];
217
278
  try {
218
279
  for (const [i, raw] of scenarios.entries()) {
280
+ checkStop(signal);
219
281
  const sc = engineScenario(raw, engine, cfg);
220
282
  const out = path.join(tmp, `run-${i + 1}.json`);
221
283
  const argv = [...base, ...scenarioArgs(engine, base, sc, { out })];
222
284
  log(`run ${i + 1}/${scenarios.length}: ${label(sc)} …`);
223
285
  const t0 = Date.now();
224
- const r = await runBuild(argv, { cwd: root, timeoutMs: sc.max_s * 1000 });
286
+ const r = await runBuild(argv, { cwd: root, timeoutMs: sc.max_s * 1000, signal });
287
+ checkStop(signal);
225
288
  const measure = parseMeasure(r.output) || readIfNew(out, t0) || (cfg.measure_file ? readIfNew(path.resolve(root, home(cfg.measure_file)), t0) : null);
226
289
  const shown = argv.filter((a) => !a.includes('glitchless-out='));
227
290
  const result = { scenario: sc.name || null, params: sc.params, args: sc.args, seconds: sc.seconds, warmup: sc.warmup, command: shown, session_id: measure?.session_id || null, elapsed_s: r.seconds, finished: !!measure && !measure.error, crashed: false, exit_code: r.code, measure: measure && !measure.error ? measure : null };
@@ -371,8 +434,8 @@ export function measureSummary(results) {
371
434
  }
372
435
 
373
436
  /** Plays every scenario with the build and returns a run record ready to save or compare. */
374
- export async function engineRun(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {} } = {}) {
375
- const { engine, command: argv, results } = await runEngineScenarios(cfg, { command, scenarios, log });
437
+ export async function engineRun(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {}, signal } = {}) {
438
+ const { engine, command: argv, results } = await runEngineScenarios(cfg, { command, scenarios, log, signal });
376
439
  const summary = measureSummary(results);
377
440
  const measured = results.filter((r) => r.measure);
378
441
  const noLevel = measured.every((r) => r.measure.level_start == null && r.measure.level_end == null);
package/src/index.js CHANGED
@@ -15,6 +15,7 @@ import { robloxRun, matchingRobloxBaseline } from './roblox.js';
15
15
  import { compareRuns } from './compare.js';
16
16
  import { comparisonReport, runReport } from './report.js';
17
17
  import { saveRun, loadRun, listRuns } from './runs.js';
18
+ import { checkStop } from './stop.js';
18
19
 
19
20
  export { loadConfig, DEFAULT_SCENARIOS, DEFAULT_THRESHOLDS } from './config.js';
20
21
  export { compareRuns, judge } from './compare.js';
@@ -23,6 +24,9 @@ export { saveRun, loadRun, listRuns } from './runs.js';
23
24
  export { playtestRun, loadPlaywright } from './run.js';
24
25
  export { engineRun, measureSummary, parseMeasure, detectEngine, splitCommand, ENGINES } from './engine.js';
25
26
  export { robloxRun } from './roblox.js';
27
+ // Stopping a run part-way with an AbortSignal (0.5.0 on): glitchless-mcp checks for these to tell whether a cancel stops
28
+ // the run.
29
+ export { onStop, checkStop, stopped } from './stop.js';
26
30
  // A game check: any web game, nothing installed in it (check.js).
27
31
  export { gameCheck, CHECK_SECONDS } from './check.js';
28
32
  export { checkReport, checkDm, checkDashboard, headlines, engineWords } from './check-report.js';
@@ -38,25 +42,27 @@ export { itchFrame, robotsAllow, refusal, siteOf } from './check-site.js';
38
42
  * @param {number} [o.maxSeconds] cap each run (an engine build: the seconds it measures)
39
43
  * @param {object} [o.config] overrides for glitchless.playtest.json / defaults (game, command, engine, server, service, channel, headed, api_key)
40
44
  * @param {(msg: string) => void} [o.log]
45
+ * @param {AbortSignal} [o.signal] stops it part-way: the browser closes, the build is killed or Studio's play test stops,
46
+ * nothing is saved, and it ends with the signal's reason
41
47
  */
42
- export async function playtest({ saveAs, compareTo, baselineUrl, baselineCommand, quick = false, maxSeconds, config = {}, cwd = process.cwd(), log = () => {} } = {}) {
48
+ export async function playtest({ saveAs, compareTo, baselineUrl, baselineCommand, quick = false, maxSeconds, config = {}, cwd = process.cwd(), log = () => {}, signal } = {}) {
43
49
  const cfg = loadConfig(cwd, config);
44
50
  const roblox = cfg.engine === 'roblox';
45
51
  const engine = !roblox && !!cfg.command;
46
52
  if (roblox && (baselineUrl || baselineCommand)) throw new Error('A Roblox game plays in the open Roblox Studio: save a baseline with --save baseline before the change instead of playing another build.');
47
53
  if (engine && baselineUrl) throw new Error('This project runs an engine build ("command"), not a web game: give the baseline build with --baseline-command instead of --baseline-url.');
48
54
  if (!engine && baselineCommand) throw new Error('--baseline-command runs an engine build: set "command" in glitchless.playtest.json (or pass --command) to the build being tested too.');
49
- const play = (opts) => (roblox ? robloxRun(cfg, opts) : engine ? engineRun(cfg, opts) : playtestRun(cfg, opts));
55
+ const play = (opts) => (roblox ? robloxRun(cfg, { ...opts, signal }) : engine ? engineRun(cfg, { ...opts, signal }) : playtestRun(cfg, { ...opts, signal }));
50
56
  let scenarios = quick ? cfg.scenarios.slice(0, 1) : cfg.scenarios;
51
57
  if (maxSeconds) scenarios = scenarios.map((s) => (engine ? { ...s, seconds: Math.min(s.seconds ?? cfg.seconds ?? maxSeconds, maxSeconds) } : { ...s, max_s: maxSeconds }));
52
58
 
53
59
  let baseline = null;
54
60
  if (baselineUrl) {
55
61
  log(`Baseline: playing ${baselineUrl}`);
56
- baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log })), name: 'baseline-url' };
62
+ baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log, signal })), name: 'baseline-url' };
57
63
  } else if (baselineCommand) {
58
64
  log(`Baseline: running ${[].concat(baselineCommand).join(' ')}`);
59
- baseline = { ...(await engineRun(cfg, { command: baselineCommand, scenarios, log })), name: 'baseline-command' };
65
+ baseline = { ...(await engineRun(cfg, { command: baselineCommand, scenarios, log, signal })), name: 'baseline-command' };
60
66
  } else {
61
67
  const target = compareTo ?? (saveAs === 'baseline' ? null : 'baseline');
62
68
  if (target) {
@@ -70,6 +76,7 @@ export async function playtest({ saveAs, compareTo, baselineUrl, baselineCommand
70
76
 
71
77
  log(`Candidate: ${roblox ? 'playing in Roblox Studio' : engine ? `running ${[].concat(cfg.command).join(' ')}` : `playing ${cfg.game}`}`);
72
78
  const candidate = await play({ scenarios, log });
79
+ checkStop(signal);
73
80
  const files = { latest: saveRun(cfg.runs_dir, 'latest', candidate) };
74
81
  if (saveAs) files[saveAs] = saveRun(cfg.runs_dir, saveAs, candidate);
75
82
  candidate.name = saveAs || 'latest';
package/src/roblox.js CHANGED
@@ -10,6 +10,7 @@ import os from 'node:os';
10
10
  import path from 'node:path';
11
11
  import { spawn } from 'node:child_process';
12
12
  import { fetchSummary, gitInfo, machineInfo } from './run.js';
13
+ import { checkStop, pause } from './stop.js';
13
14
 
14
15
  export const DEFAULT_ROBLOX_SCENARIOS = [
15
16
  { name: 'autoplay, seed 7', params: { autoplay: true, seed: 7 }, max_s: 90 },
@@ -167,8 +168,8 @@ function checkParams(sc) {
167
168
 
168
169
  const label = (sc) => sc.name || JSON.stringify(sc.params || {});
169
170
 
170
- // One play test: attributes on, play until done or the cap, stop, attributes back as they were.
171
- async function playOnce(mcp, studio, sc, cfg, log) {
171
+ // One play test: attributes on, play until done, the cap or signal, stop, attributes back as they were.
172
+ async function playOnce(mcp, studio, sc, cfg, log, signal) {
172
173
  const params = sc.params || {};
173
174
  const before = unmark(await luau(mcp, studio.id, attributes(params, ['GlitchlessPlaytestDone']))) || {};
174
175
  const restore = () => luau(mcp, studio.id, attributes(before, [...Object.keys(params), 'GlitchlessPlaytestDone'].filter((k) => !(k in before)))).catch(() => {});
@@ -179,8 +180,9 @@ async function playOnce(mcp, studio, sc, cfg, log) {
179
180
  await mcp.tool('start_stop_play', { studio_id: studio.id, is_start: true });
180
181
  const maxMs = (sc.max_s || 90) * 1000;
181
182
  const done = `-- glitchless-playtest: done_when\nreturn if (${sc.done_when || cfg.done_when || ROBLOX_DONE_WHEN}) then ${MARK('true')} else ${MARK('false')}`;
182
- while (Date.now() - started < maxMs) {
183
+ while (Date.now() - started < maxMs && !signal?.aborted) {
183
184
  await sleep(1000);
185
+ if (signal?.aborted) break;
184
186
  finished = (await luau(mcp, studio.id, done, 'Server').then(unmark).catch(() => false)) === true;
185
187
  if (finished) break;
186
188
  }
@@ -223,8 +225,8 @@ function assign(results, sessions, key) {
223
225
 
224
226
  // One summary for the players' sessions, with the server's errors and crashes added: a script error on the server is
225
227
  // the game's error too.
226
- async function robloxSummary(cfg, service, players, servers, since, log) {
227
- const summary = await fetchSummary(cfg, service, players, since, { log });
228
+ async function robloxSummary(cfg, service, players, servers, since, log, signal) {
229
+ const summary = await fetchSummary(cfg, service, players, since, { log, signal });
228
230
  if (!servers.length || !summary) return summary;
229
231
  const server = await fetchSummary(cfg, `${service}.server`, servers, since, { log, timeoutMs: 10_000 }).catch(() => null);
230
232
  if (!server) return summary;
@@ -234,7 +236,7 @@ async function robloxSummary(cfg, service, players, servers, since, log) {
234
236
  }
235
237
 
236
238
  /** Plays every scenario in Roblox Studio and returns a run record ready to save or compare. */
237
- export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {} } = {}) {
239
+ export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {}, signal } = {}) {
238
240
  for (const sc of scenarios) checkParams(sc);
239
241
  const mcp = connectStudio(studioMcpCommand(cfg));
240
242
  let studio;
@@ -252,12 +254,14 @@ export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {}
252
254
  service ||= place.service;
253
255
  if (!service) throw new Error('Could not tell which game this is from its Glitchless.init: set "service" in glitchless.playtest.json (or pass --service) to the service name it sends as.');
254
256
  for (const [i, sc] of scenarios.entries()) {
257
+ checkStop(signal);
255
258
  log(`run ${i + 1}/${scenarios.length}: ${label(sc)} …`);
256
- results.push(await playOnce(mcp, studio, sc, cfg, log));
259
+ results.push(await playOnce(mcp, studio, sc, cfg, log, signal));
257
260
  }
258
261
  } finally {
259
262
  mcp.close();
260
263
  }
264
+ checkStop(signal);
261
265
 
262
266
  // BindToClose sends the last batches as the play test's server closes: give them a moment to land.
263
267
  log(`collecting the play tests' sessions from ${cfg.server} …`);
@@ -266,7 +270,7 @@ export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {}
266
270
  for (let i = 0; i < (cfg.sessions_wait_s ?? 30); i++) {
267
271
  assign(results, await sessionsOf(cfg, service, from, to), 'session_ids');
268
272
  if (results.every((r) => r.session_ids.length)) break;
269
- await sleep(1000);
273
+ await pause(1000, signal);
270
274
  }
271
275
  assign(results, await sessionsOf(cfg, `${service}.server`, from, to), 'server_session_ids');
272
276
  for (const r of results) r.session_id = r.session_ids[0] || null;
@@ -277,7 +281,7 @@ export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {}
277
281
  }
278
282
  const servers = results.flatMap((r) => r.server_session_ids);
279
283
  const started = Math.min(...results.map((r) => r.started));
280
- const summary = await robloxSummary(cfg, service, players, servers, started, log);
284
+ const summary = await robloxSummary(cfg, service, players, servers, started, log, signal);
281
285
  const notes = [];
282
286
  const noLevel = !Object.keys(summary?.levels || {}).length && !summary?.level_attempts;
283
287
  if (noLevel && cfg.default_scenarios) throw new Error(`The play tests ran with the default scenarios (Workspace attributes autoplay = true, seed = 7) but no player started a level, so the game probably has no autoplay mode. ${ROBLOX_AUTOPLAY} Then list the runs in glitchless.playtest.json under "scenarios".`);
package/src/run.js CHANGED
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import { execFileSync } from 'node:child_process';
8
8
  import { createRequire } from 'node:module';
9
9
  import { pathToFileURL } from 'node:url';
10
+ import { onStop, stopped, checkStop, pause } from './stop.js';
10
11
 
11
12
  // Real GPU (Metal via ANGLE on macOS) and no background throttling, same as scripts/bots.js.
12
13
  export const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
@@ -29,7 +30,8 @@ export async function loadPlaywright(cwd = process.cwd()) {
29
30
  }
30
31
  }
31
32
 
32
- export async function runScenarios(cfg, { scenarios = cfg.scenarios, game = cfg.game, log = () => {} } = {}) {
33
+ // signal stops it part-way: the browser closes, and the run ends with the signal's reason.
34
+ export async function runScenarios(cfg, { scenarios = cfg.scenarios, game = cfg.game, log = () => {}, signal } = {}) {
33
35
  const { chromium } = await loadPlaywright();
34
36
  const channel = cfg.channel === 'chromium' ? undefined : cfg.channel;
35
37
  const browser = await chromium.launch({ headless: !cfg.headed, channel, args: CHROME_ARGS }).catch(async (err) => {
@@ -40,8 +42,10 @@ export async function runScenarios(cfg, { scenarios = cfg.scenarios, game = cfg.
40
42
  const started = Date.now();
41
43
  const results = [];
42
44
  let service = cfg.service;
45
+ const forget = onStop(signal, () => browser.close().catch(() => {}));
43
46
  try {
44
47
  for (const [i, sc] of scenarios.entries()) {
48
+ checkStop(signal);
45
49
  const qs = new URLSearchParams({ mute: '1', env: cfg.env, intake: cfg.server.replace(/\/$/, ''), ...Object.fromEntries(Object.entries(sc.params || {}).map(([k, v]) => [k, String(v)])) });
46
50
  const url = `${game}${game.includes('?') ? '&' : '?'}${qs}`;
47
51
  const ctx = await browser.newContext({ viewport: cfg.viewport });
@@ -77,21 +81,26 @@ export async function runScenarios(cfg, { scenarios = cfg.scenarios, game = cfg.
77
81
  results.push({ scenario: sc.name || null, params: sc.params, session_id: info.session, game_version: info.version, seconds, finished, events_failed: info.failed || 0 });
78
82
  log(` → ${info.session} · ${seconds}s${finished ? '' : ' (hit the time cap)'}${info.failed ? ` · ${info.failed} events failed to send` : ''}`);
79
83
  }
84
+ } catch (err) {
85
+ throw stopped(signal, err);
80
86
  } finally {
87
+ forget();
81
88
  await browser.close();
82
89
  }
90
+ checkStop(signal);
83
91
  return { started, service, results };
84
92
  }
85
93
 
86
94
  // The SDK sends on a timer and on pagehide, so give the server a moment to have every session.
87
- export async function fetchSummary(cfg, service, sessionIds, started, { log = () => {}, timeoutMs = 20_000 } = {}) {
95
+ export async function fetchSummary(cfg, service, sessionIds, started, { log = () => {}, timeoutMs = 20_000, signal } = {}) {
88
96
  const base = cfg.server.replace(/\/$/, '');
89
97
  const qs = new URLSearchParams({ service, sessions: sessionIds.join(','), from: String(started - 60_000), to: String(Date.now() + 60_000) });
90
98
  const headers = { 'x-glitchless-client': 'playtest', ...(cfg.api_key ? { 'x-glitchless-api-key': cfg.api_key } : {}) };
91
99
  const deadline = Date.now() + timeoutMs;
92
100
  let last;
93
101
  while (true) {
94
- const res = await fetch(`${base}/v1/query/playtest?${qs}`, { headers });
102
+ checkStop(signal);
103
+ const res = await fetch(`${base}/v1/query/playtest?${qs}`, { headers, signal });
95
104
  if (!res.ok) throw new Error(`Glitchless server ${base} answered HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
96
105
  const body = await res.json();
97
106
  if (body.error) throw new Error(`Glitchless server: ${body.error}`);
@@ -102,7 +111,7 @@ export async function fetchSummary(cfg, service, sessionIds, started, { log = ()
102
111
  log(` ${sessionIds.filter((id) => !seen.has(id)).length} session(s) never reported an end; using what arrived.`);
103
112
  return last;
104
113
  }
105
- await new Promise((r) => setTimeout(r, 1500));
114
+ await pause(1500, signal);
106
115
  }
107
116
  }
108
117
 
@@ -122,12 +131,12 @@ export function machineInfo(summary, channel) {
122
131
  }
123
132
 
124
133
  // Play every scenario and return a run record ready to save or compare.
125
- export async function playtestRun(cfg, { game = cfg.game, scenarios = cfg.scenarios, log = () => {} } = {}) {
126
- const { started, service, results } = await runScenarios(cfg, { game, scenarios, log });
134
+ export async function playtestRun(cfg, { game = cfg.game, scenarios = cfg.scenarios, log = () => {}, signal } = {}) {
135
+ const { started, service, results } = await runScenarios(cfg, { game, scenarios, log, signal });
127
136
  if (!service) throw new Error('Could not tell which game this is. Pass --service or set "service" in glitchless.playtest.json.');
128
137
  const ids = results.map((r) => r.session_id).filter(Boolean);
129
138
  log(`collecting results for ${ids.length} session(s) from ${cfg.server} …`);
130
- const summary = await fetchSummary(cfg, service, ids, started, { log });
139
+ const summary = await fetchSummary(cfg, service, ids, started, { log, signal });
131
140
  return {
132
141
  created: new Date().toISOString(),
133
142
  game,
package/src/stop.js ADDED
@@ -0,0 +1,36 @@
1
+ // Stopping a playtest or a game check part-way, with an AbortSignal (signal): an MCP client cancelling its task, or a
2
+ // script giving up. Each runner closes its browser, kills its build or stops Studio's play test when the signal fires,
3
+ // and the run ends with the signal's reason instead of whatever closing the browser made the step in hand throw.
4
+
5
+ // Calls stop() once the signal fires (at once if it already has). → a function that forgets it.
6
+ export function onStop(signal, stop) {
7
+ if (!signal) return () => {};
8
+ if (signal.aborted) {
9
+ stop();
10
+ return () => {};
11
+ }
12
+ signal.addEventListener('abort', stop, { once: true });
13
+ return () => signal.removeEventListener('abort', stop);
14
+ }
15
+
16
+ // The error a run ends with: the signal's reason once it has fired, else err.
17
+ export function stopped(signal, err) {
18
+ if (!signal?.aborted) return err;
19
+ return signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason ?? 'The playtest was stopped.'));
20
+ }
21
+
22
+ // Throws the signal's reason once it has fired.
23
+ export function checkStop(signal) {
24
+ if (signal?.aborted) throw stopped(signal);
25
+ }
26
+
27
+ // A pause that ends early, with the signal's reason, once the signal fires.
28
+ export function pause(ms, signal) {
29
+ return new Promise((resolve, reject) => {
30
+ const timer = setTimeout(() => (forget(), resolve()), ms);
31
+ const forget = onStop(signal, () => {
32
+ clearTimeout(timer);
33
+ reject(stopped(signal));
34
+ });
35
+ });
36
+ }