@vehicle-sil/gui-client 0.2.0-rc.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -632,22 +632,22 @@ var readRunParticipant = (value, path, u) => {
632
632
  };
633
633
  var readRunTiming = (value, path, u) => {
634
634
  const f = object(value, path);
635
- const count2 = (key) => field(f, path, key, soft(nullable(number), null, u));
635
+ const count = (key) => field(f, path, key, soft(nullable(number), null, u));
636
636
  return withRaw(f, {
637
637
  speed: field(f, path, "speed", soft(readSpeed, null, u)),
638
- time_step_ms: count2("time_step_ms"),
639
- ecu_step_ms: count2("ecu_step_ms"),
640
- step_delay_ms: count2("step_delay_ms"),
641
- late_tolerance_ms: count2("late_tolerance_ms"),
642
- sim_ms: count2("sim_ms"),
643
- wall_ms: count2("wall_ms"),
644
- actual_speed: count2("actual_speed"),
645
- paced_steps: count2("paced_steps"),
646
- late_steps: count2("late_steps"),
647
- max_late_ms: count2("max_late_ms"),
648
- slipped_ms: count2("slipped_ms"),
649
- late_ms: count2("late_ms"),
650
- paused_ms: count2("paused_ms")
638
+ time_step_ms: count("time_step_ms"),
639
+ ecu_step_ms: count("ecu_step_ms"),
640
+ step_delay_ms: count("step_delay_ms"),
641
+ late_tolerance_ms: count("late_tolerance_ms"),
642
+ sim_ms: count("sim_ms"),
643
+ wall_ms: count("wall_ms"),
644
+ actual_speed: count("actual_speed"),
645
+ paced_steps: count("paced_steps"),
646
+ late_steps: count("late_steps"),
647
+ max_late_ms: count("max_late_ms"),
648
+ slipped_ms: count("slipped_ms"),
649
+ late_ms: count("late_ms"),
650
+ paused_ms: count("paused_ms")
651
651
  });
652
652
  };
653
653
  var readTrafficUnplaced = (value, path, u) => {
@@ -780,14 +780,14 @@ var readRunResult = (value, path, u) => {
780
780
  };
781
781
  var PHASES = ["checking", "starting", "waiting", "running", "stopping", "ended"];
782
782
  function readTimeFields(f, path, u) {
783
- const count2 = (key) => field(f, path, key, soft(nullable(number), null, u));
783
+ const count = (key) => field(f, path, key, soft(nullable(number), null, u));
784
784
  return {
785
785
  sim_ms: field(f, path, "sim_ms", number),
786
- actual_speed: count2("actual_speed"),
787
- late_steps: count2("late_steps"),
788
- max_late_ms: count2("max_late_ms"),
789
- slipped_ms: count2("slipped_ms"),
790
- late_ms: count2("late_ms")
786
+ actual_speed: count("actual_speed"),
787
+ late_steps: count("late_steps"),
788
+ max_late_ms: count("max_late_ms"),
789
+ slipped_ms: count("slipped_ms"),
790
+ late_ms: count("late_ms")
791
791
  };
792
792
  }
793
793
  function readCommandFields(f, path, u) {
@@ -1157,10 +1157,32 @@ var readSummaryParticipant = (value, path, u) => {
1157
1157
  )
1158
1158
  };
1159
1159
  };
