glitchless-playtest 0.3.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/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
@@ -2,7 +2,8 @@
2
2
  // a saved baseline. Used by the glitchless-playtest CLI and the glitchless_playtest MCP tool. A web game
3
3
  // plays in Chrome (run.js); an engine build (Unity, Godot, Unreal, GameMaker) runs from its command with
4
4
  // the SDK's --glitchless-measure (engine.js); a Roblox game plays in the open Roblox Studio over Studio's MCP
5
- // server (roblox.js).
5
+ // server (roblox.js). A game check (check.js) plays any web game with nothing installed in it, and makes a report and a
6
+ // dashboard for its maker.
6
7
  //
7
8
  // await playtest({ saveAs: 'baseline' }) // before a change
8
9
  // await playtest({ compareTo: 'baseline' }) // after it → { verdict, report, ... }
@@ -14,6 +15,7 @@ import { robloxRun, matchingRobloxBaseline } from './roblox.js';
14
15
  import { compareRuns } from './compare.js';
15
16
  import { comparisonReport, runReport } from './report.js';
16
17
  import { saveRun, loadRun, listRuns } from './runs.js';
18
+ import { checkStop } from './stop.js';
17
19
 
18
20
  export { loadConfig, DEFAULT_SCENARIOS, DEFAULT_THRESHOLDS } from './config.js';
19
21
  export { compareRuns, judge } from './compare.js';
@@ -22,6 +24,13 @@ export { saveRun, loadRun, listRuns } from './runs.js';
22
24
  export { playtestRun, loadPlaywright } from './run.js';
23
25
  export { engineRun, measureSummary, parseMeasure, detectEngine, splitCommand, ENGINES } from './engine.js';
24
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';
30
+ // A game check: any web game, nothing installed in it (check.js).
31
+ export { gameCheck, CHECK_SECONDS } from './check.js';
32
+ export { checkReport, checkDm, checkDashboard, headlines, engineWords } from './check-report.js';
33
+ export { itchFrame, robotsAllow, refusal, siteOf } from './check-site.js';
25
34
 
26
35
  /**
27
36
  * @param {object} o
@@ -33,25 +42,27 @@ export { robloxRun } from './roblox.js';
33
42
  * @param {number} [o.maxSeconds] cap each run (an engine build: the seconds it measures)
34
43
  * @param {object} [o.config] overrides for glitchless.playtest.json / defaults (game, command, engine, server, service, channel, headed, api_key)
35
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
36
47
  */
37
- 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 } = {}) {
38
49
  const cfg = loadConfig(cwd, config);
39
50
  const roblox = cfg.engine === 'roblox';
40
51
  const engine = !roblox && !!cfg.command;
41
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.');
42
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.');
43
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.');
44
- 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 }));
45
56
  let scenarios = quick ? cfg.scenarios.slice(0, 1) : cfg.scenarios;
46
57
  if (maxSeconds) scenarios = scenarios.map((s) => (engine ? { ...s, seconds: Math.min(s.seconds ?? cfg.seconds ?? maxSeconds, maxSeconds) } : { ...s, max_s: maxSeconds }));
47
58
 
48
59
  let baseline = null;
49
60
  if (baselineUrl) {
50
61
  log(`Baseline: playing ${baselineUrl}`);
51
- baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log })), name: 'baseline-url' };
62
+ baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log, signal })), name: 'baseline-url' };
52
63
  } else if (baselineCommand) {
53
64
  log(`Baseline: running ${[].concat(baselineCommand).join(' ')}`);
54
- baseline = { ...(await engineRun(cfg, { command: baselineCommand, scenarios, log })), name: 'baseline-command' };
65
+ baseline = { ...(await engineRun(cfg, { command: baselineCommand, scenarios, log, signal })), name: 'baseline-command' };
55
66
  } else {
56
67
  const target = compareTo ?? (saveAs === 'baseline' ? null : 'baseline');
57
68
  if (target) {
@@ -65,6 +76,7 @@ export async function playtest({ saveAs, compareTo, baselineUrl, baselineCommand
65
76
 
66
77
  log(`Candidate: ${roblox ? 'playing in Roblox Studio' : engine ? `running ${[].concat(cfg.command).join(' ')}` : `playing ${cfg.game}`}`);
67
78
  const candidate = await play({ scenarios, log });
79
+ checkStop(signal);
68
80
  const files = { latest: saveRun(cfg.runs_dir, 'latest', candidate) };
69
81
  if (saveAs) files[saveAs] = saveRun(cfg.runs_dir, saveAs, candidate);
70
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,9 +7,10 @@ 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
- const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
13
+ export const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
13
14
 
14
15
  // Resolve Playwright from the game project first (where people install it), then from here.
15
16
  export async function loadPlaywright(cwd = process.cwd()) {
@@ -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
+ }