@threenative/playtest 0.3.2 → 0.3.3

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.
@@ -31,6 +31,7 @@ var PLAYTEST_CAPABILITY_REGISTRY = [
31
31
  capability("runtime.diagnostics", "Captures application runtime errors."),
32
32
  capability("runtime.events", "Drains bounded application event observations."),
33
33
  capability("runtime.fixedStep", "Advances an application-owned deterministic tick."),
34
+ capability("runtime.geometry", "Answers one armed per-object geometry capture for the frame it was requested on."),
34
35
  capability("runtime.physics", "Samples bounded application-owned physics observations."),
35
36
  capability("runtime.performance", "Samples bounded per-render frame cost and renderer counts."),
36
37
  capability("runtime.pipelineCensus", "Samples bounded shader and pipeline creation observations."),
@@ -565,14 +566,16 @@ var PLAYTEST_ASSERTION_REGISTRY = [
565
566
  trivialityRationale: "It evaluates captured error and readiness channels across the run; no initial scalar value can satisfy those diagnostics by itself."
566
567
  },
567
568
  {
568
- description: "Proves a live render sample exists and optionally bounds frame time, an fps floor, per-phase frame budget, draw calls, and triangles.",
569
- example: { performance: { maxPhaseMsP95: { render: 12 }, minFps: 30 } },
569
+ description: "Proves a live render sample exists and optionally bounds frame time, an fps floor, per-phase frame budget, whole-frame or per-pass draw calls and triangles.",
570
+ example: { performance: { maxPassDrawCalls: { shadow: 400 }, maxPhaseMsP95: { render: 12 }, minFps: 30 } },
570
571
  fields: [
571
572
  { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds.", name: "maxFrameMsP95", type: "number" },
572
573
  { description: "Minimum sustained frames per second, from the median sampled frame.", name: "minFps", type: "number" },
573
574
  { description: "Per-phase millisecond ceilings at nearest-rank p95. Phases: hostGap, update, render, overlay, residual.", name: "maxPhaseMsP95", type: "{ [phase]: number }" },
574
- { description: "Maximum observed renderer draw-call count.", name: "maxDrawCalls", type: "number" },
575
- { description: "Maximum observed renderer triangle count.", name: "maxTriangles", type: "number" }
575
+ { description: "Maximum observed renderer draw-call count across every pass combined.", name: "maxDrawCalls", type: "number" },
576
+ { description: "Per-pass draw-call ceilings, keyed by pass kind: main, shadow, reflection, nested. Fails closed when a sampled frame carries no pass split or omits the declared kind.", name: "maxPassDrawCalls", type: "{ [pass: 'main' | 'shadow' | 'reflection' | 'nested']: number }" },
577
+ { description: "Per-pass triangle ceilings, keyed by pass kind: main, shadow, reflection, nested. Fails closed when a sampled frame carries no pass split or omits the declared kind.", name: "maxPassTriangles", type: "{ [pass: 'main' | 'shadow' | 'reflection' | 'nested']: number }" },
578
+ { description: "Maximum observed renderer triangle count across every pass combined.", name: "maxTriangles", type: "number" }
576
579
  ],
577
580
  cardinality: "object",
578
581
  kind: "performance",
@@ -621,6 +624,24 @@ var PLAYTEST_ASSERTION_REGISTRY = [
621
624
  triviality: "reject-initial-value",
622
625
  trivialityRationale: "An entity can be present and in-frame before input; the scenario must prove visibility after its setup or document why that presence is held."
623
626
  },
627
+ {
628
+ description: "Proves which labelled audio cues the game actually played, and how often.",
629
+ example: { audio: [{ cue: "speech:p01", maxPlays: 1 }] },
630
+ fields: [
631
+ { description: "Cue label the game passed to AudioBus.play/playAt.", name: "cue", required: true, type: "string" },
632
+ { description: "Fewest plays required. Defaults to 1, so naming a cue asserts it was heard.", name: "minPlays", type: "non-negative integer" },
633
+ { description: "Most plays allowed; 0 proves silence and 1 proves a one-shot stayed one.", name: "maxPlays", type: "non-negative integer" },
634
+ { description: "Fewest milliseconds between this cue and the cue played before it, so one line cannot cut another.", name: "minGapMs", type: "non-negative integer" }
635
+ ],
636
+ cardinality: "array",
637
+ kind: "audio",
638
+ observationPath: "runtimeObservations",
639
+ requiredCapabilities: ["runtime.audio"],
640
+ resultIdPrefix: "audio.",
641
+ supportedOn: ["web", "desktop"],
642
+ triviality: "not-applicable",
643
+ trivialityRationale: "A cue count starts at zero and only a played cue moves it, so there is no initial value to reject."
644
+ },
624
645
  {
625
646
  description: "Proves runtime world metadata exposed by the application bridge.",
626
647
  example: { world: { seed: 90210 } },
@@ -860,6 +881,9 @@ function requiredPlaytestCapabilities(scenario, target) {
860
881
  if (scenario.steps.some((step) => step.kind === "aimAt")) {
861
882
  required.add("entity.setup");
862
883
  }
884
+ if (scenario.assert?.geometry !== void 0) {
885
+ required.add("runtime.geometry");
886
+ }
863
887
  if (scenario.artifacts?.screenshots !== false) {
864
888
  required.add("browser.screenshot");
865
889
  }
@@ -1520,6 +1544,53 @@ function contactAssertionSatisfiedAtStep(assertion, observations, scenario) {
1520
1544
  const minimum = assertion.minCount ?? (assertion.maxCount === void 0 ? 1 : 0);
1521
1545
  return stepAvailable && (!anonymous || candidates.length > 0) && count >= minimum && (assertion.maxCount === void 0 || count <= assertion.maxCount);
1522
1546
  }
1547
+ function smallestGapBefore(recent, cue) {
1548
+ let smallest;
1549
+ for (let index = 1; index < recent.length; index += 1) {
1550
+ const entry = recent[index];
1551
+ const previous = recent[index - 1];
1552
+ if (!isRecord(entry) || !isRecord(previous)) continue;
1553
+ if (entry.cue !== cue) continue;
1554
+ if (typeof entry.atMs !== "number" || typeof previous.atMs !== "number") continue;
1555
+ const gap = entry.atMs - previous.atMs;
1556
+ if (smallest === void 0 || gap < smallest) smallest = gap;
1557
+ }
1558
+ return smallest;
1559
+ }
1560
+ function evaluateAudioAssertion(assertion, observations) {
1561
+ const gameplay = gameplayObservations(observations);
1562
+ const audio = isRecord(gameplay?.audio) ? gameplay.audio : void 0;
1563
+ const cues = isRecord(audio?.cues) ? audio.cues : void 0;
1564
+ const observed = cues === void 0 ? void 0 : cues[assertion.cue];
1565
+ const plays = typeof observed === "number" ? observed : 0;
1566
+ const minimum = assertion.minPlays ?? 1;
1567
+ const recent = Array.isArray(audio?.recentCues) ? audio.recentCues : [];
1568
+ const gap = smallestGapBefore(recent, assertion.cue);
1569
+ const gapPass = assertion.minGapMs === void 0 || gap === void 0 || gap >= assertion.minGapMs;
1570
+ const pass = cues !== void 0 && plays >= minimum && (assertion.maxPlays === void 0 || plays <= assertion.maxPlays) && gapPass;
1571
+ const result = {
1572
+ details: {
1573
+ cue: assertion.cue,
1574
+ maxPlays: assertion.maxPlays ?? null,
1575
+ minGapMs: assertion.minGapMs ?? null,
1576
+ minPlays: minimum,
1577
+ observed: cues === void 0 ? null : plays,
1578
+ observedGapMs: gap ?? null
1579
+ },
1580
+ id: `audio.${assertion.cue}`,
1581
+ pass
1582
+ };
1583
+ return pass ? { assertion: result } : {
1584
+ assertion: result,
1585
+ diagnostic: {
1586
+ code: "TN_PLAYTEST_AUDIO_ASSERTION_FAILED",
1587
+ message: cues === void 0 ? `No runtime audio ledger was published, so cue '${assertion.cue}' cannot be proved either way.` : gapPass ? `Cue '${assertion.cue}' played ${plays} time(s); expected at least ${minimum}${assertion.maxPlays === void 0 ? "" : ` and at most ${assertion.maxPlays}`}.` : `Cue '${assertion.cue}' started ${gap ?? 0} ms after the line before it, which is under the ${String(assertion.minGapMs)} ms it needs; one of them was cut off.`,
1588
+ observedRuntimePath: "observations.json/runtimeObservations/gameplay/audio/cues",
1589
+ severity: "error",
1590
+ suggestion: cues === void 0 ? "Run on a target whose bridge advertises runtime.audio, and pass `cue` to AudioBus.play/playAt for the lines under test." : "Read observations.json/runtimeObservations/gameplay/audio/recentCues for when each play happened, and check the one-shot flag that gates the cue."
1591
+ }
1592
+ };
1593
+ }
1523
1594
  function evaluateWorldAssertion(assertion, observations) {
1524
1595
  const gameplay = gameplayObservations(observations);
1525
1596
  const world = isRecord(gameplay?.world) ? gameplay.world : void 0;
@@ -1691,6 +1762,44 @@ function runtimeAnimationObservations(value) {
1691
1762
  return isRecord(gameplay?.animation) ? gameplay.animation : void 0;
1692
1763
  }
1693
1764
 
1765
+ // src/protocol.ts
1766
+ var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
1767
+ var PLAYTEST_PROTOCOL_VERSION = 1;
1768
+ var PLAYTEST_ADVANCE_TICK_BUDGET_MS = 250;
1769
+ var PLAYTEST_STARTUP_COMPILE_BUDGET_MS = 15e3;
1770
+ var PLAYTEST_PROTOCOL_LIMITS = {
1771
+ maxPayloadBytes: 1e6,
1772
+ operationTimeoutMs: 5e3
1773
+ };
1774
+ var PLAYTEST_STARTUP_READY_TIMEOUT_MS = 18e4;
1775
+ var PLAYTEST_FRAME_BUDGET_PHASES = ["hostGap", "overlay", "render", "residual", "update"];
1776
+ var PLAYTEST_FRAME_PASS_KINDS = ["main", "shadow", "reflection", "nested"];
1777
+ function jsonByteLength(value) {
1778
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1779
+ }
1780
+ function assertJsonSafe(value, path = "$") {
1781
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
1782
+ return;
1783
+ }
1784
+ if (typeof value === "number") {
1785
+ if (Number.isFinite(value)) {
1786
+ return;
1787
+ }
1788
+ throw new TypeError(`${path} must contain only finite JSON numbers.`);
1789
+ }
1790
+ if (Array.isArray(value)) {
1791
+ value.forEach((item, index) => assertJsonSafe(item, `${path}[${index}]`));
1792
+ return;
1793
+ }
1794
+ if (typeof value === "object") {
1795
+ for (const [key, item] of Object.entries(value)) {
1796
+ assertJsonSafe(item, `${path}.${key}`);
1797
+ }
1798
+ return;
1799
+ }
1800
+ throw new TypeError(`${path} must be JSON-safe.`);
1801
+ }
1802
+
1694
1803
  // src/evaluators/render-evidence.ts
1695
1804
  function projectedPixelsForEntity(snapshot, entity, viewport) {
1696
1805
  const rendered = renderedEntity(snapshot, entity);
@@ -1813,13 +1922,47 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1813
1922
  samplesPass && triangles.length === samples.length && maxObservedTriangles !== void 0 && maxObservedTriangles <= assertion.maxTriangles
1814
1923
  );
1815
1924
  }
1925
+ const addPassBound = (unit, kind, ceiling) => {
1926
+ const noun = unit === "draws" ? "draw calls" : "triangles";
1927
+ const measured = observed.flatMap((sample) => {
1928
+ const pass2 = sample.passes?.find((candidate) => candidate.kind === kind);
1929
+ return pass2 === void 0 ? [] : [pass2[unit]];
1930
+ });
1931
+ const actual = measured.length === samples.length ? Math.max(...measured) : void 0;
1932
+ const id = unit === "draws" ? `performance.maxPassDrawCalls.${kind}` : `performance.maxPassTriangles.${kind}`;
1933
+ const pass = samplesPass && actual !== void 0 && actual <= ceiling;
1934
+ results.push({
1935
+ details: { actual: actual ?? null, expected: ceiling, pass: kind, sampleCount: samples.length, unit: noun },
1936
+ id,
1937
+ pass
1938
+ });
1939
+ if (!pass) diagnostics.push({
1940
+ code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1941
+ message: actual === void 0 ? `${id} received no per-pass samples for '${kind}'; ${measured.length} of ${samples.length} frames carried that pass.` : `${id} expected at most ${ceiling} ${noun}, observed ${actual}.`,
1942
+ observedRuntimePath: path,
1943
+ severity: "error",
1944
+ sourcePath,
1945
+ suggestion: "Keep the engine frame budget installed so the run carries a per-pass split; a renderer that reports no split cannot satisfy a per-pass ceiling."
1946
+ });
1947
+ };
1948
+ for (const [kind, ceiling] of Object.entries(assertion.maxPassDrawCalls ?? {}))
1949
+ addPassBound("draws", kind, ceiling);
1950
+ for (const [kind, ceiling] of Object.entries(assertion.maxPassTriangles ?? {}))
1951
+ addPassBound("triangles", kind, ceiling);
1816
1952
  return { assertions: results, diagnostics };
1817
1953
  }
1818
1954
  function isRuntimeDiagnosticsSample(value) {
1819
1955
  if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
1820
1956
  return false;
1821
1957
  }
1822
- return (value.drawCalls === void 0 || typeof value.drawCalls === "number" && Number.isFinite(value.drawCalls) && value.drawCalls >= 0) && (value.triangles === void 0 || typeof value.triangles === "number" && Number.isFinite(value.triangles) && value.triangles >= 0) && isFramePhaseSplit(value.phases);
1958
+ return (value.drawCalls === void 0 || typeof value.drawCalls === "number" && Number.isFinite(value.drawCalls) && value.drawCalls >= 0) && (value.triangles === void 0 || typeof value.triangles === "number" && Number.isFinite(value.triangles) && value.triangles >= 0) && isFramePhaseSplit(value.phases) && isFramePassSplit(value.passes);
1959
+ }
1960
+ function isFramePassSplit(value) {
1961
+ if (value === void 0) return true;
1962
+ if (!Array.isArray(value)) return false;
1963
+ return value.every(
1964
+ (pass) => isRecord(pass) && PLAYTEST_FRAME_PASS_KINDS.includes(pass.kind) && typeof pass.draws === "number" && Number.isFinite(pass.draws) && pass.draws >= 0 && typeof pass.triangles === "number" && Number.isFinite(pass.triangles) && pass.triangles >= 0
1965
+ );
1823
1966
  }
1824
1967
  function isFramePhaseSplit(value) {
1825
1968
  if (value === void 0) return true;
@@ -3053,6 +3196,11 @@ function emitPerfSignalsWorld(ctx) {
3053
3196
  suggestion: "Expose a bounded events callback on the playtest bridge and inspect the emitted signal name and entity."
3054
3197
  });
3055
3198
  }
3199
+ for (const assertion of scenarioAssertions.audio ?? []) {
3200
+ const result = evaluateAudioAssertion(assertion, input.report.observations?.runtimeObservations);
3201
+ assertions.push(result.assertion);
3202
+ if (result.diagnostic !== void 0) diagnostics.push(result.diagnostic);
3203
+ }
3056
3204
  if (scenarioAssertions.world !== void 0) {
3057
3205
  const result = evaluateWorldAssertion(scenarioAssertions.world, input.report.observations?.runtimeObservations);
3058
3206
  assertions.push(result.assertion);
@@ -4174,6 +4322,19 @@ function evaluateRichPlaytestAssertions(input) {
4174
4322
  emitRenderChain(ctx);
4175
4323
  emitScene(ctx);
4176
4324
  emitSceneNodes(ctx);
4325
+ if (scenarioAssertions.geometry !== void 0) {
4326
+ const observed = input.report.observations?.geometry;
4327
+ const status = observed?.status;
4328
+ const pass = status === "captured";
4329
+ assertions.push({ details: { observed, status }, id: "geometry.observed", pass });
4330
+ if (!pass) diagnostics.push({
4331
+ code: "TN_PLAYTEST_GEOMETRY_UNOBSERVED",
4332
+ message: "A geometry assertion was evaluated against a run whose bridge reported no captured geometry frame.",
4333
+ observedRuntimePath: "observations.json/geometry",
4334
+ severity: "error",
4335
+ suggestion: "Request the capture on a target whose bridge advertises runtime.geometry and is presenting world frames."
4336
+ });
4337
+ }
4177
4338
  emitCausedBy(ctx);
4178
4339
  emitStartup(ctx);
4179
4340
  emitMovementEvidence(ctx);
@@ -4479,43 +4640,6 @@ function playtestDiagnostic(code, message, instruction, details = {}) {
4479
4640
  };
4480
4641
  }
4481
4642
 
4482
- // src/protocol.ts
4483
- var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
4484
- var PLAYTEST_PROTOCOL_VERSION = 1;
4485
- var PLAYTEST_ADVANCE_TICK_BUDGET_MS = 250;
4486
- var PLAYTEST_STARTUP_COMPILE_BUDGET_MS = 15e3;
4487
- var PLAYTEST_PROTOCOL_LIMITS = {
4488
- maxPayloadBytes: 1e6,
4489
- operationTimeoutMs: 5e3
4490
- };
4491
- var PLAYTEST_STARTUP_READY_TIMEOUT_MS = 18e4;
4492
- var PLAYTEST_FRAME_BUDGET_PHASES = ["hostGap", "overlay", "render", "residual", "update"];
4493
- function jsonByteLength(value) {
4494
- return new TextEncoder().encode(JSON.stringify(value)).byteLength;
4495
- }
4496
- function assertJsonSafe(value, path = "$") {
4497
- if (value === null || typeof value === "string" || typeof value === "boolean") {
4498
- return;
4499
- }
4500
- if (typeof value === "number") {
4501
- if (Number.isFinite(value)) {
4502
- return;
4503
- }
4504
- throw new TypeError(`${path} must contain only finite JSON numbers.`);
4505
- }
4506
- if (Array.isArray(value)) {
4507
- value.forEach((item, index) => assertJsonSafe(item, `${path}[${index}]`));
4508
- return;
4509
- }
4510
- if (typeof value === "object") {
4511
- for (const [key, item] of Object.entries(value)) {
4512
- assertJsonSafe(item, `${path}.${key}`);
4513
- }
4514
- return;
4515
- }
4516
- throw new TypeError(`${path} must be JSON-safe.`);
4517
- }
4518
-
4519
4643
  // src/scenario/errors.ts
4520
4644
  var PlaytestScenarioError = class extends Error {
4521
4645
  constructor(diagnostic) {
@@ -4693,6 +4817,8 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4693
4817
  "minFps": (value) => typeof value === "number" && Number.isFinite(value),
4694
4818
  "maxPhaseMsP95": (value) => isRecord2(value),
4695
4819
  "maxDrawCalls": (value) => typeof value === "number" && Number.isFinite(value),
4820
+ "maxPassDrawCalls": (value) => isRecord2(value),
4821
+ "maxPassTriangles": (value) => isRecord2(value),
4696
4822
  "maxTriangles": (value) => typeof value === "number" && Number.isFinite(value)
4697
4823
  }),
4698
4824
  "parity": Object.freeze({
@@ -4709,6 +4835,12 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4709
4835
  "present": (value) => typeof value === "boolean",
4710
4836
  "allowTrivial": (value) => typeof value === "string" && value.replace(/\s/gu, "").length >= MIN_TRIVIALITY_REASON_LENGTH
4711
4837
  }),
4838
+ "audio": Object.freeze({
4839
+ "cue": (value) => typeof value === "string" && value.trim() !== "",
4840
+ "minPlays": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
4841
+ "maxPlays": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
4842
+ "minGapMs": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0
4843
+ }),
4712
4844
  "world": Object.freeze({
4713
4845
  "seed": (value) => true,
4714
4846
  "runtime": (value) => isRecord2(value)
@@ -5012,10 +5144,12 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
5012
5144
  }
5013
5145
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
5014
5146
  const record4 = requireRecord(value, scenarioPath, objectPath);
5015
- rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
5147
+ rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
5016
5148
  return {
5017
5149
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
5018
5150
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
5151
+ ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
5152
+ ...present("maxPassTriangles", validatePassBudget(record4.maxPassTriangles, scenarioPath, `${objectPath}.maxPassTriangles`)),
5019
5153
  ...present("maxPhaseMsP95", validatePhaseBudget(record4.maxPhaseMsP95, scenarioPath, `${objectPath}.maxPhaseMsP95`)),
5020
5154
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
5021
5155
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
@@ -5152,6 +5286,25 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
5152
5286
  }
5153
5287
  return result;
5154
5288
  }
5289
+ function validatePassBudget(value, scenarioPath, objectPath) {
5290
+ if (value === void 0) return void 0;
5291
+ const record4 = requireRecord(value, scenarioPath, objectPath);
5292
+ const entries = Object.entries(record4);
5293
+ if (entries.length === 0)
5294
+ throw invalidScenario(scenarioPath, `${objectPath} must name at least one render pass.`);
5295
+ const budget = {};
5296
+ for (const [pass, ceiling] of entries) {
5297
+ if (!PLAYTEST_FRAME_PASS_KINDS.includes(pass))
5298
+ throw invalidScenario(
5299
+ scenarioPath,
5300
+ `${objectPath}.${pass} is not a render pass. Expected one of: ${PLAYTEST_FRAME_PASS_KINDS.join(", ")}.`
5301
+ );
5302
+ if (typeof ceiling !== "number" || !Number.isFinite(ceiling) || ceiling < 0)
5303
+ throw invalidScenario(scenarioPath, `${objectPath}.${pass} must be a non-negative number of draw calls or triangles.`);
5304
+ budget[pass] = ceiling;
5305
+ }
5306
+ return budget;
5307
+ }
5155
5308
  function validatePhaseBudget(value, scenarioPath, objectPath) {
5156
5309
  if (value === void 0) return void 0;
5157
5310
  const record4 = requireRecord(value, scenarioPath, objectPath);
@@ -6290,14 +6443,16 @@ function validateStepLabels(steps, assertions, scenarioPath) {
6290
6443
  }
6291
6444
  }
6292
6445
  function playtestStepHoldTicks(step, fallback = 1) {
6293
- if (step.press === void 0 || step.holdFrames !== void 0 || step.waitFrames !== void 0) return 0;
6446
+ const pointerHold = (step.pointers !== void 0 || step.pointerPosition !== void 0) && step.holdTicks !== void 0;
6447
+ if (step.press === void 0 && !pointerHold || step.holdFrames !== void 0 || step.waitFrames !== void 0)
6448
+ return 0;
6294
6449
  return Math.max(1, step.holdTicks ?? fallback);
6295
6450
  }
6296
6451
  function playtestStepWaitTicks(step) {
6297
6452
  return step.waitFrames === void 0 ? Math.max(0, step.waitTicks ?? 0) : 0;
6298
6453
  }
6299
6454
  function validateAssertions(value, scenarioPath) {
6300
- rejectUnknownKeys(value, PLAYTEST_ASSERTION_REGISTRY.map((entry) => entry.kind), scenarioPath, "assert");
6455
+ rejectUnknownKeys(value, [...PLAYTEST_ASSERTION_REGISTRY.map((entry) => entry.kind), "geometry"], scenarioPath, "assert");
6301
6456
  validateAssertionShapes(value, scenarioPath);
6302
6457
  validateAssertionKeys(value, scenarioPath);
6303
6458
  if (Array.isArray(value.signals) && value.signals.length === 0) {
@@ -6323,6 +6478,7 @@ function validateAssertions(value, scenarioPath) {
6323
6478
  const renderChain = value.renderChain === void 0 ? void 0 : validateRenderChainAssertion(value.renderChain, scenarioPath, "assert.renderChain");
6324
6479
  const startup = value.startup === void 0 ? void 0 : validateStartupAssertion(value.startup, scenarioPath, "assert.startup");
6325
6480
  const scene = value.scene === void 0 ? void 0 : validateSceneAssertion(value.scene, scenarioPath, "assert.scene");
6481
+ const geometry = value.geometry === void 0 ? void 0 : validateGeometryCaptureRequest(value.geometry, scenarioPath, "assert.geometry");
6326
6482
  const world = isRecord3(value.world) ? value.world : void 0;
6327
6483
  const optOuts = [
6328
6484
  ["noConsoleErrors", "consoleErrorsOptOutReason"],
@@ -6340,6 +6496,7 @@ function validateAssertions(value, scenarioPath) {
6340
6496
  return {
6341
6497
  ...Array.isArray(value.aerodynamics) ? { aerodynamics: value.aerodynamics.map((entry, index) => validateAerodynamicsAssertion(entry, scenarioPath, `assert.aerodynamics[${index}]`)) } : {},
6342
6498
  ...Array.isArray(value.animation) ? { animation: value.animation.map((entry, index) => validateAnimationAssertion(entry, scenarioPath, `assert.animation[${index}]`)) } : {},
6499
+ ...Array.isArray(value.audio) ? { audio: value.audio.map((entry, index) => validateAudioAssertion(entry, scenarioPath, `assert.audio[${index}]`)) } : {},
6343
6500
  ...camera === void 0 ? {} : {
6344
6501
  camera: {
6345
6502
  ...typeof camera.entity === "string" ? { entity: camera.entity } : {},
@@ -6372,6 +6529,7 @@ function validateAssertions(value, scenarioPath) {
6372
6529
  ...renderChain === void 0 ? {} : { renderChain },
6373
6530
  ...startup === void 0 ? {} : { startup },
6374
6531
  ...scene === void 0 ? {} : { scene },
6532
+ ...geometry === void 0 ? {} : { geometry },
6375
6533
  ...hasKey(value, "causedBy") ? {
6376
6534
  causedBy: requireArray(value, "causedBy", scenarioPath, "assert.causedBy").map((entry, index) => validateCausedByAssertion(entry, scenarioPath, `assert.causedBy[${index}]`))
6377
6535
  } : {},
@@ -6431,6 +6589,34 @@ function validateAssertions(value, scenarioPath) {
6431
6589
  ...world === void 0 ? {} : { world: validateWorldAssertion(world, scenarioPath) }
6432
6590
  };
6433
6591
  }
6592
+ function validateAudioAssertion(value, scenarioPath, objectPath) {
6593
+ const record4 = requireRecord(value, scenarioPath, objectPath);
6594
+ rejectUnknownKeys(record4, ["cue", "maxPlays", "minGapMs", "minPlays"], scenarioPath, objectPath);
6595
+ if (typeof record4.cue !== "string" || record4.cue.trim() === "")
6596
+ throw invalidScenario(scenarioPath, `Assertion '${objectPath}.cue' must be a non-empty string.`);
6597
+ const bound = (name) => {
6598
+ const raw = record4[name];
6599
+ if (raw === void 0) return void 0;
6600
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0)
6601
+ throw invalidScenario(scenarioPath, `Assertion '${objectPath}.${name}' must be a non-negative integer.`);
6602
+ return raw;
6603
+ };
6604
+ const minPlays = bound("minPlays");
6605
+ const maxPlays = bound("maxPlays");
6606
+ const minGapMs = bound("minGapMs");
6607
+ if (minPlays !== void 0 && maxPlays !== void 0 && maxPlays < minPlays) {
6608
+ throw invalidScenario(
6609
+ scenarioPath,
6610
+ `Assertion '${objectPath}' cannot require at least ${minPlays} play(s) and at most ${maxPlays}.`
6611
+ );
6612
+ }
6613
+ return {
6614
+ cue: record4.cue,
6615
+ ...maxPlays === void 0 ? {} : { maxPlays },
6616
+ ...minGapMs === void 0 ? {} : { minGapMs },
6617
+ ...minPlays === void 0 ? {} : { minPlays }
6618
+ };
6619
+ }
6434
6620
  function validateWorldAssertion(value, scenarioPath) {
6435
6621
  rejectUnknownKeys(value, ["runtime", "seed"], scenarioPath, "assert.world");
6436
6622
  if (!hasKey(value, "seed") || value.seed !== null && (typeof value.seed !== "number" || !Number.isFinite(value.seed))) {
@@ -6597,6 +6783,24 @@ function validateOccludedAssertion(value, scenarioPath, objectPath) {
6597
6783
  ...present("target", optionalString(record4, "target", scenarioPath, objectPath))
6598
6784
  };
6599
6785
  }
6786
+ function validateGeometryCaptureRequest(value, scenarioPath, objectPath) {
6787
+ const record4 = requireRecord(value, scenarioPath, objectPath);
6788
+ rejectUnknownKeys(record4, ["limit", "sort", "timeoutMs"], scenarioPath, objectPath);
6789
+ if (record4.limit !== void 0 && (typeof record4.limit !== "number" || !Number.isInteger(record4.limit) || record4.limit < 1 || record4.limit > 500)) {
6790
+ throw invalidScenario(scenarioPath, `'${objectPath}.limit' must be an integer from 1 to 500, received ${describeValue(record4.limit)}.`);
6791
+ }
6792
+ if (record4.sort !== void 0 && record4.sort !== "triangles" && record4.sort !== "draws" && record4.sort !== "projected") {
6793
+ throw invalidScenario(scenarioPath, `'${objectPath}.sort' must be one of triangles, draws, projected, received ${describeValue(record4.sort)}.`);
6794
+ }
6795
+ if (record4.timeoutMs !== void 0 && (typeof record4.timeoutMs !== "number" || !Number.isFinite(record4.timeoutMs) || record4.timeoutMs <= 0)) {
6796
+ throw invalidScenario(scenarioPath, `'${objectPath}.timeoutMs' must be a positive finite number, received ${describeValue(record4.timeoutMs)}.`);
6797
+ }
6798
+ return {
6799
+ ...record4.limit === void 0 ? {} : { limit: record4.limit },
6800
+ ...record4.sort === void 0 ? {} : { sort: record4.sort },
6801
+ ...record4.timeoutMs === void 0 ? {} : { timeoutMs: record4.timeoutMs }
6802
+ };
6803
+ }
6600
6804
 
6601
6805
  // src/scenario/orientation.ts
6602
6806
  function aimAngles(from, to) {
@@ -6755,6 +6959,7 @@ var STANDALONE_PLAYTEST_OBSERVATION_FIELDS = [
6755
6959
  "console",
6756
6960
  "effectLogBefore",
6757
6961
  "framebufferCoverage",
6962
+ "geometry",
6758
6963
  "hud",
6759
6964
  "network",
6760
6965
  "physicsDebugSeries",
@@ -7365,9 +7570,9 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7365
7570
  const user = await this.resolveUser();
7366
7571
  this.activeUser = user;
7367
7572
  await this.adb(["reverse", `tcp:${port}`, `tcp:${port}`]);
7368
- await this.adb(["logcat", "-c"]);
7369
7573
  await this.adb(["shell", "am", "force-stop", "--user", user, this.options.packageName]);
7370
7574
  if (viewport !== void 0) await this.presentViewport(viewport);
7575
+ await this.adb(["logcat", "-c"]);
7371
7576
  await this.adb([
7372
7577
  "shell",
7373
7578
  "am",
@@ -8275,7 +8480,7 @@ var DeviceMailboxTransport = class {
8275
8480
  async waitForResponse(id, method, order, timeoutMs) {
8276
8481
  const deadline = Date.now() + timeoutMs;
8277
8482
  while (!this.closed && Date.now() < deadline) {
8278
- const raw = await this.mailbox.read(this.paths.response);
8483
+ const raw = await readMailboxFile(this.mailbox, this.paths.response);
8279
8484
  if (raw !== void 0) {
8280
8485
  const response = parseResponse(raw);
8281
8486
  this.responseObserver?.({ body: raw, method, order, requestId: response.id });
@@ -8292,7 +8497,7 @@ var DeviceMailboxTransport = class {
8292
8497
  ));
8293
8498
  }
8294
8499
  async readResponse() {
8295
- const raw = await this.mailbox.read(this.paths.response);
8500
+ const raw = await readMailboxFile(this.mailbox, this.paths.response);
8296
8501
  return raw === void 0 ? void 0 : parseResponse(raw);
8297
8502
  }
8298
8503
  };
@@ -8367,6 +8572,18 @@ async function delayUntil(deadline) {
8367
8572
  const remaining = deadline - Date.now();
8368
8573
  if (remaining > 0) await new Promise((resolve8) => setTimeout(resolve8, Math.min(40, remaining)));
8369
8574
  }
8575
+ var kMailboxLockCodes = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
8576
+ async function readMailboxFile(mailbox, path) {
8577
+ try {
8578
+ return await mailbox.read(path);
8579
+ } catch (error) {
8580
+ if (isMailboxLockError(error)) return void 0;
8581
+ throw error;
8582
+ }
8583
+ }
8584
+ function isMailboxLockError(error) {
8585
+ return typeof error === "object" && error !== null && "code" in error && kMailboxLockCodes.has(String(error.code));
8586
+ }
8370
8587
 
8371
8588
  // src/runner/deviceSignal.ts
8372
8589
  async function withTargetAbortSignal(target, run, abortSignal) {
@@ -9129,10 +9346,17 @@ async function provideDisplay(options = {}) {
9129
9346
  platform
9130
9347
  });
9131
9348
  if (strategy.kind === "host") {
9132
- return { display: void 0, env: { ...env }, release: async () => void 0, strategy };
9349
+ return {
9350
+ compositor: void 0,
9351
+ display: void 0,
9352
+ env: { ...env },
9353
+ release: async () => void 0,
9354
+ strategy
9355
+ };
9133
9356
  }
9134
9357
  if (strategy.kind === "existing") {
9135
9358
  return {
9359
+ compositor: void 0,
9136
9360
  display: strategy.display,
9137
9361
  env: childEnvForDisplay(env, strategy.display),
9138
9362
  release: async () => void 0,
@@ -9151,6 +9375,16 @@ async function provideDisplay(options = {}) {
9151
9375
  "3",
9152
9376
  "-nolisten",
9153
9377
  "tcp",
9378
+ // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
9379
+ // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
9380
+ // does not enable them by default, so every native UI run on a private display reported
9381
+ // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
9382
+ // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
9383
+ // the box on a freshly scaffolded project. A browser run does not care either way.
9384
+ "+extension",
9385
+ "COMPOSITE",
9386
+ "+extension",
9387
+ "SHAPE",
9154
9388
  "-screen",
9155
9389
  "0",
9156
9390
  strategy.screen
@@ -9159,17 +9393,44 @@ async function provideDisplay(options = {}) {
9159
9393
  try {
9160
9394
  const number = await readXvfbDisplayNumber(xvfb);
9161
9395
  const display = `:${number}`;
9396
+ const compositor = await startCompositor(display, { commandExists, env, spawnProcess });
9162
9397
  return {
9398
+ compositor: compositor?.name,
9163
9399
  display,
9164
9400
  env: childEnvForDisplay(env, display),
9165
- release: () => stopXvfb(xvfb),
9401
+ release: async () => {
9402
+ if (compositor !== void 0) await stopChild(compositor.child);
9403
+ await stopChild(xvfb);
9404
+ },
9166
9405
  strategy
9167
9406
  };
9168
9407
  } catch (error) {
9169
- await stopXvfb(xvfb);
9408
+ await stopChild(xvfb);
9170
9409
  throw error;
9171
9410
  }
9172
9411
  }
9412
+ var COMPOSITORS = [
9413
+ { args: ["-n"], name: "xcompmgr" },
9414
+ { args: [], name: "picom" },
9415
+ { args: [], name: "compton" }
9416
+ ];
9417
+ var COMPOSITOR_SETTLE_MS = 250;
9418
+ async function startCompositor(display, options) {
9419
+ const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
9420
+ if (choice === void 0) return void 0;
9421
+ const child = options.spawnProcess(choice.name, [...choice.args], {
9422
+ env: { ...options.env, DISPLAY: display },
9423
+ stdio: "ignore"
9424
+ });
9425
+ let spawnFailed = false;
9426
+ child.on?.("error", () => {
9427
+ spawnFailed = true;
9428
+ });
9429
+ await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
9430
+ if (spawnFailed) return void 0;
9431
+ if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
9432
+ return { child, name: choice.name };
9433
+ }
9173
9434
  var XVFB_DISPLAY_TIMEOUT_MS = 1e4;
9174
9435
  async function readXvfbDisplayNumber(xvfb) {
9175
9436
  const report = xvfb.stdio[3];
@@ -9199,15 +9460,15 @@ async function readXvfbDisplayNumber(xvfb) {
9199
9460
  stream.on("close", onClose);
9200
9461
  });
9201
9462
  }
9202
- async function stopXvfb(xvfb) {
9203
- const exitedAlready = () => (xvfb.exitCode ?? null) !== null || (xvfb.signalCode ?? null) !== null;
9463
+ async function stopChild(child) {
9464
+ const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
9204
9465
  if (exitedAlready()) return;
9205
- xvfb.kill("SIGTERM");
9466
+ child.kill("SIGTERM");
9206
9467
  const started = Date.now();
9207
9468
  while (Date.now() - started < 1e3 && !exitedAlready()) {
9208
9469
  await new Promise((resolveWait) => setTimeout(resolveWait, 25));
9209
9470
  }
9210
- if (!exitedAlready()) xvfb.kill("SIGKILL");
9471
+ if (!exitedAlready()) child.kill("SIGKILL");
9211
9472
  }
9212
9473
  function defaultCommandExists(command) {
9213
9474
  const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
@@ -10230,6 +10491,7 @@ async function provideRunDisplay() {
10230
10491
  const provided = await provideDisplay();
10231
10492
  writeCaptureState({
10232
10493
  captureDisplay: {
10494
+ ...provided.compositor === void 0 ? {} : { compositor: provided.compositor },
10233
10495
  ...provided.display === void 0 ? {} : { display: provided.display },
10234
10496
  ...provided.strategy.kind === "private-xvfb" ? { screen: provided.strategy.screen } : {},
10235
10497
  strategy: provided.strategy.kind
@@ -10244,6 +10506,10 @@ function writeCaptureState(payload) {
10244
10506
  function addPreflightDiagnostic(report, diagnostic) {
10245
10507
  return diagnostic === void 0 ? report : { ...report, diagnostics: [diagnostic, ...report.diagnostics] };
10246
10508
  }
10509
+ var SOFTWARE_DEVICE_LOSS = /TN_DEVICE_LOST|WebGPU Device Lost|A valid external Instance reference no longer exists/iu;
10510
+ function isSoftwareDeviceLossEntry(entry) {
10511
+ return (entry.type === "error" || entry.type === "assert" || entry.type === "pageerror") && SOFTWARE_DEVICE_LOSS.test(entry.text);
10512
+ }
10247
10513
  function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEntries, networkEntries, pathLength = void 0, hud = {}, runtimeReady = true, visual = void 0, labeledSamples = [], framebufferCoverage = void 0, capture = void 0, captureFailure = void 0, movementSamples = [], setup = void 0, deviceMetrics = void 0, movementBaselineSnapshot = void 0, startup = void 0) {
10248
10514
  const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
10249
10515
  const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
@@ -10259,6 +10525,10 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10259
10525
  const movementDelta = beforePosition === void 0 || afterPosition === void 0 ? void 0 : subtract(afterPosition, beforePosition);
10260
10526
  const distance = movementDelta === void 0 ? 0 : length(movementDelta);
10261
10527
  const performanceSeries = scenario.assert?.performance === void 0 && scenario.assert?.parity === void 0 ? void 0 : afterSnapshot?.runtimeDiagnosticsSeries ?? beforeSnapshot?.runtimeDiagnosticsSeries;
10528
+ const softwareAdapter = capture?.rendererKind === "webgpu" ? softwareAdapterName(capture.adapter) : void 0;
10529
+ const softwareLane = config.allowSoftwareAdapter === true && softwareAdapter !== void 0;
10530
+ const deviceLossEntries = softwareLane ? consoleEntries.filter(isSoftwareDeviceLossEntry) : [];
10531
+ const observedConsoleEntries = deviceLossEntries.length === 0 ? consoleEntries : consoleEntries.filter((entry) => !isSoftwareDeviceLossEntry(entry));
10262
10532
  const diagnostics = [];
10263
10533
  if (runtimeReady === false && scenario.assert?.diagnostics?.runtimeReady === true) {
10264
10534
  diagnostics.push({
@@ -10291,7 +10561,7 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10291
10561
  // Honest placement reporting: what the scenario asked to override, and what applied.
10292
10562
  ...setup === void 0 ? {} : { setup },
10293
10563
  observations: buildObservations({
10294
- console: consoleEntries,
10564
+ console: observedConsoleEntries,
10295
10565
  ...components === void 0 ? {} : { components },
10296
10566
  ...labeledSamples.length === 0 ? {} : {
10297
10567
  componentSeries: labeledSamples.map(({ label, snapshot }) => ({ label, snapshots: snapshot.components ?? {}, tick: snapshot.clock.tick ?? 0 })),
@@ -10305,6 +10575,9 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10305
10575
  network: networkEntries,
10306
10576
  ...performanceSeries === void 0 ? {} : { performanceSeries },
10307
10577
  ...afterSnapshot?.pipelineCensus === void 0 && beforeSnapshot?.pipelineCensus === void 0 ? {} : { pipelineCensus: afterSnapshot?.pipelineCensus ?? beforeSnapshot?.pipelineCensus },
10578
+ // Like the pipeline census: a report about the frame it was requested on, kept whole. The
10579
+ // last sample wins, because a capture describes the world as the run left it.
10580
+ ...afterSnapshot?.geometry === void 0 && beforeSnapshot?.geometry === void 0 ? {} : { geometry: afterSnapshot?.geometry ?? beforeSnapshot?.geometry },
10308
10581
  ...afterSnapshot?.renderChain === void 0 && beforeSnapshot?.renderChain === void 0 ? {} : { renderChain: afterSnapshot?.renderChain ?? beforeSnapshot?.renderChain },
10309
10582
  resources: resourceObservations(beforeSnapshot, afterSnapshot),
10310
10583
  // The room as the run left it, falling back to how it started. A scene assertion is about
@@ -10326,8 +10599,8 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10326
10599
  },
10327
10600
  ...afterSnapshot?.physicsDebugSeries === void 0 ? {} : { physicsDebugSeries: afterSnapshot.physicsDebugSeries },
10328
10601
  ...beforeSnapshot?.physicsDebugSeries?.[0]?.snapshot === void 0 ? {} : { physicsDebugBefore: beforeSnapshot.physicsDebugSeries[0].snapshot },
10329
- runtimeDiagnostics: normalizedRuntimeDiagnostics(afterSnapshot, scenario, consoleEntries),
10330
- ...beforeSnapshot === void 0 ? {} : { runtimeDiagnosticsBefore: normalizedRuntimeDiagnostics(beforeSnapshot, scenario, consoleEntries) },
10602
+ runtimeDiagnostics: normalizedRuntimeDiagnostics(afterSnapshot, scenario, observedConsoleEntries),
10603
+ ...beforeSnapshot === void 0 ? {} : { runtimeDiagnosticsBefore: normalizedRuntimeDiagnostics(beforeSnapshot, scenario, observedConsoleEntries) },
10331
10604
  ...visual === void 0 ? {} : { visual }
10332
10605
  })
10333
10606
  };
@@ -10339,7 +10612,14 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10339
10612
  const assertionResults = [...evaluated.assertions, ...cameraResult === void 0 ? [] : [cameraResult]];
10340
10613
  const trivialityOptOuts = collectTrivialityOptOuts(assertionResults);
10341
10614
  const allDiagnostics = [...diagnostics, ...evaluated.diagnostics];
10342
- const softwareAdapter = capture?.rendererKind === "webgpu" ? softwareAdapterName(capture.adapter) : void 0;
10615
+ if (deviceLossEntries.length > 0) {
10616
+ allDiagnostics.push({
10617
+ code: "TN_PLAYTEST_SOFTWARE_DEVICE_LOST",
10618
+ message: `The software adapter '${softwareAdapter}' lost its WebGPU device during the run; ${deviceLossEntries.length} device-loss console error(s) were recorded instead of failing noConsoleErrors. This lane is not render evidence.`,
10619
+ severity: "warning",
10620
+ suggestion: "Expected on a CPU rasteriser when a frame outlasts the GPU process; rerun on a hardware adapter before reading any pixels."
10621
+ });
10622
+ }
10343
10623
  if (softwareAdapter !== void 0 && config.allowSoftwareAdapter !== true) {
10344
10624
  allDiagnostics.push({
10345
10625
  code: "TN_PLAYTEST_SOFTWARE_ADAPTER",
@@ -10655,6 +10935,19 @@ function removeStrandedProfiles(before, root = tmpdir()) {
10655
10935
  }
10656
10936
  return removed;
10657
10937
  }
10938
+ async function startBrowserCpuProfile(page, outputPath) {
10939
+ const cdp = await page.context().newCDPSession(page);
10940
+ await cdp.send("Profiler.enable");
10941
+ await cdp.send("Profiler.start");
10942
+ return {
10943
+ async stop() {
10944
+ const { profile } = await cdp.send("Profiler.stop");
10945
+ await writeFile(outputPath, `${JSON.stringify(profile)}
10946
+ `);
10947
+ return outputPath;
10948
+ }
10949
+ };
10950
+ }
10658
10951
 
10659
10952
  // src/runner/runner.ts
10660
10953
  var SCREENSHOT_TIMEOUT_MS = 12e4;
@@ -10738,6 +11031,25 @@ async function runStandalonePlaytestInternal(config, options = {}) {
10738
11031
  await serverTeardownPromise;
10739
11032
  };
10740
11033
  let profilesBeforeLaunch;
11034
+ let cpuProfile;
11035
+ let cpuProfileStopped = false;
11036
+ const stopCpuProfile = async (failClosed) => {
11037
+ if (cpuProfile === void 0 || cpuProfileStopped) return;
11038
+ cpuProfileStopped = true;
11039
+ try {
11040
+ const written = await cpuProfile.stop();
11041
+ process.stderr.write(`${JSON.stringify({ cpuProfile: written })}
11042
+ `);
11043
+ } catch (error) {
11044
+ if (failClosed) {
11045
+ throw new Error(`TN_PLAYTEST_CPU_PROFILE_WRITE_FAILED: ${error instanceof Error ? error.message : String(error)}`);
11046
+ }
11047
+ process.stderr.write(
11048
+ `${JSON.stringify({ diagnostics: [{ code: "TN_PLAYTEST_CPU_PROFILE_WRITE_FAILED", message: error instanceof Error ? error.message : String(error), severity: "error" }] })}
11049
+ `
11050
+ );
11051
+ }
11052
+ };
10741
11053
  const teardown = async (stopManagedServerOnTeardown = ownsServer) => {
10742
11054
  teardownPromise ??= (async () => {
10743
11055
  await teardownBrowserSession(page, context, browser, browserLaunch, options.remoteBrowser);
@@ -10882,13 +11194,15 @@ async function runStandalonePlaytestInternal(config, options = {}) {
10882
11194
  "entities",
10883
11195
  "resources",
10884
11196
  ...scenario.assert?.aerodynamics === void 0 && scenario.assert?.contacts === void 0 && scenario.assert?.settled === void 0 ? [] : ["physicsDebugSeries"],
10885
- ...scenario.assert?.performance === void 0 ? [] : ["runtimeDiagnosticsSeries"],
11197
+ ...scenario.assert?.performance === void 0 && scenario.assert?.parity === void 0 ? [] : ["runtimeDiagnosticsSeries"],
10886
11198
  ...scenario.assert?.renderChain === void 0 ? [] : ["renderChain"]
10887
11199
  ],
10888
11200
  resources: resourceIds,
10889
11201
  // One selector per assertion, in scenario order: the evaluator reads observation `i` for
10890
11202
  // assertion `i`, so the mapping has to be positional and never deduplicated.
10891
- ...scenario.assert?.sceneNodes === void 0 ? {} : { sceneNodes: scenario.assert.sceneNodes.map(({ select }) => select) }
11203
+ ...scenario.assert?.sceneNodes === void 0 ? {} : { sceneNodes: scenario.assert.sceneNodes.map(({ select }) => select) },
11204
+ // One armed capture per sample; absent means the bridge does no geometry work at all.
11205
+ ...scenario.assert?.geometry === void 0 ? {} : { geometry: scenario.assert.geometry }
10892
11206
  };
10893
11207
  const labeledSamples = [];
10894
11208
  const capturesAnonymousMovement = isAnonymousMovementScenario(scenario);
@@ -11028,6 +11342,9 @@ async function runStandalonePlaytestInternal(config, options = {}) {
11028
11342
  scenario.artifacts?.screenshots === "before-after" ? join(activeConfig.artifactDirectory, "before.png") : void 0
11029
11343
  ) : await capturePage("before.png", scenario.artifacts?.screenshots === "before-after" ? { path: join(activeConfig.artifactDirectory, "before.png") } : {}) : void 0;
11030
11344
  let framebufferCoverage;
11345
+ if (activeConfig.cpuProfilePath !== void 0) {
11346
+ cpuProfile = await startBrowserCpuProfile(activePage, activeConfig.cpuProfilePath);
11347
+ }
11031
11348
  for (const [index, step] of scenario.steps.entries()) {
11032
11349
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
11033
11350
  if (framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
@@ -11125,6 +11442,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
11125
11442
  network: networkEntries,
11126
11443
  runtimeTrace: normalizedRuntimeDiagnostics(afterSnapshot, scenario, consoleEntries)
11127
11444
  });
11445
+ await stopCpuProfile(true);
11128
11446
  if (options.remoteBrowser === void 0) await context.close();
11129
11447
  else await page.close();
11130
11448
  return addPreflightDiagnostic(report, preflight);
@@ -11140,6 +11458,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
11140
11458
  } finally {
11141
11459
  process.off("SIGINT", handleSignal);
11142
11460
  process.off("SIGTERM", handleSignal);
11461
+ await stopCpuProfile(false);
11143
11462
  await teardown();
11144
11463
  await providedDisplay?.release().catch(() => void 0);
11145
11464
  await captureLease?.release().catch(() => void 0);
@@ -11561,12 +11880,21 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11561
11880
  "diagnostics",
11562
11881
  "entities",
11563
11882
  "resources",
11564
- ...scenario.assert?.aerodynamics === void 0 && scenario.assert?.contacts === void 0 && scenario.assert?.settled === void 0 ? [] : ["physicsDebugSeries"]
11883
+ ...scenario.assert?.aerodynamics === void 0 && scenario.assert?.contacts === void 0 && scenario.assert?.settled === void 0 ? [] : ["physicsDebugSeries"],
11884
+ // The same two fields the browser lane requests, for the same reason: the bridge answers
11885
+ // only what it was asked for, so a `performance`, `parity` or `renderChain` assertion on a
11886
+ // device or desktop target used to evaluate against an empty series and fail as
11887
+ // "unobserved" even though the handshake advertises `runtime.performance` and
11888
+ // `runtime.renderChain`.
11889
+ ...scenario.assert?.performance === void 0 && scenario.assert?.parity === void 0 ? [] : ["runtimeDiagnosticsSeries"],
11890
+ ...scenario.assert?.renderChain === void 0 ? [] : ["renderChain"]
11565
11891
  ],
11566
11892
  resources: observedResourceIds(scenario),
11567
11893
  // One selector per assertion in scenario order: the evaluator reads observation `i` for
11568
11894
  // assertion `i`, so the mapping has to be positional and never deduplicated.
11569
- ...scenario.assert?.sceneNodes === void 0 ? {} : { sceneNodes: scenario.assert.sceneNodes.map(({ select }) => select) }
11895
+ ...scenario.assert?.sceneNodes === void 0 ? {} : { sceneNodes: scenario.assert.sceneNodes.map(({ select }) => select) },
11896
+ // One armed capture per sample; absent means the bridge does no geometry work at all.
11897
+ ...scenario.assert?.geometry === void 0 ? {} : { geometry: scenario.assert.geometry }
11570
11898
  };
11571
11899
  const before = await bridge.sample(sampleRequest);
11572
11900
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
@@ -11579,6 +11907,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11579
11907
  const heldKeys = /* @__PURE__ */ new Set();
11580
11908
  let pointerButtons = 0;
11581
11909
  let pointerCount = 0;
11910
+ let pointerX = 0;
11911
+ let pointerY = 0;
11912
+ let pointerHeld = false;
11582
11913
  for (const [index, step] of scenario.steps.entries()) {
11583
11914
  await throwIfAborted(target);
11584
11915
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
@@ -11624,11 +11955,14 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11624
11955
  if (step.pointerPosition !== void 0) {
11625
11956
  const previousPointerButtons = pointerButtons;
11626
11957
  pointerButtons = step.pointerPosition.buttons ?? pointerButtons;
11958
+ if (pointerButtons !== 0) pointerHeld = true;
11959
+ pointerX = step.pointerPosition.x * scenario.viewport.width;
11960
+ pointerY = step.pointerPosition.y * scenario.viewport.height;
11627
11961
  await transport.call("input.pointer", {
11628
11962
  buttons: pointerButtons,
11629
11963
  type: pointerButtons === 0 ? "move" : previousPointerButtons === 0 ? "down" : "move",
11630
- x: step.pointerPosition.x * scenario.viewport.width,
11631
- y: step.pointerPosition.y * scenario.viewport.height
11964
+ x: pointerX,
11965
+ y: pointerY
11632
11966
  });
11633
11967
  }
11634
11968
  if (step.pointers !== void 0) {
@@ -11702,9 +12036,10 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11702
12036
  if (capturesAnonymousMovement) afterStep = await bridge.sample(sampleRequest);
11703
12037
  }
11704
12038
  }
11705
- if (step.pointerPosition?.buttons !== void 0 && step.release) {
12039
+ if (pointerHeld && step.release && step.kind !== "wait") {
11706
12040
  pointerButtons = 0;
11707
- await transport.call("input.pointer", { buttons: 0, type: "up", x: 0, y: 0 });
12041
+ pointerHeld = false;
12042
+ await transport.call("input.pointer", { buttons: 0, type: "up", x: pointerX, y: pointerY });
11708
12043
  }
11709
12044
  if (step.pointers !== void 0 && step.release) {
11710
12045
  await setDevicePointers(target, transport, [], scenario.viewport);
@@ -11861,7 +12196,7 @@ function createDeviceTransport(driver, endpoint, paths, operationTimeoutMs) {
11861
12196
  return new DeviceBridgeTransport(endpoint);
11862
12197
  }
11863
12198
  async function setDevicePointers(target, transport, pointers, viewport) {
11864
- if (target.name === "ios") {
12199
+ if (target.name === "ios" || target.name === "desktop") {
11865
12200
  await transport.call("input.pointers", {
11866
12201
  pointers: pointers.map((pointer) => ({
11867
12202
  ...pointer.buttons === void 0 ? {} : { buttons: pointer.buttons },
@@ -11950,14 +12285,6 @@ function unsupportedAssertion(scenario, target, hasPointerTransport) {
11950
12285
  target
11951
12286
  );
11952
12287
  }
11953
- const hasMultiPointerInput = scenario.steps.some((step) => step.pointers !== void 0);
11954
- if (hasMultiPointerInput && target === "desktop") {
11955
- return unsupportedDiagnostic(
11956
- "complete held-pointer input",
11957
- "Run this scenario on --target browser or --target android; the desktop mailbox host exposes one pointer.",
11958
- target
11959
- );
11960
- }
11961
12288
  if (scenario.assert?.deviceMetrics !== void 0 && target !== "android") {
11962
12289
  return unsupportedDiagnostic(
11963
12290
  "device thermal and power assertions",
@@ -12036,12 +12363,15 @@ var PLAYTEST_FLAGS = {
12036
12363
  "--no-screenshots": { default: "false", summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one", takesValue: false },
12037
12364
  "--browser-arg": { allowDashValue: true, default: "none (repeatable)", repeatable: true, summary: "one additional Chromium argument", takesValue: true },
12038
12365
  "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu)", takesValue: true },
12366
+ "--cpu-prof": { default: "none", summary: "write a Chrome DevTools .cpuprofile for this run (browser and desktop targets)", takesValue: true },
12039
12367
  "--bundle-id": { default: "dev.threenative.runtime", summary: "iOS application bundle identifier", takesValue: true },
12040
12368
  "--device": { default: "platform default", summary: "Android serial or iOS device identifier", takesValue: true },
12041
12369
  "--executable": { default: "required for desktop", summary: "native desktop game executable", takesValue: true },
12042
12370
  "--endpoint": { default: "http://127.0.0.1:41777/playtest", summary: "device bridge endpoint", takesValue: true },
12043
12371
  "--headed": { default: "false", summary: "show the browser window", takesValue: false },
12044
- "--host-arg": { default: "none", repeatable: true, summary: "argument passed to the native desktop host, repeatable", takesValue: true },
12372
+ // `allowDashValue` so a host flag can be passed as one: `--host-arg --ui` is the UI root the
12373
+ // overlay serves, and the parser would otherwise read `--ui` as a playtest flag and reject it.
12374
+ "--host-arg": { allowDashValue: true, default: "none", repeatable: true, summary: "argument passed to the native desktop host, repeatable", takesValue: true },
12045
12375
  "--mailbox-root": { default: "Android external files directory", summary: "native device mailbox directory", takesValue: true },
12046
12376
  "--ios-transport": { default: "simulator", summary: "iOS transport (simulator or device)", takesValue: true },
12047
12377
  "--project": { default: ".", summary: "project root used to resolve paths", takesValue: true },
@@ -12087,6 +12417,9 @@ function formatUsage() {
12087
12417
  " with repeatable --host-arg, or --logcat <serial>",
12088
12418
  " bounds: --max-frame-p95 <ms>, --min-fps <fps>",
12089
12419
  " --require-windows <n> (default 2), --timeout <s>, --text",
12420
+ " --allow-virtual-display accepts a frame rate the display did not",
12421
+ " see (a private Xvfb, or a loop the presentation cap outran); without",
12422
+ " it such a run prints no fps column and refuses a --min-fps bound",
12090
12423
  " trace record a Chrome performance trace of a running game and name the",
12091
12424
  " functions inside its slow frames \u2014 a percentile says a frame was",
12092
12425
  " slow, a trace says which function. Take one BEFORE attributing any",
@@ -12181,6 +12514,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
12181
12514
  throw new PlaytestCliUsageError("Choose --browser-recipe or --browser-arg, not both.");
12182
12515
  }
12183
12516
  const device = flags.get("--device")?.[0];
12517
+ const cpuProfilePath = flags.get("--cpu-prof")?.[0];
12184
12518
  if (target === "browser" && device !== void 0) {
12185
12519
  if (browserRecipe !== void 0) {
12186
12520
  throw new PlaytestCliUsageError("Android Chrome device runs cannot honor --browser-recipe; remove it.");
@@ -12223,6 +12557,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
12223
12557
  artifactDirectory: resolve(projectPath, flags.get("--artifacts")?.[0] ?? "artifacts/playtest"),
12224
12558
  captureArtifactScreenshots: !argv.includes("--no-screenshots"),
12225
12559
  ...browserArgs.length === 0 ? {} : { browserArgs },
12560
+ ...cpuProfilePath === void 0 ? {} : { cpuProfilePath: resolve(projectPath, cpuProfilePath) },
12226
12561
  ...device === void 0 ? {} : { device },
12227
12562
  ...executable === void 0 ? {} : {
12228
12563
  desktop: {
@@ -12359,12 +12694,20 @@ var LocalDeviceMailbox = class {
12359
12694
  try {
12360
12695
  return await readFile(path, "utf8");
12361
12696
  } catch (error) {
12362
- if (isMissingFile(error)) return void 0;
12697
+ if (isMissingFile(error) || isTransientMailboxLock(error)) return void 0;
12363
12698
  throw error;
12364
12699
  }
12365
12700
  }
12366
12701
  async remove(path) {
12367
- await rm(path, { force: true });
12702
+ for (let retry = 0; ; retry += 1) {
12703
+ try {
12704
+ await rm(path, { force: true });
12705
+ return;
12706
+ } catch (error) {
12707
+ if (retry >= 10 || !isTransientMailboxLock(error)) throw error;
12708
+ await delay2(20);
12709
+ }
12710
+ }
12368
12711
  }
12369
12712
  async write(path, contents) {
12370
12713
  await mkdir(dirname(path), { recursive: true });
@@ -12498,10 +12841,12 @@ var DesktopPlaytestDriver = class {
12498
12841
  function desktopConsoleType(stream, line) {
12499
12842
  const text = line.trimStart();
12500
12843
  if (/^(?:\[error\]|(?:error|fatal):)/iu.test(text)) return "error";
12501
- if (/^(?:\[warn(?:ing)?\]|warning:|MESA-EGL:\s*warning:|\*\* \([^)]*\): WARNING \*\*:)/iu.test(text)) {
12844
+ if (/^(?:\[warn(?:ing)?\]|warning:|MESA-EGL:\s*warning:|libEGL\s+warning:|\*\* \([^)]*\): WARNING \*\*:|\([^)]*\): dbind-WARNING \*\*:)/iu.test(
12845
+ text
12846
+ )) {
12502
12847
  return "warning";
12503
12848
  }
12504
- if (/^Gtk-Message:/u.test(text)) return "log";
12849
+ if (/^ALSA lib\b|^\[Audio\] Failed to open audio device: ALSA:|^Gtk-Message:/u.test(text)) return "log";
12505
12850
  return stream === "stderr" ? "error" : "log";
12506
12851
  }
12507
12852
  function terminateProcess(child, signal) {
@@ -12550,11 +12895,16 @@ function isProcessExited(child) {
12550
12895
  function delay2(milliseconds) {
12551
12896
  return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
12552
12897
  }
12898
+ function isTransientMailboxLock(error) {
12899
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
12900
+ return code === "EPERM" || code === "EBUSY";
12901
+ }
12553
12902
  function isMissingFile(error) {
12554
12903
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
12555
12904
  }
12556
12905
  function desktopHostArgs(config) {
12557
- return config.desktop?.hostArgs ?? [];
12906
+ const args = config.desktop?.hostArgs ?? [];
12907
+ return config.cpuProfilePath === void 0 ? args : [...args, `--cpu-prof=${config.cpuProfilePath}`];
12558
12908
  }
12559
12909
  async function runDesktopPlaytest(config, dependencies = {}) {
12560
12910
  const executable = config.desktop?.executable;
@@ -12728,6 +13078,22 @@ installThreePlaytestBridge({
12728
13078
  return { created };
12729
13079
  }
12730
13080
  var execFileAsync3 = promisify(execFile);
13081
+ var kIosCompactAppleRecord = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+ (Df|Db|A|I|E|F) +\S+\[\d+:[0-9a-f]+\] \[([^\]:]+):[^\]]+\]/u;
13082
+ var kIosExplicitErrorMarker = /\[error\]|\bFATAL\b|GPUValidationError|uncaught/iu;
13083
+ var kIosAppleFaultFailure = /\b(?:error|fail(?:ed|ure)?|abort(?:ed)?|crash(?:ed)?)\b/iu;
13084
+ var kIosTextError = /\[error\]|\b(?:Error|Fault|FATAL|FAILED|GPUValidationError|uncaught)\b/u;
13085
+ function classifyIosConsoleLine(text) {
13086
+ const compact = kIosCompactAppleRecord.exec(text);
13087
+ if (compact !== null) {
13088
+ if (kIosExplicitErrorMarker.test(text)) return "error";
13089
+ if (compact[2].startsWith("com.apple.")) {
13090
+ return compact[1] === "F" && kIosAppleFaultFailure.test(text) ? "error" : "log";
13091
+ }
13092
+ if (compact[1] === "E" || compact[1] === "F") return "error";
13093
+ return kIosTextError.test(text) ? "error" : "log";
13094
+ }
13095
+ return kIosTextError.test(text) ? "error" : "log";
13096
+ }
12731
13097
  var XcrunIosDriver = class {
12732
13098
  constructor(options, run) {
12733
13099
  this.options = options;
@@ -12764,6 +13130,8 @@ var XcrunIosDriver = class {
12764
13130
  await this.prepareDevice(endpoint, mailboxRoot);
12765
13131
  }
12766
13132
  async captureConsole() {
13133
+ if (this.pid === void 0) throw new Error("iOS console capture requires a launched process.");
13134
+ const predicate = `processIdentifier == ${this.pid}`;
12767
13135
  const output = this.options.transport === "simulator" ? await this.run([
12768
13136
  "simctl",
12769
13137
  "spawn",
@@ -12775,7 +13143,7 @@ var XcrunIosDriver = class {
12775
13143
  "--last",
12776
13144
  "5m",
12777
13145
  "--predicate",
12778
- `process == "${this.processName()}"`
13146
+ predicate
12779
13147
  ]) : await this.run([
12780
13148
  "devicectl",
12781
13149
  "device",
@@ -12786,12 +13154,9 @@ var XcrunIosDriver = class {
12786
13154
  "--last",
12787
13155
  "5m",
12788
13156
  "--predicate",
12789
- `process == "${this.processName()}"`
13157
+ predicate
12790
13158
  ]);
12791
- return output.split(/\r?\n/u).filter((line) => /ThreeNative|THREENATIVE|Mystral|TN_PLAYTEST/u.test(line)).map((text) => ({
12792
- text,
12793
- type: /\b(?:Error|Fault|FATAL|FAILED|GPUValidationError)\b/u.test(text) ? "error" : "log"
12794
- }));
13159
+ return output.split(/\r?\n/u).filter((line) => line.trim().length > 0).map((text) => ({ text, type: classifyIosConsoleLine(text) }));
12795
13160
  }
12796
13161
  async isAlive() {
12797
13162
  if (this.pid === void 0) return false;
@@ -12976,9 +13341,6 @@ var XcrunIosDriver = class {
12976
13341
  device() {
12977
13342
  return this.options.device ?? "booted";
12978
13343
  }
12979
- processName() {
12980
- return basename(this.options.appPath, ".app");
12981
- }
12982
13344
  mailboxPath(path) {
12983
13345
  return this.mailboxRoot === void 0 ? path : join(this.mailboxRoot, basename(path));
12984
13346
  }
@@ -14098,5 +14460,153 @@ function malformed(detail) {
14098
14460
  function errorMessage2(error) {
14099
14461
  return error instanceof Error ? error.message : String(error);
14100
14462
  }
14463
+ function abortError(signal) {
14464
+ return signal.reason instanceof Error ? signal.reason : new Error("TN_CAPTURE_SESSION_ABORTED");
14465
+ }
14466
+ async function captureStage(stage, timeoutMs, controller, operation) {
14467
+ if (controller.signal.aborted) throw abortError(controller.signal);
14468
+ let timer;
14469
+ let onAbort;
14470
+ try {
14471
+ const interrupted = new Promise((_resolve, reject) => {
14472
+ onAbort = () => reject(abortError(controller.signal));
14473
+ controller.signal.addEventListener("abort", onAbort, { once: true });
14474
+ timer = setTimeout(() => controller.abort(new Error(`TN_CAPTURE_SESSION_TIMEOUT: ${stage} exceeded ${timeoutMs}ms`)), timeoutMs);
14475
+ });
14476
+ return await Promise.race([Promise.resolve().then(() => {
14477
+ if (controller.signal.aborted) throw abortError(controller.signal);
14478
+ return operation();
14479
+ }), interrupted]);
14480
+ } finally {
14481
+ if (timer !== void 0) clearTimeout(timer);
14482
+ if (onAbort !== void 0) controller.signal.removeEventListener("abort", onAbort);
14483
+ }
14484
+ }
14485
+ async function withBrowserCapture(config, capture, signal) {
14486
+ if ((config.target ?? "browser") !== "browser") throw new Error("TN_CAPTURE_SESSION_TARGET: only an owned browser is supported");
14487
+ if (!Number.isSafeInteger(config.timeoutMs) || config.timeoutMs <= 0 || config.timeoutMs > 2147483647 || config.server?.timeoutMs !== void 0 && (!Number.isSafeInteger(config.server.timeoutMs) || config.server.timeoutMs <= 0 || config.server.timeoutMs > 2147483647)) {
14488
+ throw new Error("TN_CAPTURE_SESSION_TIMEOUT_INVALID: operation and server budgets must be finite positive milliseconds");
14489
+ }
14490
+ const controller = new AbortController();
14491
+ const abort = () => controller.abort(signal?.reason);
14492
+ if (signal?.aborted) abort();
14493
+ else signal?.addEventListener("abort", abort, { once: true });
14494
+ let display;
14495
+ let lease;
14496
+ let server;
14497
+ let browser;
14498
+ let browserLaunch;
14499
+ let context;
14500
+ let page;
14501
+ let profilesBeforeLaunch;
14502
+ const stage = (name, operation, timeoutMs = config.timeoutMs) => captureStage(name, timeoutMs, controller, operation);
14503
+ const checkAbort = () => {
14504
+ if (controller.signal.aborted) throw abortError(controller.signal);
14505
+ };
14506
+ try {
14507
+ checkAbort();
14508
+ const scenario = await stage("scenario load", () => loadPlaytestScenario(config.projectPath, config.scenarioPath));
14509
+ if (scenario.target !== "web") throw new Error("TN_CAPTURE_SESSION_TARGET: browser captures require a web scenario");
14510
+ if (scenario.bootFailure !== void 0 || scenario.awaitStartup === false) {
14511
+ throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: custom captures cannot bypass startup; use the scenario runner for boot-failure tests");
14512
+ }
14513
+ lease = await acquireRunnerCaptureLock();
14514
+ checkAbort();
14515
+ display = await provideRunDisplay();
14516
+ checkAbort();
14517
+ const needsFreePort = config.server !== void 0 && config.port === 0;
14518
+ const port = needsFreePort ? await findFreePort() : config.port;
14519
+ const active = {
14520
+ ...config,
14521
+ browserArgs: resolveBrowserArguments(config.browserArgs ?? WEBGPU_BROWSER_ARGS),
14522
+ headless: false,
14523
+ ...port === void 0 ? {} : { port },
14524
+ url: needsFreePort && port !== void 0 ? withPort(config.url, port) : config.url
14525
+ };
14526
+ await mkdir(active.artifactDirectory, { recursive: true });
14527
+ if (active.server !== void 0) {
14528
+ await stage("server availability", () => assertManagedUrlAvailable(active.url));
14529
+ server = startManagedServer(active, port);
14530
+ const ownedServer = server;
14531
+ await stage("server readiness", () => waitForUrl(active.url, active.server?.timeoutMs ?? active.timeoutMs, ownedServer), active.server.timeoutMs ?? active.timeoutMs);
14532
+ }
14533
+ checkAbort();
14534
+ profilesBeforeLaunch = playwrightProfileDirectories();
14535
+ browserLaunch = chromium.launch({ args: active.browserArgs, env: display.env, headless: false, timeout: active.timeoutMs });
14536
+ const launchingBrowser = browserLaunch;
14537
+ browser = await stage("browser launch", () => launchingBrowser);
14538
+ checkAbort();
14539
+ const ownedBrowser = browser;
14540
+ context = await stage("context creation", () => ownedBrowser.newContext({ viewport: scenario.viewport }));
14541
+ const ownedContext = context;
14542
+ page = await stage("page creation", () => ownedContext.newPage());
14543
+ const activePage = page;
14544
+ await stage("runner handshake marker", () => activePage.addInitScript(() => {
14545
+ Object.assign(globalThis, { __THREENATIVE_PLAYTEST_RUNNER_EXPECTED__: true });
14546
+ }));
14547
+ const startupBudget = Math.min(2147483647, PLAYTEST_STARTUP_READY_TIMEOUT_MS + active.timeoutMs);
14548
+ const bridge = await stage("navigation and bridge handshake", () => openRunnerPage(activePage, active, scenario, void 0), startupBudget);
14549
+ if (bridge === void 0 || !bridge.description.capabilities.includes("runtime.startup")) {
14550
+ throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: the page must report runtime.startup");
14551
+ }
14552
+ await stage("warmup", () => waitFrames(activePage, scenario.warmupFrames), startupBudget);
14553
+ const startup = await stage("engine startup readiness", () => waitForStartupReady({
14554
+ aborted: () => controller.signal.aborted,
14555
+ acceptCompileSettled: active.allowSoftwareAdapter === true,
14556
+ bridge,
14557
+ pump: () => waitFrames(activePage, 1)
14558
+ }), startupBudget);
14559
+ if (startup === void 0) throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: no startup observation was returned");
14560
+ const provenance = await stage("adapter provenance", () => readCaptureProvenance(activePage, active, scenario));
14561
+ const software = softwareAdapterName(provenance.adapter);
14562
+ if (provenance.rendererKind !== "webgpu" || software !== void 0 && active.allowSoftwareAdapter !== true) {
14563
+ throw new Error(`TN_CAPTURE_SESSION_ADAPTER_REJECTED: renderer=${provenance.rendererKind}, software=${software ?? "not detected"}`);
14564
+ }
14565
+ await writeFile(join(active.artifactDirectory, "capture.json"), `${JSON.stringify(provenance, null, 2)}
14566
+ `);
14567
+ await writeFile(join(active.artifactDirectory, "capture-session.json"), `${JSON.stringify({
14568
+ display: display.strategy,
14569
+ startup,
14570
+ setup: bridge.setupApplication,
14571
+ softwareAllowed: active.allowSoftwareAdapter === true,
14572
+ timingEvidence: "not-qualified"
14573
+ }, null, 2)}
14574
+ `);
14575
+ return await stage("custom capture callback", () => capture({
14576
+ bridge,
14577
+ page: activePage,
14578
+ provenance,
14579
+ signal: controller.signal,
14580
+ screenshot: async (label) => {
14581
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(label)) throw new Error("TN_CAPTURE_SESSION_LABEL_INVALID: use a file-safe label without an extension");
14582
+ return stage(`screenshot ${label}`, async () => {
14583
+ const destination = join(active.artifactDirectory, `${label}.png`);
14584
+ await rm(destination, { force: true });
14585
+ const bytes = await activePage.screenshot({ timeout: active.timeoutMs });
14586
+ assertCaptureNotBlank(bytes, `${label}.png`);
14587
+ await writeFile(destination, bytes);
14588
+ return destination;
14589
+ });
14590
+ }
14591
+ }));
14592
+ } finally {
14593
+ controller.abort(new Error("TN_CAPTURE_SESSION_CLOSED"));
14594
+ signal?.removeEventListener("abort", abort);
14595
+ try {
14596
+ await teardownBrowserSession(page, context, browser, browserLaunch, void 0);
14597
+ if (profilesBeforeLaunch !== void 0) removeStrandedProfiles(profilesBeforeLaunch);
14598
+ } finally {
14599
+ try {
14600
+ await stopManagedServer(server);
14601
+ } finally {
14602
+ try {
14603
+ await display?.release();
14604
+ } finally {
14605
+ await lease?.release();
14606
+ }
14607
+ }
14608
+ }
14609
+ }
14610
+ }
14101
14611
 
14102
- export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DesktopPlaytestDriver, DeviceBridgeTransport, DeviceMailboxTransport, LocalDeviceMailbox, ManagedServerError, PERFORMANCE_BROWSER_ARGS, PIPELINE_CAPTURE_VERSION, PIPELINE_EVENT_MARKER, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, WEBGPU_BROWSER_ARGS, XcrunIosDriver, advanceFixedStep, advanceTimeoutMs, androidMailboxPaths, androidTouchBatches, batchArtifactDirectory, boundedTeardownStep, bridgeWaitTimeoutMs, buildReport, captureVisualSurface, connectPlaytestBridge, connectPlaytestBridgeTransport, deviceMailboxPaths, deviceTimeoutDiagnostic, discoverAdb, failedDiagnosticsAssertion, formatPipelineSummary, formatUsage, handlePlaytestSignal, initStandalonePlaytest, isRuntimeReadout, keyboardIsShown, openPageAndConnectBridge, pageLifecycleDiagnostic, parseAndroidConsole, parseAndroidTouchViewport, parseLaunchedPid, parsePipelineCapture, parsePipelineEventMarkers, parseStandalonePlaytestArgs, playtestStepDrivesMovement, preflightDisplay, reconcileBrowserPointers, recordToScenario, requireAssertions, resolveBrowserArguments, resolveManagedServerCommand, resolveManagedServerConfig, rotatedTouchPosition, runAndroidPlaytest, runDesktopPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, runStandalonePlaytests, softwareAdapterName, substituteManagedPort, summarizePipelineCapture, tapCommand, touchPositionForViewport, touchRotationFromWindowDump, validateDeviceEndpoint, viewportPresentationCommands, viewportPresentationObserved, viewportRestoreCommands, writeCaptureProvenance, writeObservationArtifacts };
14612
+ export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DesktopPlaytestDriver, DeviceBridgeTransport, DeviceMailboxTransport, LocalDeviceMailbox, ManagedServerError, PERFORMANCE_BROWSER_ARGS, PIPELINE_CAPTURE_VERSION, PIPELINE_EVENT_MARKER, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, WEBGPU_BROWSER_ARGS, XcrunIosDriver, advanceFixedStep, advanceTimeoutMs, androidMailboxPaths, androidTouchBatches, batchArtifactDirectory, boundedTeardownStep, bridgeWaitTimeoutMs, buildReport, captureVisualSurface, connectPlaytestBridge, connectPlaytestBridgeTransport, deviceMailboxPaths, deviceTimeoutDiagnostic, discoverAdb, failedDiagnosticsAssertion, formatPipelineSummary, formatUsage, handlePlaytestSignal, initStandalonePlaytest, isRuntimeReadout, keyboardIsShown, openPageAndConnectBridge, pageLifecycleDiagnostic, parseAndroidConsole, parseAndroidTouchViewport, parseLaunchedPid, parsePipelineCapture, parsePipelineEventMarkers, parseStandalonePlaytestArgs, playtestStepDrivesMovement, preflightDisplay, reconcileBrowserPointers, recordToScenario, requireAssertions, resolveBrowserArguments, resolveManagedServerCommand, resolveManagedServerConfig, rotatedTouchPosition, runAndroidPlaytest, runDesktopPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, runStandalonePlaytests, softwareAdapterName, substituteManagedPort, summarizePipelineCapture, tapCommand, touchPositionForViewport, touchRotationFromWindowDump, validateDeviceEndpoint, viewportPresentationCommands, viewportPresentationObserved, viewportRestoreCommands, withBrowserCapture, writeCaptureProvenance, writeObservationArtifacts };