1160
+ var readRuntimeStatus = (value, path) => {
1161
+ const f = object(value, path);
1162
+ return {
1163
+ mode: field(f, path, "mode", string),
1164
+ state: field(f, path, "state", string),
1165
+ config: field(f, path, "config", nullable(string)),
1166
+ reason: field(f, path, "reason", nullable(string)),
1167
+ message: field(f, path, "message", nullable(string))
1168
+ };
1169
+ };
1170
+ var readPrepareResponse = (value) => {
1171
+ const path = "response";
1172
+ const f = object(value, path);
1173
+ return {
1174
+ instance: field(f, path, "instance", string),
1175
+ runtime: field(f, path, "runtime", readRuntimeStatus)
1176
+ };
1177
+ };
1160
1178
  var readSummaryLauncher = (value, path) => {
1161
1179
  const f = object(value, path);
1180
+ const mode = field(f, path, "mode", optional(string, void 0));
1181
+ const processAlive = field(f, path, "process_alive", optional(boolean, void 0));
1162
1182
  return {
1163
1183
  running: field(f, path, "running", boolean),
1184
+ ...mode === void 0 ? {} : { mode },
1185
+ ...processAlive === void 0 ? {} : { process_alive: processAlive },
1164
1186
  exit_code: field(f, path, "exit_code", nullable(integer)),
1165
1187
  signal: field(f, path, "signal", nullable(integer)),
1166
1188
  silent_s: field(f, path, "silent_s", optional(nullable(integer), null))
@@ -1193,6 +1215,7 @@ var readSessionSummary = (value, path) => {
1193
1215
  const u = new Unreadable(path);
1194
1216
  const time = field(f, path, "time", soft(nullable(object), null, u));
1195
1217
  const timePath = `${path}.time`;
1218
+ const stopAt = field(f, path, "stop_at_ms", soft(nullable(integer), void 0, u));
1196
1219
  const summary = {
1197
1220
  id: field(f, path, "id", integer),
1198
1221
  ...f["snapshot_rev"] === void 0 ? {} : { snapshot_rev: field(f, path, "snapshot_rev", soft(nullable(integer), null, u)) },
@@ -1243,6 +1266,7 @@ var readSessionSummary = (value, path) => {
1243
1266
  )
1244
1267
  ),
1245
1268
  allowed: field(f, path, "allowed", soft(nullable(readServerAllowed), null, u)),
1269
+ ...stopAt === void 0 ? {} : { stop_at_ms: stopAt },
1246
1270
  check: field(
1247
1271
  f,
1248
1272
  path,
@@ -1315,6 +1339,7 @@ var readServerAllowed = (value, path) => {
1315
1339
  };
1316
1340
  };
1317
1341
  function partlyRecord(read2, u) {
1342
+ if (!u) return record(read2);
1318
1343
  return (value, path) => {
1319
1344
  const out = {};
1320
1345
  for (const [key, item] of Object.entries(object(value, path))) {
@@ -1336,6 +1361,12 @@ var readSessionAllowed = (value) => field(
1336
1361
  "allowed",
1337
1362
  optional(nullable(readServerAllowed), null)
1338
1363
  );
1364
+ var readSessionRuntime = (value) => field(
1365
+ object(value, "response"),
1366
+ "response",
1367
+ "runtime",
1368
+ optional(nullable(readRuntimeStatus), void 0)
1369
+ );
1339
1370
  var readTimeResponse = (value) => {
1340
1371
  const path = "response";
1341
1372
  const f = object(value, path);
@@ -1347,89 +1378,140 @@ var readTimeResponse = (value) => {
1347
1378
  };
1348
1379
  };
1349
1380
  var readAvailability = (value) => value === "unknown" || value === "inactive" ? value : "active";
1350
- var readOperationReport = (value, path) => {
1381
+ var safeInteger = (value, path) => {
1382
+ if (!Number.isSafeInteger(value)) throw new ProtocolError(path, "an integer");
1383
+ return value;
1384
+ };
1385
+ var nonNegativeInteger = (value, path) => {
1386
+ const n = safeInteger(value, path);
1387
+ if (n < 0) throw new ProtocolError(path, "a non-negative integer");
1388
+ return n;
1389
+ };
1390
+ var readOperationReport = (value, path, u) => {
1351
1391
  const f = object(value, path);
1352
1392
  return {
1353
- seq: field(f, path, "seq", integer),
1393
+ seq: field(f, path, "seq", safeInteger),
1354
1394
  state: field(f, path, "state", string),
1355
- done: field(f, path, "done", boolean),
1395
+ done: field(f, path, "done", lenient(boolean, false, u)),
1356
1396
  peers: field(
1357
1397
  f,
1358
1398
  path,
1359
1399
  "peers",
1360
- record((v, p) => {
1361
- const t = object(v, p);
1362
- return {
1363
- state: field(t, p, "state", string),
1364
- applied_at_ms: field(t, p, "applied_at_ms", optional(nullable(number), null)),
1365
- late: field(t, p, "late", optional(boolean, false)),
1366
- reason: field(t, p, "reason", optional(nullable(string), null)),
1367
- applied_writes: field(t, p, "applied_writes", optional(nullable(integer), null)),
1368
- failed_write: field(t, p, "failed_write", optional(nullable(integer), null))
1369
- };
1370
- })
1400
+ soft(
1401
+ partlyRecord((v, p) => {
1402
+ const t = object(v, p);
1403
+ return {
1404
+ state: field(t, p, "state", lenient(string, "unknown", u)),
1405
+ applied_at_ms: field(t, p, "applied_at_ms", soft(nullable(number), null, u)),
1406
+ late: field(t, p, "late", soft(boolean, false, u)),
1407
+ reason: field(t, p, "reason", soft(nullable(string), null, u)),
1408
+ applied_writes: field(
1409
+ t,
1410
+ p,
1411
+ "applied_writes",
1412
+ soft(nullable(nonNegativeInteger), null, u)
1413
+ ),
1414
+ failed_write: field(t, p, "failed_write", soft(nullable(nonNegativeInteger), null, u))
1415
+ };
1416
+ }, u),
1417
+ {},
1418
+ u
1419
+ )
1371
1420
  )
1372
1421
  };
1373
1422
  };
1374
- var readVariableSummary = (value, path) => {
1423
+ var readEnumItem = (value, path) => {
1424
+ const item = object(value, path);
1425
+ return { name: field(item, path, "name", string), value: field(item, path, "value", number) };
1426
+ };
1427
+ var readVariableSummary = (value, path, u) => {
1375
1428
  const f = object(value, path);
1376
1429
  return {
1377
1430
  name: field(f, path, "name", string),
1378
- type: field(f, path, "type", string),
1379
- role: field(f, path, "role", optional(string, "output")),
1380
- writable: field(f, path, "writable", optional(boolean, false)),
1381
- unit: field(f, path, "unit", optional(string, "")),
1382
- min: field(f, path, "min", optional(nullable(number), null)),
1383
- max: field(f, path, "max", optional(nullable(number), null)),
1384
- step: field(f, path, "step", optional(nullable(number), null)),
1385
- description: field(f, path, "description", optional(string, "")),
1431
+ type: field(f, path, "type", lenient(string, "", u)),
1432
+ role: field(f, path, "role", soft(string, "output", u)),
1433
+ writable: field(f, path, "writable", soft(boolean, false, u)),
1434
+ unit: field(f, path, "unit", soft(string, "", u)),
1435
+ min: field(f, path, "min", soft(nullable(number), null, u)),
1436
+ max: field(f, path, "max", soft(nullable(number), null, u)),
1437
+ step: field(f, path, "step", soft(nullable(number), null, u)),
1438
+ description: field(f, path, "description", soft(string, "", u)),
1386
1439
  enum: field(
1387
1440
  f,
1388
1441
  path,
1389
1442
  "enum",
1390
- optional(
1391
- nullable(
1392
- array((v, p) => {
1393
- const item = object(v, p);
1394
- return { name: field(item, p, "name", string), value: field(item, p, "value", number) };
1395
- })
1396
- ),
1397
- null
1443
+ soft(
1444
+ nullable((v, p) => {
1445
+ if (!Array.isArray(v)) throw new ProtocolError(p, "an array");
1446
+ return items(readEnumItem, u)(v, p);
1447
+ }),
1448
+ null,
1449
+ u
1398
1450
  )
1399
1451
  ),
1400
1452
  availability: readAvailability(f["availability"])
1401
1453
  };
1402
1454
  };
1403
- var readVariablesSummary = (value) => readVariables(value, "variables");
1404
- var readVariables = (value, path) => {
1455
+ var readVariablesSummary = (value) => readVariablesReport(value, "variables");
1456
+ var readVariablesReport = (value, path, u) => {
1405
1457
  const f = object(value, path);
1406
1458
  return {
1407
- ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", optional(nullable(integer), null)) },
1408
- state: field(f, path, "state", string),
1409
- reason: field(f, path, "reason", optional(nullable(string), null)),
1459
+ ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", soft(nullable(nonNegativeInteger), null, u)) },
1460
+ state: field(f, path, "state", lenient(string, "unknown", u)),
1461
+ reason: field(f, path, "reason", soft(nullable(string), null, u)),
1410
1462
  peers: field(
1411
1463
  f,
1412
1464
  path,
1413
1465
  "peers",
1414
- optional(
1415
- array((v, p) => {
1466
+ soft(
1467
+ items((v, p) => {
1416
1468
  const peer = object(v, p);
1417
1469
  return {
1418
1470
  name: field(peer, p, "name", string),
1419
- connected: field(peer, p, "connected", optional(boolean, false)),
1420
- variables: field(peer, p, "variables", optional(array(readVariableSummary), []))
1471
+ connected: field(peer, p, "connected", soft(boolean, false, u)),
1472
+ variables: field(
1473
+ peer,
1474
+ p,
1475
+ "variables",
1476
+ soft(
1477
+ items((item, ip) => readVariableSummary(item, ip, u), u),
1478
+ [],
1479
+ u
1480
+ )
1481
+ )
1421
1482
  };
1422
- }),
1423
- []
1483
+ }, u),
1484
+ [],
1485
+ u
1486
+ )
1487
+ ),
1488
+ peers_omitted: field(f, path, "peers_omitted", soft(nonNegativeInteger, 0, u)),
1489
+ variables_omitted: field(f, path, "variables_omitted", soft(nonNegativeInteger, 0, u)),
1490
+ operations: field(
1491
+ f,
1492
+ path,
1493
+ "operations",
1494
+ soft(
1495
+ items((item, ip) => readOperationReport(item, ip, u), u),
1496
+ [],
1497
+ u
1424
1498
  )
1425
1499
  ),
1426
- peers_omitted: field(f, path, "peers_omitted", optional(integer, 0)),
1427
- variables_omitted: field(f, path, "variables_omitted", optional(integer, 0)),
1428
- operations: field(f, path, "operations", optional(array(readOperationReport), [])),
1429
- operations_from_seq: field(f, path, "operations_from_seq", optional(integer, null)),
1430
- operations_open_omitted: field(f, path, "operations_open_omitted", optional(integer, 0))
1500
+ operations_from_seq: field(
1501
+ f,
1502
+ path,
1503
+ "operations_from_seq",
1504
+ soft(nullable(safeInteger), null, u)
1505
+ ),
1506
+ operations_open_omitted: field(
1507
+ f,
1508
+ path,
1509
+ "operations_open_omitted",
1510
+ soft(nonNegativeInteger, 0, u)
1511
+ )
1431
1512
  };
1432
1513
  };
1514
+ var readVariables = readVariablesReport;
1433
1515
  var readWriteResponse = (value) => {
1434
1516
  const f = object(value, "response");
1435
1517
  return {
@@ -1527,15 +1609,20 @@ var readServerMessage = (value) => {
1527
1609
  const f = object(value, path);
1528
1610
  const type = field(f, path, "type", string);
1529
1611
  switch (type) {
1530
- case "hello":
1612
+ case "hello": {
1531
1613
  version(f, path, "vehicle_sil_gui", PROTOCOL_VERSION);
1614
+ const runtime = field(f, path, "runtime", optional(nullable(readRuntimeStatus), void 0));
1532
1615
  return {
1533
1616
  type,
1534
1617
  instance: field(f, path, "instance", string),
1535
1618
  session: field(f, path, "session", nullable(readSessionSummary)),
1536
1619
  allowed: field(f, path, "allowed", optional(nullable(readServerAllowed), null)),
1537
- replay: field(f, path, "replay", nullable(readReplay))
1620
+ replay: field(f, path, "replay", nullable(readReplay)),
1621
+ ...runtime === void 0 ? {} : { runtime }
1538
1622
  };
1623
+ }
1624
+ case "runtime":
1625
+ return { type, runtime: field(f, path, "runtime", readRuntimeStatus) };
1539
1626
  case "event": {
1540
1627
  const event = field(f, path, "event", (v, p) => readLauncherEvent(v, p, true));
1541
1628
  return event && { type, session: field(f, path, "session", integer), event };
@@ -1717,248 +1804,23 @@ function fetchTransport(options) {
1717
1804
  };
1718
1805
  }
1719
1806
 
1720
- // ../client/src/run.ts
1721
- function answerMissing(path, error) {
1722
- if (!error.timedOut) return null;
1723
- return path === "api/run" ? `${error.message}: the server may still start the run (it checks the file again when it has changed); whether it did shows in the session over the WebSocket` : `${error.message}: the server may have done it; the session over the WebSocket shows what happened`;
1724
- }
1725
- var RunControl = class {
1726
- constructor(feed, transport, onError = rethrowLater, startTimeoutMs = () => 0) {
1727
- this.feed = feed;
1728
- this.transport = transport;
1729
- this.startTimeoutMs = startTimeoutMs;
1730
- this.startSending = new Writable(false, Object.is, onError);
1731
- this.stopSending = new Writable(null, Object.is, onError);
1732
- this.pendingRevision = new Writable(0, Object.is, onError);
1733
- this.stopAskedWhileStarting = new Writable(false, Object.is, onError);
1734
- this.failure = new Writable(null, Object.is, onError);
1735
- this.starting = this.startSending.readonly();
1736
- this.stopping = this.stopSending.readonly();
1737
- this.currentStopping = derived(
1738
- [this.pendingRevision, this.startSending, feed.session],
1739
- () => {
1740
- const key = this.startSending.get() ? this.startOperation : JSON.stringify(feed.currentTarget());
1741
- return [...this.pendingStops].filter((pending) => pending.key === key).at(-1)?.action ?? null;
1742
- },
1743
- Object.is,
1744
- onError
1745
- );
1746
- this.stopWhileStarting = this.stopAskedWhileStarting.readonly();
1747
- this.error = derived(
1748
- [this.failure, feed.session],
1749
- () => {
1750
- const failure = this.failure.get();
1751
- const session = feed.session.get();
1752
- if (!failure) return null;
1753
- const same = failure.session === (session?.id ?? null) && failure.running === (session?.launcher.running ?? false);
1754
- return same ? failure.message : null;
1755
- },
1756
- Object.is,
1757
- onError
1758
- );
1759
- }
1760
- feed;
1761
- transport;
1762
- startTimeoutMs;
1763
- startOperation = null;
1764
- pendingStops = /* @__PURE__ */ new Set();
1765
- pendingRevision;
1766
- startSending;
1767
- stopSending;
1768
- stopAskedWhileStarting;
1769
- failure;
1770
- starting;
1771
- stopping;
1772
- currentStopping;
1773
- stopWhileStarting;
1774
- error;
1775
- /** Starts a run. */
1776
- start(request) {
1777
- if (this.startSending.get()) return Promise.reject(new Error("a start is already pending"));
1778
- let resolveStart;
1779
- let rejectStart;
1780
- const operation = new Promise(
1781
- (resolve, reject) => {
1782
- resolveStart = resolve;
1783
- rejectStart = reject;
1784
- }
1785
- );
1786
- this.startOperation = operation;
1787
- this.stopAskedWhileStarting.set(false);
1788
- this.startSending.set(true);
1789
- let instance = null;
1790
- this.send(
1791
- "api/run",
1792
- request,
1793
- this.startTimeoutMs() || void 0,
1794
- () => {
1795
- this.startSending.set(false);
1796
- },
1797
- (seen) => {
1798
- instance = seen;
1799
- }
1800
- ).then((summary) => resolveStart({ summary, instance }), rejectStart);
1801
- return operation.then(({ summary }) => summary);
1802
- }
1803
- /** Stops in order (waits for the participants to end). Asking again never turns it into a stop without waiting. */
1804
- stop() {
1805
- return this.requestStop(false);
1806
- }
1807
- /** Stops without waiting (kills the participants). */
1808
- forceStop() {
1809
- return this.requestStop(true);
1810
- }
1811
- captureStop() {
1812
- const starting = this.startSending.get() ? this.startOperation : null;
1813
- const target = starting ? null : this.feed.currentTarget();
1807
+ // ../client/src/session-state.ts
1808
+ function launcherAnswer(state, name) {
1809
+ if (!state) {
1814
1810
  return {
1815
- key: starting ?? JSON.stringify(target),
1816
- send: (force) => this.requestStop(force, starting, target)
1811
+ reason: { code: "unsupported", message: "the launcher has not said yet what it accepts" },
1812
+ caution: null
1817
1813
  };
1818
1814
  }
1819
- requestStop(force, starting = this.startSending.get() ? this.startOperation : null, target = starting ? null : this.feed.currentTarget()) {
1820
- const session = this.feed.session.get();
1821
- const pending = {
1822
- action: force ? "force" : "stop",
1823
- starting: !!starting,
1824
- key: starting ?? JSON.stringify(target)
1825
- };
1826
- this.pendingStops.add(pending);
1827
- this.pendingRevision.update((n) => n + 1);
1828
- this.stopSending.set(pending.action);
1829
- const done = () => {
1830
- this.pendingStops.delete(pending);
1831
- this.pendingRevision.update((n) => n + 1);
1832
- const remaining = [...this.pendingStops];
1833
- this.stopAskedWhileStarting.set(remaining.some((p) => p.starting));
1834
- this.stopSending.set(remaining.at(-1)?.action ?? null);
1835
- };
1836
- if (!starting) {
1837
- if (!target) {
1838
- const message = "no session and server instance are known: no stop was sent; reconnect and check the current run";
1839
- this.failure.set({
1840
- message,
1841
- session: session?.id ?? null,
1842
- running: session?.launcher.running ?? false
1843
- });
1844
- done();
1845
- return Promise.reject(new Error(message));
1846
- }
1847
- return this.send("api/stop-session", { force, ...target }, void 0, done);
1848
- }
1849
- this.stopAskedWhileStarting.set(true);
1850
- return starting.then(
1851
- ({ summary, instance }) => {
1852
- if (!summary || !instance) {
1853
- const message = "the start answer did not identify the run; no stop was sent";
1854
- const session2 = this.feed.session.get();
1855
- this.failure.set({
1856
- message,
1857
- session: session2?.id ?? null,
1858
- running: session2?.launcher.running ?? false
1859
- });
1860
- throw new Error(message);
1861
- }
1862
- pending.key = JSON.stringify({ session: summary.id, instance });
1863
- this.pendingRevision.update((n) => n + 1);
1864
- return this.send(
1865
- "api/stop-session",
1866
- { force, session: summary.id, instance },
1867
- void 0,
1868
- () => void 0
1869
- );
1815
+ const item = Object.hasOwn(state.allowed, name) ? state.allowed[name] : void 0;
1816
+ if (!item) {
1817
+ return {
1818
+ reason: {
1819
+ code: "unsupported",
1820
+ message: `this launcher does not say whether it accepts ${name}`
1870
1821
  },
1871
- (error) => {
1872
- const message = `the start was not confirmed; no stop was sent: ${errorMessage(error)}`;
1873
- const session2 = this.feed.session.get();
1874
- this.failure.set({
1875
- message,
1876
- session: session2?.id ?? null,
1877
- running: session2?.launcher.running ?? false
1878
- });
1879
- throw new Error(message);
1880
- }
1881
- ).finally(done);
1882
- }
1883
- /**
1884
- * Sends and applies the summary in the answer. done is called after the answer (failures too), before the Promise
1885
- * settles.
1886
- */
1887
- send(path, body, timeoutMs, done, onInstance) {
1888
- const incompatible = this.feed.incompatible.get();
1889
- if (incompatible) {
1890
- done();
1891
- return Promise.reject(new Error(incompatible));
1892
- }
1893
- this.failure.set(null);
1894
- return new Promise((resolve, reject) => {
1895
- this.transport({ method: "POST", path, body, timeoutMs }, (outcome) => {
1896
- if (!outcome.ok) {
1897
- const failure = path === "api/stop-session" && outcome.error.status === 404 ? new HttpError(404, outcome.error.statusText, {
1898
- code: "targeted-stop-unsupported",
1899
- message: "the GUI server cannot stop a particular session: no stop was sent; use the GUI server of this release"
1900
- }) : outcome.error;
1901
- const session = this.feed.session.get();
1902
- this.failure.set({
1903
- message: answerMissing(path, failure) ?? errorMessage(failure),
1904
- session: session?.id ?? null,
1905
- running: session?.launcher.running ?? false
1906
- });
1907
- done();
1908
- reject(failure);
1909
- return;
1910
- }
1911
- let summary = null;
1912
- try {
1913
- const instance = path === "api/stop-session" ? body.instance : readSessionInstance(outcome.body);
1914
- summary = readSessionResponse(outcome.body);
1915
- if (path === "api/stop-session" && (!summary || summary.id !== body.session)) {
1916
- throw new Error("the stop answer did not identify the requested session");
1917
- }
1918
- onInstance?.(instance);
1919
- this.feed.adopt(summary, instance);
1920
- } catch (error) {
1921
- this.feed.report(
1922
- error instanceof ProtocolError ? `unreadable answer: ${error.message}` : String(error)
1923
- );
1924
- const missingInstance = error instanceof ProtocolError && error.path === "response.instance";
1925
- if (path === "api/stop-session" || missingInstance) {
1926
- const message = missingInstance ? `${error.message}. The run may have started. Check the current run before retrying` : "the stop answer was unreadable: check the session before trying again";
1927
- const session = this.feed.session.get();
1928
- this.failure.set({
1929
- message,
1930
- session: session?.id ?? null,
1931
- running: session?.launcher.running ?? false
1932
- });
1933
- done();
1934
- reject(new Error(message));
1935
- return;
1936
- }
1937
- }
1938
- done();
1939
- resolve(summary);
1940
- });
1941
- });
1942
- }
1943
- };
1944
-
1945
- // ../client/src/session-state.ts
1946
- function launcherAnswer(state, name) {
1947
- if (!state) {
1948
- return {
1949
- reason: { code: "unsupported", message: "the launcher has not said yet what it accepts" },
1950
- caution: null
1951
- };
1952
- }
1953
- const item = Object.hasOwn(state.allowed, name) ? state.allowed[name] : void 0;
1954
- if (!item) {
1955
- return {
1956
- reason: {
1957
- code: "unsupported",
1958
- message: `this launcher does not say whether it accepts ${name}`
1959
- },
1960
- caution: null
1961
- };
1822
+ caution: null
1823
+ };
1962
1824
  }
1963
1825
  const caution = item.caution ? { code: item.caution.code, message: item.caution.message } : null;
1964
1826
  if (item.ok) return { reason: null, caution };
@@ -2035,11 +1897,25 @@ function withStep(steps, step) {
2035
1897
  if (steps[i].index === step.index) return steps.map((s, j) => j === i ? step : s);
2036
1898
  return [...steps.slice(0, i), step, ...steps.slice(i)];
2037
1899
  }
1900
+ function isSessionRunning(session) {
1901
+ return !!session && session.state === "running";
1902
+ }
1903
+ function isRunActive(session) {
1904
+ return !!session && session.state === "running" && session.launcher.running;
1905
+ }
1906
+ function isLauncherFinishing(session) {
1907
+ return !!session && isRunActive(session) && session.result !== null;
1908
+ }
1909
+ function isLauncherAlive(session) {
1910
+ if (!session) return false;
1911
+ const launcher = session.launcher;
1912
+ return launcher.processAlive ?? launcher.process_alive ?? launcher.running;
1913
+ }
2038
1914
  function isHolding(session) {
2039
- return !!session && session.launcher.running && session.launcherState?.holding === true;
1915
+ return isRunActive(session) && session.launcherState?.holding === true;
2040
1916
  }
2041
1917
  function runOutcome(session) {
2042
- if (session.launcher.running) {
1918
+ if (isRunActive(session)) {
2043
1919
  if (session.result) return "finishing";
2044
1920
  if (session.stopRequests >= 2) return "forcing";
2045
1921
  return session.stopRequests >= 1 ? "stopping" : "running";
@@ -2056,6 +1932,7 @@ function sessionFromSummary(summary) {
2056
1932
  manual: summary.manual,
2057
1933
  speed: summary.speed,
2058
1934
  startPaused: summary.start_paused,
1935
+ state: summary.state,
2059
1936
  phase: null,
2060
1937
  phaseRank: -1,
2061
1938
  check: null,
@@ -2086,24 +1963,24 @@ function sessionFromSummary(summary) {
2086
1963
  };
2087
1964
  }
2088
1965
  function addDropped(session, dropped) {
2089
- const counts = Object.entries(dropped.log).filter(([, count2]) => count2 > 0);
1966
+ const counts = Object.entries(dropped.log).filter(([, count]) => count > 0);
2090
1967
  if (counts.length === 0) return session;
2091
1968
  const mark = session.droppedMarks + 1;
2092
- const gaps = counts.map(([source, count2]) => ({
1969
+ const gaps = counts.map(([source, count]) => ({
2093
1970
  seq: session.lastSeq + 0.5,
2094
1971
  key: `dropped ${mark} ${source}`,
2095
1972
  source,
2096
1973
  line: "",
2097
1974
  gap: {
2098
- count: count2,
1975
+ count,
2099
1976
  atLeast: dropped.at_least.includes(source),
2100
1977
  ...dropped.reason === "not-kept" ? { notKept: true } : {}
2101
1978
  }
2102
1979
  }));
2103
1980
  const next = { ...appendLogs(session, gaps), droppedMarks: mark };
2104
1981
  const sources = { ...next.logSources };
2105
- for (const [source, count2] of counts) {
2106
- sources[source] = { ...sources[source], dropped: sources[source].dropped + count2 };
1982
+ for (const [source, count] of counts) {
1983
+ sources[source] = { ...sources[source], dropped: sources[source].dropped + count };
2107
1984
  }
2108
1985
  return { ...next, logSources: sources };
2109
1986
  }
@@ -2114,6 +1991,8 @@ function stopRequestsOf(stop) {
2114
1991
  function launcherOf(summary) {
2115
1992
  return {
2116
1993
  running: summary.launcher.running,
1994
+ ...summary.launcher.mode === void 0 ? {} : { mode: summary.launcher.mode },
1995
+ ...summary.launcher.process_alive === void 0 ? {} : { processAlive: summary.launcher.process_alive },
2117
1996
  exitCode: summary.launcher.exit_code,
2118
1997
  signal: summary.launcher.signal,
2119
1998
  silentSeconds: summary.launcher.silent_s
@@ -2127,7 +2006,10 @@ function applySummary(session, summary, force = false, controlOnly = false) {
2127
2006
  const staleProjection = projectionRev !== null && (incomingRev === null || incomingRev < projectionRev);
2128
2007
  if (staleControl && (staleProjection || !force && controlOnly)) return session;
2129
2008
  const newer = force || (summary.last_seq ?? -1) > Math.max(session.lastSeq, session.observedSeq ?? -1, session.projectionSeq ?? -1);
2130
- const launcher = !force && !session.launcher.running && summary.launcher.running ? session.launcher : launcherOf(summary);
2009
+ const staleEndRegression = !force && session.state === "ended" && summary.state === "running";
2010
+ const stillEnded = staleEndRegression || !force && !isRunActive(session) && summary.launcher.running && summary.state === "running";
2011
+ const launcher = stillEnded ? session.launcher : launcherOf(summary);
2012
+ const state = staleEndRegression ? session.state : summary.state;
2131
2013
  const notLess = summary.problems.length + summary.problems_omitted >= session.problems.length + session.problemsOmitted;
2132
2014
  const mergedProblems = [...summary.problems];
2133
2015
  let omitted = summary.problems_omitted;
@@ -2145,7 +2027,9 @@ function applySummary(session, summary, force = false, controlOnly = false) {
2145
2027
  const next = staleControl ? session : {
2146
2028
  ...session,
2147
2029
  ...incomingRev === null ? {} : { snapshotRev: incomingRev },
2030
+ ...summary.stop_at_ms === void 0 ? {} : { stopAtMs: summary.stop_at_ms },
2148
2031
  ...summary.problem_seq == null ? {} : { problemSeq: Math.max(session.problemSeq ?? 0, summary.problem_seq) },
2032
+ state,
2149
2033
  launcher,
2150
2034
  stopRequests: Math.max(session.stopRequests, stopRequestsOf(summary.stop)),
2151
2035
  logSources: withSources(session.logSources, Object.keys(summary.log)),
@@ -2376,19 +2260,19 @@ function recoverReplayLogs(session, recovered, notKept) {
2376
2260
  const source = sources[line.source] ??= { lines: 0, dropped: 0 };
2377
2261
  if (line.gap) source.dropped += line.gap.count;
2378
2262
  else {
2379
- const count2 = restored.get(line.source) ?? 0;
2380
- if (count2 < (notKept.get(line.source) ?? 0)) {
2263
+ const count = restored.get(line.source) ?? 0;
2264
+ if (count < (notKept.get(line.source) ?? 0)) {
2381
2265
  source.dropped--;
2382
- restored.set(line.source, count2 + 1);
2266
+ restored.set(line.source, count + 1);
2383
2267
  }
2384
2268
  }
2385
2269
  }
2386
2270
  const logs = session.logs.flatMap((line) => {
2387
2271
  if (!line.gap?.notKept) return [line];
2388
2272
  const available = restored.get(line.source) ?? 0;
2389
- const count2 = Math.max(0, line.gap.count - available);
2273
+ const count = Math.max(0, line.gap.count - available);
2390
2274
  restored.set(line.source, Math.max(0, available - line.gap.count));
2391
- return count2 > 0 ? [{ ...line, gap: { ...line.gap, count: count2 } }] : [];
2275
+ return count > 0 ? [{ ...line, gap: { ...line.gap, count } }] : [];
2392
2276
  });
2393
2277
  logs.push(...recovered);
2394
2278
  logs.sort((a, b) => a.seq - b.seq);
@@ -2403,10 +2287,10 @@ function appendLogs(session, added) {
2403
2287
  if (!line.gap) counts.lines++;
2404
2288
  }
2405
2289
  const drop = /* @__PURE__ */ new Map();
2406
- const take = (source, count2) => {
2407
- sources[source].lines -= count2;
2408
- sources[source].dropped += count2;
2409
- drop.set(source, (drop.get(source) ?? 0) + count2);
2290
+ const take = (source, count) => {
2291
+ sources[source].lines -= count;
2292
+ sources[source].dropped += count;
2293
+ drop.set(source, (drop.get(source) ?? 0) + count);
2410
2294
  };
2411
2295
  let total = 0;
2412
2296
  for (const [source, counts] of Object.entries(sources)) {
@@ -2416,12 +2300,12 @@ function appendLogs(session, added) {
2416
2300
  }
2417
2301
  while (total > MAX_LOG_LINES) {
2418
2302
  const [largest, second] = Object.entries(sources).sort(([, a], [, b]) => b.lines - a.lines);
2419
- const count2 = Math.max(
2303
+ const count = Math.max(
2420
2304
  1,
2421
2305
  Math.min(total - MAX_LOG_LINES, largest[1].lines - (second?.[1].lines ?? 0))
2422
2306
  );
2423
- take(largest[0], count2);
2424
- total -= count2;
2307
+ take(largest[0], count);
2308
+ total -= count;
2425
2309
  }
2426
2310
  const all = [...session.logs, ...added];
2427
2311
  if (drop.size === 0) return { ...session, logs: all, logSources: sources };
@@ -2470,143 +2354,370 @@ function applyOne(session, event, logs) {
2470
2354
  participants: known ? next.participants.map((p) => p === known ? updated : p) : [...next.participants, updated]
2471
2355
  };
2472
2356
  }
2473
- case "log":
2474
- logs.push({ seq: event.seq, key: String(event.seq), source: event.source, line: event.line });
2475
- return next;
2476
- case "log_dropped":
2477
- for (const [source, count2] of Object.entries(event.sources)) {
2478
- if (count2 > 0) {
2479
- logs.push({
2480
- seq: event.seq,
2481
- key: `${event.seq} ${source}`,
2482
- source,
2483
- line: "",
2484
- gap: { count: count2, atLeast: false, launcher: true }
2357
+ case "log":
2358
+ logs.push({ seq: event.seq, key: String(event.seq), source: event.source, line: event.line });
2359
+ return next;
2360
+ case "log_dropped":
2361
+ for (const [source, count] of Object.entries(event.sources)) {
2362
+ if (count > 0) {
2363
+ logs.push({
2364
+ seq: event.seq,
2365
+ key: `${event.seq} ${source}`,
2366
+ source,
2367
+ line: "",
2368
+ gap: { count, atLeast: false, launcher: true }
2369
+ });
2370
+ }
2371
+ }
2372
+ return next;
2373
+ case "finding":
2374
+ return next.findings.length >= MAX_FINDINGS ? next : {
2375
+ ...next,
2376
+ findings: next.findings.every((finding) => finding.event_seq !== void 0) ? mergeFindings(next.findings, [{ ...event.finding, event_seq: event.seq }]) : [...next.findings, { ...event.finding, event_seq: event.seq }]
2377
+ };
2378
+ case "time":
2379
+ return { ...next, simMs: event.sim_ms, timeOmittedFields: [], time: timeView(event) };
2380
+ case "command":
2381
+ return { ...next, lastCommand: commandView(event, event.seq) };
2382
+ case "state":
2383
+ return { ...next, launcherState: newerState(next.launcherState, event) };
2384
+ case "result":
2385
+ return {
2386
+ ...next,
2387
+ result: event.result,
2388
+ phase: "ended",
2389
+ phaseRank: phaseIndex("ended"),
2390
+ check: next.check ?? event.result.check,
2391
+ participants: mergeResult(next.participants, event.result),
2392
+ scenario: next.scenario && event.result.scenario ? {
2393
+ ...next.scenario,
2394
+ name: event.result.scenario.name,
2395
+ stepCount: next.scenario.stepCount ?? event.result.scenario.steps.length,
2396
+ steps: event.result.scenario.steps,
2397
+ status: event.result.scenario.status,
2398
+ overAtMs: event.result.scenario.over_at_ms
2399
+ } : next.scenario
2400
+ };
2401
+ default:
2402
+ return next;
2403
+ }
2404
+ }
2405
+ function mergeCheck(current, check) {
2406
+ const byName = new Map(current.map((p) => [p.name, p]));
2407
+ const ordered = [];
2408
+ for (const p of check.participants) {
2409
+ if (p.name === null) continue;
2410
+ const known = byName.get(p.name);
2411
+ byName.delete(p.name);
2412
+ ordered.push({
2413
+ ...known ?? blankParticipant(p.name),
2414
+ required: p.required,
2415
+ state: known?.state ?? (p.enabled === false ? "disabled" : null),
2416
+ manual: p.manual || !!known?.manual
2417
+ });
2418
+ }
2419
+ return [...ordered, ...byName.values()];
2420
+ }
2421
+ function updateParticipant(current, event) {
2422
+ const known = current.find((p) => p.name === event.name);
2423
+ const updated = {
2424
+ ...known ?? blankParticipant(event.name),
2425
+ state: event.state,
2426
+ // Events arrive whole (only the summary leaves fields out)
2427
+ omittedFields: []
2428
+ };
2429
+ if (event.pid !== null) updated.pid = event.pid;
2430
+ if (event.state === "failed") updated.failure = event.reason ?? "";
2431
+ if (event.state === "stop_requested") updated.stopRequested = true;
2432
+ if (event.message) updated.message = event.message;
2433
+ if (event.state === "manual") updated.manual = true;
2434
+ if (typeof event.command_line === "string") updated.commandLine = event.command_line;
2435
+ if (typeof event.working_directory === "string")
2436
+ updated.workingDirectory = event.working_directory;
2437
+ if (event.state === "manual") updated.environment = event.environment ?? {};
2438
+ if (event.state === "ended" || event.state === "killed") {
2439
+ updated.exitCode = event.exit_code;
2440
+ updated.signal = event.signal;
2441
+ }
2442
+ return known ? current.map((p) => p === known ? updated : p) : [...current, updated];
2443
+ }
2444
+ function withResult(participants, result) {
2445
+ return result ? mergeResult(participants, result) : participants;
2446
+ }
2447
+ function mergeResult(current, result) {
2448
+ const merged = [...current];
2449
+ for (const p of result.participants) {
2450
+ const i = merged.findIndex((known) => known.name === p.name);
2451
+ const base = i >= 0 ? merged[i] : blankParticipant(p.name);
2452
+ const state = !p.enabled ? "disabled" : p.ended === "killed" ? "killed" : p.ended === "not_started" ? base.state ?? "not_started" : "ended";
2453
+ const view = {
2454
+ ...base,
2455
+ required: p.required,
2456
+ state,
2457
+ exitCode: p.exit_code,
2458
+ signal: p.signal,
2459
+ stopRequested: base.stopRequested || p.ended === "stopped",
2460
+ // Keep what the events told about the connection (number of variables and so on); without it, only the result's
2461
+ // state. The result is newer (it has the count of messages that arrived late). What the result lacks comes from
2462
+ // the events
2463
+ controlLink: p.control_link ?? base.controlLink,
2464
+ manual: base.manual || p.manual
2465
+ };
2466
+ if (i >= 0) merged[i] = view;
2467
+ else merged.push(view);
2468
+ }
2469
+ return merged;
2470
+ }
2471
+ function blankParticipant(name) {
2472
+ return {
2473
+ name,
2474
+ state: null,
2475
+ required: null,
2476
+ pid: null,
2477
+ exitCode: null,
2478
+ signal: null,
2479
+ failure: null,
2480
+ message: null,
2481
+ stopRequested: false,
2482
+ omittedFields: [],
2483
+ controlLink: null,
2484
+ manual: false,
2485
+ commandLine: null,
2486
+ workingDirectory: null,
2487
+ environment: {}
2488
+ };
2489
+ }
2490
+
2491
+ // ../client/src/run.ts
2492
+ function answerMissing(path, error) {
2493
+ if (!error.timedOut) return null;
2494
+ return path === "api/run" ? `${error.message}: the server may still start the run (it checks the file again when it has changed); whether it did shows in the session over the WebSocket` : `${error.message}: the server may have done it; the session over the WebSocket shows what happened`;
2495
+ }
2496
+ var RunControl = class {
2497
+ constructor(feed, transport, onError = rethrowLater, startTimeoutMs = () => 0) {
2498
+ this.feed = feed;
2499
+ this.transport = transport;
2500
+ this.startTimeoutMs = startTimeoutMs;
2501
+ this.startSending = new Writable(false, Object.is, onError);
2502
+ this.stopSending = new Writable(null, Object.is, onError);
2503
+ this.pendingRevision = new Writable(0, Object.is, onError);
2504
+ this.stopAskedWhileStarting = new Writable(false, Object.is, onError);
2505
+ this.failure = new Writable(null, Object.is, onError);
2506
+ this.starting = this.startSending.readonly();
2507
+ this.stopping = this.stopSending.readonly();
2508
+ this.currentStopping = derived(
2509
+ [this.pendingRevision, this.startSending, feed.session],
2510
+ () => {
2511
+ const key = this.startSending.get() ? this.startOperation : JSON.stringify(feed.currentTarget());
2512
+ return [...this.pendingStops].filter((pending) => pending.key === key).at(-1)?.action ?? null;
2513
+ },
2514
+ Object.is,
2515
+ onError
2516
+ );
2517
+ this.stopWhileStarting = this.stopAskedWhileStarting.readonly();
2518
+ this.error = derived(
2519
+ [this.failure, feed.session],
2520
+ () => {
2521
+ const failure = this.failure.get();
2522
+ const session = feed.session.get();
2523
+ if (!failure) return null;
2524
+ const same = failure.session === (session?.id ?? null) && failure.running === isRunActive(session);
2525
+ return same ? failure.message : null;
2526
+ },
2527
+ Object.is,
2528
+ onError
2529
+ );
2530
+ }
2531
+ feed;
2532
+ transport;
2533
+ startTimeoutMs;
2534
+ startOperation = null;
2535
+ pendingStops = /* @__PURE__ */ new Set();
2536
+ pendingRevision;
2537
+ startSending;
2538
+ stopSending;
2539
+ stopAskedWhileStarting;
2540
+ failure;
2541
+ starting;
2542
+ stopping;
2543
+ currentStopping;
2544
+ stopWhileStarting;
2545
+ error;
2546
+ /** Starts a run. */
2547
+ start(request) {
2548
+ if (this.startSending.get()) return Promise.reject(new Error("a start is already pending"));
2549
+ let resolveStart;
2550
+ let rejectStart;
2551
+ const operation = new Promise(
2552
+ (resolve, reject) => {
2553
+ resolveStart = resolve;
2554
+ rejectStart = reject;
2555
+ }
2556
+ );
2557
+ this.startOperation = operation;
2558
+ this.stopAskedWhileStarting.set(false);
2559
+ this.startSending.set(true);
2560
+ let instance = null;
2561
+ this.send(
2562
+ "api/run",
2563
+ request,
2564
+ this.startTimeoutMs() || void 0,
2565
+ () => {
2566
+ this.startSending.set(false);
2567
+ },
2568
+ (seen) => {
2569
+ instance = seen;
2570
+ }
2571
+ ).then((summary) => resolveStart({ summary, instance }), rejectStart);
2572
+ return operation.then(({ summary }) => summary);
2573
+ }
2574
+ /** Stops in order (waits for the participants to end). Asking again never turns it into a stop without waiting. */
2575
+ stop() {
2576
+ return this.requestStop(false);
2577
+ }
2578
+ /** Stops without waiting (kills the participants). */
2579
+ forceStop() {
2580
+ return this.requestStop(true);
2581
+ }
2582
+ captureStop() {
2583
+ const starting = this.startSending.get() ? this.startOperation : null;
2584
+ const target = starting ? null : this.feed.currentTarget();
2585
+ return {
2586
+ key: starting ?? JSON.stringify(target),
2587
+ send: (force) => this.requestStop(force, starting, target)
2588
+ };
2589
+ }
2590
+ requestStop(force, starting = this.startSending.get() ? this.startOperation : null, target = starting ? null : this.feed.currentTarget()) {
2591
+ const session = this.feed.session.get();
2592
+ const pending = {
2593
+ action: force ? "force" : "stop",
2594
+ starting: !!starting,
2595
+ key: starting ?? JSON.stringify(target)
2596
+ };
2597
+ this.pendingStops.add(pending);
2598
+ this.pendingRevision.update((n) => n + 1);
2599
+ this.stopSending.set(pending.action);
2600
+ const done = () => {
2601
+ this.pendingStops.delete(pending);
2602
+ this.pendingRevision.update((n) => n + 1);
2603
+ const remaining = [...this.pendingStops];
2604
+ this.stopAskedWhileStarting.set(remaining.some((p) => p.starting));
2605
+ this.stopSending.set(remaining.at(-1)?.action ?? null);
2606
+ };
2607
+ if (!starting) {
2608
+ if (!target) {
2609
+ const message = "no session and server instance are known: no stop was sent; reconnect and check the current run";
2610
+ this.failure.set({
2611
+ message,
2612
+ session: session?.id ?? null,
2613
+ running: isRunActive(session)
2614
+ });
2615
+ done();
2616
+ return Promise.reject(new Error(message));
2617
+ }
2618
+ return this.send("api/stop-session", { force, ...target }, void 0, done);
2619
+ }
2620
+ this.stopAskedWhileStarting.set(true);
2621
+ return starting.then(
2622
+ ({ summary, instance }) => {
2623
+ if (!summary || !instance) {
2624
+ const message = "the start answer did not identify the run; no stop was sent";
2625
+ const session2 = this.feed.session.get();
2626
+ this.failure.set({
2627
+ message,
2628
+ session: session2?.id ?? null,
2629
+ running: isRunActive(session2)
2485
2630
  });
2631
+ throw new Error(message);
2486
2632
  }
2633
+ pending.key = JSON.stringify({ session: summary.id, instance });
2634
+ this.pendingRevision.update((n) => n + 1);
2635
+ return this.send(
2636
+ "api/stop-session",
2637
+ { force, session: summary.id, instance },
2638
+ void 0,
2639
+ () => void 0
2640
+ );
2641
+ },
2642
+ (error) => {
2643
+ const session2 = this.feed.session.get();
2644
+ this.failure.set({
2645
+ message: `the start was not confirmed; no stop was sent: ${errorMessage(error)}`,
2646
+ session: session2?.id ?? null,
2647
+ running: isRunActive(session2)
2648
+ });
2649
+ throw new Error(`the start was not confirmed; no stop was sent: ${errorMessage(error)}`);
2487
2650
  }
2488
- return next;
2489
- case "finding":
2490
- return next.findings.length >= MAX_FINDINGS ? next : {
2491
- ...next,
2492
- findings: next.findings.every((finding) => finding.event_seq !== void 0) ? mergeFindings(next.findings, [{ ...event.finding, event_seq: event.seq }]) : [...next.findings, { ...event.finding, event_seq: event.seq }]
2493
- };
2494
- case "time":
2495
- return { ...next, simMs: event.sim_ms, timeOmittedFields: [], time: timeView(event) };
2496
- case "command":
2497
- return { ...next, lastCommand: commandView(event, event.seq) };
2498
- case "state":
2499
- return { ...next, launcherState: newerState(next.launcherState, event) };
2500
- case "result":
2501
- return {
2502
- ...next,
2503
- result: event.result,
2504
- phase: "ended",
2505
- phaseRank: phaseIndex("ended"),
2506
- check: next.check ?? event.result.check,
2507
- participants: mergeResult(next.participants, event.result),
2508
- scenario: next.scenario && event.result.scenario ? {
2509
- ...next.scenario,
2510
- name: event.result.scenario.name,
2511
- stepCount: next.scenario.stepCount ?? event.result.scenario.steps.length,
2512
- steps: event.result.scenario.steps,
2513
- status: event.result.scenario.status,
2514
- overAtMs: event.result.scenario.over_at_ms
2515
- } : next.scenario
2516
- };
2517
- default:
2518
- return next;
2651
+ ).finally(done);
2519
2652
  }
2520
- }
2521
- function mergeCheck(current, check) {
2522
- const byName = new Map(current.map((p) => [p.name, p]));
2523
- const ordered = [];
2524
- for (const p of check.participants) {
2525
- if (p.name === null) continue;
2526
- const known = byName.get(p.name);
2527
- byName.delete(p.name);
2528
- ordered.push({
2529
- ...known ?? blankParticipant(p.name),
2530
- required: p.required,
2531
- state: known?.state ?? (p.enabled === false ? "disabled" : null),
2532
- manual: p.manual || !!known?.manual
2653
+ /**
2654
+ * Sends and applies the summary in the answer. done is called after the answer (failures too), before the Promise
2655
+ * settles.
2656
+ */
2657
+ send(path, body, timeoutMs, done, onInstance) {
2658
+ const incompatible = this.feed.incompatible.get();
2659
+ if (incompatible) {
2660
+ done();
2661
+ return Promise.reject(new Error(incompatible));
2662
+ }
2663
+ this.failure.set(null);
2664
+ return new Promise((resolve, reject) => {
2665
+ this.transport({ method: "POST", path, body, timeoutMs }, (outcome) => {
2666
+ if (!outcome.ok) {
2667
+ const failure = path === "api/stop-session" && outcome.error.status === 404 ? new HttpError(404, outcome.error.statusText, {
2668
+ code: "targeted-stop-unsupported",
2669
+ message: "the GUI server cannot stop a particular session: no stop was sent; use the GUI server of this release"
2670
+ }) : outcome.error;
2671
+ const session = this.feed.session.get();
2672
+ this.failure.set({
2673
+ message: answerMissing(path, failure) ?? errorMessage(failure),
2674
+ session: session?.id ?? null,
2675
+ running: isRunActive(session)
2676
+ });
2677
+ done();
2678
+ reject(failure);
2679
+ return;
2680
+ }
2681
+ let summary = null;
2682
+ try {
2683
+ const instance = path === "api/stop-session" ? body.instance : readSessionInstance(outcome.body);
2684
+ summary = readSessionResponse(outcome.body);
2685
+ if (path === "api/stop-session" && (!summary || summary.id !== body.session)) {
2686
+ throw new Error("the stop answer did not identify the requested session");
2687
+ }
2688
+ onInstance?.(instance);
2689
+ this.feed.adopt(summary, instance);
2690
+ } catch (error) {
2691
+ this.feed.report(
2692
+ error instanceof ProtocolError ? `unreadable answer: ${error.message}` : String(error)
2693
+ );
2694
+ const missingInstance = error instanceof ProtocolError && error.path === "response.instance";
2695
+ if (path === "api/stop-session" || missingInstance) {
2696
+ const message = missingInstance ? `${error.message}. The run may have started. Check the current run before retrying` : "the stop answer was unreadable: check the session before trying again";
2697
+ const session = this.feed.session.get();
2698
+ this.failure.set({
2699
+ message,
2700
+ session: session?.id ?? null,
2701
+ running: isRunActive(session)
2702
+ });
2703
+ done();
2704
+ reject(new Error(message));
2705
+ return;
2706
+ }
2707
+ }
2708
+ done();
2709
+ resolve(summary);
2710
+ });
2533
2711
  });
2534
2712
  }
2535
- return [...ordered, ...byName.values()];
2536
- }
2537
- function updateParticipant(current, event) {
2538
- const known = current.find((p) => p.name === event.name);
2539
- const updated = {
2540
- ...known ?? blankParticipant(event.name),
2541
- state: event.state,
2542
- // Events arrive whole (only the summary leaves fields out)
2543
- omittedFields: []
2544
- };
2545
- if (event.pid !== null) updated.pid = event.pid;
2546
- if (event.state === "failed") updated.failure = event.reason ?? "";
2547
- if (event.state === "stop_requested") updated.stopRequested = true;
2548
- if (event.message) updated.message = event.message;
2549
- if (event.state === "manual") updated.manual = true;
2550
- if (typeof event.command_line === "string") updated.commandLine = event.command_line;
2551
- if (typeof event.working_directory === "string")
2552
- updated.workingDirectory = event.working_directory;
2553
- if (event.state === "manual") updated.environment = event.environment ?? {};
2554
- if (event.state === "ended" || event.state === "killed") {
2555
- updated.exitCode = event.exit_code;
2556
- updated.signal = event.signal;
2557
- }
2558
- return known ? current.map((p) => p === known ? updated : p) : [...current, updated];
2559
- }
2560
- function withResult(participants, result) {
2561
- return result ? mergeResult(participants, result) : participants;
2562
- }
2563
- function mergeResult(current, result) {
2564
- const merged = [...current];
2565
- for (const p of result.participants) {
2566
- const i = merged.findIndex((known) => known.name === p.name);
2567
- const base = i >= 0 ? merged[i] : blankParticipant(p.name);
2568
- const state = !p.enabled ? "disabled" : p.ended === "killed" ? "killed" : p.ended === "not_started" ? base.state ?? "not_started" : "ended";
2569
- const view = {
2570
- ...base,
2571
- required: p.required,
2572
- state,
2573
- exitCode: p.exit_code,
2574
- signal: p.signal,
2575
- stopRequested: base.stopRequested || p.ended === "stopped",
2576
- // Keep what the events told about the connection (number of variables and so on); without it, only the result's
2577
- // state. The result is newer (it has the count of messages that arrived late). What the result lacks comes from
2578
- // the events
2579
- controlLink: p.control_link ?? base.controlLink,
2580
- manual: base.manual || p.manual
2581
- };
2582
- if (i >= 0) merged[i] = view;
2583
- else merged.push(view);
2584
- }
2585
- return merged;
2586
- }
2587
- function blankParticipant(name) {
2588
- return {
2589
- name,
2590
- state: null,
2591
- required: null,
2592
- pid: null,
2593
- exitCode: null,
2594
- signal: null,
2595
- failure: null,
2596
- message: null,
2597
- stopRequested: false,
2598
- omittedFields: [],
2599
- controlLink: null,
2600
- manual: false,
2601
- commandLine: null,
2602
- workingDirectory: null,
2603
- environment: {}
2604
- };
2605
- }
2713
+ };
2606
2714
 
2607
2715
  // ../client/src/session.ts
2608
2716
  var MAX_NOTICES = 20;
2609
2717
  var STALE_EVENTS_NOTICE = "events came with a seq that is not after the last one, and were not shown (the launcher wrote them out of order, or the server sent them again)";
2718
+ function sameRunTarget(left, right) {
2719
+ return left !== null && right !== null && left.session === right.session && left.instance === right.instance;
2720
+ }
2610
2721
  var SessionFeed = class {
2611
2722
  constructor(connection, onError = rethrowLater) {
2612
2723
  this.connection = connection;
@@ -2615,6 +2726,8 @@ var SessionFeed = class {
2615
2726
  this.synced = new Writable(false, Object.is, onError);
2616
2727
  this.allowedValue = new Writable(null, Object.is, onError);
2617
2728
  this.allowed = this.allowedValue.readonly();
2729
+ this.runtimeValue = new Writable(null, Object.is, onError);
2730
+ this.runtime = this.runtimeValue.readonly();
2618
2731
  this.receivedAt = new Writable(0, Object.is, onError);
2619
2732
  this.noticeList = new Writable([], Object.is, onError);
2620
2733
  this.rejectedValue = new Writable(false, Object.is, onError);
@@ -2646,6 +2759,7 @@ var SessionFeed = class {
2646
2759
  current;
2647
2760
  synced;
2648
2761
  allowedValue;
2762
+ runtimeValue;
2649
2763
  receivedAt;
2650
2764
  noticeList;
2651
2765
  rejectedValue;
@@ -2657,6 +2771,7 @@ var SessionFeed = class {
2657
2771
  session;
2658
2772
  ready;
2659
2773
  allowed;
2774
+ runtime;
2660
2775
  lastEventAt;
2661
2776
  notices;
2662
2777
  rejected;
@@ -2746,8 +2861,12 @@ var SessionFeed = class {
2746
2861
  const current = this.allowedValue.get();
2747
2862
  if (!current || allowed.rev === 0 || allowed.rev >= current.rev) this.allowedValue.set(allowed);
2748
2863
  }
2749
- report(message, count2 = 1) {
2750
- this.notify(message, count2);
2864
+ /** Updates the current persistent runtime status (from HTTP `prepare`/`session`). Used inside the library. */
2865
+ adoptRuntime(runtime) {
2866
+ this.runtimeValue.set(runtime);
2867
+ }
2868
+ report(message, count = 1) {
2869
+ this.notify(message, count);
2751
2870
  }
2752
2871
  dismissNotice(id) {
2753
2872
  this.noticeList.update((list) => list.filter((notice) => notice.id !== id));
@@ -2856,6 +2975,7 @@ var SessionFeed = class {
2856
2975
  let applied = false;
2857
2976
  let synced = this.synced.get();
2858
2977
  let allowedNow = this.allowedValue.get();
2978
+ let runtimeNow = this.runtimeValue.get();
2859
2979
  const takeAllowed = (incoming, replace = false) => {
2860
2980
  if (!incoming) return;
2861
2981
  if (replace || !allowedNow || incoming.rev === 0 || incoming.rev >= allowedNow.rev) {
@@ -2879,6 +2999,11 @@ var SessionFeed = class {
2879
2999
  const { session: summary, replay } = message;
2880
3000
  const staleSnapshot = !!summary && instance === message.instance && session?.id === summary.id && session.snapshotRev != null && (summary.snapshot_rev == null || summary.snapshot_rev < session.snapshotRev);
2881
3001
  takeAllowed(message.allowed ?? summary?.allowed ?? null, !staleSnapshot);
3002
+ if (message.runtime !== void 0) {
3003
+ runtimeNow = message.runtime;
3004
+ } else if (message.instance !== instance) {
3005
+ runtimeNow = null;
3006
+ }
2882
3007
  const sameRun2 = summary && instance === message.instance && session?.id === summary.id;
2883
3008
  const resumed = sameRun2 && replay?.from_seq != null;
2884
3009
  instance = message.instance;
@@ -2907,8 +3032,8 @@ var SessionFeed = class {
2907
3032
  if (session && message.session === session.id) {
2908
3033
  session = addDropped(session, message);
2909
3034
  if (message.reason === "not-kept" && replayLogs) {
2910
- for (const [source, count2] of Object.entries(message.log))
2911
- replayLogs.notKept.set(source, (replayLogs.notKept.get(source) ?? 0) + count2);
3035
+ for (const [source, count] of Object.entries(message.log))
3036
+ replayLogs.notKept.set(source, (replayLogs.notKept.get(source) ?? 0) + count);
2912
3037
  }
2913
3038
  }
2914
3039
  break;
@@ -2923,6 +3048,9 @@ var SessionFeed = class {
2923
3048
  case "allowed":
2924
3049
  takeAllowed(message.allowed);
2925
3050
  break;
3051
+ case "runtime":
3052
+ runtimeNow = message.runtime;
3053
+ break;
2926
3054
  case "session":
2927
3055
  if (session?.id !== message.session.id) replayLogs = null;
2928
3056
  takeAllowed(message.session.allowed);
@@ -2971,10 +3099,12 @@ var SessionFeed = class {
2971
3099
  const sameRun = () => currentOrigin() && this.instanceId === instance && (this.current.get()?.id ?? null) === sessionId;
2972
3100
  const notifySession = this.current.setDeferred(session);
2973
3101
  const notifyAllowed = this.allowedValue.setDeferred(allowedNow);
3102
+ const notifyRuntime = this.runtimeValue.setDeferred(runtimeNow);
2974
3103
  const notifySynced = this.synced.setDeferred(synced);
2975
3104
  if (instance && instance !== originalInstance) this.instanceListener(instance, sameRun);
2976
3105
  notifySession();
2977
3106
  notifyAllowed();
3107
+ notifyRuntime();
2978
3108
  notifySynced();
2979
3109
  if (!sameRun()) return;
2980
3110
  for (const notice of notices) {
@@ -2989,13 +3119,13 @@ var SessionFeed = class {
2989
3119
  if (!sameRun()) return;
2990
3120
  callEach(this.messageListeners, [batch], this.onError, sameRun);
2991
3121
  }
2992
- notify(message, count2 = 1) {
3122
+ notify(message, count = 1) {
2993
3123
  this.noticeList.update((list) => {
2994
3124
  const same = list.find((notice) => notice.message === message);
2995
3125
  if (same) {
2996
- return [...list.filter((n) => n !== same), { ...same, count: same.count + count2 }];
3126
+ return [...list.filter((n) => n !== same), { ...same, count: same.count + count }];
2997
3127
  }
2998
- return [...list, { id: ++this.noticeId, message, count: count2 }].slice(-MAX_NOTICES);
3128
+ return [...list, { id: ++this.noticeId, message, count }].slice(-MAX_NOTICES);
2999
3129
  });
3000
3130
  }
3001
3131
  };
@@ -3003,15 +3133,20 @@ var SessionFeed = class {
3003
3133
  // ../client/src/time.ts
3004
3134
  var ANSWER_TIMEOUT_MS = 5e3;
3005
3135
  var TimeControl = class {
3006
- constructor(session, transport, answerTimeoutMs = ANSWER_TIMEOUT_MS, onError = rethrowLater) {
3136
+ constructor(session, transport, currentTarget, answerTimeoutMs = ANSWER_TIMEOUT_MS, onError = rethrowLater) {
3007
3137
  this.session = session;
3008
3138
  this.transport = transport;
3139
+ this.currentTarget = currentTarget;
3009
3140
  this.answerTimeoutMs = answerTimeoutMs;
3010
- this.inFlight = new Writable(0, Object.is, onError);
3141
+ this.awaitingHttp = new Writable(null, Object.is, onError);
3011
3142
  this.pending = new Writable(null, Object.is, onError);
3012
- this.failureValue = new Writable(null, Object.is, onError);
3143
+ this.failureValue = new Writable(
3144
+ null,
3145
+ Object.is,
3146
+ onError
3147
+ );
3013
3148
  this.state = derived(
3014
- [session, this.inFlight, this.pending, this.failureValue],
3149
+ [session, this.awaitingHttp, this.pending, this.failureValue],
3015
3150
  () => this.compute(session.get()),
3016
3151
  shallowEqual,
3017
3152
  onError
@@ -3019,8 +3154,9 @@ var TimeControl = class {
3019
3154
  }
3020
3155
  session;
3021
3156
  transport;
3157
+ currentTarget;
3022
3158
  answerTimeoutMs;
3023
- inFlight;
3159
+ awaitingHttp;
3024
3160
  pending;
3025
3161
  failureValue;
3026
3162
  answerTimer;
@@ -3051,46 +3187,58 @@ var TimeControl = class {
3051
3187
  */
3052
3188
  send(command) {
3053
3189
  const session = this.session.get();
3054
- if (!session) return { sent: false, reason: "no-session" };
3190
+ const target = this.currentTarget();
3191
+ if (!session || target?.session !== session.id) return { sent: false, reason: "no-session" };
3055
3192
  if (this.state.get().sending !== null) return { sent: false, reason: "waiting" };
3056
3193
  this.failureValue.set(null);
3057
3194
  const pending = {
3058
3195
  command: command.command,
3059
- session: session.id,
3196
+ target,
3060
3197
  afterSeq: session.lastCommand?.seq ?? -1
3061
3198
  };
3199
+ this.awaitingHttp.set(pending);
3062
3200
  this.pending.set(pending);
3063
- this.inFlight.update((n) => n + 1);
3064
3201
  clearTimeout(this.answerTimer);
3065
3202
  this.answerTimer = setTimeout(() => this.giveUp(pending), this.answerTimeoutMs);
3066
- this.transport({ method: "POST", path: "api/time", body: command }, (outcome) => {
3067
- this.inFlight.update((n) => n - 1);
3068
- if (outcome.ok || this.pending.get() !== pending) return;
3069
- clearTimeout(this.answerTimer);
3070
- this.pending.set(null);
3071
- this.failureValue.set({
3072
- kind: "server",
3073
- message: errorMessage(outcome.error),
3074
- command: pending.command,
3075
- session: this.session.get()?.id ?? null
3076
- });
3077
- });
3203
+ this.transport(
3204
+ { method: "POST", path: "api/time", body: { ...command, ...target } },
3205
+ (outcome) => {
3206
+ if (this.awaitingHttp.get() === pending) this.awaitingHttp.set(null);
3207
+ if (outcome.ok || this.pending.get() !== pending) return;
3208
+ clearTimeout(this.answerTimer);
3209
+ this.pending.set(null);
3210
+ if (!sameRunTarget(this.currentTarget(), target)) return;
3211
+ this.failureValue.set({
3212
+ target,
3213
+ report: {
3214
+ kind: "server",
3215
+ message: errorMessage(outcome.error),
3216
+ command: pending.command,
3217
+ session: target.session
3218
+ }
3219
+ });
3220
+ }
3221
+ );
3078
3222
  return { sent: true };
3079
3223
  }
3080
3224
  /** Stops the wait timer and stops waiting for the answer (when the client closes). */
3081
3225
  dispose() {
3082
3226
  clearTimeout(this.answerTimer);
3083
3227
  this.pending.set(null);
3228
+ this.awaitingHttp.set(null);
3084
3229
  }
3085
3230
  /** The answer timed out: if no answer has come yet, stop waiting and say so. */
3086
3231
  giveUp(pending) {
3087
3232
  if (this.pending.get() !== pending || this.state.get().sending === null) return;
3088
3233
  this.pending.set(null);
3089
3234
  this.failureValue.set({
3090
- kind: "no-answer",
3091
- message: `the launcher did not answer the command (${pending.command}) within ${this.answerTimeoutMs / 1e3} s; it may not read its input. You can send it again.`,
3092
- command: pending.command,
3093
- session: pending.session
3235
+ target: pending.target,
3236
+ report: {
3237
+ kind: "no-answer",
3238
+ message: `the launcher did not answer the command (${pending.command}) within ${this.answerTimeoutMs / 1e3} s; it may not read its input. You can send it again.`,
3239
+ command: pending.command,
3240
+ session: pending.target.session
3241
+ }
3094
3242
  });
3095
3243
  }
3096
3244
  compute(session) {
@@ -3107,10 +3255,11 @@ var TimeControl = class {
3107
3255
  this.lastLateness = lateness;
3108
3256
  const lastCommand = session?.lastCommand ?? null;
3109
3257
  const pending = this.pending.get();
3258
+ const target = this.currentTarget();
3110
3259
  let sending = null;
3111
- if (pending) {
3112
- const answered = !session || session.id !== pending.session || !session.launcher.running || (session.lastCommand?.seq ?? -1) > pending.afterSeq;
3113
- sending = this.inFlight.get() > 0 || !answered ? pending.command : null;
3260
+ if (pending && sameRunTarget(pending.target, target)) {
3261
+ const answered = !session || !isRunActive(session) || (session.lastCommand?.seq ?? -1) > pending.afterSeq;
3262
+ sending = this.awaitingHttp.get() === pending || !answered ? pending.command : null;
3114
3263
  }
3115
3264
  const failure = this.failureValue.get();
3116
3265
  return {
@@ -3120,7 +3269,7 @@ var TimeControl = class {
3120
3269
  behind: (lateness?.lateSteps ?? 0) > 0,
3121
3270
  lastCommand,
3122
3271
  sending,
3123
- failure: failure && failure.session === (session?.id ?? null) ? failure : null
3272
+ failure: failure && sameRunTarget(failure.target, target) ? failure.report : null
3124
3273
  };
3125
3274
  }
3126
3275
  };
@@ -3218,69 +3367,57 @@ var keyOf = (peer, name) => `${peer}\0${name}`;
3218
3367
  var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3219
3368
  var text = (value, fallback = "") => typeof value === "string" ? value : fallback;
3220
3369
  var numberOrNull = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
3221
- var count = (value) => typeof value === "number" && value >= 0 ? value : 0;
3222
3370
  var positionOrNull = (value) => Number.isSafeInteger(value) && value >= 0 ? value : null;
3223
3371
  function readVariables2(value, session) {
3224
- if (!isObject(value)) return { ...NO_VARIABLES, session };
3372
+ const u = new Unreadable("variables");
3373
+ const summary = lenient(
3374
+ (v) => readVariablesReport(v, "variables", u),
3375
+ null,
3376
+ u
3377
+ )(value, "variables");
3378
+ if (!summary) return { ...NO_VARIABLES, session };
3225
3379
  const peers = [];
3226
3380
  const availability = /* @__PURE__ */ new Map();
3227
- for (const p of Array.isArray(value["peers"]) ? value["peers"] : []) {
3228
- if (!isObject(p) || typeof p["name"] !== "string") continue;
3381
+ for (const p of summary.peers) {
3229
3382
  const variables = [];
3230
3383
  const states = /* @__PURE__ */ new Map();
3231
- for (const v of Array.isArray(p["variables"]) ? p["variables"] : []) {
3232
- if (!isObject(v) || typeof v["name"] !== "string") continue;
3233
- const items2 = Array.isArray(v["enum"]) ? v["enum"].flatMap(
3234
- (i) => isObject(i) && typeof i["name"] === "string" && typeof i["value"] === "number" ? [{ name: i["name"], value: i["value"] }] : []
3235
- ) : null;
3236
- variables.push({
3237
- name: v["name"],
3238
- type: text(v["type"]),
3239
- role: text(v["role"], "output"),
3240
- writable: v["writable"] === true,
3241
- unit: text(v["unit"]),
3242
- min: numberOrNull(v["min"]),
3243
- max: numberOrNull(v["max"]),
3244
- step: numberOrNull(v["step"]),
3245
- description: text(v["description"]),
3246
- enum: items2
3247
- });
3248
- states.set(v["name"], readAvailability(v["availability"]));
3384
+ for (const { availability: state, ...info } of p.variables) {
3385
+ variables.push(info);
3386
+ states.set(info.name, state);
3249
3387
  }
3250
- availability.set(p["name"], states);
3251
- peers.push({ name: p["name"], connected: p["connected"] === true, variables });
3388
+ availability.set(p.name, states);
3389
+ peers.push({ name: p.name, connected: p.connected, variables });
3252
3390
  }
3253
3391
  return {
3254
3392
  session,
3255
- status: text(value["state"], "unknown"),
3256
- reason: typeof value["reason"] === "string" ? value["reason"] : null,
3393
+ status: summary.state,
3394
+ reason: summary.reason,
3257
3395
  peers,
3258
3396
  availability,
3259
- peersOmitted: count(value["peers_omitted"]),
3260
- variablesOmitted: count(value["variables_omitted"])
3397
+ peersOmitted: summary.peers_omitted,
3398
+ variablesOmitted: summary.variables_omitted
3261
3399
  };
3262
3400
  }
3263
3401
  function readOperation(value, session) {
3264
- if (!isObject(value) || !Number.isSafeInteger(value["seq"]) || typeof value["state"] !== "string") {
3265
- return null;
3266
- }
3402
+ const u = new Unreadable("operation");
3403
+ const report = lenient((v, p) => readOperationReport(v, p, u), null, u)(value, "operation");
3404
+ if (!report) return null;
3267
3405
  const peers = {};
3268
- for (const [name, p] of Object.entries(isObject(value["peers"]) ? value["peers"] : {})) {
3269
- if (!isObject(p)) continue;
3406
+ for (const [name, p] of Object.entries(report.peers)) {
3270
3407
  peers[name] = {
3271
- state: text(p["state"], "unknown"),
3272
- appliedAtMs: numberOrNull(p["applied_at_ms"]),
3273
- late: p["late"] === true,
3274
- reason: typeof p["reason"] === "string" ? p["reason"] : null,
3275
- appliedWrites: positionOrNull(p["applied_writes"]),
3276
- failedWrite: positionOrNull(p["failed_write"])
3408
+ state: p.state,
3409
+ appliedAtMs: p.applied_at_ms,
3410
+ late: p.late,
3411
+ reason: p.reason,
3412
+ appliedWrites: p.applied_writes,
3413
+ failedWrite: p.failed_write
3277
3414
  };
3278
3415
  }
3279
3416
  return {
3280
3417
  session,
3281
- seq: value["seq"],
3282
- state: value["state"],
3283
- done: value["done"] === true,
3418
+ seq: report.seq,
3419
+ state: report.state,
3420
+ done: report.done,
3284
3421
  peers
3285
3422
  };
3286
3423
  }
@@ -3854,6 +3991,7 @@ var VariablesFeed = class {
3854
3991
  );
3855
3992
  }
3856
3993
  const body = { session, writes };
3994
+ if (options.instance !== void 0) body["instance"] = options.instance;
3857
3995
  if (options.atMs !== void 0) body["at_ms"] = options.atMs;
3858
3996
  if (options.late !== void 0) body["late"] = options.late;
3859
3997
  return new Promise((resolve, reject) => {
@@ -4499,6 +4637,7 @@ function buildClient(options) {
4499
4637
  const time = new TimeControl(
4500
4638
  session.session,
4501
4639
  http,
4640
+ () => session.currentTarget(),
4502
4641
  options.answerTimeoutMs ?? ANSWER_TIMEOUT_MS,
4503
4642
  onError
4504
4643
  );
@@ -4539,12 +4678,13 @@ function buildClient(options) {
4539
4678
  currentInstance: () => session.currentInstance(),
4540
4679
  ready: session.ready,
4541
4680
  allowed: session.allowed,
4681
+ runtime: session.runtime,
4542
4682
  lastEventAt: session.lastEventAt,
4543
4683
  notices: session.notices,
4544
4684
  rejected: session.rejected,
4545
4685
  incompatible: session.incompatible,
4546
4686
  onMessages: (listener) => session.onMessages(listener),
4547
- report: (message, count2) => session.report(message, count2),
4687
+ report: (message, count) => session.report(message, count),
4548
4688
  dismissNotice: (id) => session.dismissNotice(id)
4549
4689
  },
4550
4690
  run: {
@@ -4627,6 +4767,16 @@ function buildClient(options) {
4627
4767
  },
4628
4768
  readConnections
4629
4769
  ),
4770
+ prepare: (body) => call(
4771
+ {
4772
+ method: "POST",
4773
+ path: "api/prepare",
4774
+ body,
4775
+ timeoutMs: longRequestMs(limits.get())
4776
+ },
4777
+ readPrepareResponse,
4778
+ (res) => session.adoptRuntime(res.runtime)
4779
+ ),
4630
4780
  fetchSession: () => {
4631
4781
  const resyncFrom = session.currentInstance();
4632
4782
  const snapshotVersion = variables.snapshotVersion();
@@ -4639,8 +4789,10 @@ function buildClient(options) {
4639
4789
  try {
4640
4790
  const summary = readSessionResponse(outcome.body);
4641
4791
  const instance = readSessionInstance(outcome.body);
4792
+ const runtime = readSessionRuntime(outcome.body);
4642
4793
  const adoption = session.adopt(summary, instance, resyncFrom);
4643
4794
  if (adoption !== null) {
4795
+ if (runtime !== void 0) session.adoptRuntime(runtime);
4644
4796
  const rawSession = outcome.body?.session;
4645
4797
  const rev = rawSession?.variables?.rev;
4646
4798
  const current = () => variables.isSnapshotCurrent(
@@ -4811,8 +4963,7 @@ function standsAt(session) {
4811
4963
  }
4812
4964
  function onItsWay(session) {
4813
4965
  const last = session?.lastCommand;
4814
- if (!session || !session.launcher.running || !last || !last.accepted || last.atMs === null)
4815
- return false;
4966
+ if (!isRunActive(session) || !last || !last.accepted || last.atMs === null) return false;
4816
4967
  if (last.name !== "step" && last.name !== "run_until") return false;
4817
4968
  const stands = standsAt(session);
4818
4969
  return !(stands !== null && stands >= last.atMs);
@@ -4821,7 +4972,7 @@ function clockOf(s) {
4821
4972
  const session = s.session;
4822
4973
  const state = session?.launcherState ?? null;
4823
4974
  const time = session?.time ?? null;
4824
- const live = !!session && session.launcher.running;
4975
+ const live = isRunActive(session);
4825
4976
  const pacing = state?.pacing;
4826
4977
  return {
4827
4978
  sim_ms: simMsOf(session ?? null),
@@ -4879,7 +5030,7 @@ function composeControls(s, run) {
4879
5030
  const link = linkOf(s);
4880
5031
  const down = linkReason(link, s);
4881
5032
  const session = s.session;
4882
- const live = !!session && session.launcher.running && run !== "ended" && run !== "crashed";
5033
+ const live = isRunActive(session) && run !== "ended" && run !== "crashed";
4883
5034
  const state = session?.launcherState ?? null;
4884
5035
  const stopsAsked = session?.stopRequests ?? 0;
4885
5036
  let start;
@@ -5073,7 +5224,12 @@ var FrontActions = class {
5073
5224
  const own = this.refusalOfStart();
5074
5225
  if (own) return this.fail(own);
5075
5226
  const start = this.src.low.run.start(request);
5076
- return this.guarded("start", () => start.then(() => void 0));
5227
+ return this.guarded(
5228
+ "start",
5229
+ () => start.then((started) => {
5230
+ if (started) options.onStarted?.(started);
5231
+ })
5232
+ );
5077
5233
  }
5078
5234
  /**
5079
5235
  * Checks what `intent` would start (`api/check`). Its failure is the caller's: it is not kept for `status.problem`.
@@ -5288,13 +5444,13 @@ var FrontActions = class {
5288
5444
  );
5289
5445
  }
5290
5446
  // --- time --------------------------------------------------------------------------------------
5291
- pause() {
5292
- return this.time("pause", { command: "pause" }, 0);
5447
+ pause(target) {
5448
+ return this.time("pause", { command: "pause" }, 0, target);
5293
5449
  }
5294
- resume() {
5295
- return this.time("resume", { command: "resume" }, 0);
5450
+ resume(target) {
5451
+ return this.time("resume", { command: "resume" }, 0, target);
5296
5452
  }
5297
- step(ms) {
5453
+ step(ms, target) {
5298
5454
  if (!Number.isFinite(ms) || ms <= 0) {
5299
5455
  return this.fail(
5300
5456
  new ActionError(
@@ -5304,9 +5460,9 @@ var FrontActions = class {
5304
5460
  )
5305
5461
  );
5306
5462
  }
5307
- return this.time("step", { command: "step", ms }, ms);
5463
+ return this.time("step", { command: "step", ms }, ms, target);
5308
5464
  }
5309
- setSpeed(value) {
5465
+ setSpeed(value, target) {
5310
5466
  if (value !== "max" && !(Number.isFinite(value) && value > 0)) {
5311
5467
  return this.fail(
5312
5468
  new ActionError(
@@ -5316,9 +5472,9 @@ var FrontActions = class {
5316
5472
  )
5317
5473
  );
5318
5474
  }
5319
- return this.time("speed", { command: "speed", value }, 0);
5475
+ return this.time("speed", { command: "speed", value }, 0, target);
5320
5476
  }
5321
- runUntil(ms) {
5477
+ runUntil(ms, target) {
5322
5478
  if (!Number.isFinite(ms) || ms < 0) {
5323
5479
  return this.fail(
5324
5480
  new ActionError(
@@ -5328,26 +5484,32 @@ var FrontActions = class {
5328
5484
  )
5329
5485
  );
5330
5486
  }
5331
- return this.time("run_until", { command: "run_until", at_ms: ms }, ms);
5487
+ return this.time("run_until", { command: "run_until", at_ms: ms }, ms, target);
5332
5488
  }
5333
- time(op, body, amount) {
5489
+ time(op, body, amount, shownTarget) {
5490
+ const target = this.src.low.session.currentTarget();
5334
5491
  this.failureValue.set(null);
5335
5492
  const snapshot = this.src.snapshot();
5336
5493
  const link = linkOf(snapshot);
5337
5494
  const own = link === "rejected" || link === "incompatible" ? this.src.controls()[op].reason : this.busyValue.get().has(op) ? { code: "busy", message: `the previous ${op} has not been answered yet: wait for it` } : null;
5338
5495
  if (own) return this.fail(new ActionError(own.code, own.message, "refused"));
5496
+ if (shownTarget !== void 0 && !sameRunTarget(shownTarget, target))
5497
+ return this.fail(
5498
+ new ActionError("session-changed", "the displayed run has changed", "refused")
5499
+ );
5500
+ if (!target)
5501
+ return this.fail(new ActionError("not-running", "there is no identified run", "refused"));
5339
5502
  const code = this.src.controls()[op === "pause" ? "pause" : "resume"].reason?.code;
5340
5503
  if (op === "pause" && code === "paused" || op === "resume" && code === "not-paused") {
5341
5504
  return Promise.resolve();
5342
5505
  }
5343
- const session = snapshot.session;
5344
5506
  const id = this.nextId++;
5345
5507
  return new Promise((resolve, reject) => {
5346
5508
  const waiting = {
5347
5509
  id,
5348
5510
  op,
5349
5511
  amount,
5350
- session: session?.id ?? -1,
5512
+ ...target,
5351
5513
  stage: "sent",
5352
5514
  target: 0,
5353
5515
  from: 0,
@@ -5368,9 +5530,12 @@ var FrontActions = class {
5368
5530
  )
5369
5531
  );
5370
5532
  }, this.src.answerTimeoutMs);
5371
- this.src.http({ method: "POST", path: "api/time", body: { ...body, id } }, (outcome) => {
5372
- if (!outcome.ok) this.settle(waiting, actionError(outcome.error));
5373
- });
5533
+ this.src.http(
5534
+ { method: "POST", path: "api/time", body: { ...body, id, ...target } },
5535
+ (outcome) => {
5536
+ if (!outcome.ok) this.settle(waiting, actionError(outcome.error));
5537
+ }
5538
+ );
5374
5539
  });
5375
5540
  }
5376
5541
  /** Ends a waiting command: with an error, or (null) as done. A command ended twice is ended once. */
@@ -5462,8 +5627,9 @@ var FrontActions = class {
5462
5627
  evaluate() {
5463
5628
  if (this.waiting.size === 0) return;
5464
5629
  const session = this.src.low.session.session.get();
5630
+ const instance = this.src.low.session.currentInstance();
5465
5631
  for (const w of [...this.waiting.values()]) {
5466
- if (!session || session.id !== w.session || !session.launcher.running || session.result) {
5632
+ if (!session || !isRunActive(session) || session.id !== w.session || instance !== w.instance || session.result) {
5467
5633
  this.settle(
5468
5634
  w,
5469
5635
  new ActionError(
@@ -5566,11 +5732,11 @@ function outsideRows(low, onError) {
5566
5732
  [low.session.session, counts],
5567
5733
  () => {
5568
5734
  const session = low.session.session.get();
5569
- if (!session?.launcher.running) return [];
5735
+ if (!session || !isRunActive(session)) return [];
5570
5736
  const known = counts.get();
5571
5737
  const of = known?.session === session.id ? known.networks : /* @__PURE__ */ new Map();
5572
5738
  return (session.launcherState?.outside ?? []).map((row) => {
5573
- const count2 = of.get(row.network);
5739
+ const count = of.get(row.network);
5574
5740
  return {
5575
5741
  network: row.network,
5576
5742
  target: row.target,
@@ -5580,8 +5746,8 @@ function outsideRows(low, onError) {
5580
5746
  condition: row.condition,
5581
5747
  reasons: row.reasons,
5582
5748
  nothing_received: row.nothing_received,
5583
- to_outside: count2?.to ?? null,
5584
- from_outside: count2?.from ?? null
5749
+ to_outside: count?.to ?? null,
5750
+ from_outside: count?.from ?? null
5585
5751
  };
5586
5752
  });
5587
5753
  },
@@ -5689,7 +5855,7 @@ function makeVariable(low, ref, refuse, launcher) {
5689
5855
  const track = new Writable({ writing: false, problem: null }, sameData);
5690
5856
  const view = new Writable(null, sameData);
5691
5857
  let binding = null;
5692
- let count2 = 0;
5858
+ let count = 0;
5693
5859
  let stops = [];
5694
5860
  const refresh = () => {
5695
5861
  if (binding) view.set(viewOf(binding.state.get(), track.get(), launcher.get()));
@@ -5711,7 +5877,7 @@ function makeVariable(low, ref, refuse, launcher) {
5711
5877
  return view.get();
5712
5878
  },
5713
5879
  subscribe: (listener) => {
5714
- if (count2++ === 0) {
5880
+ if (count++ === 0) {
5715
5881
  binding = low.variables.bind(ref);
5716
5882
  stops = [
5717
5883
  binding.state.subscribe(refresh),
@@ -5726,7 +5892,7 @@ function makeVariable(low, ref, refuse, launcher) {
5726
5892
  if (done) return;
5727
5893
  done = true;
5728
5894
  off();
5729
- if (--count2 === 0) {
5895
+ if (--count === 0) {
5730
5896
  for (const stop of stops) stop();
5731
5897
  stops = [];
5732
5898
  binding?.close();
@@ -5894,7 +6060,32 @@ function makeFront(options, onClose) {
5894
6060
  clock,
5895
6061
  controls,
5896
6062
  scenario,
6063
+ runtime: low.session.runtime,
5897
6064
  outside: outside.value,
6065
+ prepare: (prepareOptions = {}) => {
6066
+ const file = prepareOptions.file ?? initialFile();
6067
+ if (file === null) {
6068
+ return Promise.reject(noFileError());
6069
+ }
6070
+ return low.prepare({
6071
+ file,
6072
+ ...prepareOptions.variant !== void 0 ? { variant: prepareOptions.variant } : {},
6073
+ ...prepareOptions.disable !== void 0 ? { disable: prepareOptions.disable } : {},
6074
+ ...prepareOptions.enable !== void 0 ? { enable: prepareOptions.enable } : {},
6075
+ ...prepareOptions.manual !== void 0 ? { manual: prepareOptions.manual } : {}
6076
+ }).then(
6077
+ (res) => res.runtime,
6078
+ (error) => {
6079
+ throw actionError(error);
6080
+ }
6081
+ );
6082
+ },
6083
+ configs: () => low.configs().catch((error) => {
6084
+ throw actionError(error);
6085
+ }),
6086
+ recording: () => low.recording().catch((error) => {
6087
+ throw actionError(error);
6088
+ }),
5898
6089
  connections: ({ network }, listOptions = {}) => {
5899
6090
  const file = listOptions.file ?? initialFile();
5900
6091
  if (file === null) {
@@ -5932,11 +6123,11 @@ function makeFront(options, onClose) {
5932
6123
  forceStop: (target) => actions.forceStop(target)
5933
6124
  },
5934
6125
  time: {
5935
- pause: () => actions.pause(),
5936
- resume: () => actions.resume(),
5937
- step: (ms) => actions.step(ms),
5938
- setSpeed: (value) => actions.setSpeed(value),
5939
- runUntil: (ms) => actions.runUntil(ms)
6126
+ pause: (target) => actions.pause(target),
6127
+ resume: (target) => actions.resume(target),
6128
+ step: (ms, target) => actions.step(ms, target),
6129
+ setSpeed: (value, target) => actions.setSpeed(value, target),
6130
+ runUntil: (ms, target) => actions.runUntil(ms, target)
5940
6131
  },
5941
6132
  variable: (ref) => {
5942
6133
  const named = refOf(ref);
@@ -6262,6 +6453,10 @@ export {
6262
6453
  fetchTransport,
6263
6454
  hasRange,
6264
6455
  isHolding,
6456
+ isLauncherAlive,
6457
+ isLauncherFinishing,
6458
+ isRunActive,
6459
+ isSessionRunning,
6265
6460
  isWriteError,
6266
6461
  launcherAnswer,
6267
6462
  phaseIndex,
@@ -6271,12 +6466,15 @@ export {
6271
6466
  readConfigText,
6272
6467
  readConnections,
6273
6468
  readDashboardResponse,
6469
+ readPrepareResponse,
6274
6470
  readRecording,
6471
+ readRuntimeStatus,
6275
6472
  readSavedConfig,
6276
6473
  readScenarioList,
6277
6474
  readServerMessage,
6278
6475
  readSessionAllowed,
6279
6476
  readSessionResponse,
6477
+ readSessionRuntime,
6280
6478
  readTimeResponse,
6281
6479
  readVariablesSummary,
6282
6480
  readWriteResponse,