@threenative/playtest 0.3.3 → 0.3.4

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.
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { writeFile, stat, mkdtemp, rm, mkdir, readFile, rename, access, unlink, readdir, copyFile, rmdir } from 'fs/promises';
3
3
  import { join, resolve, relative, dirname, isAbsolute, basename } from 'path';
4
- import { execFile, spawn, spawnSync } from 'child_process';
5
4
  import { existsSync, readdirSync, rmSync, readFileSync } from 'fs';
5
+ import { execFile, spawn, spawnSync } from 'child_process';
6
6
  import { tmpdir, homedir } from 'os';
7
7
  import { promisify } from 'util';
8
8
  import { PNG } from 'pngjs';
9
+ import 'crypto';
9
10
  import { createServer } from 'http';
10
11
  import { chromium } from 'playwright';
11
12
  import { createServer as createServer$1 } from 'net';
@@ -74,11 +75,11 @@ function resolveDiagnosticsPolicy(policy, target) {
74
75
  ...policy?.runtimeDiagnosticsOptOutReason === void 0 ? {} : { runtimeDiagnosticsOptOutReason: policy.runtimeDiagnosticsOptOutReason }
75
76
  };
76
77
  }
77
- function trivialAssertionDiagnostic(id, path, before, sourcePath) {
78
+ function trivialAssertionDiagnostic(id, path2, before, sourcePath) {
78
79
  return {
79
80
  code: "TN_PLAYTEST_ASSERTION_TRIVIAL",
80
- message: `Assertion '${id}'${path === void 0 ? "" : ` at path '${path}'`} was already satisfied before the scenario ran (value ${JSON.stringify(before)}).`,
81
- path,
81
+ message: `Assertion '${id}'${path2 === void 0 ? "" : ` at path '${path2}'`} was already satisfied before the scenario ran (value ${JSON.stringify(before)}).`,
82
+ path: path2,
82
83
  severity: "error",
83
84
  ...sourcePath === void 0 ? {} : { sourcePath },
84
85
  suggestion: "Drive the asserted value from a failing initial state, or assert changed:true. If the value is genuinely a held invariant, allowTrivial takes the reason it is held \u2014 it is recorded in the report and counted against the run."
@@ -139,7 +140,7 @@ function pathAssertionDiagnostic(kind, assertion, before, after, context) {
139
140
  suggestion: unchanged ? `${kind === "hud" ? "Observed HUD value" : "Observed resource value"} did not change during the scenario. Inspect effect-log.json for the owning system's resource writes, run tn build --project . --json for undeclared writes, and check whether duplicate/stale systems or route/collision setup prevented the state transition.` : kind === "hud" ? "Check UI binding IDs and whether the backing resource changes during the scenario." : "Check resource IDs, script writes, and assertion path spelling."
140
141
  };
141
142
  }
142
- function summarizeResourceEffectLog(effectLog, resourceId, path) {
143
+ function summarizeResourceEffectLog(effectLog, resourceId, path2) {
143
144
  if (!isRecord(effectLog) || !Array.isArray(effectLog.entries)) {
144
145
  return void 0;
145
146
  }
@@ -153,7 +154,7 @@ function summarizeResourceEffectLog(effectLog, resourceId, path) {
153
154
  if (typeof entry.system === "string") {
154
155
  systems.add(entry.system);
155
156
  }
156
- values.add(shortJson(readPath(entry.value, path)));
157
+ values.add(shortJson(readPath(entry.value, path2)));
157
158
  }
158
159
  return {
159
160
  distinctValues: Array.from(values).slice(0, 3).join(", "),
@@ -193,11 +194,11 @@ function runtimeDiagnosticsSnapshot(value) {
193
194
  function consoleErrors(entries) {
194
195
  return entries.filter((entry) => entry.type === "error" || entry.type === "assert" || entry.type === "pageerror");
195
196
  }
196
- function readPath(value, path) {
197
- if (path === void 0 || path.length === 0) {
197
+ function readPath(value, path2) {
198
+ if (path2 === void 0 || path2.length === 0) {
198
199
  return value;
199
200
  }
200
- return path.split(".").reduce((current, part) => {
201
+ return path2.split(".").reduce((current, part) => {
201
202
  if (Array.isArray(current) && /^(0|[1-9]\d*)$/u.test(part)) {
202
203
  return current[Number(part)];
203
204
  }
@@ -250,7 +251,24 @@ function formatNumber(value) {
250
251
  return Number.isInteger(value) ? String(value) : value.toFixed(3);
251
252
  }
252
253
  function jsonEqual(left, right) {
253
- return JSON.stringify(left) === JSON.stringify(right);
254
+ return JSON.stringify(sortedKeys(left)) === JSON.stringify(sortedKeys(right));
255
+ }
256
+ function sortedKeys(value) {
257
+ if (Array.isArray(value)) {
258
+ return value.map(sortedKeys);
259
+ }
260
+ if (!isRecord(value)) {
261
+ return value;
262
+ }
263
+ const prototype = Object.getPrototypeOf(value);
264
+ if (prototype !== Object.prototype && prototype !== null) {
265
+ return value;
266
+ }
267
+ const sorted = {};
268
+ for (const key of Object.keys(value).sort()) {
269
+ sorted[key] = sortedKeys(value[key]);
270
+ }
271
+ return sorted;
254
272
  }
255
273
  function isRecord(value) {
256
274
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -831,7 +849,8 @@ var PLAYTEST_ASSERTION_REGISTRY = [
831
849
  { description: "Exact render-chain quality tier required after the chain applies.", name: "tier", type: "string" },
832
850
  { description: "Stage ids to include, exclude, or find as an ordered subsequence in the applied chain.", name: "stages", type: "object" },
833
851
  { description: "Applied stage ids whose build returned a different graph node than its input; this is graph evidence, not pixel attribution.", name: "contributions", type: "object" },
834
- { description: "Temporal history rejection ceiling as a fraction from 0 to 1.", name: "velocity", type: "object" }
852
+ { description: "Temporal history rejection ceiling as a fraction from 0 to 1.", name: "velocity", type: "object" },
853
+ { description: "What the chain must be on each adapter class the harness classified from its own adapter.info reading; an unclassifiable adapter fails rather than matching either branch.", name: "perAdapter", type: "object" }
835
854
  ],
836
855
  cardinality: "object",
837
856
  kind: "renderChain",
@@ -1777,7 +1796,7 @@ var PLAYTEST_FRAME_PASS_KINDS = ["main", "shadow", "reflection", "nested"];
1777
1796
  function jsonByteLength(value) {
1778
1797
  return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1779
1798
  }
1780
- function assertJsonSafe(value, path = "$") {
1799
+ function assertJsonSafe(value, path2 = "$") {
1781
1800
  if (value === null || typeof value === "string" || typeof value === "boolean") {
1782
1801
  return;
1783
1802
  }
@@ -1785,19 +1804,19 @@ function assertJsonSafe(value, path = "$") {
1785
1804
  if (Number.isFinite(value)) {
1786
1805
  return;
1787
1806
  }
1788
- throw new TypeError(`${path} must contain only finite JSON numbers.`);
1807
+ throw new TypeError(`${path2} must contain only finite JSON numbers.`);
1789
1808
  }
1790
1809
  if (Array.isArray(value)) {
1791
- value.forEach((item, index) => assertJsonSafe(item, `${path}[${index}]`));
1810
+ value.forEach((item, index) => assertJsonSafe(item, `${path2}[${index}]`));
1792
1811
  return;
1793
1812
  }
1794
1813
  if (typeof value === "object") {
1795
1814
  for (const [key, item] of Object.entries(value)) {
1796
- assertJsonSafe(item, `${path}.${key}`);
1815
+ assertJsonSafe(item, `${path2}.${key}`);
1797
1816
  }
1798
1817
  return;
1799
1818
  }
1800
- throw new TypeError(`${path} must be JSON-safe.`);
1819
+ throw new TypeError(`${path2} must be JSON-safe.`);
1801
1820
  }
1802
1821
 
1803
1822
  // src/evaluators/render-evidence.ts
@@ -1830,7 +1849,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1830
1849
  const maxObservedTriangles = triangles.length === 0 ? void 0 : Math.max(...triangles);
1831
1850
  const results = [];
1832
1851
  const diagnostics = [];
1833
- const path = `${sourcePath ?? "playtest"}/observations.json/performanceSeries`;
1852
+ const path2 = `${sourcePath ?? "playtest"}/observations.json/performanceSeries`;
1834
1853
  const samplesPass = validSamples;
1835
1854
  results.push({
1836
1855
  details: { sampleCount: samples.length, valid: validSamples },
@@ -1841,7 +1860,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1841
1860
  diagnostics.push({
1842
1861
  code: "TN_PLAYTEST_PERFORMANCE_SAMPLES_MISSING",
1843
1862
  message: samples.length === 0 ? "Performance assertion received no render samples." : "Performance assertion received an invalid render sample series.",
1844
- observedRuntimePath: path,
1863
+ observedRuntimePath: path2,
1845
1864
  severity: "error",
1846
1865
  sourcePath,
1847
1866
  suggestion: "Run the scenario against the real render loop and keep the performance bridge provider installed."
@@ -1852,7 +1871,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1852
1871
  if (!pass) diagnostics.push({
1853
1872
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1854
1873
  message: `${id} expected at most ${expected} ${unit}, observed ${actual ?? "unavailable"}.`,
1855
- observedRuntimePath: path,
1874
+ observedRuntimePath: path2,
1856
1875
  severity: "error",
1857
1876
  sourcePath,
1858
1877
  suggestion: "Inspect the recorded frame-cost series and reduce the authored scene cost that owns the regression."
@@ -1887,7 +1906,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1887
1906
  if (!pass) diagnostics.push({
1888
1907
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1889
1908
  message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observed2 ?? "unavailable"}.`,
1890
- observedRuntimePath: path,
1909
+ observedRuntimePath: path2,
1891
1910
  severity: "error",
1892
1911
  sourcePath,
1893
1912
  suggestion: "Read the TN_FRAME_BUDGET marker for this run: it names which frame phase owns the time."
@@ -1906,7 +1925,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1906
1925
  if (!pass) diagnostics.push({
1907
1926
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1908
1927
  message: actual === void 0 ? `performance.maxPhaseMsP95.${phase} received no frame-budget phase samples; the run produced ${measured.length} of ${samples.length}.` : `performance.maxPhaseMsP95.${phase} expected at most ${ceiling} ms, observed ${actual}.`,
1909
- observedRuntimePath: path,
1928
+ observedRuntimePath: path2,
1910
1929
  severity: "error",
1911
1930
  sourcePath,
1912
1931
  suggestion: actual === void 0 ? "Keep the engine frame budget installed: defineGame({ frameBudget: false }) silences the marker but a phase ceiling still needs the per-frame split." : "Reduce the cost of that phase, or move the ceiling and say why in the scenario."
@@ -1939,7 +1958,7 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1939
1958
  if (!pass) diagnostics.push({
1940
1959
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1941
1960
  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,
1961
+ observedRuntimePath: path2,
1943
1962
  severity: "error",
1944
1963
  sourcePath,
1945
1964
  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."
@@ -3772,34 +3791,150 @@ function emitWorldTopology(value, assertions, diagnostics) {
3772
3791
  }
3773
3792
  }
3774
3793
 
3794
+ // src/runner/browser.ts
3795
+ var WEBGPU_BROWSER_ARGS = [
3796
+ "--ozone-platform=x11",
3797
+ "--enable-unsafe-webgpu",
3798
+ "--disable-gpu-sandbox",
3799
+ "--ignore-gpu-blocklist",
3800
+ // Without this Chromium never reaches the Vulkan driver on Linux and silently serves WebGPU
3801
+ // from SwiftShader, its CPU rasteriser. Nothing errors: the adapter answers, the run
3802
+ // proceeds, and the results are a software renderer's. Measured on an RTX 2080 under Xvfb,
3803
+ // `adapter.info` reads `swiftshader / google` without the flag and `turing / nvidia` with it,
3804
+ // which is the difference between blank captures and a rendered frame.
3805
+ "--enable-features=Vulkan"
3806
+ ];
3807
+ var PERFORMANCE_BROWSER_ARGS = [
3808
+ "--disable-frame-rate-limit",
3809
+ "--disable-gpu-vsync"
3810
+ ];
3811
+ function resolveBrowserArguments(browserArgs) {
3812
+ return [...browserArgs ?? []];
3813
+ }
3814
+ var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3815
+ function softwareAdapterName(adapter) {
3816
+ if (adapter === void 0) return void 0;
3817
+ for (const value of Object.values(adapter)) {
3818
+ if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3819
+ }
3820
+ return void 0;
3821
+ }
3822
+ function reconcileBrowserPointers(previous, next) {
3823
+ const normalized = new Map(next.map((pointer) => [pointer.id, {
3824
+ buttons: pointer.buttons ?? 1,
3825
+ id: pointer.id,
3826
+ x: pointer.x,
3827
+ y: pointer.y
3828
+ }]));
3829
+ const previousPrimary = previous.keys().next().value;
3830
+ const nextPrimary = normalized.keys().next().value;
3831
+ const changes = [];
3832
+ for (const pointer of previous.values()) {
3833
+ if (!normalized.has(pointer.id)) {
3834
+ changes.push({ isPrimary: pointer.id === previousPrimary, pointer: { ...pointer, buttons: 0 }, type: "pointerup" });
3835
+ }
3836
+ }
3837
+ for (const pointer of normalized.values()) {
3838
+ const old = previous.get(pointer.id);
3839
+ if (old === void 0) {
3840
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointerdown" });
3841
+ } else if (old.x !== pointer.x || old.y !== pointer.y || old.buttons !== pointer.buttons) {
3842
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointermove" });
3843
+ }
3844
+ }
3845
+ return changes;
3846
+ }
3847
+
3848
+ // src/evaluators/adapter-class.ts
3849
+ function classifyAdapter(report) {
3850
+ const capture = report.capture;
3851
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3852
+ if (adapterIdentity(capture.adapter) === void 0) return {};
3853
+ const software = softwareAdapterName(capture.adapter);
3854
+ return software === void 0 ? { adapterClass: "hardware" } : { adapterClass: "software", softwareAdapter: software };
3855
+ }
3856
+ var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3857
+ function adapterIdentity(adapter) {
3858
+ if (adapter === void 0) return void 0;
3859
+ for (const key of ADAPTER_IDENTITY_KEYS) {
3860
+ const value = adapter[key];
3861
+ if (typeof value === "string" && value.trim() !== "") return value;
3862
+ }
3863
+ return void 0;
3864
+ }
3865
+ function adapterFieldsFromIdentity(identity) {
3866
+ if (typeof identity !== "string") return void 0;
3867
+ const prefix = "webgpu:";
3868
+ if (!identity.startsWith(prefix)) return void 0;
3869
+ const fields = /* @__PURE__ */ Object.create(null);
3870
+ for (const pair of identity.slice(prefix.length).split("|")) {
3871
+ const separator = pair.indexOf("=");
3872
+ if (separator <= 0) return void 0;
3873
+ const key = pair.slice(0, separator);
3874
+ if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
3875
+ return void 0;
3876
+ }
3877
+ let value;
3878
+ try {
3879
+ value = decodeURIComponent(pair.slice(separator + 1));
3880
+ } catch {
3881
+ return void 0;
3882
+ }
3883
+ if (value.trim() === "") return void 0;
3884
+ fields[key] = value;
3885
+ }
3886
+ if (Object.keys(fields).length === 0) return void 0;
3887
+ return fields;
3888
+ }
3889
+ function nativeCaptureProvenance(census, target, viewport) {
3890
+ if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
3891
+ const adapterRecord = census.adapter;
3892
+ if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
3893
+ const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
3894
+ if (adapter === void 0) return void 0;
3895
+ return {
3896
+ adapter,
3897
+ // A native launch carries no browser command line; there is no argument list to report and
3898
+ // inventing one would be a flag nobody can check.
3899
+ browserArgs: [],
3900
+ captureMethod: "device.screenshot",
3901
+ rendererKind: "webgpu",
3902
+ target,
3903
+ viewport
3904
+ };
3905
+ }
3906
+
3775
3907
  // src/evaluators/render-chain.ts
3776
3908
  function emitRenderChain(ctx) {
3777
3909
  const assertion = ctx.scenarioAssertions.renderChain;
3778
3910
  if (assertion === void 0) return;
3779
3911
  const observed = ctx.input.report.observations?.renderChain;
3780
- if (assertion.tier !== void 0) {
3781
- const pass = observed?.tier === assertion.tier;
3912
+ const selected = selectExpectation(ctx, assertion);
3913
+ const expected = selected.expectation;
3914
+ if (expected.tier !== void 0) {
3915
+ const pass = observed?.tier === expected.tier;
3782
3916
  ctx.assertions.push({
3783
- details: { expected: assertion.tier, observed: observed?.tier },
3917
+ details: { ...selected.provenance, expected: expected.tier, observed: observed?.tier },
3784
3918
  id: "renderChain.tier",
3785
3919
  pass
3786
3920
  });
3787
3921
  if (!pass) {
3788
3922
  ctx.diagnostics.push({
3789
3923
  code: observed === void 0 ? "TN_PLAYTEST_RENDER_CHAIN_UNOBSERVABLE" : "TN_PLAYTEST_RENDER_CHAIN_TIER_FAILED",
3790
- message: observed === void 0 ? "Render-chain tier was not observed because the TN_RENDER_CHAIN marker was absent." : `Render-chain tier '${observed.tier}' did not match the asserted tier '${assertion.tier}'.`,
3924
+ message: observed === void 0 ? "Render-chain tier was not observed because the TN_RENDER_CHAIN marker was absent." : `Render-chain tier '${observed.tier}' did not match the asserted tier '${expected.tier}'.`,
3791
3925
  observedRuntimePath: "observations.json/renderChain/tier",
3792
3926
  severity: "error",
3793
3927
  suggestion: "Install the RenderChain through the renderer seam and keep its marker callback connected to the playtest bridge."
3794
3928
  });
3795
3929
  }
3796
3930
  }
3797
- const stageAssertion = assertion.stages;
3931
+ const stageAssertion = expected.stages;
3798
3932
  if (stageAssertion !== void 0) {
3799
3933
  const observedStages = observed?.stages;
3800
3934
  if (stageAssertion.includes !== void 0) {
3801
3935
  emitStageCheck(
3802
3936
  ctx,
3937
+ selected.provenance,
3803
3938
  observedStages,
3804
3939
  "includes",
3805
3940
  stageAssertion.includes,
@@ -3809,6 +3944,7 @@ function emitRenderChain(ctx) {
3809
3944
  if (stageAssertion.excludes !== void 0) {
3810
3945
  emitStageCheck(
3811
3946
  ctx,
3947
+ selected.provenance,
3812
3948
  observedStages,
3813
3949
  "excludes",
3814
3950
  stageAssertion.excludes,
@@ -3818,6 +3954,7 @@ function emitRenderChain(ctx) {
3818
3954
  if (stageAssertion.order !== void 0) {
3819
3955
  emitStageCheck(
3820
3956
  ctx,
3957
+ selected.provenance,
3821
3958
  observedStages,
3822
3959
  "order",
3823
3960
  stageAssertion.order,
@@ -3825,7 +3962,7 @@ function emitRenderChain(ctx) {
3825
3962
  );
3826
3963
  }
3827
3964
  }
3828
- const contributionAssertion = assertion.contributions;
3965
+ const contributionAssertion = expected.contributions;
3829
3966
  if (contributionAssertion !== void 0) {
3830
3967
  const observedContributions = observed?.contributions;
3831
3968
  const pass = Array.isArray(observedContributions) && contributionAssertion.graphOutputChanged.every(
@@ -3833,6 +3970,7 @@ function emitRenderChain(ctx) {
3833
3970
  );
3834
3971
  ctx.assertions.push({
3835
3972
  details: {
3973
+ ...selected.provenance,
3836
3974
  expected: contributionAssertion.graphOutputChanged,
3837
3975
  observed: observedContributions
3838
3976
  },
@@ -3849,14 +3987,15 @@ function emitRenderChain(ctx) {
3849
3987
  });
3850
3988
  }
3851
3989
  }
3852
- if (assertion.velocity !== void 0) {
3990
+ if (expected.velocity !== void 0) {
3853
3991
  const rejectionFraction = observed?.velocity.rejectionFraction;
3854
3992
  const measurementFrame = observed?.velocity.measurementFrame;
3855
3993
  const hasMeasurement = rejectionFraction !== void 0 && Number.isFinite(rejectionFraction) && typeof measurementFrame === "number" && Number.isInteger(measurementFrame) && measurementFrame >= 0;
3856
- const pass = hasMeasurement && rejectionFraction !== void 0 && rejectionFraction <= assertion.velocity.maxRejectionFraction;
3994
+ const pass = hasMeasurement && rejectionFraction !== void 0 && rejectionFraction <= expected.velocity.maxRejectionFraction;
3857
3995
  ctx.assertions.push({
3858
3996
  details: {
3859
- expected: assertion.velocity.maxRejectionFraction,
3997
+ ...selected.provenance,
3998
+ expected: expected.velocity.maxRejectionFraction,
3860
3999
  measurementFrame,
3861
4000
  observed: rejectionFraction
3862
4001
  },
@@ -3866,17 +4005,47 @@ function emitRenderChain(ctx) {
3866
4005
  if (!pass) {
3867
4006
  ctx.diagnostics.push({
3868
4007
  code: observed === void 0 || !hasMeasurement ? "TN_PLAYTEST_RENDER_CHAIN_UNOBSERVABLE" : "TN_PLAYTEST_RENDER_CHAIN_REJECTION_FAILED",
3869
- message: observed === void 0 ? "Render-chain velocity rejection was not observed because the TN_RENDER_CHAIN marker was absent." : !hasMeasurement ? "Render-chain velocity was provisioned without a fresh completed-frame history-rejection measurement." : `Render-chain history rejection fraction ${rejectionFraction ?? "missing"} exceeded the asserted ceiling ${assertion.velocity.maxRejectionFraction}.`,
4008
+ message: observed === void 0 ? "Render-chain velocity rejection was not observed because the TN_RENDER_CHAIN marker was absent." : !hasMeasurement ? "Render-chain velocity was provisioned without a fresh completed-frame history-rejection measurement." : `Render-chain history rejection fraction ${rejectionFraction ?? "missing"} exceeded the asserted ceiling ${expected.velocity.maxRejectionFraction}.`,
3870
4009
  observedRuntimePath: "observations.json/renderChain/velocity/rejectionFraction",
3871
4010
  severity: "error",
3872
4011
  suggestion: "Publish the temporal stage's measured rejection fraction on the same render-chain marker used for tier reporting."
3873
4012
  });
3874
4013
  }
3875
4014
  }
4015
+ if (assertion.perAdapter !== void 0 && selected.classification === void 0) {
4016
+ ctx.assertions.push({
4017
+ details: { ...selected.provenance, expected: Object.keys(assertion.perAdapter) },
4018
+ id: "renderChain.adapterClass",
4019
+ pass: false
4020
+ });
4021
+ ctx.diagnostics.push({
4022
+ code: "TN_PLAYTEST_RENDER_CHAIN_ADAPTER_UNCLASSIFIED",
4023
+ message: "No adapter.info field named a software rasteriser, so this run is not proven to be either adapter class and was held to the flat render-chain expectation.",
4024
+ observedRuntimePath: "observations.json/capture/adapter",
4025
+ severity: "error",
4026
+ suggestion: "Run on a lane that reports adapter.info, or drop perAdapter and assert one policy for every adapter."
4027
+ });
4028
+ }
4029
+ }
4030
+ function selectExpectation(ctx, assertion) {
4031
+ const flat = {
4032
+ ...assertion.tier === void 0 ? {} : { tier: assertion.tier },
4033
+ ...assertion.stages === void 0 ? {} : { stages: assertion.stages },
4034
+ ...assertion.contributions === void 0 ? {} : { contributions: assertion.contributions },
4035
+ ...assertion.velocity === void 0 ? {} : { velocity: assertion.velocity }
4036
+ };
4037
+ const provenance = classifyAdapter(ctx.input.report);
4038
+ const { adapterClass } = provenance;
4039
+ const branch = adapterClass === void 0 ? void 0 : assertion.perAdapter?.[adapterClass];
4040
+ return {
4041
+ classification: adapterClass,
4042
+ expectation: branch ?? flat,
4043
+ provenance
4044
+ };
3876
4045
  }
3877
- function emitStageCheck(ctx, observed, kind, expected, pass) {
4046
+ function emitStageCheck(ctx, provenance, observed, kind, expected, pass) {
3878
4047
  ctx.assertions.push({
3879
- details: { expected, observed },
4048
+ details: { ...provenance, expected, observed },
3880
4049
  id: `renderChain.stages.${kind}`,
3881
4050
  pass
3882
4051
  });
@@ -4910,7 +5079,8 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4910
5079
  "tier": (value) => typeof value === "string" && value.trim() !== "",
4911
5080
  "stages": (value) => isRecord2(value),
4912
5081
  "contributions": (value) => isRecord2(value),
4913
- "velocity": (value) => isRecord2(value)
5082
+ "velocity": (value) => isRecord2(value),
5083
+ "perAdapter": (value) => isRecord2(value)
4914
5084
  })
4915
5085
  });
4916
5086
 
@@ -5208,6 +5378,33 @@ function validateParityAssertion(value, scenarioPath, objectPath) {
5208
5378
  }
5209
5379
  function validateRenderChainAssertion(value, scenarioPath, objectPath) {
5210
5380
  const record4 = requireRecord(value, scenarioPath, objectPath);
5381
+ const perAdapter = record4.perAdapter === void 0 ? void 0 : validateRenderChainPerAdapter(record4.perAdapter, scenarioPath, `${objectPath}.perAdapter`);
5382
+ const expectation = validateRenderChainExpectation(record4, scenarioPath, objectPath);
5383
+ return perAdapter === void 0 ? expectation : { ...expectation, perAdapter };
5384
+ }
5385
+ function validateRenderChainPerAdapter(value, scenarioPath, objectPath) {
5386
+ const record4 = requireRecord(value, scenarioPath, objectPath);
5387
+ const entries = Object.entries(record4);
5388
+ if (entries.length === 0) {
5389
+ throw invalidScenario(scenarioPath, `'${objectPath}' must name at least one adapter class.`);
5390
+ }
5391
+ const result = {};
5392
+ for (const [kind, branch] of entries) {
5393
+ if (kind !== "hardware" && kind !== "software") {
5394
+ throw invalidScenario(
5395
+ scenarioPath,
5396
+ `'${objectPath}.${kind}' is not an adapter class this harness can classify; expected hardware or software.`
5397
+ );
5398
+ }
5399
+ result[kind] = validateRenderChainExpectation(
5400
+ requireRecord(branch, scenarioPath, `${objectPath}.${kind}`),
5401
+ scenarioPath,
5402
+ `${objectPath}.${kind}`
5403
+ );
5404
+ }
5405
+ return result;
5406
+ }
5407
+ function validateRenderChainExpectation(record4, scenarioPath, objectPath) {
5211
5408
  const tier = record4.tier;
5212
5409
  if (tier !== void 0 && tier !== "high" && tier !== "medium" && tier !== "low" && tier !== "off") {
5213
5410
  throw invalidScenario(scenarioPath, `'${objectPath}.tier' must be high, medium, low, or off, received ${describeValue(tier)}.`);
@@ -5770,29 +5967,30 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
5770
5967
  `assert.${kind}${suffix}.runtime`
5771
5968
  );
5772
5969
  }
5773
- if (kind === "renderChain" && isRecord3(value.velocity)) {
5774
- rejectUnknownKeys(
5775
- value.velocity,
5776
- ["maxRejectionFraction"],
5777
- scenarioPath,
5778
- `assert.${kind}${suffix}.velocity`
5779
- );
5780
- }
5781
- if (kind === "renderChain" && isRecord3(value.contributions)) {
5782
- rejectUnknownKeys(
5783
- value.contributions,
5784
- ["graphOutputChanged"],
5785
- scenarioPath,
5786
- `assert.${kind}${suffix}.contributions`
5787
- );
5970
+ if (kind === "renderChain") {
5971
+ rejectRenderChainExpectationKeys(value, scenarioPath, `assert.${kind}${suffix}`);
5972
+ if (isRecord3(value.perAdapter)) {
5973
+ const branchPath = `assert.renderChain${suffix}.perAdapter`;
5974
+ rejectUnknownKeys(value.perAdapter, ["hardware", "software"], scenarioPath, branchPath);
5975
+ for (const [adapterKind, branch] of Object.entries(value.perAdapter)) {
5976
+ if (isRecord3(branch)) {
5977
+ rejectUnknownKeys(branch, ["contributions", "stages", "tier", "velocity"], scenarioPath, `${branchPath}.${adapterKind}`);
5978
+ rejectRenderChainExpectationKeys(branch, scenarioPath, `${branchPath}.${adapterKind}`);
5979
+ }
5980
+ }
5981
+ }
5788
5982
  }
5789
- if (kind === "renderChain" && isRecord3(value.stages)) {
5790
- rejectUnknownKeys(
5791
- value.stages,
5792
- ["excludes", "includes", "order"],
5793
- scenarioPath,
5794
- `assert.${kind}${suffix}.stages`
5795
- );
5983
+ }
5984
+ var RENDER_CHAIN_NESTED_KEYS = {
5985
+ contributions: ["graphOutputChanged"],
5986
+ stages: ["excludes", "includes", "order"],
5987
+ velocity: ["maxRejectionFraction"]
5988
+ };
5989
+ function rejectRenderChainExpectationKeys(value, scenarioPath, objectPath) {
5990
+ for (const [field, keys] of Object.entries(RENDER_CHAIN_NESTED_KEYS)) {
5991
+ if (isRecord3(value[field])) {
5992
+ rejectUnknownKeys(value[field], keys, scenarioPath, `${objectPath}.${field}`);
5993
+ }
5796
5994
  }
5797
5995
  }
5798
5996
 
@@ -6093,6 +6291,7 @@ var PLAYTEST_STEP_KEYS = [
6093
6291
  "holdTicks",
6094
6292
  "kind",
6095
6293
  "label",
6294
+ "lifecycle",
6096
6295
  "overlayMessage",
6097
6296
  "pitch",
6098
6297
  "pointerPosition",
@@ -6129,6 +6328,7 @@ function validateStep(value, scenarioPath, index) {
6129
6328
  "holdFrames",
6130
6329
  "holdTicks",
6131
6330
  "kind",
6331
+ "lifecycle",
6132
6332
  "overlayMessage",
6133
6333
  "pitch",
6134
6334
  "pointerPosition",
@@ -6178,9 +6378,9 @@ function validateStep(value, scenarioPath, index) {
6178
6378
  const holdTicks = positiveInteger(value.holdTicks);
6179
6379
  const waitFrames2 = positiveInteger(value.waitFrames);
6180
6380
  const waitTicks = positiveInteger(value.waitTicks);
6181
- const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
6381
+ const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "lifecycle" ? "lifecycle" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
6182
6382
  if (value.kind !== void 0 && kind === void 0) {
6183
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', or 'wait'.`);
6383
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
6184
6384
  }
6185
6385
  const at = validateClickTarget(value.at, scenarioPath, index);
6186
6386
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -6194,6 +6394,10 @@ function validateStep(value, scenarioPath, index) {
6194
6394
  if (isRecord3(value.window)) {
6195
6395
  rejectUnknownKeys(value.window, ["height", "operation", "width"], scenarioPath, `steps[${index}].window`);
6196
6396
  }
6397
+ if (isRecord3(value.lifecycle)) {
6398
+ rejectUnknownKeys(value.lifecycle, ["operation", "rotation"], scenarioPath, `steps[${index}].lifecycle`);
6399
+ }
6400
+ const lifecycle = validateLifecycleStep(value.lifecycle, scenarioPath, index);
6197
6401
  if (kind !== "click" && (at !== void 0 || value.at !== void 0)) {
6198
6402
  throw invalidStep(scenarioPath, `Scenario step ${index} declares at, which belongs to kind 'click'.`);
6199
6403
  }
@@ -6260,8 +6464,38 @@ function validateStep(value, scenarioPath, index) {
6260
6464
  if (value.window !== void 0 && window2 === void 0) {
6261
6465
  throw invalidStep(scenarioPath, `Scenario step ${index} window must define minimize, restore, or resize with positive width and height.`);
6262
6466
  }
6263
- if (at === void 0 && press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && pointers === void 0 && wheel === void 0 && window2 === void 0 && waitFrames2 === void 0 && waitTicks === void 0 && target === void 0 && waitForResource2 === void 0) {
6264
- throw invalidStep(scenarioPath, `Scenario step ${index} must define click at, press, overlayMessage, pointerPosition, pointers, wheel, window, aimAt target, or waitFrames/waitTicks.`);
6467
+ if (value.lifecycle !== void 0 && lifecycle === void 0) {
6468
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle must define an operation of 'background', 'foreground', or 'rotate', and 'rotate' must name a rotation from 0 through 3.`);
6469
+ }
6470
+ if (kind !== "lifecycle" && value.lifecycle !== void 0) {
6471
+ throw invalidStep(scenarioPath, `Scenario step ${index} declares lifecycle, which belongs to kind 'lifecycle'.`);
6472
+ }
6473
+ if (kind === "lifecycle") {
6474
+ if (lifecycle === void 0) {
6475
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'lifecycle' must define lifecycle.operation.`);
6476
+ }
6477
+ for (const forbidden of [
6478
+ "holdFrames",
6479
+ "holdTicks",
6480
+ "label",
6481
+ "overlayMessage",
6482
+ "pointerPosition",
6483
+ "pointers",
6484
+ "press",
6485
+ "screenshot",
6486
+ "target",
6487
+ "waitFrames",
6488
+ "waitTicks",
6489
+ "wheel",
6490
+ "window"
6491
+ ]) {
6492
+ if (value[forbidden] !== void 0) {
6493
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'lifecycle' cannot define ${forbidden}; a lifecycle step is one device operation and nothing else.`);
6494
+ }
6495
+ }
6496
+ }
6497
+ if (at === void 0 && press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && pointers === void 0 && wheel === void 0 && window2 === void 0 && waitFrames2 === void 0 && waitTicks === void 0 && target === void 0 && waitForResource2 === void 0 && lifecycle === void 0) {
6498
+ throw invalidStep(scenarioPath, `Scenario step ${index} must define click at, press, overlayMessage, pointerPosition, pointers, wheel, window, aimAt target, lifecycle operation, or waitFrames/waitTicks.`);
6265
6499
  }
6266
6500
  if (value.holdFrames !== void 0 && holdFrames === void 0) {
6267
6501
  throw invalidStep(scenarioPath, `Scenario step ${index} holdFrames must be a positive integer.`);
@@ -6290,6 +6524,7 @@ function validateStep(value, scenarioPath, index) {
6290
6524
  ...holdTicks === void 0 ? {} : { holdTicks },
6291
6525
  ...typeof value.label === "string" ? { label: value.label } : {},
6292
6526
  ...at === void 0 ? {} : { at },
6527
+ ...lifecycle === void 0 ? {} : { lifecycle },
6293
6528
  ...overlayMessage === void 0 ? {} : { overlayMessage },
6294
6529
  ...pitch === void 0 ? {} : { pitch },
6295
6530
  ...pointerPosition === void 0 ? {} : { pointerPosition },
@@ -6306,6 +6541,22 @@ function validateStep(value, scenarioPath, index) {
6306
6541
  ...window2 === void 0 ? {} : { window: window2 }
6307
6542
  };
6308
6543
  }
6544
+ function validateLifecycleStep(value, scenarioPath, index) {
6545
+ if (!isRecord3(value)) return void 0;
6546
+ const rotation = value.rotation;
6547
+ const rotationValue = typeof rotation === "number" && Number.isInteger(rotation) && rotation >= 0 && rotation <= 3 ? rotation : void 0;
6548
+ if (value.operation === "rotate") {
6549
+ if (rotationValue === void 0) {
6550
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle.operation 'rotate' must name a rotation from 0 through 3.`);
6551
+ }
6552
+ return { operation: "rotate", rotation: rotationValue };
6553
+ }
6554
+ if (value.operation !== "background" && value.operation !== "foreground") return void 0;
6555
+ if (rotation !== void 0) {
6556
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle.operation '${value.operation}' cannot define rotation; only 'rotate' takes one.`);
6557
+ }
6558
+ return { operation: value.operation };
6559
+ }
6309
6560
  function validateResourceWait(value, scenarioPath, index) {
6310
6561
  const objectPath = `steps[${index}].waitForResource`;
6311
6562
  if (!isRecord3(value)) {
@@ -6327,8 +6578,8 @@ function validateResourceWait(value, scenarioPath, index) {
6327
6578
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource.lte must be a finite number.`);
6328
6579
  }
6329
6580
  const id = requireString(value, "id", scenarioPath, objectPath);
6330
- const path = requireString(value, "path", scenarioPath, objectPath);
6331
- if (path.split(".").some((part) => part.length === 0)) {
6581
+ const path2 = requireString(value, "path", scenarioPath, objectPath);
6582
+ if (path2.split(".").some((part) => part.length === 0)) {
6332
6583
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource.path must be a non-empty dot path.`);
6333
6584
  }
6334
6585
  return {
@@ -6336,7 +6587,7 @@ function validateResourceWait(value, scenarioPath, index) {
6336
6587
  ...gte === void 0 ? {} : { gte },
6337
6588
  id,
6338
6589
  ...lte === void 0 ? {} : { lte },
6339
- path
6590
+ path: path2
6340
6591
  };
6341
6592
  }
6342
6593
  function validateClickTarget(value, scenarioPath, index) {
@@ -6371,17 +6622,17 @@ function validateAimTarget(value, scenarioPath, stepIndex) {
6371
6622
  return { x, z };
6372
6623
  }
6373
6624
  function validatePointer(value, scenarioPath, stepIndex, pointerIndex) {
6374
- const path = `steps[${stepIndex}].pointers[${pointerIndex}]`;
6375
- if (!isRecord3(value)) throw invalidStep(scenarioPath, `${path} must be an object.`);
6376
- rejectUnknownKeys(value, ["buttons", "id", "x", "y"], scenarioPath, path);
6625
+ const path2 = `steps[${stepIndex}].pointers[${pointerIndex}]`;
6626
+ if (!isRecord3(value)) throw invalidStep(scenarioPath, `${path2} must be an object.`);
6627
+ rejectUnknownKeys(value, ["buttons", "id", "x", "y"], scenarioPath, path2);
6377
6628
  if (!Number.isInteger(value.id) || value.id < 1) {
6378
- throw invalidStep(scenarioPath, `${path}.id must be a positive integer.`);
6629
+ throw invalidStep(scenarioPath, `${path2}.id must be a positive integer.`);
6379
6630
  }
6380
6631
  if (typeof value.x !== "number" || !Number.isFinite(value.x) || value.x < 0 || value.x > 1 || typeof value.y !== "number" || !Number.isFinite(value.y) || value.y < 0 || value.y > 1) {
6381
- throw invalidStep(scenarioPath, `${path} must define normalized x and y values from 0 through 1.`);
6632
+ throw invalidStep(scenarioPath, `${path2} must define normalized x and y values from 0 through 1.`);
6382
6633
  }
6383
6634
  if (value.buttons !== void 0 && (!Number.isInteger(value.buttons) || value.buttons < 1)) {
6384
- throw invalidStep(scenarioPath, `${path}.buttons must be a positive integer when present.`);
6635
+ throw invalidStep(scenarioPath, `${path2}.buttons must be a positive integer when present.`);
6385
6636
  }
6386
6637
  return {
6387
6638
  ...typeof value.buttons === "number" ? { buttons: value.buttons } : {},
@@ -6403,9 +6654,9 @@ function validateStepLabels(steps, assertions, scenarioPath) {
6403
6654
  labels.add(step.label);
6404
6655
  }
6405
6656
  if (assertions === void 0) return;
6406
- const requireLabel = (label, path) => {
6657
+ const requireLabel = (label, path2) => {
6407
6658
  if (label !== void 0 && !labels.has(label)) {
6408
- throw invalidScenario(scenarioPath, `Assertion '${path}' names step label '${label}', but no scenario step defines it.`);
6659
+ throw invalidScenario(scenarioPath, `Assertion '${path2}' names step label '${label}', but no scenario step defines it.`);
6409
6660
  }
6410
6661
  };
6411
6662
  for (const [index, assertion] of (assertions.resources ?? []).entries()) {
@@ -6979,7 +7230,7 @@ var STANDALONE_PLAYTEST_OBSERVATION_FIELDS = [
6979
7230
  "startup",
6980
7231
  "visual"
6981
7232
  ];
6982
- var HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceMetrics"];
7233
+ var HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics"];
6983
7234
 
6984
7235
  // src/runner/setup-confirmation.ts
6985
7236
  function unconfirmed(requested, confirmation) {
@@ -7009,6 +7260,7 @@ function setupApplication(requested, confirmation) {
7009
7260
 
7010
7261
  // src/runner/shared.ts
7011
7262
  var UNHANDLED_REJECTION_PREFIX = "__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:";
7263
+ var SCREENSHOT_TIMEOUT_MS = 12e4;
7012
7264
  var MAX_FIXED_STEP_STARTUP_RETRIES = 120;
7013
7265
  var STOPPED_LOOP_ERROR = "Cannot advance a stopped loop.";
7014
7266
  var ManagedServerError = class extends Error {
@@ -7085,9 +7337,9 @@ function setupRequest(scenario) {
7085
7337
  }))
7086
7338
  },
7087
7339
  ...scenario.setup?.resources === void 0 ? {} : {
7088
- resources: scenario.setup.resources.map(({ id, path, value }) => ({
7340
+ resources: scenario.setup.resources.map(({ id, path: path2, value }) => ({
7089
7341
  id,
7090
- ...path === void 0 ? {} : { path },
7342
+ ...path2 === void 0 ? {} : { path: path2 },
7091
7343
  value
7092
7344
  }))
7093
7345
  }
@@ -7412,13 +7664,13 @@ function unavailableObservation(scenario) {
7412
7664
  reason: `Assertion '${entry.kind}' is not supported on target '${scenario.target}'.`
7413
7665
  };
7414
7666
  }
7415
- for (const path of requiredObservationPaths(scenario, entry.kind, entry.observationPath)) {
7416
- if (HOST_OBSERVATION_FIELD_SET.includes(path)) continue;
7417
- if (!STANDALONE_OBSERVATION_FIELD_SET.includes(path)) {
7667
+ for (const path2 of requiredObservationPaths(scenario, entry.kind, entry.observationPath)) {
7668
+ if (HOST_OBSERVATION_FIELD_SET.includes(path2)) continue;
7669
+ if (!STANDALONE_OBSERVATION_FIELD_SET.includes(path2)) {
7418
7670
  return {
7419
7671
  assertion: entry.kind,
7420
- path,
7421
- reason: `The standalone runner does not produce an ${path} observation required by this assertion.`
7672
+ path: path2,
7673
+ reason: `The standalone runner does not produce an ${path2} observation required by this assertion.`
7422
7674
  };
7423
7675
  }
7424
7676
  }
@@ -7483,95 +7735,223 @@ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_
7483
7735
  if (timeout !== void 0) clearTimeout(timeout);
7484
7736
  }
7485
7737
  }
7486
-
7487
- // src/runner/browser.ts
7488
- var WEBGPU_BROWSER_ARGS = [
7489
- "--ozone-platform=x11",
7490
- "--enable-unsafe-webgpu",
7491
- "--disable-gpu-sandbox",
7492
- "--ignore-gpu-blocklist",
7493
- // Without this Chromium never reaches the Vulkan driver on Linux and silently serves WebGPU
7494
- // from SwiftShader, its CPU rasteriser. Nothing errors: the adapter answers, the run
7495
- // proceeds, and the results are a software renderer's. Measured on an RTX 2080 under Xvfb,
7496
- // `adapter.info` reads `swiftshader / google` without the flag and `turing / nvidia` with it,
7497
- // which is the difference between blank captures and a rendered frame.
7498
- "--enable-features=Vulkan"
7499
- ];
7500
- var PERFORMANCE_BROWSER_ARGS = [
7501
- "--disable-frame-rate-limit",
7502
- "--disable-gpu-vsync"
7503
- ];
7504
- function resolveBrowserArguments(browserArgs) {
7505
- return [...browserArgs ?? []];
7506
- }
7507
- var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
7508
- function softwareAdapterName(adapter) {
7509
- if (adapter === void 0) return void 0;
7510
- for (const value of Object.values(adapter)) {
7511
- if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
7738
+ var DEFAULT_XVFB_SCREEN = "1600x900x24";
7739
+ var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
7740
+ var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
7741
+ var X11_SOCKET_DIR = "/tmp/.X11-unix";
7742
+ function decideDisplayStrategy(input) {
7743
+ if (input.platform !== "linux") return { kind: "host" };
7744
+ const privateXvfb = {
7745
+ kind: "private-xvfb",
7746
+ screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
7747
+ };
7748
+ if (!hostDisplayRequested(input.env)) return privateXvfb;
7749
+ const display = input.env.DISPLAY;
7750
+ if (display !== void 0 && display.length > 0 && (input.displaySocketExists ?? x11SocketExists)(display)) {
7751
+ return { display, kind: "existing" };
7512
7752
  }
7513
- return void 0;
7753
+ return privateXvfb;
7514
7754
  }
7515
- function reconcileBrowserPointers(previous, next) {
7516
- const normalized = new Map(next.map((pointer) => [pointer.id, {
7517
- buttons: pointer.buttons ?? 1,
7518
- id: pointer.id,
7519
- x: pointer.x,
7520
- y: pointer.y
7521
- }]));
7522
- const previousPrimary = previous.keys().next().value;
7523
- const nextPrimary = normalized.keys().next().value;
7524
- const changes = [];
7525
- for (const pointer of previous.values()) {
7526
- if (!normalized.has(pointer.id)) {
7527
- changes.push({ isPrimary: pointer.id === previousPrimary, pointer: { ...pointer, buttons: 0 }, type: "pointerup" });
7528
- }
7529
- }
7530
- for (const pointer of normalized.values()) {
7531
- const old = previous.get(pointer.id);
7532
- if (old === void 0) {
7533
- changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointerdown" });
7534
- } else if (old.x !== pointer.x || old.y !== pointer.y || old.buttons !== pointer.buttons) {
7535
- changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointermove" });
7536
- }
7537
- }
7538
- return changes;
7755
+ function hostDisplayRequested(env) {
7756
+ const value = env[HOST_DISPLAY_ENV];
7757
+ return value === "1" || value?.toLowerCase() === "true";
7539
7758
  }
7540
- var execFileAsync = promisify(execFile);
7541
- var AdbAndroidDriver = class _AdbAndroidDriver {
7542
- constructor(options) {
7543
- this.options = options;
7544
- this.adbPath = options.adbPath ?? discoverAdb();
7545
- this.user = options.user === void 0 ? void 0 : validateAndroidUser(options.user);
7546
- if (options.touchRotation !== void 0) {
7547
- if (![0, 1, 2, 3].includes(options.touchRotation)) {
7548
- throw new Error(
7549
- `TN_PLAYTEST_ANDROID_ROTATION_INVALID: touch rotation must be 0, 1, 2 or 3, got '${String(options.touchRotation)}'.`
7550
- );
7551
- }
7552
- this.rotation = options.touchRotation;
7553
- }
7554
- }
7555
- options;
7556
- static COVERAGE_VIDEO_PATH = "/sdcard/tn-playtest-framebuffer-coverage.mp4";
7557
- adbPath;
7558
- screenrecord;
7559
- screenrecordError;
7560
- touchSlots = /* @__PURE__ */ new Map();
7561
- nextTrackingId = 100;
7562
- rotation;
7563
- touchViewport;
7564
- user;
7565
- activeUser;
7566
- viewportPresented = false;
7567
- async prepare(endpoint, mailboxRoot, viewport) {
7568
- const url = new URL(endpoint);
7569
- const port = url.port;
7570
- const user = await this.resolveUser();
7571
- this.activeUser = user;
7572
- await this.adb(["reverse", `tcp:${port}`, `tcp:${port}`]);
7573
- await this.adb(["shell", "am", "force-stop", "--user", user, this.options.packageName]);
7574
- if (viewport !== void 0) await this.presentViewport(viewport);
7759
+ function x11SocketExists(display) {
7760
+ const number = displayNumber(display);
7761
+ return number === void 0 ? false : existsSync(join(X11_SOCKET_DIR, `X${number}`));
7762
+ }
7763
+ function displayNumber(display) {
7764
+ const parsed = Number.parseInt(display.replace(/^:/u, ""), 10);
7765
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
7766
+ }
7767
+ function childEnvForDisplay(env, display) {
7768
+ const child = { ...env };
7769
+ for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
7770
+ child.DISPLAY = display;
7771
+ return child;
7772
+ }
7773
+ function runNeedsPixels(config, scenario) {
7774
+ if (config.headless !== true) return true;
7775
+ const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
7776
+ const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0;
7777
+ return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
7778
+ }
7779
+ async function provideDisplay(options = {}) {
7780
+ const env = options.env ?? process.env;
7781
+ const platform = options.platform ?? process.platform;
7782
+ const strategy = decideDisplayStrategy({
7783
+ displaySocketExists: options.displaySocketExists,
7784
+ env,
7785
+ platform
7786
+ });
7787
+ if (strategy.kind === "host") {
7788
+ return {
7789
+ compositor: void 0,
7790
+ display: void 0,
7791
+ env: { ...env },
7792
+ release: async () => void 0,
7793
+ strategy
7794
+ };
7795
+ }
7796
+ if (strategy.kind === "existing") {
7797
+ return {
7798
+ compositor: void 0,
7799
+ display: strategy.display,
7800
+ env: childEnvForDisplay(env, strategy.display),
7801
+ release: async () => void 0,
7802
+ strategy
7803
+ };
7804
+ }
7805
+ const commandExists = options.commandExists ?? defaultCommandExists;
7806
+ if (!commandExists("Xvfb")) {
7807
+ throw new Error(
7808
+ "No usable X display is available and Xvfb is not installed, so this pixel-producing run cannot start (Debian/Ubuntu 'xvfb', Arch 'xorg-server-xvfb', Fedora 'xorg-x11-server-Xvfb'). Refusing to render blind."
7809
+ );
7810
+ }
7811
+ const spawnProcess = options.spawnProcess ?? spawn;
7812
+ const xvfb = spawnProcess("Xvfb", [
7813
+ "-displayfd",
7814
+ "3",
7815
+ "-nolisten",
7816
+ "tcp",
7817
+ // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
7818
+ // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
7819
+ // does not enable them by default, so every native UI run on a private display reported
7820
+ // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
7821
+ // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
7822
+ // the box on a freshly scaffolded project. A browser run does not care either way.
7823
+ "+extension",
7824
+ "COMPOSITE",
7825
+ "+extension",
7826
+ "SHAPE",
7827
+ "-screen",
7828
+ "0",
7829
+ strategy.screen
7830
+ ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
7831
+ xvfb.on?.("error", () => void 0);
7832
+ try {
7833
+ const number = await readXvfbDisplayNumber(xvfb);
7834
+ const display = `:${number}`;
7835
+ const compositor = await startCompositor(display, { commandExists, env, spawnProcess });
7836
+ return {
7837
+ compositor: compositor?.name,
7838
+ display,
7839
+ env: childEnvForDisplay(env, display),
7840
+ release: async () => {
7841
+ if (compositor !== void 0) await stopChild(compositor.child);
7842
+ await stopChild(xvfb);
7843
+ },
7844
+ strategy
7845
+ };
7846
+ } catch (error) {
7847
+ await stopChild(xvfb);
7848
+ throw error;
7849
+ }
7850
+ }
7851
+ var COMPOSITORS = [
7852
+ { args: ["-n"], name: "xcompmgr" },
7853
+ { args: [], name: "picom" },
7854
+ { args: [], name: "compton" }
7855
+ ];
7856
+ var COMPOSITOR_SETTLE_MS = 250;
7857
+ async function startCompositor(display, options) {
7858
+ const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
7859
+ if (choice === void 0) return void 0;
7860
+ const child = options.spawnProcess(choice.name, [...choice.args], {
7861
+ env: { ...options.env, DISPLAY: display },
7862
+ stdio: "ignore"
7863
+ });
7864
+ let spawnFailed = false;
7865
+ child.on?.("error", () => {
7866
+ spawnFailed = true;
7867
+ });
7868
+ await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
7869
+ if (spawnFailed) return void 0;
7870
+ if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
7871
+ return { child, name: choice.name };
7872
+ }
7873
+ var XVFB_DISPLAY_TIMEOUT_MS = 1e4;
7874
+ async function readXvfbDisplayNumber(xvfb) {
7875
+ const report = xvfb.stdio[3];
7876
+ if (report === null || report === void 0 || typeof report.on !== "function") {
7877
+ throw new Error("Xvfb was spawned without a display-report descriptor to read.");
7878
+ }
7879
+ const stream = report;
7880
+ return new Promise((resolveDisplay, rejectDisplay) => {
7881
+ let settled = false;
7882
+ const finish = (settle) => {
7883
+ if (settled) return;
7884
+ settled = true;
7885
+ clearTimeout(timer);
7886
+ stream.removeListener("data", onData);
7887
+ stream.removeListener("close", onClose);
7888
+ settle();
7889
+ };
7890
+ const onData = (chunk) => {
7891
+ const number = Number.parseInt(String(chunk).trim(), 10);
7892
+ if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
7893
+ };
7894
+ const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
7895
+ const timer = setTimeout(() => finish(() => {
7896
+ rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
7897
+ }), XVFB_DISPLAY_TIMEOUT_MS);
7898
+ stream.on("data", onData);
7899
+ stream.on("close", onClose);
7900
+ });
7901
+ }
7902
+ async function stopChild(child) {
7903
+ const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
7904
+ if (exitedAlready()) return;
7905
+ child.kill("SIGTERM");
7906
+ const started = Date.now();
7907
+ while (Date.now() - started < 1e3 && !exitedAlready()) {
7908
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
7909
+ }
7910
+ if (!exitedAlready()) child.kill("SIGKILL");
7911
+ }
7912
+ function defaultCommandExists(command) {
7913
+ const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
7914
+ return paths.some((directory) => existsSync(join(directory, command)));
7915
+ }
7916
+ var execFileAsync = promisify(execFile);
7917
+ var AdbAndroidDriver = class _AdbAndroidDriver {
7918
+ constructor(options) {
7919
+ this.options = options;
7920
+ this.adbPath = options.adbPath ?? discoverAdb();
7921
+ this.user = options.user === void 0 ? void 0 : validateAndroidUser(options.user);
7922
+ if (options.touchRotation !== void 0) {
7923
+ if (![0, 1, 2, 3].includes(options.touchRotation)) {
7924
+ throw new Error(
7925
+ `TN_PLAYTEST_ANDROID_ROTATION_INVALID: touch rotation must be 0, 1, 2 or 3, got '${String(options.touchRotation)}'.`
7926
+ );
7927
+ }
7928
+ this.rotation = options.touchRotation;
7929
+ }
7930
+ }
7931
+ options;
7932
+ static COVERAGE_VIDEO_PATH = "/sdcard/tn-playtest-framebuffer-coverage.mp4";
7933
+ /** Bounded polls for a lifecycle operation to become visible to the device's own readings. */
7934
+ static LIFECYCLE_ATTEMPTS = 50;
7935
+ adbPath;
7936
+ screenrecord;
7937
+ screenrecordError;
7938
+ touchSlots = /* @__PURE__ */ new Map();
7939
+ nextTrackingId = 100;
7940
+ rotation;
7941
+ touchViewport;
7942
+ user;
7943
+ activeUser;
7944
+ /** Set by a lifecycle `rotate`, whose display lock `stop()` has to free on its own account. */
7945
+ lifecycleRotationLocked = false;
7946
+ viewportPresented = false;
7947
+ async prepare(endpoint, mailboxRoot, viewport) {
7948
+ const url = new URL(endpoint);
7949
+ const port = url.port;
7950
+ const user = await this.resolveUser();
7951
+ this.activeUser = user;
7952
+ await this.adb(["reverse", `tcp:${port}`, `tcp:${port}`]);
7953
+ await this.adb(["shell", "am", "force-stop", "--user", user, this.options.packageName]);
7954
+ if (viewport !== void 0) await this.presentViewport(viewport);
7575
7955
  await this.adb(["logcat", "-c"]);
7576
7956
  await this.adb([
7577
7957
  "shell",
@@ -7625,6 +8005,80 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7625
8005
  async tap(x, y) {
7626
8006
  await this.adb(tapCommand(x, y));
7627
8007
  }
8008
+ /**
8009
+ * The three device operations a `lifecycle` step names, each waiting for the device to *report*
8010
+ * the effect rather than for the command to return.
8011
+ *
8012
+ * `input keyevent 3` and `am start` both answer `OK` whether or not anything moved, and `wm
8013
+ * user-rotation lock` answers the same way on a device whose rotation is pinned. A step that
8014
+ * recorded a phase on the strength of the exit code alone would certify a device that never went
8015
+ * away — which is the exact value the gate exists to read off the phone, so each op polls the
8016
+ * reading it is about to claim and throws when the claim is false.
8017
+ */
8018
+ async background() {
8019
+ await this.adb(["shell", "input", "keyevent", "3"]);
8020
+ await this.waitForFocus(false);
8021
+ }
8022
+ async foreground() {
8023
+ const user = this.activeUser ?? await this.resolveUser();
8024
+ await this.adb([
8025
+ "shell",
8026
+ "am",
8027
+ "start",
8028
+ "--user",
8029
+ user,
8030
+ "-n",
8031
+ `${this.options.packageName}/${this.options.activity}`
8032
+ ]);
8033
+ await this.waitForFocus(true);
8034
+ }
8035
+ async rotate(rotation) {
8036
+ if (![0, 1, 2, 3].includes(rotation)) {
8037
+ throw new Error(
8038
+ `TN_PLAYTEST_ANDROID_ROTATION_INVALID: rotation must be 0, 1, 2 or 3, got '${String(rotation)}'.`
8039
+ );
8040
+ }
8041
+ await this.adb(["shell", "wm", "user-rotation", "lock", String(rotation)]);
8042
+ this.lifecycleRotationLocked = true;
8043
+ let observed;
8044
+ for (let attempt = 0; attempt < _AdbAndroidDriver.LIFECYCLE_ATTEMPTS; attempt += 1) {
8045
+ observed = windowRotationFromDump(await this.adb(["shell", "dumpsys", "window"]));
8046
+ if (observed === rotation) return;
8047
+ await delay(100);
8048
+ }
8049
+ throw new Error(
8050
+ `TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED: asked the device for rotation ${rotation} and dumpsys window still reports ${String(observed)}.`
8051
+ );
8052
+ }
8053
+ async lifecycleState() {
8054
+ const [pids, window2, frames] = await Promise.all([
8055
+ this.adb(["shell", "pidof", this.options.packageName]),
8056
+ this.adb(["shell", "dumpsys", "window"]),
8057
+ this.adb(["shell", "dumpsys", "gfxinfo", this.options.packageName])
8058
+ ]);
8059
+ const pid = parseAndroidAppPid(pids);
8060
+ const appFrames = parseAndroidAppFrames(frames);
8061
+ const windowRotation = windowRotationFromDump(window2);
8062
+ return {
8063
+ focused: windowHasFocus(window2, this.options.packageName),
8064
+ ...appFrames === void 0 ? {} : { frames: appFrames },
8065
+ ...pid === void 0 ? {} : { pid },
8066
+ ...windowRotation === void 0 ? {} : { windowRotation }
8067
+ };
8068
+ }
8069
+ async waitForFocus(expected) {
8070
+ for (let attempt = 0; attempt < _AdbAndroidDriver.LIFECYCLE_ATTEMPTS; attempt += 1) {
8071
+ const focused = windowHasFocus(
8072
+ await this.adb(["shell", "dumpsys", "window"]),
8073
+ this.options.packageName
8074
+ );
8075
+ if (focused === expected) return;
8076
+ await delay(100);
8077
+ }
8078
+ throw new Error(
8079
+ `TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED: the device still reports '${this.options.packageName}' as ${expected ? "not focused" : "focused"} after the operation.`
8080
+ );
8081
+ }
7628
8082
  /**
7629
8083
  * Dismiss the soft keyboard and wait for it to actually be gone.
7630
8084
  *
@@ -7651,14 +8105,14 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7651
8105
  const output = await this.adb(["logcat", "-d", "-v", "brief"]);
7652
8106
  return parseAndroidConsole(output);
7653
8107
  }
7654
- async screenshot(path) {
8108
+ async screenshot(path2) {
7655
8109
  const { stdout } = await execFileAsync(this.adbPath, [
7656
8110
  ...this.serialArgs(),
7657
8111
  "exec-out",
7658
8112
  "screencap",
7659
8113
  "-p"
7660
8114
  ], { encoding: "buffer", maxBuffer: 32 * 1024 * 1024 });
7661
- await writeFile(path, stdout);
8115
+ await writeFile(path2, stdout);
7662
8116
  }
7663
8117
  async startScreenRecording() {
7664
8118
  if (this.screenrecord !== void 0) {
@@ -7689,7 +8143,7 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7689
8143
  throw error;
7690
8144
  }
7691
8145
  }
7692
- async stopScreenRecording(path) {
8146
+ async stopScreenRecording(path2) {
7693
8147
  const recorder = this.screenrecord;
7694
8148
  if (recorder === void 0) {
7695
8149
  throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_NOT_ACTIVE");
@@ -7700,8 +8154,8 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7700
8154
  const pids = (await this.adb(["shell", "pidof", "screenrecord"]).catch(() => "")).trim().split(/\s+/u).filter((pid) => /^\d+$/u.test(pid));
7701
8155
  for (const pid of pids) await this.adb(["shell", "kill", "-2", pid]);
7702
8156
  await waitForProcessExit(recorder, 5e3);
7703
- await this.adb(["pull", _AdbAndroidDriver.COVERAGE_VIDEO_PATH, path]);
7704
- if ((await stat(path)).size === 0) {
8157
+ await this.adb(["pull", _AdbAndroidDriver.COVERAGE_VIDEO_PATH, path2]);
8158
+ if ((await stat(path2)).size === 0) {
7705
8159
  throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_EMPTY");
7706
8160
  }
7707
8161
  } finally {
@@ -7773,21 +8227,25 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7773
8227
  trackingIds: [...this.touchSlots.values()].map(({ trackingId }) => trackingId)
7774
8228
  };
7775
8229
  }
7776
- async readFile(path) {
8230
+ async readFile(path2) {
7777
8231
  try {
7778
- const contents = await this.adb(["exec-out", "cat", path]);
8232
+ const contents = await this.adb(["exec-out", "cat", path2]);
7779
8233
  return isMissingRemoteFileOutput(contents) ? void 0 : contents;
7780
8234
  } catch (error) {
7781
8235
  if (isMissingRemoteFile(error)) return void 0;
7782
8236
  throw error;
7783
8237
  }
7784
8238
  }
7785
- async removeFile(path) {
7786
- await this.adb(["shell", "rm", "-f", path]);
8239
+ async removeFile(path2) {
8240
+ await this.adb(["shell", "rm", "-f", path2]);
7787
8241
  }
7788
8242
  async stop() {
7789
8243
  await this.abortScreenRecording();
7790
8244
  await this.setPointers([]).catch(() => void 0);
8245
+ if (this.lifecycleRotationLocked) {
8246
+ this.lifecycleRotationLocked = false;
8247
+ await this.adb(["shell", "wm", "user-rotation", "free"]).catch(() => void 0);
8248
+ }
7791
8249
  if (this.viewportPresented) {
7792
8250
  this.viewportPresented = false;
7793
8251
  this.touchViewport = void 0;
@@ -7814,14 +8272,14 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
7814
8272
  if (/^[0-3]$/u.test(setting)) return Number(setting);
7815
8273
  throw new Error("TN_PLAYTEST_ANDROID_ROTATION_UNKNOWN: dumpsys window, dumpsys input and user_rotation did not report 0 through 3.");
7816
8274
  }
7817
- async writeFile(path, contents) {
8275
+ async writeFile(path2, contents) {
7818
8276
  const directory = await mkdtemp(join(tmpdir(), "threenative-adb-mailbox-"));
7819
8277
  const localPath = join(directory, "payload.json");
7820
- const remotePath = `${path}.incoming-${process.pid}-${Date.now()}`;
8278
+ const remotePath = `${path2}.incoming-${process.pid}-${Date.now()}`;
7821
8279
  try {
7822
8280
  await writeFile(localPath, contents, "utf8");
7823
8281
  await this.adb(["push", localPath, remotePath]);
7824
- await this.adb(["shell", "mv", remotePath, path]);
8282
+ await this.adb(["shell", "mv", remotePath, path2]);
7825
8283
  } finally {
7826
8284
  await rm(directory, { force: true, recursive: true });
7827
8285
  await this.adb(["shell", "rm", "-f", remotePath]).catch(() => void 0);
@@ -8001,8 +8459,24 @@ function viewportPresentationObserved(override, expected, physical) {
8001
8459
  return expected !== void 0 && (override === expected || override === void 0 && expected === `${physical.width}x${physical.height}`);
8002
8460
  }
8003
8461
  function touchRotationFromWindowDump(dump) {
8462
+ const rotation = windowRotationFromDump(dump);
8463
+ return rotation === void 0 ? void 0 : (4 - rotation) % 4;
8464
+ }
8465
+ function windowRotationFromDump(dump) {
8004
8466
  const rotation = /\bmRotation=([0-3])\b/u.exec(dump)?.[1];
8005
- return rotation === void 0 ? void 0 : (4 - Number(rotation)) % 4;
8467
+ return rotation === void 0 ? void 0 : Number(rotation);
8468
+ }
8469
+ function windowHasFocus(dump, packageName) {
8470
+ const escaped = packageName.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
8471
+ return new RegExp(`mCurrentFocus=.*\\s${escaped}/`, "u").test(dump);
8472
+ }
8473
+ function parseAndroidAppPid(output) {
8474
+ const pid = output.trim().split(/\s+/u)[0];
8475
+ return pid !== void 0 && /^\d+$/u.test(pid) ? Number(pid) : void 0;
8476
+ }
8477
+ function parseAndroidAppFrames(dump) {
8478
+ const frames = /Total frames rendered:\s*(\d+)/u.exec(dump)?.[1];
8479
+ return frames === void 0 ? void 0 : Number(frames);
8006
8480
  }
8007
8481
  function viewportPresentationCommands(viewport, physical) {
8008
8482
  if (!(viewport.width > 0) || !(viewport.height > 0)) {
@@ -8072,6 +8546,9 @@ function discoverAdb(environment = process.env) {
8072
8546
  "adb was not found. Install Android SDK Platform Tools, set ANDROID_HOME, or pass --adb /absolute/path/to/adb."
8073
8547
  );
8074
8548
  }
8549
+ function delay(milliseconds) {
8550
+ return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
8551
+ }
8075
8552
  var CAPTURE_GUARD_LIMITS = {
8076
8553
  brightLuminance: 0.05,
8077
8554
  darkFrameMinDistinctColors: 32,
@@ -8153,37 +8630,436 @@ function assertCaptureNotBlank(png, label) {
8153
8630
  }
8154
8631
  return stats;
8155
8632
  }
8156
-
8157
- // src/runner/startupReady.ts
8158
- async function waitForStartupReady(options) {
8159
- const { bridge, pump } = options;
8160
- if (!bridge.description.capabilities.includes("runtime.startup")) return void 0;
8161
- const now = options.now ?? (() => Date.now());
8162
- const timeoutMs = options.timeoutMs ?? PLAYTEST_STARTUP_READY_TIMEOUT_MS;
8163
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
8164
- throw new Error(`TN_PLAYTEST_STARTUP_TIMEOUT_INVALID: ${String(options.timeoutMs)}`);
8165
- const deadline = now() + timeoutMs;
8166
- const settled = (observation) => options.acceptCompileSettled === true && observation.compileSettled === true;
8167
- const aborted = options.aborted ?? (() => false);
8168
- if (aborted()) throw abortedDuringStartup();
8169
- const hostAlive = options.hostAlive ?? (async () => void 0);
8170
- let observed = await pollStartup(bridge);
8171
- while (observed === BUSY || observed.phase !== "ready" && !settled(observed)) {
8172
- if (aborted()) throw abortedDuringStartup();
8173
- if (observed === BUSY && await hostAlive() === false) throw hostExitedDuringStartup();
8174
- if (now() >= deadline) {
8175
- throw new PlaytestBridgeError(playtestDiagnostic(
8176
- "TN_PLAYTEST_STARTUP_NOT_READY",
8177
- `Application startup stayed '${observed === BUSY ? "unreadable, the bridge kept timing out" : observed.phase}' for ${timeoutMs}ms; the run would have observed a game that has not finished loading.`,
8178
- "Let the application reach startup readiness \u2014 check that its loading gate can complete headlessly \u2014 or remove the runtime.startup capability if it has no startup phase."
8179
- ));
8180
- }
8181
- await pump();
8182
- observed = await pollStartup(bridge);
8183
- }
8184
- return {
8185
- rule: observed.phase === "ready" ? "sustained-frames" : "compile-settled",
8186
- startup: observed
8633
+ var PLAYTEST_FLAGS = {
8634
+ "--adb": { default: "auto-discover", summary: "absolute adb executable path", takesValue: true },
8635
+ "--touch-rotation": {
8636
+ default: "read from the device",
8637
+ summary: "Android raw-touch rotation (0-3) when the app's window and the display disagree",
8638
+ takesValue: true
8639
+ },
8640
+ "--allow-software": { default: "false", summary: "accept a software WebGPU adapter as evidence", takesValue: false },
8641
+ "--activity": { default: ".MystralActivity", summary: "Android launch activity", takesValue: true },
8642
+ "--user": { default: "current foreground Android user", summary: "Android user id for force-stop and launch", takesValue: true },
8643
+ "--app": { default: "required for iOS", summary: "built iOS .app bundle", takesValue: true },
8644
+ "--artifact": { default: "none (browser and android: with --build-report)", summary: "the built artifact this run exercises, hashed to prove the build report describes it", takesValue: true },
8645
+ "--artifacts": { default: "artifacts/playtest", summary: "artifact output directory", takesValue: true },
8646
+ "--build-report": { default: "none", summary: "the <artifact>.build-report.json threenative build published; its performanceBudget bounds every scenario, and a stale or foreign report refuses the run", takesValue: true },
8647
+ "--no-screenshots": { default: "false", summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one", takesValue: false },
8648
+ "--browser-arg": { allowDashValue: true, default: "none (repeatable)", repeatable: true, summary: "one additional Chromium argument", takesValue: true },
8649
+ "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu)", takesValue: true },
8650
+ "--cpu-prof": { default: "none", summary: "write a Chrome DevTools .cpuprofile for this run (browser and desktop targets)", takesValue: true },
8651
+ "--bundle-id": { default: "dev.threenative.runtime", summary: "iOS application bundle identifier", takesValue: true },
8652
+ "--device": { default: "platform default", summary: "Android serial or iOS device identifier", takesValue: true },
8653
+ "--executable": { default: "required for desktop", summary: "native desktop game executable", takesValue: true },
8654
+ "--endpoint": { default: "http://127.0.0.1:41777/playtest", summary: "device bridge endpoint", takesValue: true },
8655
+ "--headed": { default: "false", summary: "show the browser window", takesValue: false },
8656
+ "--judge-marker-url": { default: "none", summary: "judge-owned loopback marker URL whose POST failures are not network errors", takesValue: true },
8657
+ // `allowDashValue` so a host flag can be passed as one: `--host-arg --ui` is the UI root the
8658
+ // overlay serves, and the parser would otherwise read `--ui` as a playtest flag and reject it.
8659
+ "--host-arg": { allowDashValue: true, default: "none", repeatable: true, summary: "argument passed to the native desktop host, repeatable", takesValue: true },
8660
+ "--mailbox-root": { default: "Android external files directory", summary: "native device mailbox directory", takesValue: true },
8661
+ "--ios-transport": { default: "simulator", summary: "iOS transport (simulator or device)", takesValue: true },
8662
+ "--project": { default: ".", summary: "project root used to resolve paths", takesValue: true },
8663
+ "--package": { default: "com.mystral.engine", summary: "Android application id", takesValue: true },
8664
+ "--scenario": { default: "required (or positional; repeatable)", repeatable: true, summary: "scenario JSON path or glob", takesValue: true },
8665
+ "--server-command": { default: "none", summary: "command for a managed app server", takesValue: true },
8666
+ "--server-timeout": { default: "15000", summary: "managed server readiness timeout in ms", takesValue: true },
8667
+ "--timeout": { default: "15000", summary: "page operation timeout in ms", takesValue: true },
8668
+ "--target": { default: "browser", summary: "execution target (browser, android, desktop, or ios)", takesValue: true },
8669
+ "--trace": { default: "false", summary: "write a Playwright trace", takesValue: false },
8670
+ "--url": { default: "http://127.0.0.1:5173 (or a free managed port)", summary: "application URL", takesValue: true },
8671
+ "--port": { default: "free when managing a server", summary: "managed server port (0 chooses a free port)", takesValue: true },
8672
+ "--xcrun": { default: "auto-discover", summary: "absolute xcrun executable path", takesValue: true }
8673
+ };
8674
+ var PlaytestCliUsageError = class extends Error {
8675
+ constructor(message) {
8676
+ super(message);
8677
+ this.name = "PlaytestCliUsageError";
8678
+ }
8679
+ };
8680
+ function formatUsage() {
8681
+ const flags = Object.entries(PLAYTEST_FLAGS).map(
8682
+ ([name, details]) => ` ${name.padEnd(20)} ${details.summary} (default: ${details.default})`
8683
+ );
8684
+ return [
8685
+ "Usage: threenative-playtest <scenario> [options]",
8686
+ " threenative-playtest --scenario <path> [options]",
8687
+ "",
8688
+ "Commands:",
8689
+ " doctor check this machine can run a playtest at all",
8690
+ " --url <url> also reports the running scene at a glance",
8691
+ " --device <serial> also reports whether that Android device is",
8692
+ " cool enough, charged enough and discharging to measure on",
8693
+ " --capture <path> reads a browser census JSON or native",
8694
+ " TN_PIPELINE_EVENT log and reports shader compilation contributors",
8695
+ " --text prints either as a human-readable report;",
8696
+ " --browser-arg extends the WebGPU recipe, repeatable",
8697
+ " init create a starter playtest configuration",
8698
+ " perf read TN_FRAME_BUDGET / TN_HOST_GAP from one source and report",
8699
+ " frame, phase and host-gap windows; window 1 is discarded as",
8700
+ " startup; exits 2 when not enough steady windows arrived",
8701
+ " sources (mutually exclusive): --file <log>, --executable <bin>",
8702
+ " with repeatable --host-arg, or --logcat <serial>",
8703
+ " bounds: --max-frame-p95 <ms>, --min-fps <fps>",
8704
+ " --require-windows <n> (default 2), --timeout <s>, --text",
8705
+ " --allow-virtual-display accepts a frame rate the display did not",
8706
+ " see (a private Xvfb, or a loop the presentation cap outran); without",
8707
+ " it such a run prints no fps column and refuses a --min-fps bound",
8708
+ " trace record a Chrome performance trace of a running game and name the",
8709
+ " functions inside its slow frames \u2014 a percentile says a frame was",
8710
+ " slow, a trace says which function. Take one BEFORE attributing any",
8711
+ " frame-rate or stutter complaint to a cause",
8712
+ " --url <url> (required; start the dev server first)",
8713
+ " --seconds <n> traced window (default 20), --settle <s> (default 4)",
8714
+ " --key <KeyName> held while tracing, repeatable (default KeyW);",
8715
+ " --no-input traces a standing camera and says so",
8716
+ " --wait-for <js> readiness expression (default the engine's",
8717
+ " __TN_STARTUP_READY__), --wait-timeout <s>, --no-wait",
8718
+ " --out <path> raw trace JSON, --stall-ms <n>, --top <n>,",
8719
+ " --viewport <WxH>, --browser-arg <arg>, --text",
8720
+ " samples empty same-origin rAF before the game, reports adapter.info,",
8721
+ " and records invalid depth-pipeline call-site stacks automatically",
8722
+ " --allow-virtual-display / --allow-software acknowledge a degraded",
8723
+ " run; a frame rate is never printed from a virtual display, because",
8724
+ " without vsync that number is wrong rather than missing",
8725
+ " exits 1 when part of the answer is missing or untrustworthy and 2",
8726
+ " when no trace was recorded at all",
8727
+ " audio look at the game's audio, since nobody can listen to it in CI. Band",
8728
+ " energy, peak, DC, silence and loop-seam continuity per clip, plus a",
8729
+ " spectrogram PNG per clip \u2014 the numbers are the gate and the picture",
8730
+ " is what a person looks at when the gate fires. Catches the two",
8731
+ " defects every other check passes: a hum where a chime should be,",
8732
+ " and a bed that clicks once a cycle",
8733
+ " --expect <manifest.json> (required) what the GAME declares its own",
8734
+ " clips should be; the inspector cannot know a bed is broadband and a",
8735
+ " chime is bright. Fails closed on a malformed expectation rather",
8736
+ " than skipping it",
8737
+ " --dir <dir> every audio file under it must be declared, so a clip",
8738
+ " added later is not a clip nothing checks",
8739
+ " --root <dir> resolves manifest paths (default cwd)",
8740
+ " --out <dir> spectrograms (default artifacts/audio),",
8741
+ " --no-spectrograms, --text",
8742
+ " no browser, no display, no capture lock",
8743
+ " exits 1 when a check failed, 2 when it could not run, and 69 when",
8744
+ ' ffmpeg is absent \u2014 "could not check" is never a green 0',
8745
+ " record-to-scenario convert a replay recording into a scenario",
8746
+ " (requires --oracle <json> and --out <json>)",
8747
+ "",
8748
+ "Options:",
8749
+ ...flags,
8750
+ " --help print this help and exit 0",
8751
+ "",
8752
+ "Exit codes:",
8753
+ " 0 playtest passed",
8754
+ " 1 assertions failed",
8755
+ " 2 the run never reached assertions",
8756
+ " 75 the capture lock timed out \u2014 not a test failure; rerun when the queue clears",
8757
+ "",
8758
+ "A build's own budgets:",
8759
+ " threenative build publishes <artifact>.build-report.json beside the artifact it wrote, and",
8760
+ " --build-report hands that to a run. The report is proved against the artifact under test",
8761
+ " (--artifact on browser and android; --executable / --app on desktop and iOS) and its",
8762
+ " performanceBudget is merged into every scenario's assert.performance, so a ceiling declared",
8763
+ " at build time bounds the run without being retyped into each scenario. A report that is",
8764
+ " malformed, was built for another target, or describes bytes that have since changed exits 2",
8765
+ " with TN_PLAYTEST_BUILD_REPORT_INVALID or TN_PLAYTEST_BUILD_REPORT_STALE \u2014 the run measured",
8766
+ " nothing, which is not the same as a game that failed.",
8767
+ ""
8768
+ ].join("\n");
8769
+ }
8770
+ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
8771
+ const flags = parseFlags(argv);
8772
+ const scenarioPatterns = flags.get("--scenario") ?? [positional(argv)].filter((value) => value !== void 0);
8773
+ if (scenarioPatterns.length === 0) {
8774
+ throw new PlaytestCliUsageError("Missing scenario path. Run: threenative-playtest --scenario playtests/movement.playtest.json --url http://127.0.0.1:5173");
8775
+ }
8776
+ const urlFlag = flags.get("--url")?.[0];
8777
+ const url = urlFlag ?? "http://127.0.0.1:5173";
8778
+ const target = flags.get("--target")?.[0] ?? "browser";
8779
+ if (target !== "browser" && target !== "android" && target !== "desktop" && target !== "ios") {
8780
+ throw new PlaytestCliUsageError(`Unknown target '${target}'. Expected 'browser', 'android', 'desktop', or 'ios'.`);
8781
+ }
8782
+ const projectPath = resolve(cwd, flags.get("--project")?.[0] ?? ".");
8783
+ const serverCommand = flags.get("--server-command")?.[0];
8784
+ const requestedPort = readPort(flags.get("--port")?.[0]);
8785
+ const urlPort = portFromUrl(url);
8786
+ const effectivePort = requestedPort ?? (serverCommand === void 0 || urlFlag !== void 0 ? urlPort : void 0);
8787
+ if (requestedPort !== void 0 && requestedPort > 0 && urlFlag !== void 0 && urlPort !== void 0 && requestedPort !== urlPort) {
8788
+ throw new PlaytestCliUsageError(`--port ${requestedPort} conflicts with the port in --url (${urlPort}).`);
8789
+ }
8790
+ const scenarioPaths = scenarioPatterns.flatMap((pattern) => expandScenarioPattern(projectPath, pattern));
8791
+ if (scenarioPaths.length === 0) {
8792
+ throw new PlaytestCliUsageError("No scenario files matched the requested patterns.");
8793
+ }
8794
+ const appPath = flags.get("--app")?.[0];
8795
+ const executable = flags.get("--executable")?.[0];
8796
+ if (target === "desktop" && executable === void 0) {
8797
+ throw new PlaytestCliUsageError("Desktop playtest requires --executable <native-game-executable>.");
8798
+ }
8799
+ const iosTransport = flags.get("--ios-transport")?.[0] ?? "simulator";
8800
+ if (iosTransport !== "simulator" && iosTransport !== "device") {
8801
+ throw new PlaytestCliUsageError(`Unknown iOS transport '${iosTransport}'. Expected 'simulator' or 'device'.`);
8802
+ }
8803
+ const explicitBrowserArgs = flags.get("--browser-arg") ?? [];
8804
+ const browserRecipe = flags.get("--browser-recipe")?.[0];
8805
+ if (browserRecipe !== void 0 && browserRecipe !== "webgpu") {
8806
+ throw new PlaytestCliUsageError(`Unknown browser recipe '${browserRecipe}'. Expected 'webgpu'.`);
8807
+ }
8808
+ if (browserRecipe !== void 0 && explicitBrowserArgs.length > 0) {
8809
+ throw new PlaytestCliUsageError("Choose --browser-recipe or --browser-arg, not both.");
8810
+ }
8811
+ const device = flags.get("--device")?.[0];
8812
+ const cpuProfilePath = flags.get("--cpu-prof")?.[0];
8813
+ const judgeMarkerUrl = flags.get("--judge-marker-url")?.[0];
8814
+ if (judgeMarkerUrl !== void 0) {
8815
+ let marker;
8816
+ try {
8817
+ marker = new URL(judgeMarkerUrl);
8818
+ } catch {
8819
+ throw new PlaytestCliUsageError("--judge-marker-url must be a canonical http://127.0.0.1:<port>/first-frame URL for browser runs.");
8820
+ }
8821
+ if (marker.href !== judgeMarkerUrl || marker.protocol !== "http:" || marker.hostname !== "127.0.0.1" || marker.port === "" || marker.pathname !== "/first-frame" || marker.search !== "" || marker.hash !== "" || marker.username !== "" || marker.password !== "" || target !== "browser" || device !== void 0) {
8822
+ throw new PlaytestCliUsageError("--judge-marker-url must be a canonical http://127.0.0.1:<port>/first-frame URL for browser runs.");
8823
+ }
8824
+ }
8825
+ if (target === "browser" && device !== void 0) {
8826
+ if (browserRecipe !== void 0) {
8827
+ throw new PlaytestCliUsageError("Android Chrome device runs cannot honor --browser-recipe; remove it.");
8828
+ }
8829
+ if (explicitBrowserArgs.length > 0) {
8830
+ throw new PlaytestCliUsageError("Android Chrome device runs cannot honor --browser-arg; remove it.");
8831
+ }
8832
+ if (argv.includes("--headed")) {
8833
+ throw new PlaytestCliUsageError("Android Chrome device runs are already visible on the device and cannot honor --headed; remove it.");
8834
+ }
8835
+ }
8836
+ const rawTouchRotation = flags.get("--touch-rotation")?.[0];
8837
+ if (rawTouchRotation !== void 0 && !/^[0-3]$/u.test(rawTouchRotation)) {
8838
+ throw new Error(
8839
+ `TN_PLAYTEST_ANDROID_ROTATION_INVALID: --touch-rotation must be 0, 1, 2 or 3, got '${rawTouchRotation}'.`
8840
+ );
8841
+ }
8842
+ const touchRotation = rawTouchRotation === void 0 ? void 0 : Number(rawTouchRotation);
8843
+ const androidUser = flags.get("--user")?.[0];
8844
+ if (androidUser !== void 0 && !/^\d+$/u.test(androidUser)) {
8845
+ throw new PlaytestCliUsageError(`Android --user must be numeric, got '${androidUser}'.`);
8846
+ }
8847
+ const hostArgs = flags.get("--host-arg") ?? [];
8848
+ const artifact = flags.get("--artifact")?.[0];
8849
+ const buildReport2 = flags.get("--build-report")?.[0];
8850
+ if (buildReport2 !== void 0 && artifact === void 0 && target !== "desktop" && target !== "ios") {
8851
+ throw new PlaytestCliUsageError(
8852
+ `--build-report on the ${target} target also needs --artifact <path>: nothing else says which build this run exercises.`
8853
+ );
8854
+ }
8855
+ const browserArgs = explicitBrowserArgs.length > 0 ? explicitBrowserArgs : browserRecipe === "webgpu" ? [...WEBGPU_BROWSER_ARGS] : [];
8856
+ return {
8857
+ ...flags.get("--adb")?.[0] === void 0 ? {} : { adbPath: flags.get("--adb")[0] },
8858
+ ...artifact === void 0 ? {} : { artifactPath: artifact },
8859
+ ...touchRotation === void 0 ? {} : { touchRotation },
8860
+ // A scaffolded project's own `test` script is what a user runs, and it deliberately refuses a
8861
+ // software adapter — nothing about that should change to suit a runner. But CI has no GPU and
8862
+ // still needs to prove the scaffold installs, builds and plays, so the same acceptance the
8863
+ // flag expresses is available as an environment variable a workflow can set around an
8864
+ // unmodified project. It is not a silent default: the run still reports the adapter it got,
8865
+ // and TN_PLAYTEST_SOFTWARE_ADAPTER is suppressed only because someone said so out loud.
8866
+ allowSoftwareAdapter: argv.includes("--allow-software") || process.env.TN_PLAYTEST_ALLOW_SOFTWARE === "1",
8867
+ android: {
8868
+ activity: flags.get("--activity")?.[0] ?? ".MystralActivity",
8869
+ packageName: flags.get("--package")?.[0] ?? "com.mystral.engine",
8870
+ ...androidUser === void 0 ? {} : { user: androidUser }
8871
+ },
8872
+ artifactDirectory: resolve(projectPath, flags.get("--artifacts")?.[0] ?? "artifacts/playtest"),
8873
+ captureArtifactScreenshots: !argv.includes("--no-screenshots"),
8874
+ ...browserArgs.length === 0 ? {} : { browserArgs },
8875
+ ...buildReport2 === void 0 ? {} : { buildReportPath: resolve(projectPath, buildReport2) },
8876
+ ...cpuProfilePath === void 0 ? {} : { cpuProfilePath: resolve(projectPath, cpuProfilePath) },
8877
+ ...device === void 0 ? {} : { device },
8878
+ ...executable === void 0 ? {} : {
8879
+ desktop: {
8880
+ executable: resolve(projectPath, executable),
8881
+ ...hostArgs.length === 0 ? {} : { hostArgs }
8882
+ }
8883
+ },
8884
+ endpoint: flags.get("--endpoint")?.[0] ?? "http://127.0.0.1:41777/playtest",
8885
+ headless: !argv.includes("--headed"),
8886
+ ios: {
8887
+ ...appPath === void 0 ? {} : { appPath: resolve(projectPath, appPath) },
8888
+ bundleId: flags.get("--bundle-id")?.[0] ?? "dev.threenative.runtime",
8889
+ transport: iosTransport
8890
+ },
8891
+ ...judgeMarkerUrl === void 0 ? {} : { judgeMarkerUrl },
8892
+ ...flags.get("--mailbox-root")?.[0] === void 0 ? {} : { mailboxRoot: flags.get("--mailbox-root")[0] },
8893
+ ...serverCommand === void 0 ? effectivePort === void 0 ? {} : { port: effectivePort } : { port: effectivePort ?? 0 },
8894
+ projectPath,
8895
+ scenarioPath: scenarioPaths[0],
8896
+ scenarioPaths,
8897
+ ...serverCommand === void 0 ? {} : { server: { command: serverCommand, cwd: projectPath, timeoutMs: readPositiveInteger(flags.get("--server-timeout")?.[0], 15e3) } },
8898
+ timeoutMs: readPositiveInteger(flags.get("--timeout")?.[0], 15e3),
8899
+ target,
8900
+ trace: argv.includes("--trace"),
8901
+ url: requestedPort !== void 0 && requestedPort > 0 && (urlFlag === void 0 || urlPort === void 0) ? withPort(url, requestedPort) : url,
8902
+ ...flags.get("--xcrun")?.[0] === void 0 ? {} : { xcrunPath: flags.get("--xcrun")[0] }
8903
+ };
8904
+ }
8905
+ var SCENARIO_GLOB = /[*?[]/u;
8906
+ function expandScenarioPattern(projectPath, pattern) {
8907
+ if (!SCENARIO_GLOB.test(pattern)) return [pattern];
8908
+ const normalizedPattern = pattern.replaceAll("\\", "/");
8909
+ const matches = [];
8910
+ collectScenarioFiles(projectPath, projectPath, matches);
8911
+ const matching = matches.filter((file) => globMatches(normalizedPattern, file)).sort((left, right) => left.localeCompare(right));
8912
+ if (matching.length === 0) {
8913
+ throw new PlaytestCliUsageError(`Scenario glob '${pattern}' matched no files under '${projectPath}'.`);
8914
+ }
8915
+ return matching;
8916
+ }
8917
+ function collectScenarioFiles(directory, root, files) {
8918
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
8919
+ if (entry.isDirectory()) {
8920
+ if (entry.name === ".git" || entry.name === "node_modules" || entry.name === "dist") continue;
8921
+ collectScenarioFiles(resolve(directory, entry.name), root, files);
8922
+ continue;
8923
+ }
8924
+ if (!entry.isFile()) continue;
8925
+ files.push(relative(root, resolve(directory, entry.name)).replaceAll("\\", "/"));
8926
+ }
8927
+ }
8928
+ function globMatches(pattern, file) {
8929
+ const patternParts = pattern.split("/");
8930
+ const fileParts = file.split("/");
8931
+ return matchGlobParts(patternParts, fileParts);
8932
+ }
8933
+ function matchGlobParts(pattern, file) {
8934
+ if (pattern.length === 0) return file.length === 0;
8935
+ const [head, ...tail] = pattern;
8936
+ if (head === "**") {
8937
+ return matchGlobParts(tail, file) || file.length > 0 && matchGlobParts(pattern, file.slice(1));
8938
+ }
8939
+ return file.length > 0 && segmentMatches(head ?? "", file[0]) && matchGlobParts(tail, file.slice(1));
8940
+ }
8941
+ function segmentMatches(pattern, value) {
8942
+ let expression = "^";
8943
+ for (let index = 0; index < pattern.length; index += 1) {
8944
+ const character = pattern[index];
8945
+ if (character === "*") expression += "[^/]*";
8946
+ else if (character === "?") expression += "[^/]";
8947
+ else expression += escapeRegExp(character);
8948
+ }
8949
+ return new RegExp(`${expression}$`, "u").test(value);
8950
+ }
8951
+ function escapeRegExp(value) {
8952
+ return value.replace(/[|\\{}()[\]^$+?.]/gu, "\\$&");
8953
+ }
8954
+ function portFromUrl(url) {
8955
+ try {
8956
+ const parsed = new URL(url);
8957
+ return parsed.port === "" ? void 0 : Number(parsed.port);
8958
+ } catch {
8959
+ return void 0;
8960
+ }
8961
+ }
8962
+ function withPort(url, port) {
8963
+ const parsed = new URL(url);
8964
+ parsed.port = String(port);
8965
+ const result = parsed.toString();
8966
+ return url.endsWith("/") ? result : result.replace(/\/$/u, "");
8967
+ }
8968
+ function readPort(value) {
8969
+ if (value === void 0) return void 0;
8970
+ const parsed = Number(value);
8971
+ if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
8972
+ throw new PlaytestCliUsageError(`Expected a TCP port from 0 to 65535, received '${value}'.`);
8973
+ }
8974
+ return parsed;
8975
+ }
8976
+ function parseFlags(argv) {
8977
+ const flags = /* @__PURE__ */ new Map();
8978
+ for (let index = 0; index < argv.length; index += 1) {
8979
+ const name = argv[index];
8980
+ if (!name?.startsWith("--") || name === "--help") continue;
8981
+ if (!isPlaytestFlag(name)) throw new PlaytestCliUsageError(`Unknown flag '${name}'. Run threenative-playtest --help.`);
8982
+ const details = PLAYTEST_FLAGS[name];
8983
+ if (!details.takesValue) continue;
8984
+ const next = argv[index + 1];
8985
+ if (next === void 0 || next.startsWith("--") && (!details.allowDashValue || isPlaytestFlag(next))) {
8986
+ throw new PlaytestCliUsageError(`Flag '${name}' requires a value.`);
8987
+ }
8988
+ flags.set(name, [...flags.get(name) ?? [], next]);
8989
+ index += 1;
8990
+ }
8991
+ return flags;
8992
+ }
8993
+ function positional(argv) {
8994
+ return argv.find((value, index) => !value.startsWith("-") && (index === 0 || !argv[index - 1]?.startsWith("--")));
8995
+ }
8996
+ function readPositiveInteger(value, fallback) {
8997
+ const parsed = value === void 0 ? fallback : Number(value);
8998
+ if (!Number.isInteger(parsed) || parsed <= 0) {
8999
+ throw new PlaytestCliUsageError(`Expected a positive integer, received '${value ?? ""}'.`);
9000
+ }
9001
+ return parsed;
9002
+ }
9003
+ function isPlaytestFlag(value) {
9004
+ return Object.prototype.hasOwnProperty.call(PLAYTEST_FLAGS, value);
9005
+ }
9006
+
9007
+ // src/runner/buildReport.ts
9008
+ function withPerformanceBudget(scenario, budget) {
9009
+ if (budget === void 0) return scenario;
9010
+ const declared = scenario.assert?.performance;
9011
+ const maps = {
9012
+ maxPassDrawCalls: { ...budget.maxPassDrawCalls, ...declared?.maxPassDrawCalls },
9013
+ maxPassTriangles: { ...budget.maxPassTriangles, ...declared?.maxPassTriangles },
9014
+ maxPhaseMsP95: { ...budget.maxPhaseMsP95, ...declared?.maxPhaseMsP95 }
9015
+ };
9016
+ const performance = {
9017
+ ...budget,
9018
+ ...declared,
9019
+ ...Object.fromEntries(Object.entries(maps).filter(([, value]) => Object.keys(value).length > 0))
9020
+ };
9021
+ return { ...scenario, assert: { ...scenario.assert, performance } };
9022
+ }
9023
+
9024
+ // src/runner/startupReady.ts
9025
+ async function waitForStartupReady(options) {
9026
+ const { bridge, pump } = options;
9027
+ if (!bridge.description.capabilities.includes("runtime.startup")) return void 0;
9028
+ const now = options.now ?? (() => Date.now());
9029
+ const timeoutMs = options.timeoutMs ?? PLAYTEST_STARTUP_READY_TIMEOUT_MS;
9030
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
9031
+ throw new Error(`TN_PLAYTEST_STARTUP_TIMEOUT_INVALID: ${String(options.timeoutMs)}`);
9032
+ const deadline = now() + timeoutMs;
9033
+ const aborted = options.aborted ?? (() => false);
9034
+ if (aborted()) throw abortedDuringStartup();
9035
+ const hostAlive = options.hostAlive ?? (async () => void 0);
9036
+ let observed = await pollStartup(bridge);
9037
+ while (observed === BUSY || observed.phase !== "ready") {
9038
+ if (aborted()) throw abortedDuringStartup();
9039
+ if (observed === BUSY && await hostAlive() === false) throw hostExitedDuringStartup();
9040
+ if (now() >= deadline) {
9041
+ throw new PlaytestBridgeError(playtestDiagnostic(
9042
+ "TN_PLAYTEST_STARTUP_NOT_READY",
9043
+ `Application startup stayed '${observed === BUSY ? "unreadable, the bridge kept timing out" : observed.phase}' for ${timeoutMs}ms; the run would have observed a game that has not finished loading.`,
9044
+ "Let the application reach startup readiness \u2014 check that its loading gate can complete headlessly \u2014 or remove the runtime.startup capability if it has no startup phase."
9045
+ ));
9046
+ }
9047
+ try {
9048
+ await pump();
9049
+ } catch (error) {
9050
+ if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
9051
+ observed = BUSY;
9052
+ continue;
9053
+ }
9054
+ throw error;
9055
+ }
9056
+ observed = await pollStartup(bridge);
9057
+ }
9058
+ return {
9059
+ // A declared software lane reaches `ready` on the bounded window rather than on sustained
9060
+ // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
9061
+ rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
9062
+ startup: observed
8187
9063
  };
8188
9064
  }
8189
9065
  function abortedDuringStartup() {
@@ -8287,12 +9163,12 @@ async function waitForResource(options) {
8287
9163
  if (options.advance !== void 0 && now() < deadline) await options.advance();
8288
9164
  }
8289
9165
  }
8290
- function waitFailure(message, instruction, path) {
9166
+ function waitFailure(message, instruction, path2) {
8291
9167
  return new PlaytestBridgeError(playtestDiagnostic(
8292
9168
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
8293
9169
  message,
8294
9170
  instruction,
8295
- { path }
9171
+ { path: path2 }
8296
9172
  ));
8297
9173
  }
8298
9174
  function json(value) {
@@ -8428,6 +9304,9 @@ var DeviceMailboxTransport = class {
8428
9304
  closed = false;
8429
9305
  nextId = 1;
8430
9306
  nextOrder = 1;
9307
+ // Calls that gave up before the host answered. The host still answers them, late, and that
9308
+ // answer is theirs, not an error in whichever call is waiting when it lands.
9309
+ abandonedIds = /* @__PURE__ */ new Set();
8431
9310
  responseObserver;
8432
9311
  setResponseObserver(observer) {
8433
9312
  this.responseObserver = observer;
@@ -8437,6 +9316,7 @@ var DeviceMailboxTransport = class {
8437
9316
  this.connected = false;
8438
9317
  this.nextId = 1;
8439
9318
  this.nextOrder = 1;
9319
+ this.abandonedIds.clear();
8440
9320
  await this.mailbox.remove(this.paths.request);
8441
9321
  await this.mailbox.remove(this.paths.response);
8442
9322
  }
@@ -8485,11 +9365,13 @@ var DeviceMailboxTransport = class {
8485
9365
  const response = parseResponse(raw);
8486
9366
  this.responseObserver?.({ body: raw, method, order, requestId: response.id });
8487
9367
  await this.mailbox.remove(this.paths.response);
8488
- if (response.id !== id) throw new Error(`Unexpected device response id '${response.id}'.`);
8489
- return response;
9368
+ if (response.id === id) return response;
9369
+ if (this.abandonedIds.has(response.id)) continue;
9370
+ throw new Error(`Unexpected device response id '${response.id}'.`);
8490
9371
  }
8491
9372
  await delayUntil(deadline);
8492
9373
  }
9374
+ this.abandonedIds.add(id);
8493
9375
  throw new PlaytestBridgeError(playtestDiagnostic(
8494
9376
  "TN_PLAYTEST_OPERATION_TIMEOUT",
8495
9377
  `Device mailbox operation '${id}' exceeded ${timeoutMs}ms.`,
@@ -8505,9 +9387,12 @@ function androidMailboxPaths(packageName, root = `/sdcard/Android/data/${package
8505
9387
  return deviceMailboxPaths(root);
8506
9388
  }
8507
9389
  function deviceTimeoutDiagnostic(diagnostic, hostAlive, lastConsoleLines) {
8508
- if (diagnostic.code !== "TN_PLAYTEST_OPERATION_TIMEOUT") return diagnostic;
8509
9390
  if (hostAlive !== false) return diagnostic;
8510
9391
  const tail = lastConsoleLines.length === 0 ? "the host produced no further output" : `last host output: ${lastConsoleLines.map((line) => line.slice(0, 160)).join(" | ").slice(0, 1e3)}`;
9392
+ if (diagnostic.code === "TN_PLAYTEST_STARTUP_HOST_EXITED") {
9393
+ return playtestDiagnostic(diagnostic.code, `${diagnostic.message} \u2014 ${tail}`, diagnostic.fix.instruction);
9394
+ }
9395
+ if (diagnostic.code !== "TN_PLAYTEST_OPERATION_TIMEOUT") return diagnostic;
8511
9396
  return playtestDiagnostic(
8512
9397
  "TN_PLAYTEST_HOST_EXITED",
8513
9398
  `${diagnostic.message}; the host process has exited \u2014 ${tail}`,
@@ -8573,9 +9458,9 @@ async function delayUntil(deadline) {
8573
9458
  if (remaining > 0) await new Promise((resolve8) => setTimeout(resolve8, Math.min(40, remaining)));
8574
9459
  }
8575
9460
  var kMailboxLockCodes = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
8576
- async function readMailboxFile(mailbox, path) {
9461
+ async function readMailboxFile(mailbox, path2) {
8577
9462
  try {
8578
- return await mailbox.read(path);
9463
+ return await mailbox.read(path2);
8579
9464
  } catch (error) {
8580
9465
  if (isMailboxLockError(error)) return void 0;
8581
9466
  throw error;
@@ -9231,248 +10116,70 @@ async function sampleElementVisibility(page, target) {
9231
10116
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
9232
10117
  `Could not capture the isolated visibility screenshot: ${screenshotFailure}.`,
9233
10118
  "Rerun the playtest after ensuring the page renderer remains available for screenshot capture."
9234
- ));
9235
- }
9236
- if (screenshot === void 0) {
9237
- throw new PlaytestBridgeError(playtestDiagnostic(
9238
- "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
9239
- "The isolated visibility screenshot was not produced.",
9240
- "Rerun the playtest after ensuring the page renderer remains available for screenshot capture."
9241
- ));
9242
- }
9243
- let rendered;
9244
- try {
9245
- rendered = containsPaintedPixels(screenshot);
9246
- } catch (error) {
9247
- const reason = error instanceof Error ? error.message : "the PNG could not be decoded";
9248
- throw new PlaytestBridgeError(playtestDiagnostic(
9249
- "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
9250
- `Could not decode the isolated visibility screenshot: ${reason}.`,
9251
- "Rerun the playtest after ensuring screenshot capture returns a valid PNG."
9252
- ));
9253
- }
9254
- return {
9255
- bounds: domSample.bounds,
9256
- rendered
9257
- };
9258
- }
9259
- function containsPaintedPixels(screenshot) {
9260
- const png = PNG.sync.read(screenshot);
9261
- for (let offset = 0; offset < png.data.length; offset += 4) {
9262
- if ((png.data[offset + 3] ?? 0) > 0) return true;
9263
- }
9264
- return false;
9265
- }
9266
- async function sampleHud(page, assertions) {
9267
- if (assertions.length === 0) return {};
9268
- const snapshots = await page.evaluate((requestedAssertions) => Object.fromEntries(requestedAssertions.flatMap(({ id, path }) => {
9269
- const element = path === void 0 ? document.getElementById(id) : (() => {
9270
- try {
9271
- return document.querySelector(path);
9272
- } catch {
9273
- return null;
9274
- }
9275
- })();
9276
- if (element === null) return [];
9277
- const text = element.textContent?.trim() ?? "";
9278
- const rawValue = element.getAttribute("data-value");
9279
- const value = rawValue === null ? void 0 : Number.isFinite(Number(rawValue)) ? Number(rawValue) : rawValue;
9280
- const snapshot = value === void 0 ? text : value;
9281
- return [[id, path === void 0 ? snapshot : { [path]: snapshot }]];
9282
- })), assertions);
9283
- for (const assertion of assertions) {
9284
- if (assertion.visible === void 0 || !Object.hasOwn(snapshots, assertion.id)) continue;
9285
- const visibility = await sampleElementVisibility(
9286
- page,
9287
- assertion.path === void 0 ? { id: assertion.id } : { selector: assertion.path }
9288
- );
9289
- const snapshot = snapshots[assertion.id];
9290
- if (assertion.path === void 0) {
9291
- snapshots[assertion.id] = { text: snapshot, visible: visibility.rendered };
9292
- continue;
9293
- }
9294
- const pathSnapshot = typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? snapshot[assertion.path] : snapshot;
9295
- snapshots[assertion.id] = { [assertion.path]: { text: pathSnapshot, visible: visibility.rendered } };
9296
- }
9297
- return snapshots;
9298
- }
9299
- var DEFAULT_XVFB_SCREEN = "1600x900x24";
9300
- var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
9301
- var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
9302
- var X11_SOCKET_DIR = "/tmp/.X11-unix";
9303
- function decideDisplayStrategy(input) {
9304
- if (input.platform !== "linux") return { kind: "host" };
9305
- const privateXvfb = {
9306
- kind: "private-xvfb",
9307
- screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
9308
- };
9309
- if (!hostDisplayRequested(input.env)) return privateXvfb;
9310
- const display = input.env.DISPLAY;
9311
- if (display !== void 0 && display.length > 0 && (input.displaySocketExists ?? x11SocketExists)(display)) {
9312
- return { display, kind: "existing" };
9313
- }
9314
- return privateXvfb;
9315
- }
9316
- function hostDisplayRequested(env) {
9317
- const value = env[HOST_DISPLAY_ENV];
9318
- return value === "1" || value?.toLowerCase() === "true";
9319
- }
9320
- function x11SocketExists(display) {
9321
- const number = displayNumber(display);
9322
- return number === void 0 ? false : existsSync(join(X11_SOCKET_DIR, `X${number}`));
9323
- }
9324
- function displayNumber(display) {
9325
- const parsed = Number.parseInt(display.replace(/^:/u, ""), 10);
9326
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
9327
- }
9328
- function childEnvForDisplay(env, display) {
9329
- const child = { ...env };
9330
- for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
9331
- child.DISPLAY = display;
9332
- return child;
9333
- }
9334
- function runNeedsPixels(config, scenario) {
9335
- if (config.headless !== true) return true;
9336
- const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
9337
- const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0;
9338
- return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
9339
- }
9340
- async function provideDisplay(options = {}) {
9341
- const env = options.env ?? process.env;
9342
- const platform = options.platform ?? process.platform;
9343
- const strategy = decideDisplayStrategy({
9344
- displaySocketExists: options.displaySocketExists,
9345
- env,
9346
- platform
9347
- });
9348
- if (strategy.kind === "host") {
9349
- return {
9350
- compositor: void 0,
9351
- display: void 0,
9352
- env: { ...env },
9353
- release: async () => void 0,
9354
- strategy
9355
- };
9356
- }
9357
- if (strategy.kind === "existing") {
9358
- return {
9359
- compositor: void 0,
9360
- display: strategy.display,
9361
- env: childEnvForDisplay(env, strategy.display),
9362
- release: async () => void 0,
9363
- strategy
9364
- };
10119
+ ));
9365
10120
  }
9366
- const commandExists = options.commandExists ?? defaultCommandExists;
9367
- if (!commandExists("Xvfb")) {
9368
- throw new Error(
9369
- "No usable X display is available and Xvfb is not installed, so this pixel-producing run cannot start (Debian/Ubuntu 'xvfb', Arch 'xorg-server-xvfb', Fedora 'xorg-x11-server-Xvfb'). Refusing to render blind."
9370
- );
10121
+ if (screenshot === void 0) {
10122
+ throw new PlaytestBridgeError(playtestDiagnostic(
10123
+ "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
10124
+ "The isolated visibility screenshot was not produced.",
10125
+ "Rerun the playtest after ensuring the page renderer remains available for screenshot capture."
10126
+ ));
9371
10127
  }
9372
- const spawnProcess = options.spawnProcess ?? spawn;
9373
- const xvfb = spawnProcess("Xvfb", [
9374
- "-displayfd",
9375
- "3",
9376
- "-nolisten",
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",
9388
- "-screen",
9389
- "0",
9390
- strategy.screen
9391
- ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
9392
- xvfb.on?.("error", () => void 0);
10128
+ let rendered;
9393
10129
  try {
9394
- const number = await readXvfbDisplayNumber(xvfb);
9395
- const display = `:${number}`;
9396
- const compositor = await startCompositor(display, { commandExists, env, spawnProcess });
9397
- return {
9398
- compositor: compositor?.name,
9399
- display,
9400
- env: childEnvForDisplay(env, display),
9401
- release: async () => {
9402
- if (compositor !== void 0) await stopChild(compositor.child);
9403
- await stopChild(xvfb);
9404
- },
9405
- strategy
9406
- };
10130
+ rendered = containsPaintedPixels(screenshot);
9407
10131
  } catch (error) {
9408
- await stopChild(xvfb);
9409
- throw error;
10132
+ const reason = error instanceof Error ? error.message : "the PNG could not be decoded";
10133
+ throw new PlaytestBridgeError(playtestDiagnostic(
10134
+ "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
10135
+ `Could not decode the isolated visibility screenshot: ${reason}.`,
10136
+ "Rerun the playtest after ensuring screenshot capture returns a valid PNG."
10137
+ ));
9410
10138
  }
10139
+ return {
10140
+ bounds: domSample.bounds,
10141
+ rendered
10142
+ };
9411
10143
  }
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
- }
9434
- var XVFB_DISPLAY_TIMEOUT_MS = 1e4;
9435
- async function readXvfbDisplayNumber(xvfb) {
9436
- const report = xvfb.stdio[3];
9437
- if (report === null || report === void 0 || typeof report.on !== "function") {
9438
- throw new Error("Xvfb was spawned without a display-report descriptor to read.");
10144
+ function containsPaintedPixels(screenshot) {
10145
+ const png = PNG.sync.read(screenshot);
10146
+ for (let offset = 0; offset < png.data.length; offset += 4) {
10147
+ if ((png.data[offset + 3] ?? 0) > 0) return true;
9439
10148
  }
9440
- const stream = report;
9441
- return new Promise((resolveDisplay, rejectDisplay) => {
9442
- let settled = false;
9443
- const finish = (settle) => {
9444
- if (settled) return;
9445
- settled = true;
9446
- clearTimeout(timer);
9447
- stream.removeListener("data", onData);
9448
- stream.removeListener("close", onClose);
9449
- settle();
9450
- };
9451
- const onData = (chunk) => {
9452
- const number = Number.parseInt(String(chunk).trim(), 10);
9453
- if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
9454
- };
9455
- const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
9456
- const timer = setTimeout(() => finish(() => {
9457
- rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
9458
- }), XVFB_DISPLAY_TIMEOUT_MS);
9459
- stream.on("data", onData);
9460
- stream.on("close", onClose);
9461
- });
10149
+ return false;
9462
10150
  }
9463
- async function stopChild(child) {
9464
- const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
9465
- if (exitedAlready()) return;
9466
- child.kill("SIGTERM");
9467
- const started = Date.now();
9468
- while (Date.now() - started < 1e3 && !exitedAlready()) {
9469
- await new Promise((resolveWait) => setTimeout(resolveWait, 25));
10151
+ async function sampleHud(page, assertions) {
10152
+ if (assertions.length === 0) return {};
10153
+ const snapshots = await page.evaluate((requestedAssertions) => Object.fromEntries(requestedAssertions.flatMap(({ id, path: path2 }) => {
10154
+ const element = path2 === void 0 ? document.getElementById(id) : (() => {
10155
+ try {
10156
+ return document.querySelector(path2);
10157
+ } catch {
10158
+ return null;
10159
+ }
10160
+ })();
10161
+ if (element === null) return [];
10162
+ const text = element.textContent?.trim() ?? "";
10163
+ const rawValue = element.getAttribute("data-value");
10164
+ const value = rawValue === null ? void 0 : Number.isFinite(Number(rawValue)) ? Number(rawValue) : rawValue;
10165
+ const snapshot = value === void 0 ? text : value;
10166
+ return [[id, path2 === void 0 ? snapshot : { [path2]: snapshot }]];
10167
+ })), assertions);
10168
+ for (const assertion of assertions) {
10169
+ if (assertion.visible === void 0 || !Object.hasOwn(snapshots, assertion.id)) continue;
10170
+ const visibility = await sampleElementVisibility(
10171
+ page,
10172
+ assertion.path === void 0 ? { id: assertion.id } : { selector: assertion.path }
10173
+ );
10174
+ const snapshot = snapshots[assertion.id];
10175
+ if (assertion.path === void 0) {
10176
+ snapshots[assertion.id] = { text: snapshot, visible: visibility.rendered };
10177
+ continue;
10178
+ }
10179
+ const pathSnapshot = typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? snapshot[assertion.path] : snapshot;
10180
+ snapshots[assertion.id] = { [assertion.path]: { text: pathSnapshot, visible: visibility.rendered } };
9470
10181
  }
9471
- if (!exitedAlready()) child.kill("SIGKILL");
9472
- }
9473
- function defaultCommandExists(command) {
9474
- const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
9475
- return paths.some((directory) => existsSync(join(directory, command)));
10182
+ return snapshots;
9476
10183
  }
9477
10184
  var CAPTURE_LOCK_TIMEOUT_MS_CONTESTED = 12e4;
9478
10185
  var CAPTURE_LOCK_TIMEOUT_MS_SOLO_FORCED = 1e4;
@@ -9512,11 +10219,11 @@ function queueDirOf(lockRoot) {
9512
10219
  return join(lockRoot, QUEUE_DIR_NAME);
9513
10220
  }
9514
10221
  function readHolder(lockDirectory) {
9515
- const path = join(lockDirectory, HOLDER_FILE);
9516
- if (!existsSync(path)) return void 0;
10222
+ const path2 = join(lockDirectory, HOLDER_FILE);
10223
+ if (!existsSync(path2)) return void 0;
9517
10224
  let raw;
9518
10225
  try {
9519
- raw = readFileSync(path, "utf8");
10226
+ raw = readFileSync(path2, "utf8");
9520
10227
  } catch {
9521
10228
  return void 0;
9522
10229
  }
@@ -9525,7 +10232,7 @@ function readHolder(lockDirectory) {
9525
10232
  if (typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid)) throw new Error("bad pid");
9526
10233
  return { ...parsed.command === void 0 ? {} : { command: parsed.command }, pid: parsed.pid, startedAt: String(parsed.startedAt ?? "") };
9527
10234
  } catch {
9528
- throw new Error(`Malformed capture lock holder record at ${path}; remove the stale '${lockDirectory}' directory if no playtest is running.`);
10235
+ throw new Error(`Malformed capture lock holder record at ${path2}; remove the stale '${lockDirectory}' directory if no playtest is running.`);
9529
10236
  }
9530
10237
  }
9531
10238
  var CaptureLockTimeoutError = class extends Error {
@@ -10503,14 +11210,17 @@ function writeCaptureState(payload) {
10503
11210
  process.stderr.write(`${JSON.stringify(payload)}
10504
11211
  `);
10505
11212
  }
11213
+ function isJudgeMarkerRequestFailure(method, url, judgeMarkerUrl) {
11214
+ return method === "POST" && judgeMarkerUrl !== void 0 && url === judgeMarkerUrl;
11215
+ }
10506
11216
  function addPreflightDiagnostic(report, diagnostic) {
10507
11217
  return diagnostic === void 0 ? report : { ...report, diagnostics: [diagnostic, ...report.diagnostics] };
10508
11218
  }
10509
- var SOFTWARE_DEVICE_LOSS = /TN_DEVICE_LOST|WebGPU Device Lost|A valid external Instance reference no longer exists/iu;
11219
+ var SOFTWARE_DEVICE_LOSS = /TN_DEVICE_LOST|WebGPU Device Lost|A valid external Instance reference no longer exists|Instance dropped in popErrorScope/iu;
10510
11220
  function isSoftwareDeviceLossEntry(entry) {
10511
11221
  return (entry.type === "error" || entry.type === "assert" || entry.type === "pageerror") && SOFTWARE_DEVICE_LOSS.test(entry.text);
10512
11222
  }
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) {
11223
+ 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, deviceLifecycle = void 0) {
10514
11224
  const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
10515
11225
  const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
10516
11226
  const wholeRunObserved = isAnonymousMovementScenario(scenario) ? false : entityPosition(beforeSnapshot, entity) !== void 0 && entityPosition(afterSnapshot, entity) !== void 0;
@@ -10541,6 +11251,11 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10541
11251
  const base = {
10542
11252
  ...afterPosition === void 0 ? {} : { after: { frame: scenario.steps.length, position: afterPosition, ...afterRotation === void 0 ? {} : { rotation: afterRotation }, tick: afterSnapshot?.clock.tick ?? 0 } },
10543
11253
  ...beforePosition === void 0 ? {} : { before: { frame: 0, position: beforePosition, ...beforeRotation === void 0 ? {} : { rotation: beforeRotation }, tick: beforeSnapshot?.clock.tick ?? 0 } },
11254
+ // The harness's own `adapter.info` reading, carried on the report the assertions are evaluated
11255
+ // against. An assertion that selects its expectation per adapter class needs the provenance
11256
+ // here, not only in the written artifact — reading it after evaluation meant every such
11257
+ // assertion saw no adapter and failed closed on a run that had a real one.
11258
+ ...capture === void 0 ? {} : { capture },
10544
11259
  diagnostics,
10545
11260
  diagnosticsPolicy: resolveDiagnosticsPolicy(scenario.assert?.diagnostics, config.target),
10546
11261
  distance,
@@ -10570,6 +11285,7 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
10570
11285
  signals: labeledSamples.flatMap(({ signals }) => signals)
10571
11286
  },
10572
11287
  hud,
11288
+ ...deviceLifecycle === void 0 ? {} : { deviceLifecycle },
10573
11289
  ...deviceMetrics === void 0 ? {} : { deviceMetrics },
10574
11290
  ...framebufferCoverage === void 0 ? {} : { framebufferCoverage },
10575
11291
  network: networkEntries,
@@ -10722,7 +11438,7 @@ function managedPort(config) {
10722
11438
  return void 0;
10723
11439
  }
10724
11440
  }
10725
- function withPort(url, port) {
11441
+ function withPort2(url, port) {
10726
11442
  const parsed = new URL(url);
10727
11443
  parsed.port = String(port);
10728
11444
  const result = parsed.toString();
@@ -10768,12 +11484,26 @@ function pageLifecycleDiagnostic(error, lifecycle, url) {
10768
11484
  "The renderer process died mid-run, so no assertion after that point was observed. Re-run with a smaller scene or a hardware GPU; under a virtual display the software WebGPU path is the usual cause."
10769
11485
  );
10770
11486
  }
10771
- const where = lifecycle.navigations.length === 0 ? "an unrecorded location" : `'${lifecycle.navigations.join("', '")}'`;
10772
11487
  const observed = [
10773
11488
  `page closed: ${lifecycle.closed}`,
10774
11489
  `main-frame navigations: ${lifecycle.frameNavigations.length}`,
10775
11490
  ...lifecycle.tail.length === 0 ? [] : [`last console: ${lifecycle.tail.join(" | ")}`]
10776
11491
  ].join("; ");
11492
+ if (lifecycle.closed && lifecycle.navigations.length === 0) {
11493
+ return playtestDiagnostic(
11494
+ "TN_PLAYTEST_PAGE_CLOSED",
11495
+ `The page went away without navigating while the scenario was running at '${url}'; runner error: ${detail}. Observed: ${observed}.`,
11496
+ "Nothing moved the document: the page closed mid-run, so every observation after that point is missing. This is the machine rather than the game \u2014 check for a GPU stall, an out-of-memory kill, or another browser benchmark competing for the display, then re-run. Nothing in the scenario can fix it."
11497
+ );
11498
+ }
11499
+ if (!lifecycle.closed && lifecycle.navigations.length === 0) {
11500
+ return playtestDiagnostic(
11501
+ "TN_PLAYTEST_PAGE_CRASHED",
11502
+ `The renderer went away without navigating or closing while the scenario was running at '${url}'; runner error: ${detail}. Observed: ${observed}.`,
11503
+ "Nothing moved the document and nothing closed the page, so Playwright destroyed the execution context because the renderer itself is gone, and every observation after that point is missing. The events say how the page died, not why: read the console tail above for the last frame cost or device-loss line. A frame that cost seconds on a software adapter is what a hardware look costs there \u2014 check the adapter and the tier the run reported before re-running, and check for a GPU stall, a lost or out-of-memory device, or another browser benchmark competing for the display. No scenario step can fix this."
11504
+ );
11505
+ }
11506
+ const where = lifecycle.navigations.length === 0 ? "an unrecorded location" : `'${lifecycle.navigations.join("', '")}'`;
10777
11507
  return playtestDiagnostic(
10778
11508
  "TN_PLAYTEST_PAGE_NAVIGATED",
10779
11509
  `The page navigated to ${where} while the scenario was running at '${url}'; runner error: ${detail}. Observed: ${observed}.`,
@@ -10950,7 +11680,6 @@ async function startBrowserCpuProfile(page, outputPath) {
10950
11680
  }
10951
11681
 
10952
11682
  // src/runner/runner.ts
10953
- var SCREENSHOT_TIMEOUT_MS = 12e4;
10954
11683
  var TOUCH_BROWSER_USER_AGENT = "Mozilla/5.0 (Linux; Android 13; Pixel 8) AppleWebKit/537.36 Chrome/151.0 Mobile Safari/537.36";
10955
11684
  function isTouchPrimaryBrowserScenario(scenario) {
10956
11685
  if (!scenario.steps.some(({ pointers }) => pointers !== void 0)) return false;
@@ -11000,7 +11729,10 @@ async function runStandalonePlaytest(config, options = {}) {
11000
11729
  async function runStandalonePlaytestInternal(config, options = {}) {
11001
11730
  const usesFreePort = config.server !== void 0 && config.port === 0;
11002
11731
  const activeConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
11003
- const scenario = await loadPlaytestScenario(activeConfig.projectPath, activeConfig.scenarioPath);
11732
+ const scenario = withPerformanceBudget(
11733
+ await loadPlaytestScenario(activeConfig.projectPath, activeConfig.scenarioPath),
11734
+ activeConfig.performanceBudget
11735
+ );
11004
11736
  const browserConfig = scenario.assert?.performance === void 0 ? activeConfig : {
11005
11737
  ...activeConfig,
11006
11738
  browserArgs: [
@@ -11147,7 +11879,12 @@ async function runStandalonePlaytestInternal(config, options = {}) {
11147
11879
  if (pageLifecycle.tail.length > 8) pageLifecycle.tail.shift();
11148
11880
  });
11149
11881
  page.on("pageerror", (error) => consoleEntries.push({ source: "page-error", text: error.stack || error.message, type: "pageerror" }));
11150
- page.on("requestfailed", (request) => networkEntries.push({ method: request.method(), url: request.url() }));
11882
+ page.on("requestfailed", (request) => {
11883
+ const method = request.method();
11884
+ const url = request.url();
11885
+ if (isJudgeMarkerRequestFailure(method, url, activeConfig.judgeMarkerUrl)) return;
11886
+ networkEntries.push({ method, url });
11887
+ });
11151
11888
  const observedPage = page;
11152
11889
  page.on("crash", () => {
11153
11890
  pageLifecycle.crashed = true;
@@ -11176,8 +11913,8 @@ async function runStandalonePlaytestInternal(config, options = {}) {
11176
11913
  await waitFrames(page, scenario.warmupFrames);
11177
11914
  const startupOutcome = bridge === void 0 || scenario.awaitStartup === false ? void 0 : await waitForStartupReady({
11178
11915
  aborted: () => tearingDown,
11179
- acceptCompileSettled: activeConfig.allowSoftwareAdapter === true,
11180
11916
  bridge,
11917
+ declaredSoftware: activeConfig.allowSoftwareAdapter === true,
11181
11918
  pump: () => waitFrames(activePage, 1)
11182
11919
  });
11183
11920
  const runtimeReady = await page.evaluate(
@@ -11485,7 +12222,10 @@ async function runStandalonePlaytests(config) {
11485
12222
  const activeConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
11486
12223
  const scenarios = [];
11487
12224
  for (const scenarioPath of scenarioPaths) {
11488
- scenarios.push(await loadPlaytestScenario(activeConfig.projectPath, scenarioPath));
12225
+ scenarios.push(withPerformanceBudget(
12226
+ await loadPlaytestScenario(activeConfig.projectPath, scenarioPath),
12227
+ activeConfig.performanceBudget
12228
+ ));
11489
12229
  }
11490
12230
  let server;
11491
12231
  try {
@@ -11541,7 +12281,7 @@ function batchArtifactDirectory(base, scenarioPath, index) {
11541
12281
  async function resolveManagedServerConfig(config) {
11542
12282
  if (config.server === void 0 || config.port !== 0) return config;
11543
12283
  const port = await findFreePort();
11544
- return { ...config, port, url: withPort(config.url, port) };
12284
+ return { ...config, port, url: withPort2(config.url, port) };
11545
12285
  }
11546
12286
  var execFileAsync2 = promisify(execFile);
11547
12287
  var DEFAULT_GRID = { columns: 32, rows: 18 };
@@ -11577,8 +12317,8 @@ async function analyzeFramebufferCoverageRecording(videoPath, artifactDirectory,
11577
12317
  }
11578
12318
  const gridSize = assertion.grid ?? DEFAULT_GRID;
11579
12319
  const grids = [];
11580
- for (const path of framePaths) {
11581
- grids.push(sampleFramebufferCoverageVideoFrame(PNG.sync.read(await readFile(path)), box, gridSize));
12320
+ for (const path2 of framePaths) {
12321
+ grids.push(sampleFramebufferCoverageVideoFrame(PNG.sync.read(await readFile(path2)), box, gridSize));
11582
12322
  }
11583
12323
  const observation = boundarySource === "scenario-steps" ? analyzeScenarioBracketedCoverageFrames(grids, framePaths, assertion) : analyzeSampledCoverageFrames(grids, framePaths, assertion);
11584
12324
  if (observation.firstViolation === void 0) return observation;
@@ -11656,8 +12396,8 @@ async function findVideoContentBoxFromFiles(framePaths) {
11656
12396
  const firstPath = appPaths[0];
11657
12397
  if (firstPath === void 0) return void 0;
11658
12398
  const accumulator = createContentBoxAccumulator(PNG.sync.read(await readFile(firstPath)));
11659
- for (const path of appPaths) {
11660
- if (!accumulateContentBox(accumulator, PNG.sync.read(await readFile(path)))) {
12399
+ for (const path2 of appPaths) {
12400
+ if (!accumulateContentBox(accumulator, PNG.sync.read(await readFile(path2)))) {
11661
12401
  throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_SIZE_CHANGED");
11662
12402
  }
11663
12403
  }
@@ -11793,14 +12533,18 @@ async function runDevicePlaytest(config, target) {
11793
12533
  return report;
11794
12534
  }
11795
12535
  async function runDevicePlaytestInternal(config, target, cleanupState) {
11796
- const scenario = await loadPlaytestScenario(config.projectPath, config.scenarioPath);
12536
+ const scenario = withPerformanceBudget(
12537
+ await loadPlaytestScenario(config.projectPath, config.scenarioPath),
12538
+ config.performanceBudget
12539
+ );
11797
12540
  await throwIfAborted(target);
11798
12541
  await mkdir(config.artifactDirectory, { recursive: true });
11799
12542
  await throwIfAborted(target);
11800
12543
  const unsupported = unsupportedAssertion(
11801
12544
  scenario,
11802
12545
  target.name,
11803
- typeof target.driver.tap === "function"
12546
+ typeof target.driver.tap === "function",
12547
+ canDriveAndroidLifecycle(target.driver)
11804
12548
  );
11805
12549
  if (unsupported !== void 0) return failureReport(config, scenario, unsupported, target.name);
11806
12550
  if (target.name === "android" && scenario.assert?.framebufferCoverage !== void 0 && (typeof target.driver.startScreenRecording !== "function" || typeof target.driver.stopScreenRecording !== "function")) {
@@ -11863,8 +12607,8 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11863
12607
  await throwIfAborted(target);
11864
12608
  const attached = bridge;
11865
12609
  const startupOutcome = scenario.awaitStartup === false ? void 0 : await waitForStartupReady({
11866
- acceptCompileSettled: config.allowSoftwareAdapter === true,
11867
12610
  bridge: attached,
12611
+ declaredSoftware: config.allowSoftwareAdapter === true,
11868
12612
  // A device host can die mid-launch, and its mailbox then simply stops answering. Without
11869
12613
  // this the wait reads that as a slow loading gate and burns its whole deadline; with it
11870
12614
  // the report names the exit and carries the console tail that says why.
@@ -11910,14 +12654,28 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
11910
12654
  let pointerX = 0;
11911
12655
  let pointerY = 0;
11912
12656
  let pointerHeld = false;
12657
+ const lifecycle = scenario.steps.some((step) => step.lifecycle !== void 0) ? new DeviceLifecycleRecorder(
12658
+ target.driver,
12659
+ // Only a build that installed a physics plugin owns a step counter, and it says so by
12660
+ // advertising the capability. Anything else is reported as unmeasured, never as zero.
12661
+ attached.description.capabilities.includes("runtime.physics"),
12662
+ // The step count is an observation like any other, read through the same sample request
12663
+ // the rest of the run uses rather than a channel of its own.
12664
+ () => attached.sample(sampleRequest)
12665
+ ) : void 0;
12666
+ if (lifecycle !== void 0) await lifecycle.launch();
11913
12667
  for (const [index, step] of scenario.steps.entries()) {
11914
12668
  await throwIfAborted(target);
12669
+ if (step.lifecycle !== void 0) {
12670
+ await lifecycle?.run(step.lifecycle, () => attached.advance(1));
12671
+ continue;
12672
+ }
11915
12673
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
11916
12674
  if (target.name === "android" && framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
11917
12675
  try {
11918
12676
  await target.driver.startScreenRecording?.();
11919
12677
  coverageRecordingStarted = true;
11920
- await delay(100);
12678
+ await delay2(100);
11921
12679
  } catch (error) {
11922
12680
  framebufferCoverage = unreadableCoverageObservation(error);
11923
12681
  }
@@ -12002,7 +12760,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
12002
12760
  if (coverageRecordingStarted) {
12003
12761
  for (let frame = 0; frame < frames; frame += 1) {
12004
12762
  await bridge.advance(1);
12005
- await delay(100);
12763
+ await delay2(100);
12006
12764
  }
12007
12765
  } else {
12008
12766
  await bridge.advance(frames);
@@ -12095,13 +12853,18 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
12095
12853
  void 0,
12096
12854
  labeledSamples,
12097
12855
  framebufferCoverage,
12098
- void 0,
12856
+ // The adapter this machine reported, read by the engine's own `adapter.info` probe and
12857
+ // carried in the census snapshot. Without it a device run reached `capture === undefined`,
12858
+ // so every `assert.renderChain.perAdapter` failed closed on a run that had a real adapter —
12859
+ // the flat expectation was used against a tier the software branch would have accepted.
12860
+ nativeCaptureProvenance(after?.pipelineCensus ?? before?.pipelineCensus, target.name, scenario.viewport),
12099
12861
  void 0,
12100
12862
  movementSamples,
12101
12863
  setupApplication2,
12102
12864
  metrics?.observation(),
12103
12865
  void 0,
12104
- startupOutcome === void 0 ? void 0 : { ...startupOutcome.startup, rule: startupOutcome.rule }
12866
+ startupOutcome === void 0 ? void 0 : { ...startupOutcome.startup, rule: startupOutcome.rule },
12867
+ lifecycle?.observation()
12105
12868
  );
12106
12869
  await writeObservationArtifacts(config.artifactDirectory, scenario.artifacts, {
12107
12870
  console: consoleEntries,
@@ -12117,7 +12880,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
12117
12880
  } catch (error) {
12118
12881
  if (error instanceof PlaytestBridgeError) {
12119
12882
  let diagnostic = error.diagnostic;
12120
- if (diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
12883
+ if (diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT" || diagnostic.code === "TN_PLAYTEST_STARTUP_HOST_EXITED") {
12121
12884
  const hostAlive = await target.driver.isAlive().catch(() => void 0);
12122
12885
  const lastConsoleLines = hostAlive === false ? (await target.driver.captureConsole().catch(() => [])).slice(-6).map((entry) => entry.text) : [];
12123
12886
  diagnostic = deviceTimeoutDiagnostic(diagnostic, hostAlive, lastConsoleLines);
@@ -12163,9 +12926,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
12163
12926
  if (cleanupErrors.length > 0) cleanupState.error = cleanupFailure(cleanupErrors);
12164
12927
  }
12165
12928
  }
12166
- async function captureDeviceScreenshot(target, path) {
12167
- await target.driver.screenshot(path);
12168
- assertCaptureNotBlank(await readFile(path), path);
12929
+ async function captureDeviceScreenshot(target, path2) {
12930
+ await target.driver.screenshot(path2);
12931
+ assertCaptureNotBlank(await readFile(path2), path2);
12169
12932
  }
12170
12933
  function deviceMetricsRecorder(target) {
12171
12934
  if (target.name !== "android") return void 0;
@@ -12187,9 +12950,9 @@ function cleanupFailure(errors) {
12187
12950
  function createDeviceTransport(driver, endpoint, paths, operationTimeoutMs) {
12188
12951
  if (isMailboxDriver(driver)) {
12189
12952
  const mailbox = {
12190
- read: (path) => driver.readFile(path),
12191
- remove: (path) => driver.removeFile(path),
12192
- write: (path, contents) => driver.writeFile(path, contents)
12953
+ read: (path2) => driver.readFile(path2),
12954
+ remove: (path2) => driver.removeFile(path2),
12955
+ write: (path2, contents) => driver.writeFile(path2, contents)
12193
12956
  };
12194
12957
  return new DeviceMailboxTransport(mailbox, paths, operationTimeoutMs);
12195
12958
  }
@@ -12229,491 +12992,356 @@ async function executeDeviceClickStep(target, bridge, step, viewport) {
12229
12992
  await target.driver.tap(point.x, point.y);
12230
12993
  }
12231
12994
  async function deviceClickPoint(bridge, step) {
12232
- const target = step.at;
12233
- if (target === void 0) {
12234
- throw new PlaytestBridgeError(playtestDiagnostic(
12235
- "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
12236
- "Click step has no target.",
12237
- "Declare at as viewport pixels ({ x, y }) or a registered entity ({ entity })."
12238
- ));
12239
- }
12240
- if (!("entity" in target)) return { x: target.x, y: target.y };
12241
- if (bridge === void 0) {
12242
- throw new PlaytestBridgeError(playtestDiagnostic(
12243
- "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
12244
- `Click target entity '${target.entity}' cannot be resolved without a playtest bridge.`,
12245
- "Install the playtest bridge and register the clickable entity, or use explicit viewport pixels."
12246
- ));
12247
- }
12248
- const snapshot = await bridge.sample({ entities: [target.entity] });
12249
- const bounds = snapshot.entities?.find((candidate) => candidate.id === target.entity)?.bounds;
12250
- if (bounds === void 0) {
12251
- throw new PlaytestBridgeError(playtestDiagnostic(
12252
- "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
12253
- `Click target entity '${target.entity}' has no observed screen bounds.`,
12254
- "Register a visible entity with the playtest bridge, or use explicit viewport pixels."
12255
- ));
12256
- }
12257
- return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
12258
- }
12259
- async function sendAndroidTextInput(target, key) {
12260
- if (target.name !== "android" || target.driver.runAdb === void 0) return;
12261
- const keyEvent = androidKeyEventCode(key);
12262
- if (keyEvent === void 0) return;
12263
- await target.driver.runAdb(["shell", "input", "keyevent", keyEvent]);
12264
- }
12265
- function androidKeyEventCode(key) {
12266
- if (key === " ") return "KEYCODE_SPACE";
12267
- const normalized = key.toUpperCase();
12268
- return /^[A-Z0-9]$/u.test(normalized) ? `KEYCODE_${normalized}` : void 0;
12269
- }
12270
- function isMailboxDriver(driver) {
12271
- return typeof driver.readFile === "function" && typeof driver.removeFile === "function" && typeof driver.writeFile === "function";
12272
- }
12273
- function unsupportedAssertion(scenario, target, hasPointerTransport) {
12274
- if (scenario.steps.some((step) => step.wheel !== void 0)) {
12275
- return unsupportedDiagnostic(
12276
- "wheel input steps",
12277
- "Run wheel input steps on --target browser; Android, desktop, and iOS runners have no wheel injector and will not skip the sample.",
12278
- target
12279
- );
12280
- }
12281
- if (scenario.steps.some((step) => step.kind === "click") && (target !== "android" || !hasPointerTransport)) {
12282
- return unsupportedDiagnostic(
12283
- "click steps",
12284
- "Run click steps on --target browser, or use an Android driver with OS pointer injection; native targets never fall back to keyboard input.",
12285
- target
12286
- );
12287
- }
12288
- if (scenario.assert?.deviceMetrics !== void 0 && target !== "android") {
12289
- return unsupportedDiagnostic(
12290
- "device thermal and power assertions",
12291
- `Run this assertion on --target android; ${targetLabel(target)} has no battery, thermal or power-rail probe.`,
12292
- target
12293
- );
12294
- }
12295
- if (scenario.assert?.diagnostics?.noNetworkErrors === true) {
12296
- return unsupportedDiagnostic(
12297
- "network assertions",
12298
- `Run this assertion on --target browser; ${targetLabel(target)} device transport has no CDP network observer. Remove the explicit network assertion, or declare "diagnostics": { "noNetworkErrors": false, "networkErrorsOptOutReason": "..." } to record a scenario-owned waiver.`,
12299
- target
12300
- );
12301
- }
12302
- if ((scenario.assert?.hud?.length ?? 0) > 0 || (scenario.assert?.overlayNodes?.length ?? 0) > 0) {
12303
- return unsupportedDiagnostic(
12304
- "DOM assertions",
12305
- `Use runtime resources/components for a cross-target scenario; ${targetLabel(target)} has no DOM observer.`,
12306
- target
12307
- );
12308
- }
12309
- if ((scenario.assert?.visual?.length ?? 0) > 0) {
12310
- return unsupportedDiagnostic(
12311
- "visual assertions",
12312
- `${targetLabel(target)} screenshots are captured as artifacts, but visual metric evaluation is not supported yet.`,
12313
- target
12314
- );
12995
+ const target = step.at;
12996
+ if (target === void 0) {
12997
+ throw new PlaytestBridgeError(playtestDiagnostic(
12998
+ "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
12999
+ "Click step has no target.",
13000
+ "Declare at as viewport pixels ({ x, y }) or a registered entity ({ entity })."
13001
+ ));
12315
13002
  }
12316
- if (scenario.assert?.framebufferCoverage !== void 0 && target === "ios") {
12317
- return unsupportedDiagnostic(
12318
- "framebuffer coverage recording",
12319
- "Run this assertion on --target browser or --target android; the iOS transport has no per-frame recorder observer.",
12320
- target
12321
- );
13003
+ if (!("entity" in target)) return { x: target.x, y: target.y };
13004
+ if (bridge === void 0) {
13005
+ throw new PlaytestBridgeError(playtestDiagnostic(
13006
+ "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
13007
+ `Click target entity '${target.entity}' cannot be resolved without a playtest bridge.`,
13008
+ "Install the playtest bridge and register the clickable entity, or use explicit viewport pixels."
13009
+ ));
12322
13010
  }
12323
- if (scenario.assert?.framebufferCoverage !== void 0 && target === "desktop") {
12324
- return unsupportedDiagnostic(
12325
- "framebuffer coverage recording",
12326
- "Run this assertion on --target browser or --target android; the desktop mailbox exposes screenshots, not a per-frame recorder observer.",
12327
- target
12328
- );
13011
+ const snapshot = await bridge.sample({ entities: [target.entity] });
13012
+ const bounds = snapshot.entities?.find((candidate) => candidate.id === target.entity)?.bounds;
13013
+ if (bounds === void 0) {
13014
+ throw new PlaytestBridgeError(playtestDiagnostic(
13015
+ "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
13016
+ `Click target entity '${target.entity}' has no observed screen bounds.`,
13017
+ "Register a visible entity with the playtest bridge, or use explicit viewport pixels."
13018
+ ));
12329
13019
  }
12330
- return void 0;
12331
- }
12332
- function unsupportedDiagnostic(subject, fix, target) {
12333
- return playtestDiagnostic(
12334
- "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
12335
- `${targetLabel(target)} ${target === "desktop" ? "desktop" : "device"} target does not support ${subject}.`,
12336
- fix
12337
- );
13020
+ return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
12338
13021
  }
12339
- function unreadableCoverageObservation(error) {
12340
- return {
12341
- boundarySource: "scenario-steps",
12342
- frameCount: 0,
12343
- unreadableReason: error instanceof Error ? error.message : String(error),
12344
- windowCompleted: false,
12345
- windowStarted: false
12346
- };
13022
+ async function sendAndroidTextInput(target, key) {
13023
+ if (target.name !== "android" || target.driver.runAdb === void 0) return;
13024
+ const keyEvent = androidKeyEventCode(key);
13025
+ if (keyEvent === void 0) return;
13026
+ await target.driver.runAdb(["shell", "input", "keyevent", keyEvent]);
12347
13027
  }
12348
- function delay(milliseconds) {
12349
- return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
13028
+ function androidKeyEventCode(key) {
13029
+ if (key === " ") return "KEYCODE_SPACE";
13030
+ const normalized = key.toUpperCase();
13031
+ return /^[A-Z0-9]$/u.test(normalized) ? `KEYCODE_${normalized}` : void 0;
12350
13032
  }
12351
- var PLAYTEST_FLAGS = {
12352
- "--adb": { default: "auto-discover", summary: "absolute adb executable path", takesValue: true },
12353
- "--touch-rotation": {
12354
- default: "read from the device",
12355
- summary: "Android raw-touch rotation (0-3) when the app's window and the display disagree",
12356
- takesValue: true
12357
- },
12358
- "--allow-software": { default: "false", summary: "accept a software WebGPU adapter as evidence", takesValue: false },
12359
- "--activity": { default: ".MystralActivity", summary: "Android launch activity", takesValue: true },
12360
- "--user": { default: "current foreground Android user", summary: "Android user id for force-stop and launch", takesValue: true },
12361
- "--app": { default: "required for iOS", summary: "built iOS .app bundle", takesValue: true },
12362
- "--artifacts": { default: "artifacts/playtest", summary: "artifact output directory", takesValue: true },
12363
- "--no-screenshots": { default: "false", summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one", takesValue: false },
12364
- "--browser-arg": { allowDashValue: true, default: "none (repeatable)", repeatable: true, summary: "one additional Chromium argument", takesValue: true },
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 },
12367
- "--bundle-id": { default: "dev.threenative.runtime", summary: "iOS application bundle identifier", takesValue: true },
12368
- "--device": { default: "platform default", summary: "Android serial or iOS device identifier", takesValue: true },
12369
- "--executable": { default: "required for desktop", summary: "native desktop game executable", takesValue: true },
12370
- "--endpoint": { default: "http://127.0.0.1:41777/playtest", summary: "device bridge endpoint", takesValue: true },
12371
- "--headed": { default: "false", summary: "show the browser window", takesValue: false },
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 },
12375
- "--mailbox-root": { default: "Android external files directory", summary: "native device mailbox directory", takesValue: true },
12376
- "--ios-transport": { default: "simulator", summary: "iOS transport (simulator or device)", takesValue: true },
12377
- "--project": { default: ".", summary: "project root used to resolve paths", takesValue: true },
12378
- "--package": { default: "com.mystral.engine", summary: "Android application id", takesValue: true },
12379
- "--scenario": { default: "required (or positional; repeatable)", repeatable: true, summary: "scenario JSON path or glob", takesValue: true },
12380
- "--server-command": { default: "none", summary: "command for a managed app server", takesValue: true },
12381
- "--server-timeout": { default: "15000", summary: "managed server readiness timeout in ms", takesValue: true },
12382
- "--timeout": { default: "15000", summary: "page operation timeout in ms", takesValue: true },
12383
- "--target": { default: "browser", summary: "execution target (browser, android, desktop, or ios)", takesValue: true },
12384
- "--trace": { default: "false", summary: "write a Playwright trace", takesValue: false },
12385
- "--url": { default: "http://127.0.0.1:5173 (or a free managed port)", summary: "application URL", takesValue: true },
12386
- "--port": { default: "free when managing a server", summary: "managed server port (0 chooses a free port)", takesValue: true },
12387
- "--xcrun": { default: "auto-discover", summary: "absolute xcrun executable path", takesValue: true }
12388
- };
12389
- var PlaytestCliUsageError = class extends Error {
12390
- constructor(message) {
12391
- super(message);
12392
- this.name = "PlaytestCliUsageError";
12393
- }
12394
- };
12395
- function formatUsage() {
12396
- const flags = Object.entries(PLAYTEST_FLAGS).map(
12397
- ([name, details]) => ` ${name.padEnd(20)} ${details.summary} (default: ${details.default})`
12398
- );
12399
- return [
12400
- "Usage: threenative-playtest <scenario> [options]",
12401
- " threenative-playtest --scenario <path> [options]",
12402
- "",
12403
- "Commands:",
12404
- " doctor check this machine can run a playtest at all",
12405
- " --url <url> also reports the running scene at a glance",
12406
- " --device <serial> also reports whether that Android device is",
12407
- " cool enough, charged enough and discharging to measure on",
12408
- " --capture <path> reads a browser census JSON or native",
12409
- " TN_PIPELINE_EVENT log and reports shader compilation contributors",
12410
- " --text prints either as a human-readable report;",
12411
- " --browser-arg extends the WebGPU recipe, repeatable",
12412
- " init create a starter playtest configuration",
12413
- " perf read TN_FRAME_BUDGET / TN_HOST_GAP from one source and report",
12414
- " frame, phase and host-gap windows; window 1 is discarded as",
12415
- " startup; exits 2 when not enough steady windows arrived",
12416
- " sources (mutually exclusive): --file <log>, --executable <bin>",
12417
- " with repeatable --host-arg, or --logcat <serial>",
12418
- " bounds: --max-frame-p95 <ms>, --min-fps <fps>",
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",
12423
- " trace record a Chrome performance trace of a running game and name the",
12424
- " functions inside its slow frames \u2014 a percentile says a frame was",
12425
- " slow, a trace says which function. Take one BEFORE attributing any",
12426
- " frame-rate or stutter complaint to a cause",
12427
- " --url <url> (required; start the dev server first)",
12428
- " --seconds <n> traced window (default 20), --settle <s> (default 4)",
12429
- " --key <KeyName> held while tracing, repeatable (default KeyW);",
12430
- " --no-input traces a standing camera and says so",
12431
- " --wait-for <js> readiness expression (default the engine's",
12432
- " __TN_STARTUP_READY__), --wait-timeout <s>, --no-wait",
12433
- " --out <path> raw trace JSON, --stall-ms <n>, --top <n>,",
12434
- " --viewport <WxH>, --browser-arg <arg>, --text",
12435
- " samples empty same-origin rAF before the game, reports adapter.info,",
12436
- " and records invalid depth-pipeline call-site stacks automatically",
12437
- " --allow-virtual-display / --allow-software acknowledge a degraded",
12438
- " run; a frame rate is never printed from a virtual display, because",
12439
- " without vsync that number is wrong rather than missing",
12440
- " exits 1 when part of the answer is missing or untrustworthy and 2",
12441
- " when no trace was recorded at all",
12442
- " audio look at the game's audio, since nobody can listen to it in CI. Band",
12443
- " energy, peak, DC, silence and loop-seam continuity per clip, plus a",
12444
- " spectrogram PNG per clip \u2014 the numbers are the gate and the picture",
12445
- " is what a person looks at when the gate fires. Catches the two",
12446
- " defects every other check passes: a hum where a chime should be,",
12447
- " and a bed that clicks once a cycle",
12448
- " --expect <manifest.json> (required) what the GAME declares its own",
12449
- " clips should be; the inspector cannot know a bed is broadband and a",
12450
- " chime is bright. Fails closed on a malformed expectation rather",
12451
- " than skipping it",
12452
- " --dir <dir> every audio file under it must be declared, so a clip",
12453
- " added later is not a clip nothing checks",
12454
- " --root <dir> resolves manifest paths (default cwd)",
12455
- " --out <dir> spectrograms (default artifacts/audio),",
12456
- " --no-spectrograms, --text",
12457
- " no browser, no display, no capture lock",
12458
- " exits 1 when a check failed, 2 when it could not run, and 69 when",
12459
- ' ffmpeg is absent \u2014 "could not check" is never a green 0',
12460
- " record-to-scenario convert a replay recording into a scenario",
12461
- " (requires --oracle <json> and --out <json>)",
12462
- "",
12463
- "Options:",
12464
- ...flags,
12465
- " --help print this help and exit 0",
12466
- "",
12467
- "Exit codes:",
12468
- " 0 playtest passed",
12469
- " 1 assertions failed",
12470
- " 2 the run never reached assertions",
12471
- " 75 the capture lock timed out \u2014 not a test failure; rerun when the queue clears",
12472
- ""
12473
- ].join("\n");
13033
+ function isMailboxDriver(driver) {
13034
+ return typeof driver.readFile === "function" && typeof driver.removeFile === "function" && typeof driver.writeFile === "function";
12474
13035
  }
12475
- function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
12476
- const flags = parseFlags(argv);
12477
- const scenarioPatterns = flags.get("--scenario") ?? [positional(argv)].filter((value) => value !== void 0);
12478
- if (scenarioPatterns.length === 0) {
12479
- throw new PlaytestCliUsageError("Missing scenario path. Run: threenative-playtest --scenario playtests/movement.playtest.json --url http://127.0.0.1:5173");
12480
- }
12481
- const urlFlag = flags.get("--url")?.[0];
12482
- const url = urlFlag ?? "http://127.0.0.1:5173";
12483
- const target = flags.get("--target")?.[0] ?? "browser";
12484
- if (target !== "browser" && target !== "android" && target !== "desktop" && target !== "ios") {
12485
- throw new PlaytestCliUsageError(`Unknown target '${target}'. Expected 'browser', 'android', 'desktop', or 'ios'.`);
12486
- }
12487
- const projectPath = resolve(cwd, flags.get("--project")?.[0] ?? ".");
12488
- const serverCommand = flags.get("--server-command")?.[0];
12489
- const requestedPort = readPort(flags.get("--port")?.[0]);
12490
- const urlPort = portFromUrl(url);
12491
- const effectivePort = requestedPort ?? (serverCommand === void 0 || urlFlag !== void 0 ? urlPort : void 0);
12492
- if (requestedPort !== void 0 && requestedPort > 0 && urlFlag !== void 0 && urlPort !== void 0 && requestedPort !== urlPort) {
12493
- throw new PlaytestCliUsageError(`--port ${requestedPort} conflicts with the port in --url (${urlPort}).`);
12494
- }
12495
- const scenarioPaths = scenarioPatterns.flatMap((pattern) => expandScenarioPattern(projectPath, pattern));
12496
- if (scenarioPaths.length === 0) {
12497
- throw new PlaytestCliUsageError("No scenario files matched the requested patterns.");
13036
+ function canDriveAndroidLifecycle(driver) {
13037
+ return typeof driver.background === "function" && typeof driver.foreground === "function" && typeof driver.rotate === "function" && typeof driver.lifecycleState === "function";
13038
+ }
13039
+ var ANDROID_LIFECYCLE_SETTLE_READS = 8;
13040
+ var ANDROID_LIFECYCLE_SETTLE_POLL_MS = 250;
13041
+ var ANDROID_LIFECYCLE_PAUSE_HOLD_MS = 1e3;
13042
+ var DeviceLifecycleRecorder = class {
13043
+ constructor(driver, countsPhysicsSteps, sample) {
13044
+ this.driver = driver;
13045
+ this.countsPhysicsSteps = countsPhysicsSteps;
13046
+ this.sample = sample;
13047
+ }
13048
+ driver;
13049
+ countsPhysicsSteps;
13050
+ sample;
13051
+ phases = [];
13052
+ startedAt = Date.now();
13053
+ physicsSteps = {
13054
+ afterAdvance: null,
13055
+ afterForeground: null,
13056
+ beforeBackground: null
13057
+ };
13058
+ pid = 0;
13059
+ /** The process the run launched, read before any step could change it. */
13060
+ async launch() {
13061
+ const state = await this.readDevice();
13062
+ if (state.pid === void 0) {
13063
+ throw new PlaytestBridgeError(playtestDiagnostic(
13064
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_UNOBSERVED",
13065
+ "`pidof` reports no process for the package this run launched, so there is no app session to follow.",
13066
+ "Launch the activity and confirm it is running before driving lifecycle steps; a lifecycle proof needs one live process to observe."
13067
+ ));
13068
+ }
13069
+ this.pid = state.pid;
12498
13070
  }
12499
- const appPath = flags.get("--app")?.[0];
12500
- const executable = flags.get("--executable")?.[0];
12501
- if (target === "desktop" && executable === void 0) {
12502
- throw new PlaytestCliUsageError("Desktop playtest requires --executable <native-game-executable>.");
13071
+ async run(step, advance) {
13072
+ const operation = step.operation;
13073
+ const rotation = step.operation === "rotate" ? step.rotation : void 0;
13074
+ const driver = this.driver;
13075
+ if (operation === "background") {
13076
+ this.physicsSteps.beforeBackground = await this.readPhysicsSteps();
13077
+ }
13078
+ try {
13079
+ if (operation === "background") await driver.background?.();
13080
+ else if (operation === "foreground") await driver.foreground?.();
13081
+ else await driver.rotate?.(rotation);
13082
+ } catch (error) {
13083
+ throw new PlaytestBridgeError(playtestDiagnostic(
13084
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED",
13085
+ `The device did not apply the '${operation}' lifecycle operation: ${error instanceof Error ? error.message : String(error)}`,
13086
+ "Inspect the device for an orientation lock, a permission prompt or a system dialog over the app, then rerun the same scenario."
13087
+ ));
13088
+ }
13089
+ if (operation === "foreground") {
13090
+ this.physicsSteps.afterForeground = await this.readPhysicsSteps();
13091
+ }
13092
+ if (operation !== "background") {
13093
+ await advance();
13094
+ this.physicsSteps.afterAdvance = await this.readPhysicsSteps();
13095
+ }
13096
+ const state = await this.read();
13097
+ this.requirePhaseEffect(operation, rotation, state);
13098
+ const settled = operation === "background" ? await this.readSettled(state) : void 0;
13099
+ const phase = settled?.state ?? state;
13100
+ this.phases.push({
13101
+ at: Date.now() - this.startedAt,
13102
+ focused: phase.focused,
13103
+ frames: phase.frames,
13104
+ ...settled === void 0 ? {} : { framesPaused: settled.framesPaused },
13105
+ phase: operation,
13106
+ pid: phase.pid,
13107
+ ...rotation === void 0 ? {} : { requestedRotation: rotation },
13108
+ ...phase.windowRotation === void 0 ? {} : { windowRotation: phase.windowRotation }
13109
+ });
12503
13110
  }
12504
- const iosTransport = flags.get("--ios-transport")?.[0] ?? "simulator";
12505
- if (iosTransport !== "simulator" && iosTransport !== "device") {
12506
- throw new PlaytestCliUsageError(`Unknown iOS transport '${iosTransport}'. Expected 'simulator' or 'device'.`);
13111
+ /**
13112
+ * The `background` phase's own claim: the surface stopped, so read the platform's frame counter
13113
+ * until it agrees. A backgrounded app that keeps rendering reports the truth —
13114
+ * `framesPaused: false`, for an assertion layer to bind to — rather than a settled value the
13115
+ * runner invented on its behalf.
13116
+ *
13117
+ * One unchanged count is not a paused surface. A renderer that is still drawing at 10 Hz answers
13118
+ * two quick reads with the same number, so a settling read followed by one equal read called a
13119
+ * live 10 Hz surface stopped — the exact claim this phase exists to make. The count therefore has
13120
+ * to hold still across a full second, and a count that moves resets the clock, so the settle is
13121
+ * bounded in wall time as well as in reads.
13122
+ */
13123
+ async readSettled(initial) {
13124
+ let state = initial;
13125
+ let heldSince = Date.now();
13126
+ for (let read = 0; read < ANDROID_LIFECYCLE_SETTLE_READS; read += 1) {
13127
+ await delay2(ANDROID_LIFECYCLE_SETTLE_POLL_MS);
13128
+ const next = await this.read();
13129
+ if (next.frames !== state.frames) {
13130
+ heldSince = Date.now();
13131
+ state = next;
13132
+ continue;
13133
+ }
13134
+ if (Date.now() - heldSince >= ANDROID_LIFECYCLE_PAUSE_HOLD_MS) return { framesPaused: true, state: next };
13135
+ state = next;
13136
+ }
13137
+ return { framesPaused: false, state };
12507
13138
  }
12508
- const explicitBrowserArgs = flags.get("--browser-arg") ?? [];
12509
- const browserRecipe = flags.get("--browser-recipe")?.[0];
12510
- if (browserRecipe !== void 0 && browserRecipe !== "webgpu") {
12511
- throw new PlaytestCliUsageError(`Unknown browser recipe '${browserRecipe}'. Expected 'webgpu'.`);
13139
+ /**
13140
+ * The driver already waited for these readings; check them again here, because a phase is a
13141
+ * claim about the device and the claim is worth more than the command's exit code.
13142
+ */
13143
+ requirePhaseEffect(operation, rotation, state) {
13144
+ if (state.focused !== (operation !== "background")) {
13145
+ throw new PlaytestBridgeError(playtestDiagnostic(
13146
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED",
13147
+ `After the '${operation}' operation the device still reports the app as ${state.focused ? "focused" : "unfocused"}.`,
13148
+ "Inspect the device for an orientation lock, a permission prompt or a system dialog over the app, then rerun the same scenario."
13149
+ ));
13150
+ }
13151
+ if (rotation !== void 0 && state.windowRotation !== rotation) {
13152
+ throw new PlaytestBridgeError(playtestDiagnostic(
13153
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED",
13154
+ `The '${operation}' operation asked for rotation ${rotation} and the device's window reports ${String(state.windowRotation)}.`,
13155
+ "Inspect the device for an orientation lock or a fixed-orientation activity, then rerun the same scenario."
13156
+ ));
13157
+ }
12512
13158
  }
12513
- if (browserRecipe !== void 0 && explicitBrowserArgs.length > 0) {
12514
- throw new PlaytestCliUsageError("Choose --browser-recipe or --browser-arg, not both.");
13159
+ observation() {
13160
+ const background = this.phases.find(({ phase }) => phase === "background");
13161
+ const last = this.phases.at(-1);
13162
+ const { afterAdvance, afterForeground, beforeBackground } = this.physicsSteps;
13163
+ return {
13164
+ phases: this.phases,
13165
+ physics: this.countsPhysicsSteps ? {
13166
+ available: true,
13167
+ steps: { afterAdvance, afterForeground, beforeBackground },
13168
+ stepsAdvanced: afterForeground === null || afterAdvance === null ? null : afterAdvance > afterForeground,
13169
+ stepsPaused: beforeBackground === null || afterForeground === null ? null : afterForeground === beforeBackground
13170
+ } : {
13171
+ available: false,
13172
+ reason: "the bridge does not advertise runtime.physics, so this build installs no physics plugin and nothing counts simulation steps; install rapier() to measure physics continuity across a lifecycle"
13173
+ },
13174
+ render: {
13175
+ framesAdvanced: background === void 0 || last === void 0 ? null : last.frames > background.frames,
13176
+ framesPaused: background?.framesPaused ?? null
13177
+ },
13178
+ session: { pid: this.pid }
13179
+ };
12515
13180
  }
12516
- const device = flags.get("--device")?.[0];
12517
- const cpuProfilePath = flags.get("--cpu-prof")?.[0];
12518
- if (target === "browser" && device !== void 0) {
12519
- if (browserRecipe !== void 0) {
12520
- throw new PlaytestCliUsageError("Android Chrome device runs cannot honor --browser-recipe; remove it.");
13181
+ /**
13182
+ * The runtime-owned simulation-step count, or nothing on a build that installs no physics plugin.
13183
+ *
13184
+ * Fails closed rather than reporting a zero: a bridge that advertises `runtime.physics` and
13185
+ * answers with no count, a string, or a negative number has not measured the simulation, and a
13186
+ * zero here would be indistinguishable from a game that genuinely never stepped.
13187
+ */
13188
+ async readPhysicsSteps() {
13189
+ if (!this.countsPhysicsSteps) return null;
13190
+ const value = (await this.sample()).physicsSteps;
13191
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
13192
+ throw new PlaytestBridgeError(playtestDiagnostic(
13193
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_PHYSICS_UNOBSERVED",
13194
+ `The bridge advertises runtime.physics but reported ${JSON.stringify(value) ?? "no simulation-step count"} instead of one, so physics continuity cannot be recorded across the lifecycle.`,
13195
+ "Install rapier(), whose runtime.physics observation carries the step count taken at simulation.step, or drop the lifecycle steps. A count a game keeps in its own state is not a measurement, and an absent one is never read as a simulation that stood still."
13196
+ ));
12521
13197
  }
12522
- if (explicitBrowserArgs.length > 0) {
12523
- throw new PlaytestCliUsageError("Android Chrome device runs cannot honor --browser-arg; remove it.");
13198
+ return value;
13199
+ }
13200
+ /** One device reading, in the process this run launched. A different pid is a failed run. */
13201
+ async read() {
13202
+ const state = await this.readDevice();
13203
+ if (state.pid !== this.pid) {
13204
+ throw new PlaytestBridgeError(playtestDiagnostic(
13205
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_SESSION_CHANGED",
13206
+ `The app process changed across the lifecycle: the run launched pid ${String(this.pid)} and the device now reports ${String(state.pid)}.`,
13207
+ "A lifecycle proof needs one process across background, foreground and rotation. Find what killed or relaunched the app before rerunning."
13208
+ ));
12524
13209
  }
12525
- if (argv.includes("--headed")) {
12526
- throw new PlaytestCliUsageError("Android Chrome device runs are already visible on the device and cannot honor --headed; remove it.");
13210
+ return { ...state, pid: this.pid };
13211
+ }
13212
+ /** One complete device reading, or a named failure. Never a default. */
13213
+ async readDevice() {
13214
+ const state = await this.driver.lifecycleState?.();
13215
+ if (state?.frames === void 0) {
13216
+ throw new PlaytestBridgeError(playtestDiagnostic(
13217
+ "TN_PLAYTEST_ANDROID_LIFECYCLE_UNOBSERVED",
13218
+ "The device reported no frame count for this process, so a lifecycle phase cannot be recorded.",
13219
+ "Run against a device that answers `dumpsys gfxinfo <package>` with a frame counter, or drop the lifecycle steps; an absent counter is never read as a paused surface."
13220
+ ));
12527
13221
  }
13222
+ return { ...state, frames: state.frames };
12528
13223
  }
12529
- const rawTouchRotation = flags.get("--touch-rotation")?.[0];
12530
- if (rawTouchRotation !== void 0 && !/^[0-3]$/u.test(rawTouchRotation)) {
12531
- throw new Error(
12532
- `TN_PLAYTEST_ANDROID_ROTATION_INVALID: --touch-rotation must be 0, 1, 2 or 3, got '${rawTouchRotation}'.`
13224
+ };
13225
+ function unsupportedAssertion(scenario, target, hasPointerTransport, canDriveLifecycle) {
13226
+ if (scenario.steps.some((step) => step.lifecycle !== void 0) && (target !== "android" || !canDriveLifecycle)) {
13227
+ return unsupportedDiagnostic(
13228
+ "lifecycle steps",
13229
+ "Run lifecycle steps on --target android with the adb-backed driver. The browser, desktop and iOS lanes cannot background, foreground or rotate the app, and the phases this step reports have to be read off the device \u2014 a game-authored GameState would only restate what the scenario already said.",
13230
+ target
12533
13231
  );
12534
13232
  }
12535
- const touchRotation = rawTouchRotation === void 0 ? void 0 : Number(rawTouchRotation);
12536
- const androidUser = flags.get("--user")?.[0];
12537
- if (androidUser !== void 0 && !/^\d+$/u.test(androidUser)) {
12538
- throw new PlaytestCliUsageError(`Android --user must be numeric, got '${androidUser}'.`);
13233
+ if (scenario.steps.some((step) => step.wheel !== void 0)) {
13234
+ return unsupportedDiagnostic(
13235
+ "wheel input steps",
13236
+ "Run wheel input steps on --target browser; Android, desktop, and iOS runners have no wheel injector and will not skip the sample.",
13237
+ target
13238
+ );
12539
13239
  }
12540
- const hostArgs = flags.get("--host-arg") ?? [];
12541
- const browserArgs = explicitBrowserArgs.length > 0 ? explicitBrowserArgs : browserRecipe === "webgpu" ? [...WEBGPU_BROWSER_ARGS] : [];
12542
- return {
12543
- ...flags.get("--adb")?.[0] === void 0 ? {} : { adbPath: flags.get("--adb")[0] },
12544
- ...touchRotation === void 0 ? {} : { touchRotation },
12545
- // A scaffolded project's own `test` script is what a user runs, and it deliberately refuses a
12546
- // software adapter — nothing about that should change to suit a runner. But CI has no GPU and
12547
- // still needs to prove the scaffold installs, builds and plays, so the same acceptance the
12548
- // flag expresses is available as an environment variable a workflow can set around an
12549
- // unmodified project. It is not a silent default: the run still reports the adapter it got,
12550
- // and TN_PLAYTEST_SOFTWARE_ADAPTER is suppressed only because someone said so out loud.
12551
- allowSoftwareAdapter: argv.includes("--allow-software") || process.env.TN_PLAYTEST_ALLOW_SOFTWARE === "1",
12552
- android: {
12553
- activity: flags.get("--activity")?.[0] ?? ".MystralActivity",
12554
- packageName: flags.get("--package")?.[0] ?? "com.mystral.engine",
12555
- ...androidUser === void 0 ? {} : { user: androidUser }
12556
- },
12557
- artifactDirectory: resolve(projectPath, flags.get("--artifacts")?.[0] ?? "artifacts/playtest"),
12558
- captureArtifactScreenshots: !argv.includes("--no-screenshots"),
12559
- ...browserArgs.length === 0 ? {} : { browserArgs },
12560
- ...cpuProfilePath === void 0 ? {} : { cpuProfilePath: resolve(projectPath, cpuProfilePath) },
12561
- ...device === void 0 ? {} : { device },
12562
- ...executable === void 0 ? {} : {
12563
- desktop: {
12564
- executable: resolve(projectPath, executable),
12565
- ...hostArgs.length === 0 ? {} : { hostArgs }
12566
- }
12567
- },
12568
- endpoint: flags.get("--endpoint")?.[0] ?? "http://127.0.0.1:41777/playtest",
12569
- headless: !argv.includes("--headed"),
12570
- ios: {
12571
- ...appPath === void 0 ? {} : { appPath: resolve(projectPath, appPath) },
12572
- bundleId: flags.get("--bundle-id")?.[0] ?? "dev.threenative.runtime",
12573
- transport: iosTransport
12574
- },
12575
- ...flags.get("--mailbox-root")?.[0] === void 0 ? {} : { mailboxRoot: flags.get("--mailbox-root")[0] },
12576
- ...serverCommand === void 0 ? effectivePort === void 0 ? {} : { port: effectivePort } : { port: effectivePort ?? 0 },
12577
- projectPath,
12578
- scenarioPath: scenarioPaths[0],
12579
- scenarioPaths,
12580
- ...serverCommand === void 0 ? {} : { server: { command: serverCommand, cwd: projectPath, timeoutMs: readPositiveInteger(flags.get("--server-timeout")?.[0], 15e3) } },
12581
- timeoutMs: readPositiveInteger(flags.get("--timeout")?.[0], 15e3),
12582
- target,
12583
- trace: argv.includes("--trace"),
12584
- url: requestedPort !== void 0 && requestedPort > 0 && (urlFlag === void 0 || urlPort === void 0) ? withPort2(url, requestedPort) : url,
12585
- ...flags.get("--xcrun")?.[0] === void 0 ? {} : { xcrunPath: flags.get("--xcrun")[0] }
12586
- };
12587
- }
12588
- var SCENARIO_GLOB = /[*?[]/u;
12589
- function expandScenarioPattern(projectPath, pattern) {
12590
- if (!SCENARIO_GLOB.test(pattern)) return [pattern];
12591
- const normalizedPattern = pattern.replaceAll("\\", "/");
12592
- const matches = [];
12593
- collectScenarioFiles(projectPath, projectPath, matches);
12594
- const matching = matches.filter((file) => globMatches(normalizedPattern, file)).sort((left, right) => left.localeCompare(right));
12595
- if (matching.length === 0) {
12596
- throw new PlaytestCliUsageError(`Scenario glob '${pattern}' matched no files under '${projectPath}'.`);
13240
+ if (scenario.steps.some((step) => step.kind === "click") && (target !== "android" || !hasPointerTransport)) {
13241
+ return unsupportedDiagnostic(
13242
+ "click steps",
13243
+ "Run click steps on --target browser, or use an Android driver with OS pointer injection; native targets never fall back to keyboard input.",
13244
+ target
13245
+ );
12597
13246
  }
12598
- return matching;
12599
- }
12600
- function collectScenarioFiles(directory, root, files) {
12601
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
12602
- if (entry.isDirectory()) {
12603
- if (entry.name === ".git" || entry.name === "node_modules" || entry.name === "dist") continue;
12604
- collectScenarioFiles(resolve(directory, entry.name), root, files);
12605
- continue;
12606
- }
12607
- if (!entry.isFile()) continue;
12608
- files.push(relative(root, resolve(directory, entry.name)).replaceAll("\\", "/"));
13247
+ if (scenario.assert?.deviceMetrics !== void 0 && target !== "android") {
13248
+ return unsupportedDiagnostic(
13249
+ "device thermal and power assertions",
13250
+ `Run this assertion on --target android; ${targetLabel(target)} has no battery, thermal or power-rail probe.`,
13251
+ target
13252
+ );
12609
13253
  }
12610
- }
12611
- function globMatches(pattern, file) {
12612
- const patternParts = pattern.split("/");
12613
- const fileParts = file.split("/");
12614
- return matchGlobParts(patternParts, fileParts);
12615
- }
12616
- function matchGlobParts(pattern, file) {
12617
- if (pattern.length === 0) return file.length === 0;
12618
- const [head, ...tail] = pattern;
12619
- if (head === "**") {
12620
- return matchGlobParts(tail, file) || file.length > 0 && matchGlobParts(pattern, file.slice(1));
13254
+ if (scenario.assert?.diagnostics?.noNetworkErrors === true) {
13255
+ return unsupportedDiagnostic(
13256
+ "network assertions",
13257
+ `Run this assertion on --target browser; ${targetLabel(target)} device transport has no CDP network observer. Remove the explicit network assertion, or declare "diagnostics": { "noNetworkErrors": false, "networkErrorsOptOutReason": "..." } to record a scenario-owned waiver.`,
13258
+ target
13259
+ );
12621
13260
  }
12622
- return file.length > 0 && segmentMatches(head ?? "", file[0]) && matchGlobParts(tail, file.slice(1));
12623
- }
12624
- function segmentMatches(pattern, value) {
12625
- let expression = "^";
12626
- for (let index = 0; index < pattern.length; index += 1) {
12627
- const character = pattern[index];
12628
- if (character === "*") expression += "[^/]*";
12629
- else if (character === "?") expression += "[^/]";
12630
- else expression += escapeRegExp(character);
13261
+ if ((scenario.assert?.hud?.length ?? 0) > 0 || (scenario.assert?.overlayNodes?.length ?? 0) > 0) {
13262
+ return unsupportedDiagnostic(
13263
+ "DOM assertions",
13264
+ `Use runtime resources/components for a cross-target scenario; ${targetLabel(target)} has no DOM observer.`,
13265
+ target
13266
+ );
12631
13267
  }
12632
- return new RegExp(`${expression}$`, "u").test(value);
12633
- }
12634
- function escapeRegExp(value) {
12635
- return value.replace(/[|\\{}()[\]^$+?.]/gu, "\\$&");
12636
- }
12637
- function portFromUrl(url) {
12638
- try {
12639
- const parsed = new URL(url);
12640
- return parsed.port === "" ? void 0 : Number(parsed.port);
12641
- } catch {
12642
- return void 0;
13268
+ if ((scenario.assert?.visual?.length ?? 0) > 0) {
13269
+ return unsupportedDiagnostic(
13270
+ "visual assertions",
13271
+ `${targetLabel(target)} screenshots are captured as artifacts, but visual metric evaluation is not supported yet.`,
13272
+ target
13273
+ );
12643
13274
  }
12644
- }
12645
- function withPort2(url, port) {
12646
- const parsed = new URL(url);
12647
- parsed.port = String(port);
12648
- const result = parsed.toString();
12649
- return url.endsWith("/") ? result : result.replace(/\/$/u, "");
12650
- }
12651
- function readPort(value) {
12652
- if (value === void 0) return void 0;
12653
- const parsed = Number(value);
12654
- if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
12655
- throw new PlaytestCliUsageError(`Expected a TCP port from 0 to 65535, received '${value}'.`);
13275
+ if (scenario.assert?.framebufferCoverage !== void 0 && target === "ios") {
13276
+ return unsupportedDiagnostic(
13277
+ "framebuffer coverage recording",
13278
+ "Run this assertion on --target browser or --target android; the iOS transport has no per-frame recorder observer.",
13279
+ target
13280
+ );
12656
13281
  }
12657
- return parsed;
12658
- }
12659
- function parseFlags(argv) {
12660
- const flags = /* @__PURE__ */ new Map();
12661
- for (let index = 0; index < argv.length; index += 1) {
12662
- const name = argv[index];
12663
- if (!name?.startsWith("--") || name === "--help") continue;
12664
- if (!isPlaytestFlag(name)) throw new PlaytestCliUsageError(`Unknown flag '${name}'. Run threenative-playtest --help.`);
12665
- const details = PLAYTEST_FLAGS[name];
12666
- if (!details.takesValue) continue;
12667
- const next = argv[index + 1];
12668
- if (next === void 0 || next.startsWith("--") && (!details.allowDashValue || isPlaytestFlag(next))) {
12669
- throw new PlaytestCliUsageError(`Flag '${name}' requires a value.`);
12670
- }
12671
- flags.set(name, [...flags.get(name) ?? [], next]);
12672
- index += 1;
13282
+ if (scenario.assert?.framebufferCoverage !== void 0 && target === "desktop") {
13283
+ return unsupportedDiagnostic(
13284
+ "framebuffer coverage recording",
13285
+ "Run this assertion on --target browser or --target android; the desktop mailbox exposes screenshots, not a per-frame recorder observer.",
13286
+ target
13287
+ );
12673
13288
  }
12674
- return flags;
13289
+ return void 0;
12675
13290
  }
12676
- function positional(argv) {
12677
- return argv.find((value, index) => !value.startsWith("-") && (index === 0 || !argv[index - 1]?.startsWith("--")));
13291
+ function unsupportedDiagnostic(subject, fix, target) {
13292
+ return playtestDiagnostic(
13293
+ "TN_PLAYTEST_UNSUPPORTED_ON_TARGET",
13294
+ `${targetLabel(target)} ${target === "desktop" ? "desktop" : "device"} target does not support ${subject}.`,
13295
+ fix
13296
+ );
12678
13297
  }
12679
- function readPositiveInteger(value, fallback) {
12680
- const parsed = value === void 0 ? fallback : Number(value);
12681
- if (!Number.isInteger(parsed) || parsed <= 0) {
12682
- throw new PlaytestCliUsageError(`Expected a positive integer, received '${value ?? ""}'.`);
12683
- }
12684
- return parsed;
13298
+ function unreadableCoverageObservation(error) {
13299
+ return {
13300
+ boundarySource: "scenario-steps",
13301
+ frameCount: 0,
13302
+ unreadableReason: error instanceof Error ? error.message : String(error),
13303
+ windowCompleted: false,
13304
+ windowStarted: false
13305
+ };
12685
13306
  }
12686
- function isPlaytestFlag(value) {
12687
- return Object.prototype.hasOwnProperty.call(PLAYTEST_FLAGS, value);
13307
+ function delay2(milliseconds) {
13308
+ return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
12688
13309
  }
12689
13310
  var SCREENSHOT_TIMEOUT_MS2 = 5e3;
12690
13311
  var SCREENSHOT_REQUEST_FILE = "tn-playtest-screenshot-request.txt";
13312
+ function nativeScreenshotTimeoutMs(environment = process.env) {
13313
+ const configured = environment.TN_PLAYTEST_NATIVE_SCREENSHOT_TIMEOUT_MS;
13314
+ if (configured === void 0 || configured.trim().length === 0) return SCREENSHOT_TIMEOUT_MS2;
13315
+ const parsed = Number(configured);
13316
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : SCREENSHOT_TIMEOUT_MS2;
13317
+ }
12691
13318
  var SCREENSHOT_REQUEST_TEMP_FILE = `${SCREENSHOT_REQUEST_FILE}.tmp`;
13319
+ var HOST_DIAGNOSTIC_LINE = /\[(?:Screenshot|Playtest)\]/u;
12692
13320
  var LocalDeviceMailbox = class {
12693
- async read(path) {
13321
+ async read(path2) {
12694
13322
  try {
12695
- return await readFile(path, "utf8");
13323
+ return await readFile(path2, "utf8");
12696
13324
  } catch (error) {
12697
13325
  if (isMissingFile(error) || isTransientMailboxLock(error)) return void 0;
12698
13326
  throw error;
12699
13327
  }
12700
13328
  }
12701
- async remove(path) {
13329
+ async remove(path2) {
12702
13330
  for (let retry = 0; ; retry += 1) {
12703
13331
  try {
12704
- await rm(path, { force: true });
13332
+ await rm(path2, { force: true });
12705
13333
  return;
12706
13334
  } catch (error) {
12707
13335
  if (retry >= 10 || !isTransientMailboxLock(error)) throw error;
12708
- await delay2(20);
13336
+ await delay3(20);
12709
13337
  }
12710
13338
  }
12711
13339
  }
12712
- async write(path, contents) {
12713
- await mkdir(dirname(path), { recursive: true });
12714
- const temporary = `${path}.tmp`;
13340
+ async write(path2, contents) {
13341
+ await mkdir(dirname(path2), { recursive: true });
13342
+ const temporary = `${path2}.tmp`;
12715
13343
  await writeFile(temporary, contents, "utf8");
12716
- await rename(temporary, path);
13344
+ await rename(temporary, path2);
12717
13345
  }
12718
13346
  };
12719
13347
  var DesktopPlaytestDriver = class {
@@ -12773,33 +13401,51 @@ var DesktopPlaytestDriver = class {
12773
13401
  throw error;
12774
13402
  }
12775
13403
  }
12776
- async screenshot(path) {
13404
+ async screenshot(path2) {
12777
13405
  const root = this.mailboxRoot;
12778
13406
  if (root === void 0) throw new Error("Desktop playtest mailbox is unavailable before prepare().");
12779
13407
  if (!await this.isAlive()) throw new Error("Desktop playtest executable exited before screenshot capture.");
12780
- await rm(path, { force: true });
13408
+ await rm(path2, { force: true });
12781
13409
  const request = join(root, SCREENSHOT_REQUEST_FILE);
12782
- await new LocalDeviceMailbox().write(request, path);
12783
- const deadline = Date.now() + (this.options.screenshotTimeoutMs ?? SCREENSHOT_TIMEOUT_MS2);
13410
+ await new LocalDeviceMailbox().write(request, path2);
13411
+ const pickupDeadline = Date.now() + (this.options.screenshotTimeoutMs ?? nativeScreenshotTimeoutMs());
13412
+ const deadline = pickupDeadline + SCREENSHOT_TIMEOUT_MS;
13413
+ let accepted = false;
12784
13414
  let lastReadError;
12785
13415
  while (Date.now() < deadline) {
12786
- try {
12787
- const png = await readFile(path);
12788
- assertCaptureNotBlank(png, path);
12789
- return;
12790
- } catch (error) {
12791
- if (error instanceof Error && error.name === "CaptureGuardError") throw error;
12792
- if (!isMissingFile(error)) lastReadError = error;
12793
- }
13416
+ const readError = await tryReadDesktopScreenshot(path2);
13417
+ if (readError === void 0) return;
13418
+ lastReadError = readError;
12794
13419
  if (!await this.isAlive()) {
12795
13420
  throw new Error("Desktop playtest executable exited before screenshot capture.");
12796
13421
  }
12797
- await delay2(25);
13422
+ if (!accepted) {
13423
+ accepted = await new LocalDeviceMailbox().read(request) === void 0;
13424
+ if (!accepted && Date.now() >= pickupDeadline) break;
13425
+ }
13426
+ await delay3(25);
12798
13427
  }
12799
13428
  throw new Error(
12800
- `TN_PLAYTEST_NATIVE_SCREENSHOT_UNAVAILABLE: ${lastReadError instanceof Error ? lastReadError.message : "request timed out"}`
13429
+ `TN_PLAYTEST_NATIVE_SCREENSHOT_UNAVAILABLE: ${await this.describeScreenshotTimeout(request, lastReadError)}`
12801
13430
  );
12802
13431
  }
13432
+ /**
13433
+ * Why a screenshot produced no file. The host's own lines are the only place that answer is
13434
+ * written, and the request file's presence splits the failure in two: left behind means the host
13435
+ * never looked, consumed means it read the request and the capture never landed. A bounded tail,
13436
+ * never the whole log — a 40k-line dump is how a timeout becomes unreadable. The tail keeps the
13437
+ * host's tagged lines and the entries classified as errors, because the root cause (an EGL
13438
+ * failure, a texture that never arrived) is usually an untagged line the tag filter alone drops.
13439
+ */
13440
+ async describeScreenshotTimeout(request, lastReadError) {
13441
+ this.flushOutput("stdout");
13442
+ this.flushOutput("stderr");
13443
+ const cause = lastReadError instanceof Error ? lastReadError.message : "request timed out";
13444
+ const requestState = await requestFileState(request);
13445
+ const diagnostic = this.consoleEntries.filter((entry) => entry.type === "error" || HOST_DIAGNOSTIC_LINE.test(entry.text));
13446
+ const tail = (diagnostic.length > 0 ? diagnostic : this.consoleEntries).slice(-6).map((entry) => entry.text);
13447
+ return `${cause}; ${requestState}; native host output: ${tail.length > 0 ? tail.join(" | ") : "none captured"}`;
13448
+ }
12803
13449
  async stop() {
12804
13450
  const child = this.child;
12805
13451
  if (child === void 0) return;
@@ -12838,6 +13484,16 @@ var DesktopPlaytestDriver = class {
12838
13484
  }
12839
13485
  }
12840
13486
  };
13487
+ async function tryReadDesktopScreenshot(path2) {
13488
+ try {
13489
+ const png = await readFile(path2);
13490
+ assertCaptureNotBlank(png, path2);
13491
+ return void 0;
13492
+ } catch (error) {
13493
+ if (error instanceof Error && error.name === "CaptureGuardError") throw error;
13494
+ return isMissingFile(error) ? "request timed out" : error;
13495
+ }
13496
+ }
12841
13497
  function desktopConsoleType(stream, line) {
12842
13498
  const text = line.trimStart();
12843
13499
  if (/^(?:\[error\]|(?:error|fatal):)/iu.test(text)) return "error";
@@ -12892,7 +13548,7 @@ function waitForExit(child, timeoutMs) {
12892
13548
  function isProcessExited(child) {
12893
13549
  return child.exitCode !== null || child.signalCode !== null;
12894
13550
  }
12895
- function delay2(milliseconds) {
13551
+ function delay3(milliseconds) {
12896
13552
  return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
12897
13553
  }
12898
13554
  function isTransientMailboxLock(error) {
@@ -12902,6 +13558,15 @@ function isTransientMailboxLock(error) {
12902
13558
  function isMissingFile(error) {
12903
13559
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
12904
13560
  }
13561
+ async function requestFileState(path2) {
13562
+ try {
13563
+ await readFile(path2);
13564
+ return "request file still present";
13565
+ } catch (error) {
13566
+ if (isMissingFile(error)) return "request file consumed";
13567
+ return `request file unreadable: ${error instanceof Error ? error.message : String(error)}`;
13568
+ }
13569
+ }
12905
13570
  function desktopHostArgs(config) {
12906
13571
  const args = config.desktop?.hostArgs ?? [];
12907
13572
  return config.cpuProfilePath === void 0 ? args : [...args, `--cpu-prof=${config.cpuProfilePath}`];
@@ -12959,7 +13624,8 @@ async function runDesktopPlaytest(config, dependencies = {}) {
12959
13624
  cwd: config.projectPath,
12960
13625
  ...providedDisplay === void 0 ? {} : { env: providedDisplay.env },
12961
13626
  executable,
12962
- mailboxRoot: root
13627
+ mailboxRoot: root,
13628
+ screenshotTimeoutMs: config.timeoutMs
12963
13629
  });
12964
13630
  transport = dependencies.transport ?? new DeviceMailboxTransport(
12965
13631
  new LocalDeviceMailbox(),
@@ -12979,6 +13645,17 @@ async function runDesktopPlaytest(config, dependencies = {}) {
12979
13645
  } catch (error) {
12980
13646
  executionFailed = true;
12981
13647
  executionError = error;
13648
+ if (driver !== void 0) {
13649
+ try {
13650
+ await mkdir(config.artifactDirectory, { recursive: true });
13651
+ await writeObservationArtifacts(config.artifactDirectory, void 0, {
13652
+ console: await driver.captureConsole(),
13653
+ network: [],
13654
+ runtimeTrace: void 0
13655
+ });
13656
+ } catch {
13657
+ }
13658
+ }
12982
13659
  } finally {
12983
13660
  process.off("SIGINT", handleSignal);
12984
13661
  process.off("SIGTERM", handleSignal);
@@ -13172,25 +13849,25 @@ var XcrunIosDriver = class {
13172
13849
  return false;
13173
13850
  }
13174
13851
  }
13175
- async screenshot(path) {
13852
+ async screenshot(path2) {
13176
13853
  if (this.options.transport === "simulator") {
13177
- await this.run(["simctl", "io", this.device(), "screenshot", path]);
13854
+ await this.run(["simctl", "io", this.device(), "screenshot", path2]);
13178
13855
  return;
13179
13856
  }
13180
- await this.run(["devicectl", "device", "capture", "screen", "--device", this.device(), "--destination", path]);
13857
+ await this.run(["devicectl", "device", "capture", "screen", "--device", this.device(), "--destination", path2]);
13181
13858
  }
13182
- async readFile(path) {
13183
- path = this.mailboxPath(path);
13859
+ async readFile(path2) {
13860
+ path2 = this.mailboxPath(path2);
13184
13861
  if (this.options.transport === "simulator") {
13185
13862
  try {
13186
- return await readFile(path, "utf8");
13863
+ return await readFile(path2, "utf8");
13187
13864
  } catch (error) {
13188
13865
  if (error.code === "ENOENT") return void 0;
13189
13866
  throw error;
13190
13867
  }
13191
13868
  }
13192
13869
  const directory = await mkdtemp(join(tmpdir(), "threenative-devicectl-read-"));
13193
- const destination = join(directory, basename(path));
13870
+ const destination = join(directory, basename(path2));
13194
13871
  try {
13195
13872
  await this.run([
13196
13873
  "devicectl",
@@ -13204,7 +13881,7 @@ var XcrunIosDriver = class {
13204
13881
  "--domain-identifier",
13205
13882
  this.options.bundleId,
13206
13883
  "--source",
13207
- path,
13884
+ path2,
13208
13885
  "--destination",
13209
13886
  destination
13210
13887
  ]);
@@ -13217,16 +13894,16 @@ var XcrunIosDriver = class {
13217
13894
  await rm(directory, { force: true, recursive: true });
13218
13895
  }
13219
13896
  }
13220
- async removeFile(path) {
13897
+ async removeFile(path2) {
13221
13898
  if (this.mailboxRoot === void 0) return;
13222
- path = this.mailboxPath(path);
13899
+ path2 = this.mailboxPath(path2);
13223
13900
  if (this.options.transport === "simulator") {
13224
- await unlink(path).catch((error) => {
13901
+ await unlink(path2).catch((error) => {
13225
13902
  if (error.code !== "ENOENT") throw error;
13226
13903
  });
13227
13904
  return;
13228
13905
  }
13229
- this.suppressedResponse = await this.readFile(path);
13906
+ this.suppressedResponse = await this.readFile(path2);
13230
13907
  }
13231
13908
  async stop() {
13232
13909
  if (this.options.transport === "simulator") {
@@ -13243,17 +13920,17 @@ var XcrunIosDriver = class {
13243
13920
  ]).catch(() => void 0);
13244
13921
  }
13245
13922
  }
13246
- async writeFile(path, contents) {
13247
- path = this.mailboxPath(path);
13923
+ async writeFile(path2, contents) {
13924
+ path2 = this.mailboxPath(path2);
13248
13925
  if (this.options.transport === "simulator") {
13249
- await mkdir(dirname(path), { recursive: true });
13250
- const temporary = `${path}.incoming-${process.pid}-${Date.now()}`;
13926
+ await mkdir(dirname(path2), { recursive: true });
13927
+ const temporary = `${path2}.incoming-${process.pid}-${Date.now()}`;
13251
13928
  await writeFile(temporary, contents, "utf8");
13252
- await rename(temporary, path);
13929
+ await rename(temporary, path2);
13253
13930
  return;
13254
13931
  }
13255
13932
  const directory = await mkdtemp(join(tmpdir(), "threenative-devicectl-write-"));
13256
- const source = join(directory, basename(path));
13933
+ const source = join(directory, basename(path2));
13257
13934
  try {
13258
13935
  await writeFile(source, contents, "utf8");
13259
13936
  await this.run([
@@ -13270,7 +13947,7 @@ var XcrunIosDriver = class {
13270
13947
  "--source",
13271
13948
  source,
13272
13949
  "--destination",
13273
- path
13950
+ path2
13274
13951
  ]);
13275
13952
  } finally {
13276
13953
  await rm(directory, { force: true, recursive: true });
@@ -13341,8 +14018,8 @@ var XcrunIosDriver = class {
13341
14018
  device() {
13342
14019
  return this.options.device ?? "booted";
13343
14020
  }
13344
- mailboxPath(path) {
13345
- return this.mailboxRoot === void 0 ? path : join(this.mailboxRoot, basename(path));
14021
+ mailboxPath(path2) {
14022
+ return this.mailboxRoot === void 0 ? path2 : join(this.mailboxRoot, basename(path2));
13346
14023
  }
13347
14024
  };
13348
14025
  function parseLaunchedPid(output) {
@@ -13376,33 +14053,33 @@ async function runIosPlaytest(config, dependencies = {}) {
13376
14053
  // src/runner/recording.ts
13377
14054
  var SCENARIO_VIEWPORT = { height: 720, width: 1280 };
13378
14055
  var FINAL_STEP_LABEL = "replay-final";
13379
- function recordNumber(value, path, integer = false) {
14056
+ function recordNumber(value, path2, integer = false) {
13380
14057
  if (typeof value !== "number" || !Number.isFinite(value) || integer && !Number.isInteger(value))
13381
- throw invalidScenario(path, `${path} must be a finite${integer ? " integer" : " number"}.`);
14058
+ throw invalidScenario(path2, `${path2} must be a finite${integer ? " integer" : " number"}.`);
13382
14059
  return value;
13383
14060
  }
13384
- function recordString(value, path) {
13385
- if (typeof value !== "string" || value.length === 0) throw invalidScenario(path, `${path} must be a non-empty string.`);
14061
+ function recordString(value, path2) {
14062
+ if (typeof value !== "string" || value.length === 0) throw invalidScenario(path2, `${path2} must be a non-empty string.`);
13386
14063
  return value;
13387
14064
  }
13388
- function recordObject(value, path) {
14065
+ function recordObject(value, path2) {
13389
14066
  if (typeof value !== "object" || value === null || Array.isArray(value))
13390
- throw invalidScenario(path, `${path} must be an object.`);
14067
+ throw invalidScenario(path2, `${path2} must be an object.`);
13391
14068
  return value;
13392
14069
  }
13393
- function recordTuple(value, path) {
14070
+ function recordTuple(value, path2) {
13394
14071
  if (!Array.isArray(value) || value.length !== 3 || !value.every((item) => typeof item === "number" && Number.isFinite(item)))
13395
- throw invalidScenario(path, `${path} must be a finite three-number tuple.`);
14072
+ throw invalidScenario(path2, `${path2} must be a finite three-number tuple.`);
13396
14073
  return value;
13397
14074
  }
13398
- function recordPointer(value, path) {
14075
+ function recordPointer(value, path2) {
13399
14076
  if (!Array.isArray(value) || value.length !== 5 || !value.every((item) => typeof item === "number" && Number.isFinite(item)))
13400
- throw invalidScenario(path, `${path} must be [x, y, buttons, viewport width, viewport height].`);
14077
+ throw invalidScenario(path2, `${path2} must be [x, y, buttons, viewport width, viewport height].`);
13401
14078
  const pointer = value;
13402
14079
  if (!Number.isInteger(pointer[2]) || pointer[2] < 0 || (pointer[2] & -8) !== 0)
13403
- throw invalidScenario(path, `${path} buttons must use left, right, or middle buttons only.`);
14080
+ throw invalidScenario(path2, `${path2} buttons must use left, right, or middle buttons only.`);
13404
14081
  if (!Number.isInteger(pointer[3]) || pointer[3] < 1 || !Number.isInteger(pointer[4]) || pointer[4] < 1)
13405
- throw invalidScenario(path, `${path} viewport dimensions must be positive integers.`);
14082
+ throw invalidScenario(path2, `${path2} viewport dimensions must be positive integers.`);
13406
14083
  return pointer;
13407
14084
  }
13408
14085
  function validateRecording(value, scenarioPath) {
@@ -14505,7 +15182,10 @@ async function withBrowserCapture(config, capture, signal) {
14505
15182
  };
14506
15183
  try {
14507
15184
  checkAbort();
14508
- const scenario = await stage("scenario load", () => loadPlaytestScenario(config.projectPath, config.scenarioPath));
15185
+ const scenario = withPerformanceBudget(
15186
+ await stage("scenario load", () => loadPlaytestScenario(config.projectPath, config.scenarioPath)),
15187
+ config.performanceBudget
15188
+ );
14509
15189
  if (scenario.target !== "web") throw new Error("TN_CAPTURE_SESSION_TARGET: browser captures require a web scenario");
14510
15190
  if (scenario.bootFailure !== void 0 || scenario.awaitStartup === false) {
14511
15191
  throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: custom captures cannot bypass startup; use the scenario runner for boot-failure tests");
@@ -14521,7 +15201,7 @@ async function withBrowserCapture(config, capture, signal) {
14521
15201
  browserArgs: resolveBrowserArguments(config.browserArgs ?? WEBGPU_BROWSER_ARGS),
14522
15202
  headless: false,
14523
15203
  ...port === void 0 ? {} : { port },
14524
- url: needsFreePort && port !== void 0 ? withPort(config.url, port) : config.url
15204
+ url: needsFreePort && port !== void 0 ? withPort2(config.url, port) : config.url
14525
15205
  };
14526
15206
  await mkdir(active.artifactDirectory, { recursive: true });
14527
15207
  if (active.server !== void 0) {
@@ -14552,8 +15232,8 @@ async function withBrowserCapture(config, capture, signal) {
14552
15232
  await stage("warmup", () => waitFrames(activePage, scenario.warmupFrames), startupBudget);
14553
15233
  const startup = await stage("engine startup readiness", () => waitForStartupReady({
14554
15234
  aborted: () => controller.signal.aborted,
14555
- acceptCompileSettled: active.allowSoftwareAdapter === true,
14556
15235
  bridge,
15236
+ declaredSoftware: active.allowSoftwareAdapter === true,
14557
15237
  pump: () => waitFrames(activePage, 1)
14558
15238
  }), startupBudget);
14559
15239
  if (startup === void 0) throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: no startup observation was returned");
@@ -14609,4 +15289,4 @@ async function withBrowserCapture(config, capture, signal) {
14609
15289
  }
14610
15290
  }
14611
15291
 
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 };
15292
+ 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, decideDisplayStrategy, 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 };