@vehicle-sil/gui-client 0.2.0-rc.1 → 0.2.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
@@ -31,10 +31,14 @@ var Writable = class {
31
31
  return this.value;
32
32
  }
33
33
  set(value) {
34
- if (this.equal(this.value, value)) return;
34
+ this.setDeferred(value)();
35
+ }
36
+ /** Changes the value immediately and returns its notification, for an atomic multi-value update. */
37
+ setDeferred(value) {
38
+ if (this.equal(this.value, value)) return () => void 0;
35
39
  this.value = value;
36
40
  const version2 = ++this.version;
37
- callEach(this.listeners, [value], this.onError, () => this.version === version2);
41
+ return () => callEach(this.listeners, [value], this.onError, () => this.version === version2);
38
42
  }
39
43
  update(change) {
40
44
  this.set(change(this.value));
@@ -114,6 +118,8 @@ var Connection = class {
114
118
  batchListeners = /* @__PURE__ */ new Set();
115
119
  unreadableListeners = /* @__PURE__ */ new Set();
116
120
  socket = null;
121
+ connectionEpoch = 0;
122
+ attemptRevision = 0;
117
123
  wanted = false;
118
124
  /** Consecutive drops without a readable notification. */
119
125
  attempts = 0;
@@ -138,6 +144,7 @@ var Connection = class {
138
144
  }
139
145
  /** Disconnects, without reconnecting. Drops notifications still being batched. */
140
146
  close() {
147
+ const revision = ++this.attemptRevision;
141
148
  this.wanted = false;
142
149
  this.restarts = 0;
143
150
  this.attempts = 0;
@@ -148,7 +155,7 @@ var Connection = class {
148
155
  const socket = this.socket;
149
156
  this.socket = null;
150
157
  socket?.close();
151
- this.stateValue.set("closed");
158
+ if (revision === this.attemptRevision) this.stateValue.set("closed");
152
159
  }
153
160
  /**
154
161
  * Drops the current connection and reconnects after a delay (when a reader could not rebuild its state from the
@@ -159,14 +166,16 @@ var Connection = class {
159
166
  }
160
167
  restartAfter(delayMs) {
161
168
  if (!this.wanted) return;
169
+ const revision = ++this.attemptRevision;
162
170
  this.restartAsked = true;
163
171
  this.dropPending();
164
172
  clearTimeout(this.steadyTimer);
165
173
  const socket = this.socket;
166
174
  this.socket = null;
167
175
  socket?.close();
176
+ if (revision !== this.attemptRevision) return;
168
177
  this.stateValue.set("closed");
169
- this.scheduleRetry(delayMs);
178
+ if (revision === this.attemptRevision) this.scheduleRetry(delayMs);
170
179
  }
171
180
  /**
172
181
  * Sends a notification to the server (one that follows authentication, such as a variable subscription). Sends only
@@ -211,22 +220,35 @@ var Connection = class {
211
220
  this.pending = [];
212
221
  }
213
222
  open() {
223
+ const revision = ++this.attemptRevision;
224
+ const currentAttempt = () => this.wanted && this.attemptRevision === revision;
214
225
  try {
215
- this.openSocket();
226
+ this.openSocket(currentAttempt);
216
227
  } catch (error) {
228
+ if (!currentAttempt()) return;
217
229
  this.onError(error);
230
+ if (!currentAttempt()) return;
218
231
  this.socket = null;
219
232
  this.lastCloseValue.set({
220
233
  code: NOT_OPENED,
221
234
  reason: `cannot open the WebSocket: ${error instanceof Error ? error.message : String(error)}`
222
235
  });
236
+ if (!currentAttempt()) return;
223
237
  this.stateValue.set("closed");
224
- this.scheduleRetry(backoffMs(++this.attempts, this.options.maxBackoffMs));
238
+ if (currentAttempt())
239
+ this.scheduleRetry(backoffMs(++this.attempts, this.options.maxBackoffMs));
225
240
  }
226
241
  }
227
- openSocket() {
242
+ /** Identifies the connection that produced a batch; restarting alone does not create the next one. */
243
+ batchEpoch() {
244
+ return this.connectionEpoch;
245
+ }
246
+ openSocket(currentAttempt) {
247
+ ++this.connectionEpoch;
228
248
  const greeting = this.options.greeting();
249
+ if (!currentAttempt()) return;
229
250
  this.stateValue.set("connecting");
251
+ if (!currentAttempt()) return;
230
252
  let opened = false;
231
253
  let socket = null;
232
254
  const current = () => socket !== null && this.socket === socket;
@@ -235,6 +257,7 @@ var Connection = class {
235
257
  if (!current()) return;
236
258
  opened = true;
237
259
  this.stateValue.set("open");
260
+ if (!current()) return;
238
261
  clearTimeout(this.steadyTimer);
239
262
  this.steadyTimer = setTimeout(() => this.garbled = 0, STEADY_MS);
240
263
  for (const message of greeting) socket?.send(JSON.stringify(message));
@@ -253,25 +276,37 @@ var Connection = class {
253
276
  message = JSON.parse(text3);
254
277
  } catch {
255
278
  callEach(this.unreadableListeners, [text3], this.onError);
279
+ if (!current()) return;
256
280
  this.restartAfter(backoffMs(++this.garbled, this.options.maxBackoffMs));
257
281
  return;
258
282
  }
259
283
  this.attempts = 0;
260
284
  if (this.lastCloseValue.get() !== null) this.lastCloseValue.set(null);
285
+ if (!current()) return;
261
286
  this.pending.push(message);
262
287
  this.batchTimer ??= setTimeout(() => this.flush(), this.options.batchMs ?? BATCH_MS);
263
288
  },
264
289
  close: (code, reason2) => {
290
+ if (!current()) return;
291
+ this.flush();
265
292
  if (!current()) return;
266
293
  this.socket = null;
294
+ const closedEpoch = this.connectionEpoch;
267
295
  clearTimeout(this.steadyTimer);
268
296
  if (!opened) this.failureCount.update((n) => n + 1);
297
+ if (this.connectionEpoch !== closedEpoch) return;
269
298
  this.lastCloseValue.set({ code, reason: reason2 });
299
+ if (this.connectionEpoch !== closedEpoch) return;
270
300
  this.stateValue.set("closed");
301
+ if (this.connectionEpoch !== closedEpoch) return;
271
302
  this.scheduleRetry(backoffMs(++this.attempts, this.options.maxBackoffMs));
272
303
  }
273
304
  };
274
305
  socket = this.options.socket(this.options.url, handlers);
306
+ if (!currentAttempt()) {
307
+ socket.close();
308
+ return;
309
+ }
275
310
  this.socket = socket;
276
311
  }
277
312
  scheduleRetry(delayMs) {
@@ -413,6 +448,7 @@ function severityRank(severity) {
413
448
  var readFinding = (value, path, u) => {
414
449
  const f = object(value, path);
415
450
  return withRaw(f, {
451
+ ...Number.isSafeInteger(f["event_seq"]) && f["event_seq"] >= 0 ? { event_seq: f["event_seq"] } : {},
416
452
  severity: field(f, path, "severity", string),
417
453
  code: field(f, path, "code", lenient(string, "", u)),
418
454
  file: field(f, path, "file", soft(nullable(string), null, u)),
@@ -518,6 +554,7 @@ var readCheckResult = (value, path, u) => {
518
554
  warnings: field(f, path, "warnings", lenient(integer, 0, u)),
519
555
  notes: field(f, path, "notes", lenient(integer, 0, u)),
520
556
  stop_at_ms: field(f, path, "stop_at_ms", soft(nullable(number), null, u)),
557
+ ...f["time_step_ms"] === void 0 ? {} : { time_step_ms: field(f, path, "time_step_ms", soft(nullable(number), null, u)) },
521
558
  participants: field(
522
559
  f,
523
560
  path,
@@ -940,13 +977,15 @@ function readEventFields(f, path, kind, base, u) {
940
977
  }
941
978
 
942
979
  // ../client/src/protocol/server.ts
943
- var PROTOCOL_VERSION = 2;
980
+ var PROTOCOL_VERSION = 3;
944
981
  var readServerProblem = (value, path) => {
945
982
  const f = object(value, path);
946
983
  const problem = {
947
984
  code: field(f, path, "code", string),
948
985
  message: field(f, path, "message", string)
949
986
  };
987
+ if (Number.isSafeInteger(f["problem_seq"]) && f["problem_seq"] >= 0)
988
+ problem.problem_seq = f["problem_seq"];
950
989
  const detail = f["detail"];
951
990
  if (typeof detail === "object" && detail !== null && "skipped" in detail) {
952
991
  const skipped = detail.skipped;
@@ -1016,7 +1055,14 @@ var readConfigList = (value) => {
1016
1055
  f,
1017
1056
  path,
1018
1057
  "files",
1019
- array((item, p) => ({ path: field(object(item, p), p, "path", string) }))
1058
+ array((item, p) => {
1059
+ const entry = object(item, p);
1060
+ const simulation = field(entry, p, "simulation", optional(boolean, void 0));
1061
+ return {
1062
+ path: field(entry, p, "path", string),
1063
+ ...simulation === void 0 ? {} : { simulation }
1064
+ };
1065
+ })
1020
1066
  ),
1021
1067
  truncated: field(f, path, "truncated", boolean)
1022
1068
  };
@@ -1147,8 +1193,10 @@ var readSessionSummary = (value, path) => {
1147
1193
  const u = new Unreadable(path);
1148
1194
  const time = field(f, path, "time", soft(nullable(object), null, u));
1149
1195
  const timePath = `${path}.time`;
1196
+ const stopAt = field(f, path, "stop_at_ms", soft(nullable(integer), void 0, u));
1150
1197
  const summary = {
1151
1198
  id: field(f, path, "id", integer),
1199
+ ...f["snapshot_rev"] === void 0 ? {} : { snapshot_rev: field(f, path, "snapshot_rev", soft(nullable(integer), null, u)) },
1152
1200
  state: field(f, path, "state", string),
1153
1201
  launcher: field(f, path, "launcher", readSummaryLauncher),
1154
1202
  stop: field(f, path, "stop", string),
@@ -1196,6 +1244,7 @@ var readSessionSummary = (value, path) => {
1196
1244
  )
1197
1245
  ),
1198
1246
  allowed: field(f, path, "allowed", soft(nullable(readServerAllowed), null, u)),
1247
+ ...stopAt === void 0 ? {} : { stop_at_ms: stopAt },
1199
1248
  check: field(
1200
1249
  f,
1201
1250
  path,
@@ -1231,6 +1280,7 @@ var readSessionSummary = (value, path) => {
1231
1280
  log: field(f, path, "log", soft(partlyRecord(readLogCounts, u), {}, u)),
1232
1281
  problems: field(f, path, "problems", items(readServerProblem, u)),
1233
1282
  problems_omitted: field(f, path, "problems_omitted", soft(integer, 0, u)),
1283
+ ...f["problem_seq"] === void 0 ? {} : { problem_seq: field(f, path, "problem_seq", soft(nullable(integer), null, u)) },
1234
1284
  scenario: field(
1235
1285
  f,
1236
1286
  path,
@@ -1277,6 +1327,11 @@ function partlyRecord(read2, u) {
1277
1327
  };
1278
1328
  }
1279
1329
  var readSessionResponse = (value) => field(object(value, "response"), "response", "session", nullable(readSessionSummary));
1330
+ var readSessionInstance = (value) => field(object(value, "response"), "response", "instance", (instance, path) => {
1331
+ if (typeof instance !== "string" || !instance)
1332
+ throw new ProtocolError(path, "a server instance ID. Use the GUI server from this release");
1333
+ return instance;
1334
+ });
1280
1335
  var readSessionAllowed = (value) => field(
1281
1336
  object(value, "response"),
1282
1337
  "response",
@@ -1351,6 +1406,7 @@ var readVariablesSummary = (value) => readVariables(value, "variables");
1351
1406
  var readVariables = (value, path) => {
1352
1407
  const f = object(value, path);
1353
1408
  return {
1409
+ ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", optional(nullable(integer), null)) },
1354
1410
  state: field(f, path, "state", string),
1355
1411
  reason: field(f, path, "reason", optional(nullable(string), null)),
1356
1412
  peers: field(
@@ -1561,6 +1617,7 @@ var readServerMessage = (value) => {
1561
1617
  return {
1562
1618
  type,
1563
1619
  session: field(f, path, "session", integer),
1620
+ ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", optional(nullable(integer), null)) },
1564
1621
  peers: field(
1565
1622
  f,
1566
1623
  path,
@@ -1674,10 +1731,20 @@ var RunControl = class {
1674
1731
  this.startTimeoutMs = startTimeoutMs;
1675
1732
  this.startSending = new Writable(false, Object.is, onError);
1676
1733
  this.stopSending = new Writable(null, Object.is, onError);
1734
+ this.pendingRevision = new Writable(0, Object.is, onError);
1677
1735
  this.stopAskedWhileStarting = new Writable(false, Object.is, onError);
1678
1736
  this.failure = new Writable(null, Object.is, onError);
1679
1737
  this.starting = this.startSending.readonly();
1680
1738
  this.stopping = this.stopSending.readonly();
1739
+ this.currentStopping = derived(
1740
+ [this.pendingRevision, this.startSending, feed.session],
1741
+ () => {
1742
+ const key = this.startSending.get() ? this.startOperation : JSON.stringify(feed.currentTarget());
1743
+ return [...this.pendingStops].filter((pending) => pending.key === key).at(-1)?.action ?? null;
1744
+ },
1745
+ Object.is,
1746
+ onError
1747
+ );
1681
1748
  this.stopWhileStarting = this.stopAskedWhileStarting.readonly();
1682
1749
  this.error = derived(
1683
1750
  [this.failure, feed.session],
@@ -1695,66 +1762,180 @@ var RunControl = class {
1695
1762
  feed;
1696
1763
  transport;
1697
1764
  startTimeoutMs;
1765
+ startOperation = null;
1766
+ pendingStops = /* @__PURE__ */ new Set();
1767
+ pendingRevision;
1698
1768
  startSending;
1699
1769
  stopSending;
1700
1770
  stopAskedWhileStarting;
1701
1771
  failure;
1702
1772
  starting;
1703
1773
  stopping;
1774
+ currentStopping;
1704
1775
  stopWhileStarting;
1705
1776
  error;
1706
1777
  /** Starts a run. */
1707
1778
  start(request) {
1708
- this.startSending.set(true);
1779
+ if (this.startSending.get()) return Promise.reject(new Error("a start is already pending"));
1780
+ let resolveStart;
1781
+ let rejectStart;
1782
+ const operation = new Promise(
1783
+ (resolve, reject) => {
1784
+ resolveStart = resolve;
1785
+ rejectStart = reject;
1786
+ }
1787
+ );
1788
+ this.startOperation = operation;
1709
1789
  this.stopAskedWhileStarting.set(false);
1710
- return this.send("api/run", request, this.startTimeoutMs() || void 0, () => {
1711
- this.startSending.set(false);
1712
- const asked = this.stopAskedWhileStarting.get();
1713
- this.stopAskedWhileStarting.set(false);
1714
- const session = this.feed.session.get();
1715
- if (asked && session?.launcher.running && session.stopRequests === 0) {
1716
- this.stop().catch(() => void 0);
1790
+ this.startSending.set(true);
1791
+ let instance = null;
1792
+ this.send(
1793
+ "api/run",
1794
+ request,
1795
+ this.startTimeoutMs() || void 0,
1796
+ () => {
1797
+ this.startSending.set(false);
1798
+ },
1799
+ (seen) => {
1800
+ instance = seen;
1717
1801
  }
1718
- });
1802
+ ).then((summary) => resolveStart({ summary, instance }), rejectStart);
1803
+ return operation.then(({ summary }) => summary);
1719
1804
  }
1720
1805
  /** Stops in order (waits for the participants to end). Asking again never turns it into a stop without waiting. */
1721
1806
  stop() {
1722
- if (this.startSending.get()) this.stopAskedWhileStarting.set(true);
1723
- this.stopSending.set("stop");
1724
- return this.send("api/stop", { force: false }, void 0, () => this.stopSending.set(null));
1807
+ return this.requestStop(false);
1725
1808
  }
1726
1809
  /** Stops without waiting (kills the participants). */
1727
1810
  forceStop() {
1728
- this.stopSending.set("force");
1729
- return this.send("api/stop", { force: true }, void 0, () => this.stopSending.set(null));
1811
+ return this.requestStop(true);
1812
+ }
1813
+ captureStop() {
1814
+ const starting = this.startSending.get() ? this.startOperation : null;
1815
+ const target = starting ? null : this.feed.currentTarget();
1816
+ return {
1817
+ key: starting ?? JSON.stringify(target),
1818
+ send: (force) => this.requestStop(force, starting, target)
1819
+ };
1820
+ }
1821
+ requestStop(force, starting = this.startSending.get() ? this.startOperation : null, target = starting ? null : this.feed.currentTarget()) {
1822
+ const session = this.feed.session.get();
1823
+ const pending = {
1824
+ action: force ? "force" : "stop",
1825
+ starting: !!starting,
1826
+ key: starting ?? JSON.stringify(target)
1827
+ };
1828
+ this.pendingStops.add(pending);
1829
+ this.pendingRevision.update((n) => n + 1);
1830
+ this.stopSending.set(pending.action);
1831
+ const done = () => {
1832
+ this.pendingStops.delete(pending);
1833
+ this.pendingRevision.update((n) => n + 1);
1834
+ const remaining = [...this.pendingStops];
1835
+ this.stopAskedWhileStarting.set(remaining.some((p) => p.starting));
1836
+ this.stopSending.set(remaining.at(-1)?.action ?? null);
1837
+ };
1838
+ if (!starting) {
1839
+ if (!target) {
1840
+ const message = "no session and server instance are known: no stop was sent; reconnect and check the current run";
1841
+ this.failure.set({
1842
+ message,
1843
+ session: session?.id ?? null,
1844
+ running: session?.launcher.running ?? false
1845
+ });
1846
+ done();
1847
+ return Promise.reject(new Error(message));
1848
+ }
1849
+ return this.send("api/stop-session", { force, ...target }, void 0, done);
1850
+ }
1851
+ this.stopAskedWhileStarting.set(true);
1852
+ return starting.then(
1853
+ ({ summary, instance }) => {
1854
+ if (!summary || !instance) {
1855
+ const message = "the start answer did not identify the run; no stop was sent";
1856
+ const session2 = this.feed.session.get();
1857
+ this.failure.set({
1858
+ message,
1859
+ session: session2?.id ?? null,
1860
+ running: session2?.launcher.running ?? false
1861
+ });
1862
+ throw new Error(message);
1863
+ }
1864
+ pending.key = JSON.stringify({ session: summary.id, instance });
1865
+ this.pendingRevision.update((n) => n + 1);
1866
+ return this.send(
1867
+ "api/stop-session",
1868
+ { force, session: summary.id, instance },
1869
+ void 0,
1870
+ () => void 0
1871
+ );
1872
+ },
1873
+ (error) => {
1874
+ const message = `the start was not confirmed; no stop was sent: ${errorMessage(error)}`;
1875
+ const session2 = this.feed.session.get();
1876
+ this.failure.set({
1877
+ message,
1878
+ session: session2?.id ?? null,
1879
+ running: session2?.launcher.running ?? false
1880
+ });
1881
+ throw new Error(message);
1882
+ }
1883
+ ).finally(done);
1730
1884
  }
1731
1885
  /**
1732
1886
  * Sends and applies the summary in the answer. done is called after the answer (failures too), before the Promise
1733
1887
  * settles.
1734
1888
  */
1735
- send(path, body, timeoutMs, done) {
1889
+ send(path, body, timeoutMs, done, onInstance) {
1890
+ const incompatible = this.feed.incompatible.get();
1891
+ if (incompatible) {
1892
+ done();
1893
+ return Promise.reject(new Error(incompatible));
1894
+ }
1736
1895
  this.failure.set(null);
1737
1896
  return new Promise((resolve, reject) => {
1738
1897
  this.transport({ method: "POST", path, body, timeoutMs }, (outcome) => {
1739
1898
  if (!outcome.ok) {
1899
+ const failure = path === "api/stop-session" && outcome.error.status === 404 ? new HttpError(404, outcome.error.statusText, {
1900
+ code: "targeted-stop-unsupported",
1901
+ message: "the GUI server cannot stop a particular session: no stop was sent; use the GUI server of this release"
1902
+ }) : outcome.error;
1740
1903
  const session = this.feed.session.get();
1741
1904
  this.failure.set({
1742
- message: answerMissing(path, outcome.error) ?? errorMessage(outcome.error),
1905
+ message: answerMissing(path, failure) ?? errorMessage(failure),
1743
1906
  session: session?.id ?? null,
1744
1907
  running: session?.launcher.running ?? false
1745
1908
  });
1746
1909
  done();
1747
- reject(outcome.error);
1910
+ reject(failure);
1748
1911
  return;
1749
1912
  }
1750
1913
  let summary = null;
1751
1914
  try {
1915
+ const instance = path === "api/stop-session" ? body.instance : readSessionInstance(outcome.body);
1752
1916
  summary = readSessionResponse(outcome.body);
1753
- this.feed.adopt(summary);
1917
+ if (path === "api/stop-session" && (!summary || summary.id !== body.session)) {
1918
+ throw new Error("the stop answer did not identify the requested session");
1919
+ }
1920
+ onInstance?.(instance);
1921
+ this.feed.adopt(summary, instance);
1754
1922
  } catch (error) {
1755
1923
  this.feed.report(
1756
1924
  error instanceof ProtocolError ? `unreadable answer: ${error.message}` : String(error)
1757
1925
  );
1926
+ const missingInstance = error instanceof ProtocolError && error.path === "response.instance";
1927
+ if (path === "api/stop-session" || missingInstance) {
1928
+ 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";
1929
+ const session = this.feed.session.get();
1930
+ this.failure.set({
1931
+ message,
1932
+ session: session?.id ?? null,
1933
+ running: session?.launcher.running ?? false
1934
+ });
1935
+ done();
1936
+ reject(new Error(message));
1937
+ return;
1938
+ }
1758
1939
  }
1759
1940
  done();
1760
1941
  resolve(summary);
@@ -1827,6 +2008,29 @@ function scenarioView(summary) {
1827
2008
  timelineUrl: summary.timeline_url
1828
2009
  };
1829
2010
  }
2011
+ function fullStepText(incoming, current) {
2012
+ if (incoming === null || current === null) return incoming;
2013
+ const cut = /^(.*)\.\.\. \((\d+) more characters\)$/s.exec(incoming);
2014
+ if (!cut) return incoming;
2015
+ const prefix = cut[1];
2016
+ return current.startsWith(prefix) && Array.from(current).length === Array.from(prefix).length + Number(cut[2]) ? current : incoming;
2017
+ }
2018
+ function mergeScenarioStep(current, incoming) {
2019
+ return {
2020
+ ...incoming,
2021
+ text: fullStepText(incoming.text, current.text) ?? incoming.text,
2022
+ message: fullStepText(incoming.message, current.message)
2023
+ };
2024
+ }
2025
+ var stepPositions = /* @__PURE__ */ new WeakMap();
2026
+ function mergeScenarioSteps(current, incoming, merge = (_old, next) => next) {
2027
+ const steps = new Map(current.map((step) => [step.index, step]));
2028
+ for (const step of incoming) {
2029
+ const old = steps.get(step.index);
2030
+ steps.set(step.index, old ? merge(old, step) : step);
2031
+ }
2032
+ return [...steps.values()].sort((a, b) => a.index - b.index);
2033
+ }
1830
2034
  function withStep(steps, step) {
1831
2035
  const i = steps.findIndex((s) => s.index >= step.index);
1832
2036
  if (i < 0) return [...steps, step];
@@ -1847,6 +2051,7 @@ function runOutcome(session) {
1847
2051
  function sessionFromSummary(summary) {
1848
2052
  const blank = {
1849
2053
  id: summary.id,
2054
+ ...summary.snapshot_rev == null ? {} : { snapshotRev: summary.snapshot_rev },
1850
2055
  lastSeq: -1,
1851
2056
  file: summary.file,
1852
2057
  disable: summary.disable,
@@ -1876,7 +2081,11 @@ function sessionFromSummary(summary) {
1876
2081
  droppedMarks: 0,
1877
2082
  scenario: null
1878
2083
  };
1879
- return applySummary(blank, summary, true);
2084
+ const adopted = applySummary(blank, summary, true);
2085
+ return summary.last_seq == null ? adopted : {
2086
+ ...adopted,
2087
+ pendingFindings: { through: summary.last_seq, keys: summary.findings.map(findingIdentity) }
2088
+ };
1880
2089
  }
1881
2090
  function addDropped(session, dropped) {
1882
2091
  const counts = Object.entries(dropped.log).filter(([, count2]) => count2 > 0);
@@ -1887,7 +2096,11 @@ function addDropped(session, dropped) {
1887
2096
  key: `dropped ${mark} ${source}`,
1888
2097
  source,
1889
2098
  line: "",
1890
- gap: { count: count2, atLeast: dropped.at_least.includes(source) }
2099
+ gap: {
2100
+ count: count2,
2101
+ atLeast: dropped.at_least.includes(source),
2102
+ ...dropped.reason === "not-kept" ? { notKept: true } : {}
2103
+ }
1891
2104
  }));
1892
2105
  const next = { ...appendLogs(session, gaps), droppedMarks: mark };
1893
2106
  const sources = { ...next.logSources };
@@ -1909,23 +2122,50 @@ function launcherOf(summary) {
1909
2122
  };
1910
2123
  }
1911
2124
  function applySummary(session, summary, force = false, controlOnly = false) {
1912
- const newer = force || (summary.last_seq ?? -1) > session.lastSeq;
2125
+ const incomingRev = summary.snapshot_rev ?? null;
2126
+ const currentRev = session.snapshotRev ?? null;
2127
+ const staleControl = currentRev !== null && (incomingRev === null || incomingRev < currentRev);
2128
+ const projectionRev = session.projectionRev ?? null;
2129
+ const staleProjection = projectionRev !== null && (incomingRev === null || incomingRev < projectionRev);
2130
+ if (staleControl && (staleProjection || !force && controlOnly)) return session;
2131
+ const newer = force || (summary.last_seq ?? -1) > Math.max(session.lastSeq, session.observedSeq ?? -1, session.projectionSeq ?? -1);
1913
2132
  const launcher = !force && !session.launcher.running && summary.launcher.running ? session.launcher : launcherOf(summary);
1914
2133
  const notLess = summary.problems.length + summary.problems_omitted >= session.problems.length + session.problemsOmitted;
1915
- const next = {
2134
+ const mergedProblems = [...summary.problems];
2135
+ let omitted = summary.problems_omitted;
2136
+ if (summary.problem_seq != null) {
2137
+ const included = new Set(mergedProblems.map((problem) => problem.problem_seq));
2138
+ for (const problem of session.problems) {
2139
+ if (problem.problem_seq === void 0 || included.has(problem.problem_seq)) continue;
2140
+ if (mergedProblems.length >= MAX_PROBLEMS) break;
2141
+ mergedProblems.push(problem);
2142
+ if (problem.problem_seq <= summary.problem_seq && omitted > 0) omitted--;
2143
+ }
2144
+ }
2145
+ if (mergedProblems.every((problem) => problem.problem_seq !== void 0))
2146
+ mergedProblems.sort((a, b) => a.problem_seq - b.problem_seq);
2147
+ const next = staleControl ? session : {
1916
2148
  ...session,
2149
+ ...incomingRev === null ? {} : { snapshotRev: incomingRev },
2150
+ ...summary.stop_at_ms === void 0 ? {} : { stopAtMs: summary.stop_at_ms },
2151
+ ...summary.problem_seq == null ? {} : { problemSeq: Math.max(session.problemSeq ?? 0, summary.problem_seq) },
1917
2152
  launcher,
1918
2153
  stopRequests: Math.max(session.stopRequests, stopRequestsOf(summary.stop)),
1919
2154
  logSources: withSources(session.logSources, Object.keys(summary.log)),
1920
- ...force || notLess ? { problems: summary.problems, problemsOmitted: summary.problems_omitted } : {}
2155
+ ...summary.scenario?.timeline_url ? {
2156
+ scenario: session.scenario ? { ...session.scenario, timelineUrl: summary.scenario.timeline_url } : scenarioView(summary.scenario)
2157
+ } : {},
2158
+ ...force || notLess ? { problems: mergedProblems, problemsOmitted: omitted } : {}
1921
2159
  };
1922
- if (!newer || !force && controlOnly) {
2160
+ if (!newer || staleProjection || !force && controlOnly) {
1923
2161
  return next;
1924
2162
  }
1925
2163
  const phase = summary.phase ?? next.phase;
1926
2164
  const rank = phaseIndex(phase);
1927
- const check = summary.check ?? next.check ?? summary.result?.check ?? null;
1928
- const result = summary.result ?? next.result;
2165
+ const preserveEvents = force && controlOnly;
2166
+ const behind = (...kinds) => summary.last_seq !== null && kinds.some((kind) => (session.eventSeqs?.[kind] ?? -1) > summary.last_seq);
2167
+ const check = (preserveEvents ? next.check : null) ?? summary.check ?? next.check ?? summary.result?.check ?? null;
2168
+ const result = (preserveEvents ? next.result : null) ?? summary.result ?? next.result;
1929
2169
  const known = new Map(session.participants.map((p) => [p.name, p]));
1930
2170
  const participants = summary.participants.map((p) => ({
1931
2171
  name: p.name,
@@ -1935,34 +2175,66 @@ function applySummary(session, summary, force = false, controlOnly = false) {
1935
2175
  exitCode: p.exit_code,
1936
2176
  signal: p.signal,
1937
2177
  failure: p.reason,
1938
- message: p.message,
2178
+ message: p.message ?? (preserveEvents ? known.get(p.name)?.message ?? null : null),
1939
2179
  // A stop the launcher asked for is kept even in summaries of later states (ended and so on)
1940
2180
  stopRequested: p.stop_requested || p.state === "stop_requested" || !!known.get(p.name)?.stopRequested,
1941
2181
  omittedFields: p.omitted_fields,
1942
2182
  controlLink: p.control_link ?? known.get(p.name)?.controlLink ?? null,
1943
2183
  manual: p.state === "manual" || p.command_line !== null || !!known.get(p.name)?.manual,
1944
- commandLine: p.command_line,
1945
- workingDirectory: p.working_directory,
1946
- environment: p.environment ?? {}
2184
+ commandLine: p.command_line ?? (preserveEvents ? known.get(p.name)?.commandLine ?? null : null),
2185
+ workingDirectory: p.working_directory ?? (preserveEvents ? known.get(p.name)?.workingDirectory ?? null : null),
2186
+ environment: p.environment ?? (preserveEvents ? known.get(p.name)?.environment ?? {} : {})
1947
2187
  }));
2188
+ const scenario = summary.scenario ? {
2189
+ ...scenarioView(summary.scenario),
2190
+ timelineUrl: next.scenario?.timelineUrl ?? summary.scenario.timeline_url
2191
+ } : next.scenario;
2192
+ let mergedScenario = preserveEvents && scenario && next.scenario ? {
2193
+ ...scenario,
2194
+ steps: mergeScenarioSteps(
2195
+ next.scenario.steps,
2196
+ scenario.steps,
2197
+ (old, step) => summary.last_seq !== null && (stepPositions.get(old) ?? -1) > summary.last_seq ? old : mergeScenarioStep(old, step)
2198
+ )
2199
+ } : scenario;
2200
+ if (mergedScenario && result?.scenario) {
2201
+ mergedScenario = {
2202
+ ...mergedScenario,
2203
+ steps: mergeScenarioSteps(mergedScenario.steps, result.scenario.steps)
2204
+ };
2205
+ }
2206
+ if (mergedScenario && scenario && mergedScenario !== scenario) {
2207
+ mergedScenario.stepsOmitted = Math.max(
2208
+ 0,
2209
+ scenario.stepsOmitted - (mergedScenario.steps.length - scenario.steps.length)
2210
+ );
2211
+ }
2212
+ const mergedParticipants = preserveEvents ? [
2213
+ ...participants,
2214
+ ...next.participants.filter(
2215
+ (p) => !participants.some((current) => current.name === p.name)
2216
+ )
2217
+ ] : participants;
1948
2218
  return {
1949
2219
  ...next,
1950
- unreadable: force ? summary.unreadable : union(next.unreadable, summary.unreadable),
1951
- phase,
1952
- phaseRank: rank >= 0 ? rank : next.phaseRank,
2220
+ ...incomingRev === null ? {} : { projectionRev: incomingRev },
2221
+ projectionSeq: Math.max(next.projectionSeq ?? -1, summary.last_seq ?? -1),
2222
+ unreadable: force && !behind("finding", "result", "participant") ? summary.unreadable : union(next.unreadable, summary.unreadable),
2223
+ phase: behind("phase", "result") ? next.phase ?? phase : phase,
2224
+ phaseRank: behind("phase", "result") ? next.phaseRank : rank >= 0 ? rank : next.phaseRank,
1953
2225
  elapsedMs: Math.max(next.elapsedMs, summary.last_t_ms ?? 0),
1954
- simMs: summary.sim_ms ?? next.simMs,
1955
- timeOmittedFields: summary.sim_ms === null ? next.timeOmittedFields : summary.time_omitted_fields,
1956
- time: summary.time ? timeView(summary.time) : next.time,
1957
- lastCommand: summary.last_command ? commandView(summary.last_command, summary.last_command.seq ?? -1) : next.lastCommand,
2226
+ simMs: behind("time") ? next.simMs ?? summary.sim_ms : summary.sim_ms ?? next.simMs,
2227
+ timeOmittedFields: behind("time") || summary.sim_ms === null ? next.timeOmittedFields : summary.time_omitted_fields,
2228
+ time: behind("time") && next.time ? next.time : summary.time ? timeView(summary.time) : next.time,
2229
+ lastCommand: behind("command") && next.lastCommand ? next.lastCommand : summary.last_command ? commandView(summary.last_command, summary.last_command.seq ?? -1) : next.lastCommand,
1958
2230
  launcherState: newerState(next.launcherState, summary.launcher_state ?? null),
1959
- findings: summary.findings,
2231
+ findings: preserveEvents ? mergeFindings(next.findings, summary.findings) : summary.findings,
1960
2232
  result,
1961
2233
  check,
1962
- scenario: summary.scenario ? scenarioView(summary.scenario) : next.scenario,
2234
+ scenario: mergedScenario,
1963
2235
  // Whether a participant is required or left out is in the check result (as is the order, that of the configuration
1964
2236
  // file). If there is a result, how it ended (stopped or not) comes from the result too
1965
- participants: withResult(check ? mergeCheck(participants, check) : participants, result)
2237
+ participants: behind("participant", "result", CONTROL_EVENT) && next.participants.length > 0 ? next.participants : withResult(check ? mergeCheck(mergedParticipants, check) : mergedParticipants, result)
1966
2238
  };
1967
2239
  }
1968
2240
  function newerState(current, incoming) {
@@ -1980,20 +2252,101 @@ function withSources(sources, names) {
1980
2252
  return next;
1981
2253
  }
1982
2254
  function addProblem(session, problem) {
1983
- if (session.problems.length >= MAX_PROBLEMS) {
1984
- return { ...session, problemsOmitted: session.problemsOmitted + 1 };
1985
- }
1986
- return { ...session, problems: [...session.problems, problem] };
2255
+ const seq = problem.problem_seq;
2256
+ if (seq !== void 0 && seq <= (session.problemEventSeq ?? 0)) return session;
2257
+ const updated = seq === void 0 ? session : { ...session, problemEventSeq: seq };
2258
+ if (seq !== void 0 && session.problems.some((item) => item.problem_seq === seq))
2259
+ return updated;
2260
+ if (updated.problems.length >= MAX_PROBLEMS) {
2261
+ const alreadyCounted2 = seq !== void 0 && seq <= (session.problemSeq ?? 0);
2262
+ return alreadyCounted2 ? updated : { ...updated, problemsOmitted: updated.problemsOmitted + 1 };
2263
+ }
2264
+ const alreadyCounted = seq !== void 0 && seq <= (session.problemSeq ?? 0);
2265
+ const problems = [...updated.problems, problem];
2266
+ if (problems.every((item) => item.problem_seq !== void 0))
2267
+ problems.sort((a, b) => a.problem_seq - b.problem_seq);
2268
+ return {
2269
+ ...updated,
2270
+ problems,
2271
+ problemsOmitted: alreadyCounted ? Math.max(0, updated.problemsOmitted - 1) : updated.problemsOmitted
2272
+ };
1987
2273
  }
1988
2274
  function phaseIndex(phase) {
1989
2275
  return phase === null ? -1 : PHASES.indexOf(phase);
1990
2276
  }
2277
+ function findingKey(finding) {
2278
+ return JSON.stringify([
2279
+ finding.severity,
2280
+ finding.code,
2281
+ finding.file,
2282
+ finding.line,
2283
+ finding.participant,
2284
+ finding.network,
2285
+ finding.message,
2286
+ finding.detail
2287
+ ]);
2288
+ }
2289
+ function findingIdentity(finding) {
2290
+ return finding.event_seq === void 0 ? `body:${findingKey(finding)}` : `seq:${finding.event_seq}`;
2291
+ }
2292
+ function mergeFindings(current, incoming) {
2293
+ const a = current.slice(0, MAX_FINDINGS);
2294
+ const b = incoming.slice(0, MAX_FINDINGS);
2295
+ if (a.every((finding) => finding.event_seq !== void 0) && b.every((finding) => finding.event_seq !== void 0)) {
2296
+ const bySeq = /* @__PURE__ */ new Map();
2297
+ for (const finding of [...b, ...a]) bySeq.set(finding.event_seq, finding);
2298
+ return [...bySeq.values()].sort((left, right) => left.event_seq - right.event_seq).slice(0, MAX_FINDINGS);
2299
+ }
2300
+ const ak = a.map(findingKey);
2301
+ const bk = b.map(findingKey);
2302
+ const sizes = Array.from({ length: a.length + 1 }, () => new Uint16Array(b.length + 1));
2303
+ for (let i2 = a.length - 1; i2 >= 0; --i2)
2304
+ for (let j2 = b.length - 1; j2 >= 0; --j2)
2305
+ sizes[i2][j2] = ak[i2] === bk[j2] ? 1 + sizes[i2 + 1][j2 + 1] : Math.max(sizes[i2 + 1][j2], sizes[i2][j2 + 1]);
2306
+ const merged = [];
2307
+ let i = 0, j = 0;
2308
+ while ((i < a.length || j < b.length) && merged.length < MAX_FINDINGS) {
2309
+ if (i < a.length && j < b.length && ak[i] === bk[j]) {
2310
+ merged.push(a[i++]);
2311
+ j++;
2312
+ } else if (j === b.length || i < a.length && sizes[i + 1][j] >= sizes[i][j + 1])
2313
+ merged.push(a[i++]);
2314
+ else merged.push(b[j++]);
2315
+ }
2316
+ return merged;
2317
+ }
1991
2318
  function applyEvents(session, events, countStale = false) {
1992
2319
  let next = session;
1993
2320
  const logs = [];
1994
2321
  let stale = 0;
1995
2322
  for (const event of events) {
1996
2323
  if (event.seq > next.lastSeq) {
2324
+ const tracked = [
2325
+ "time",
2326
+ "phase",
2327
+ "result",
2328
+ "finding",
2329
+ "participant",
2330
+ "command",
2331
+ CONTROL_EVENT
2332
+ ].includes(event.event);
2333
+ if (event.event === "scenario_step") stepPositions.set(event.step, event.seq);
2334
+ next = {
2335
+ ...next,
2336
+ observedSeq: Math.max(next.observedSeq ?? -1, event.seq),
2337
+ ...tracked ? { eventSeqs: { ...next.eventSeqs, [event.event]: event.seq } } : {}
2338
+ };
2339
+ const pending = next.pendingFindings;
2340
+ if (event.event === "finding" && pending && event.seq <= pending.through) {
2341
+ const numbered = pending.keys.indexOf(`seq:${event.seq}`);
2342
+ const index = numbered === -1 ? pending.keys.indexOf(`body:${findingKey(event.finding)}`) : numbered;
2343
+ if (index !== -1) {
2344
+ const keys = [...pending.keys];
2345
+ keys.splice(index, 1);
2346
+ next = { ...next, lastSeq: event.seq, pendingFindings: { ...pending, keys } };
2347
+ continue;
2348
+ }
2349
+ }
1997
2350
  next = applyOne(next, event, logs);
1998
2351
  if (event.unreadable)
1999
2352
  next = { ...next, unreadable: union(next.unreadable, event.unreadable) };
@@ -2013,6 +2366,37 @@ function applyEvents(session, events, countStale = false) {
2013
2366
  }
2014
2367
  return { ...next, logSources: sources };
2015
2368
  }
2369
+ function recoverReplayLogs(session, recovered, notKept) {
2370
+ if (!recovered.length) return session;
2371
+ const sources = Object.fromEntries(
2372
+ Object.entries(session.logSources).map(([name, source]) => [
2373
+ name,
2374
+ { lines: 0, dropped: source.dropped }
2375
+ ])
2376
+ );
2377
+ const restored = /* @__PURE__ */ new Map();
2378
+ for (const line of recovered) {
2379
+ const source = sources[line.source] ??= { lines: 0, dropped: 0 };
2380
+ if (line.gap) source.dropped += line.gap.count;
2381
+ else {
2382
+ const count2 = restored.get(line.source) ?? 0;
2383
+ if (count2 < (notKept.get(line.source) ?? 0)) {
2384
+ source.dropped--;
2385
+ restored.set(line.source, count2 + 1);
2386
+ }
2387
+ }
2388
+ }
2389
+ const logs = session.logs.flatMap((line) => {
2390
+ if (!line.gap?.notKept) return [line];
2391
+ const available = restored.get(line.source) ?? 0;
2392
+ const count2 = Math.max(0, line.gap.count - available);
2393
+ restored.set(line.source, Math.max(0, available - line.gap.count));
2394
+ return count2 > 0 ? [{ ...line, gap: { ...line.gap, count: count2 } }] : [];
2395
+ });
2396
+ logs.push(...recovered);
2397
+ logs.sort((a, b) => a.seq - b.seq);
2398
+ return appendLogs({ ...session, logs: [], logSources: sources }, logs);
2399
+ }
2016
2400
  function appendLogs(session, added) {
2017
2401
  const sources = {};
2018
2402
  for (const [source, counts] of Object.entries(session.logSources))
@@ -2106,7 +2490,10 @@ function applyOne(session, event, logs) {
2106
2490
  }
2107
2491
  return next;
2108
2492
  case "finding":
2109
- return next.findings.length >= MAX_FINDINGS ? next : { ...next, findings: [...next.findings, event.finding] };
2493
+ return next.findings.length >= MAX_FINDINGS ? next : {
2494
+ ...next,
2495
+ 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 }]
2496
+ };
2110
2497
  case "time":
2111
2498
  return { ...next, simMs: event.sim_ms, timeOmittedFields: [], time: timeView(event) };
2112
2499
  case "command":
@@ -2223,6 +2610,9 @@ function blankParticipant(name) {
2223
2610
  // ../client/src/session.ts
2224
2611
  var MAX_NOTICES = 20;
2225
2612
  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)";
2613
+ function sameRunTarget(left, right) {
2614
+ return left !== null && right !== null && left.session === right.session && left.instance === right.instance;
2615
+ }
2226
2616
  var SessionFeed = class {
2227
2617
  constructor(connection, onError = rethrowLater) {
2228
2618
  this.connection = connection;
@@ -2253,6 +2643,12 @@ var SessionFeed = class {
2253
2643
  }
2254
2644
  connection;
2255
2645
  onError;
2646
+ rawListeners = /* @__PURE__ */ new Set();
2647
+ snapshotVersion = () => 0;
2648
+ instanceId = null;
2649
+ adoptionRevision = 0;
2650
+ instanceListener = () => void 0;
2651
+ stopTarget = null;
2256
2652
  current;
2257
2653
  synced;
2258
2654
  allowedValue;
@@ -2263,6 +2659,7 @@ var SessionFeed = class {
2263
2659
  messageListeners = /* @__PURE__ */ new Set();
2264
2660
  noticeId = 0;
2265
2661
  stoppedFlag = false;
2662
+ replayLogs = null;
2266
2663
  session;
2267
2664
  ready;
2268
2665
  allowed;
@@ -2281,8 +2678,7 @@ var SessionFeed = class {
2281
2678
  */
2282
2679
  resumeFields() {
2283
2680
  this.synced.set(false);
2284
- const session = this.current.get();
2285
- return session ? { session: session.id, from_seq: session.lastSeq + 1 } : {};
2681
+ return {};
2286
2682
  }
2287
2683
  onMessages(listener) {
2288
2684
  this.messageListeners.add(listener);
@@ -2296,15 +2692,56 @@ var SessionFeed = class {
2296
2692
  * request for the same run (the rest arrives in notifications). A summary of an earlier run never brings back an old
2297
2693
  * run over a new one.
2298
2694
  */
2299
- adopt(summary) {
2300
- if (!summary) return;
2301
- const session = this.current.get();
2302
- if (session && summary.id < session.id) return;
2303
- const live = this.connection.state.get() === "open";
2304
- this.adoptAllowed(summary.allowed ?? null);
2305
- this.current.set(
2306
- session?.id === summary.id ? applySummary(session, summary, false, live) : sessionFromSummary(summary)
2307
- );
2695
+ onRawMessages(listener) {
2696
+ this.rawListeners.add(listener);
2697
+ return () => this.rawListeners.delete(listener);
2698
+ }
2699
+ onSnapshotVersion(read2) {
2700
+ this.snapshotVersion = read2;
2701
+ }
2702
+ /** Called before a new server's session can be published. */
2703
+ onInstance(listener) {
2704
+ this.instanceListener = listener;
2705
+ }
2706
+ /** Instance associated with the current session, or null if its origin is not known. */
2707
+ currentInstance() {
2708
+ return this.instanceId;
2709
+ }
2710
+ currentTarget() {
2711
+ return this.stopTarget ? { ...this.stopTarget } : null;
2712
+ }
2713
+ adopt(summary, instance, resyncFrom) {
2714
+ const switching = this.instanceId !== null && instance !== this.instanceId;
2715
+ if (switching && (resyncFrom !== this.instanceId || this.connection.state.get() === "open"))
2716
+ return null;
2717
+ const previous = switching ? null : this.current.get();
2718
+ if (summary && previous && summary.id < previous.id) return null;
2719
+ if (!summary && instance === this.instanceId)
2720
+ return {
2721
+ revision: this.adoptionRevision,
2722
+ instance,
2723
+ session: previous?.id ?? null
2724
+ };
2725
+ const revision = ++this.adoptionRevision;
2726
+ const next = !summary ? null : previous?.id === summary.id ? applySummary(previous, summary, false, this.connection.state.get() === "open") : sessionFromSummary(summary);
2727
+ const changedInstance = instance !== this.instanceId;
2728
+ this.instanceId = instance;
2729
+ const adoption = { revision, instance, session: next?.id ?? null };
2730
+ this.stopTarget = next ? { session: next.id, instance } : null;
2731
+ const notifySession = this.current.setDeferred(next);
2732
+ const notifyAllowed = switching ? this.allowedValue.setDeferred(null) : () => void 0;
2733
+ if (changedInstance) this.instanceListener(instance, () => this.isCurrent(revision));
2734
+ notifySession();
2735
+ notifyAllowed();
2736
+ if (!this.sameRun(adoption)) return null;
2737
+ this.adoptAllowed(summary?.allowed ?? null);
2738
+ return this.sameRun(adoption) ? adoption : null;
2739
+ }
2740
+ sameRun(adoption) {
2741
+ return this.instanceId === adoption.instance && (this.current.get()?.id ?? null) === adoption.session;
2742
+ }
2743
+ isCurrent(revision) {
2744
+ return revision === this.adoptionRevision;
2308
2745
  }
2309
2746
  /**
2310
2747
  * Takes what the server accepts (an HTTP answer or a notification): the one with the larger `rev` wins (rev 0 is a
@@ -2323,7 +2760,12 @@ var SessionFeed = class {
2323
2760
  }
2324
2761
  /** Reads and applies a batch from the connection. */
2325
2762
  receive(raw) {
2763
+ const snapshotVersion = this.snapshotVersion();
2764
+ const epoch = this.connection.batchEpoch();
2765
+ let originInstance = this.instanceId;
2766
+ const currentOrigin = () => this.connection.batchEpoch() === epoch && this.instanceId === originInstance;
2326
2767
  const batch = [];
2768
+ const accepted = [];
2327
2769
  let stop = null;
2328
2770
  let incompatible = null;
2329
2771
  for (const value of raw) {
@@ -2334,6 +2776,7 @@ var SessionFeed = class {
2334
2776
  this.notify(
2335
2777
  error instanceof ProtocolError ? `unreadable message: ${error.message}` : String(error)
2336
2778
  );
2779
+ if (!currentOrigin()) return;
2337
2780
  const type = value?.type;
2338
2781
  if (type === "hello" && error instanceof ProtocolError && error.path === "message.vehicle_sil_gui") {
2339
2782
  const version2 = JSON.stringify(value.vehicle_sil_gui);
@@ -2349,26 +2792,73 @@ var SessionFeed = class {
2349
2792
  }
2350
2793
  if (message === null) continue;
2351
2794
  batch.push(message);
2795
+ accepted.push(value);
2352
2796
  if (message.type === "error" && message.code === "unauthorized") {
2353
2797
  stop = "unauthorized";
2354
2798
  break;
2355
2799
  }
2356
2800
  }
2801
+ let filtered = this.filterOlderRuns(batch, accepted);
2802
+ if (filtered.staleHello && stop === null) stop = "lost";
2357
2803
  if (stop === "unauthorized" || stop === "incompatible") {
2358
2804
  this.stoppedFlag = true;
2359
2805
  this.connection.close();
2360
2806
  }
2807
+ if (!currentOrigin()) {
2808
+ if (stop === "unauthorized" || stop === "incompatible") this.stoppedFlag = false;
2809
+ return;
2810
+ }
2361
2811
  if (stop === "lost") this.connection.restart();
2362
- this.apply(batch);
2812
+ if (!currentOrigin()) return;
2813
+ filtered = this.filterOlderRuns(filtered.batch, filtered.raw);
2814
+ this.apply(filtered.batch, filtered.raw, snapshotVersion, currentOrigin, (instance) => {
2815
+ originInstance = instance;
2816
+ });
2817
+ if (!currentOrigin()) return;
2363
2818
  if (stop === "lost" || stop === "incompatible") this.synced.set(false);
2364
2819
  if (stop === "unauthorized") this.rejectedValue.set(true);
2365
2820
  if (incompatible !== null) this.incompatibleValue.set(incompatible);
2366
2821
  }
2367
- apply(batch) {
2822
+ /** Keep messages at or after the run already observed over HTTP, within each server instance. */
2823
+ filterOlderRuns(batch, raw) {
2824
+ let instance = this.instanceId;
2825
+ let floor = this.current.get()?.id ?? null;
2826
+ let staleHello = false;
2827
+ const selected = [];
2828
+ const selectedRaw = [];
2829
+ batch.forEach((message, index) => {
2830
+ if (message.type === "hello") {
2831
+ const id = message.session?.id ?? null;
2832
+ if (instance === message.instance && floor !== null && (id === null || id < floor)) {
2833
+ staleHello = true;
2834
+ return;
2835
+ }
2836
+ if (instance !== message.instance) {
2837
+ instance = message.instance;
2838
+ floor = id;
2839
+ } else if (id !== null) floor = id;
2840
+ } else {
2841
+ const id = message.type === "session" ? message.session.id : "session" in message && typeof message.session === "number" ? message.session : null;
2842
+ if (id !== null && floor !== null && id < floor) return;
2843
+ if (message.type === "session" && (floor === null || message.session.id > floor))
2844
+ floor = message.session.id;
2845
+ }
2846
+ selected.push(message);
2847
+ selectedRaw.push(raw[index]);
2848
+ });
2849
+ return { batch: selected, raw: selectedRaw, staleHello };
2850
+ }
2851
+ apply(batch, raw, snapshotVersion, currentOrigin, commitOrigin) {
2368
2852
  if (batch.length === 0) return;
2853
+ const revision = ++this.adoptionRevision;
2369
2854
  const before = this.current.get();
2855
+ const originalInstance = this.instanceId;
2856
+ let instance = originalInstance;
2370
2857
  let session = before;
2858
+ let replayLogs = this.replayLogs?.instance === instance && this.replayLogs?.session === session?.id ? this.replayLogs : null;
2859
+ const unseenLogs = () => replayLogs?.logs.filter((line) => replayLogs?.unseen.has(line.seq)) ?? [];
2371
2860
  let events = [];
2861
+ const notices = [];
2372
2862
  let applied = false;
2373
2863
  let synced = this.synced.get();
2374
2864
  let allowedNow = this.allowedValue.get();
@@ -2393,16 +2883,46 @@ var SessionFeed = class {
2393
2883
  synced = false;
2394
2884
  replaying = true;
2395
2885
  const { session: summary, replay } = message;
2396
- takeAllowed(message.allowed ?? summary?.allowed ?? null, true);
2397
- const resumed = summary && session?.id === summary.id && replay?.from_seq != null;
2398
- session = !summary ? null : resumed && session ? applySummary(session, summary, true) : sessionFromSummary(summary);
2886
+ const staleSnapshot = !!summary && instance === message.instance && session?.id === summary.id && session.snapshotRev != null && (summary.snapshot_rev == null || summary.snapshot_rev < session.snapshotRev);
2887
+ takeAllowed(message.allowed ?? summary?.allowed ?? null, !staleSnapshot);
2888
+ const sameRun2 = summary && instance === message.instance && session?.id === summary.id;
2889
+ const resumed = sameRun2 && replay?.from_seq != null;
2890
+ instance = message.instance;
2891
+ if (!sameRun2) replayLogs = null;
2892
+ if (!summary) {
2893
+ session = null;
2894
+ } else if (sameRun2 && session) {
2895
+ const kept = applySummary(session, summary, true, true);
2896
+ if (!resumed && instance) {
2897
+ const logs = replayLogs ? recoverReplayLogs(kept, unseenLogs(), replayLogs.notKept).logs : kept.logs;
2898
+ replayLogs = {
2899
+ instance,
2900
+ session: summary.id,
2901
+ logs: logs.filter((line) => !line.gap || line.gap.launcher),
2902
+ unseen: new Set(logs.map((line) => line.seq)),
2903
+ notKept: /* @__PURE__ */ new Map()
2904
+ };
2905
+ }
2906
+ session = resumed ? kept : { ...kept, lastSeq: -1, logs: [], logSources: {}, droppedMarks: 0 };
2907
+ } else {
2908
+ session = sessionFromSummary(summary);
2909
+ }
2399
2910
  break;
2400
2911
  }
2401
2912
  case "dropped": {
2402
- if (session && message.session === session.id) session = addDropped(session, message);
2913
+ if (session && message.session === session.id) {
2914
+ session = addDropped(session, message);
2915
+ if (message.reason === "not-kept" && replayLogs) {
2916
+ for (const [source, count2] of Object.entries(message.log))
2917
+ replayLogs.notKept.set(source, (replayLogs.notKept.get(source) ?? 0) + count2);
2918
+ }
2919
+ }
2403
2920
  break;
2404
2921
  }
2405
2922
  case "synced":
2923
+ if (session && replayLogs && replayLogs.instance === instance && replayLogs.session === session.id)
2924
+ session = recoverReplayLogs(session, unseenLogs(), replayLogs.notKept);
2925
+ replayLogs = null;
2406
2926
  synced = true;
2407
2927
  replaying = false;
2408
2928
  break;
@@ -2410,22 +2930,34 @@ var SessionFeed = class {
2410
2930
  takeAllowed(message.allowed);
2411
2931
  break;
2412
2932
  case "session":
2933
+ if (session?.id !== message.session.id) replayLogs = null;
2413
2934
  takeAllowed(message.session.allowed);
2414
- session = session?.id === message.session.id ? applySummary(session, message.session, true) : sessionFromSummary(message.session);
2935
+ session = session?.id === message.session.id ? applySummary(
2936
+ session,
2937
+ message.session,
2938
+ true,
2939
+ message.session.last_seq !== null && (session.observedSeq ?? session.lastSeq) >= message.session.last_seq
2940
+ ) : sessionFromSummary(message.session);
2415
2941
  break;
2416
2942
  case "event":
2417
- if (session?.id === message.session) events.push(message.event);
2943
+ if (session?.id === message.session) {
2944
+ if (message.event.event === "log" || message.event.event === "log_dropped")
2945
+ replayLogs?.unseen.delete(message.event.seq);
2946
+ events.push(message.event);
2947
+ }
2418
2948
  break;
2419
2949
  case "error":
2420
2950
  if (message.code === "unauthorized") {
2421
2951
  } else if (session && message.session === session.id) {
2422
- const { code, message: text3, skipped } = message;
2423
- session = addProblem(
2424
- session,
2425
- skipped === void 0 ? { code, message: text3 } : { code, message: text3, skipped }
2426
- );
2952
+ const { code, message: text3, skipped, problem_seq } = message;
2953
+ session = addProblem(session, {
2954
+ code,
2955
+ message: text3,
2956
+ ...skipped === void 0 ? {} : { skipped },
2957
+ ...problem_seq === void 0 ? {} : { problem_seq }
2958
+ });
2427
2959
  } else {
2428
- this.notify(message.message);
2960
+ notices.push(message.message);
2429
2961
  }
2430
2962
  break;
2431
2963
  case "resync":
@@ -2436,12 +2968,32 @@ var SessionFeed = class {
2436
2968
  }
2437
2969
  flush();
2438
2970
  const stale = (session?.staleEvents ?? 0) - (before?.id === session?.id ? before?.staleEvents ?? 0 : 0);
2439
- this.allowedValue.set(allowedNow);
2440
- this.current.set(session);
2441
- this.synced.set(synced);
2971
+ if (!currentOrigin() || !this.isCurrent(revision)) return;
2972
+ this.instanceId = instance;
2973
+ commitOrigin(instance);
2974
+ this.replayLogs = replayLogs && replayLogs.session === session?.id && replayLogs.instance === instance ? replayLogs : null;
2975
+ this.stopTarget = session && instance ? { session: session.id, instance } : null;
2976
+ const sessionId = session?.id ?? null;
2977
+ const sameRun = () => currentOrigin() && this.instanceId === instance && (this.current.get()?.id ?? null) === sessionId;
2978
+ const notifySession = this.current.setDeferred(session);
2979
+ const notifyAllowed = this.allowedValue.setDeferred(allowedNow);
2980
+ const notifySynced = this.synced.setDeferred(synced);
2981
+ if (instance && instance !== originalInstance) this.instanceListener(instance, sameRun);
2982
+ notifySession();
2983
+ notifyAllowed();
2984
+ notifySynced();
2985
+ if (!sameRun()) return;
2986
+ for (const notice of notices) {
2987
+ this.notify(notice);
2988
+ if (!sameRun()) return;
2989
+ }
2442
2990
  if (applied) this.receivedAt.set(Date.now());
2991
+ if (!sameRun()) return;
2443
2992
  if (stale > 0) this.notify(STALE_EVENTS_NOTICE, stale);
2444
- callEach(this.messageListeners, [batch], this.onError);
2993
+ if (!sameRun()) return;
2994
+ callEach(this.rawListeners, [raw, sameRun, snapshotVersion], this.onError, sameRun);
2995
+ if (!sameRun()) return;
2996
+ callEach(this.messageListeners, [batch], this.onError, sameRun);
2445
2997
  }
2446
2998
  notify(message, count2 = 1) {
2447
2999
  this.noticeList.update((list) => {
@@ -2457,15 +3009,20 @@ var SessionFeed = class {
2457
3009
  // ../client/src/time.ts
2458
3010
  var ANSWER_TIMEOUT_MS = 5e3;
2459
3011
  var TimeControl = class {
2460
- constructor(session, transport, answerTimeoutMs = ANSWER_TIMEOUT_MS, onError = rethrowLater) {
3012
+ constructor(session, transport, currentTarget, answerTimeoutMs = ANSWER_TIMEOUT_MS, onError = rethrowLater) {
2461
3013
  this.session = session;
2462
3014
  this.transport = transport;
3015
+ this.currentTarget = currentTarget;
2463
3016
  this.answerTimeoutMs = answerTimeoutMs;
2464
- this.inFlight = new Writable(0, Object.is, onError);
3017
+ this.awaitingHttp = new Writable(null, Object.is, onError);
2465
3018
  this.pending = new Writable(null, Object.is, onError);
2466
- this.failureValue = new Writable(null, Object.is, onError);
3019
+ this.failureValue = new Writable(
3020
+ null,
3021
+ Object.is,
3022
+ onError
3023
+ );
2467
3024
  this.state = derived(
2468
- [session, this.inFlight, this.pending, this.failureValue],
3025
+ [session, this.awaitingHttp, this.pending, this.failureValue],
2469
3026
  () => this.compute(session.get()),
2470
3027
  shallowEqual,
2471
3028
  onError
@@ -2473,8 +3030,9 @@ var TimeControl = class {
2473
3030
  }
2474
3031
  session;
2475
3032
  transport;
3033
+ currentTarget;
2476
3034
  answerTimeoutMs;
2477
- inFlight;
3035
+ awaitingHttp;
2478
3036
  pending;
2479
3037
  failureValue;
2480
3038
  answerTimer;
@@ -2505,46 +3063,58 @@ var TimeControl = class {
2505
3063
  */
2506
3064
  send(command) {
2507
3065
  const session = this.session.get();
2508
- if (!session) return { sent: false, reason: "no-session" };
3066
+ const target = this.currentTarget();
3067
+ if (!session || target?.session !== session.id) return { sent: false, reason: "no-session" };
2509
3068
  if (this.state.get().sending !== null) return { sent: false, reason: "waiting" };
2510
3069
  this.failureValue.set(null);
2511
3070
  const pending = {
2512
3071
  command: command.command,
2513
- session: session.id,
3072
+ target,
2514
3073
  afterSeq: session.lastCommand?.seq ?? -1
2515
3074
  };
3075
+ this.awaitingHttp.set(pending);
2516
3076
  this.pending.set(pending);
2517
- this.inFlight.update((n) => n + 1);
2518
3077
  clearTimeout(this.answerTimer);
2519
3078
  this.answerTimer = setTimeout(() => this.giveUp(pending), this.answerTimeoutMs);
2520
- this.transport({ method: "POST", path: "api/time", body: command }, (outcome) => {
2521
- this.inFlight.update((n) => n - 1);
2522
- if (outcome.ok || this.pending.get() !== pending) return;
2523
- clearTimeout(this.answerTimer);
2524
- this.pending.set(null);
2525
- this.failureValue.set({
2526
- kind: "server",
2527
- message: errorMessage(outcome.error),
2528
- command: pending.command,
2529
- session: this.session.get()?.id ?? null
2530
- });
2531
- });
3079
+ this.transport(
3080
+ { method: "POST", path: "api/time", body: { ...command, ...target } },
3081
+ (outcome) => {
3082
+ if (this.awaitingHttp.get() === pending) this.awaitingHttp.set(null);
3083
+ if (outcome.ok || this.pending.get() !== pending) return;
3084
+ clearTimeout(this.answerTimer);
3085
+ this.pending.set(null);
3086
+ if (!sameRunTarget(this.currentTarget(), target)) return;
3087
+ this.failureValue.set({
3088
+ target,
3089
+ report: {
3090
+ kind: "server",
3091
+ message: errorMessage(outcome.error),
3092
+ command: pending.command,
3093
+ session: target.session
3094
+ }
3095
+ });
3096
+ }
3097
+ );
2532
3098
  return { sent: true };
2533
3099
  }
2534
3100
  /** Stops the wait timer and stops waiting for the answer (when the client closes). */
2535
3101
  dispose() {
2536
3102
  clearTimeout(this.answerTimer);
2537
3103
  this.pending.set(null);
3104
+ this.awaitingHttp.set(null);
2538
3105
  }
2539
3106
  /** The answer timed out: if no answer has come yet, stop waiting and say so. */
2540
3107
  giveUp(pending) {
2541
3108
  if (this.pending.get() !== pending || this.state.get().sending === null) return;
2542
3109
  this.pending.set(null);
2543
3110
  this.failureValue.set({
2544
- kind: "no-answer",
2545
- 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.`,
2546
- command: pending.command,
2547
- session: pending.session
3111
+ target: pending.target,
3112
+ report: {
3113
+ kind: "no-answer",
3114
+ 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.`,
3115
+ command: pending.command,
3116
+ session: pending.target.session
3117
+ }
2548
3118
  });
2549
3119
  }
2550
3120
  compute(session) {
@@ -2561,10 +3131,11 @@ var TimeControl = class {
2561
3131
  this.lastLateness = lateness;
2562
3132
  const lastCommand = session?.lastCommand ?? null;
2563
3133
  const pending = this.pending.get();
3134
+ const target = this.currentTarget();
2564
3135
  let sending = null;
2565
- if (pending) {
2566
- const answered = !session || session.id !== pending.session || !session.launcher.running || (session.lastCommand?.seq ?? -1) > pending.afterSeq;
2567
- sending = this.inFlight.get() > 0 || !answered ? pending.command : null;
3136
+ if (pending && sameRunTarget(pending.target, target)) {
3137
+ const answered = !session || !session.launcher.running || (session.lastCommand?.seq ?? -1) > pending.afterSeq;
3138
+ sending = this.awaitingHttp.get() === pending || !answered ? pending.command : null;
2568
3139
  }
2569
3140
  const failure = this.failureValue.get();
2570
3141
  return {
@@ -2574,7 +3145,7 @@ var TimeControl = class {
2574
3145
  behind: (lateness?.lateSteps ?? 0) > 0,
2575
3146
  lastCommand,
2576
3147
  sending,
2577
- failure: failure && failure.session === (session?.id ?? null) ? failure : null
3148
+ failure: failure && sameRunTarget(failure.target, target) ? failure.report : null
2578
3149
  };
2579
3150
  }
2580
3151
  };
@@ -2844,12 +3415,18 @@ var VariablesFeed = class {
2844
3415
  this.state = this.stateValue.readonly();
2845
3416
  this.operations = this.operationsValue.readonly();
2846
3417
  this.watchProblem = this.problemValue.readonly();
2847
- link.onBatch((batch) => this.receive(batch));
3418
+ link.onBatch(
3419
+ (batch, current, snapshotCurrent) => this.receive(batch, current, snapshotCurrent)
3420
+ );
2848
3421
  }
2849
3422
  link;
2850
3423
  http;
2851
3424
  onError;
2852
3425
  limits;
3426
+ instanceId = null;
3427
+ snapshotVersionValue = 0;
3428
+ snapshotIdentity = null;
3429
+ serverRevision = null;
2853
3430
  stateValue;
2854
3431
  operationsValue;
2855
3432
  handles = /* @__PURE__ */ new Set();
@@ -2898,26 +3475,43 @@ var VariablesFeed = class {
2898
3475
  }
2899
3476
  }
2900
3477
  // --- Notifications --------------------------------------------------------------------------
2901
- receive(batch) {
3478
+ receive(batch, current = () => true, initialSnapshotVersion = this.snapshotVersionValue) {
3479
+ let snapshotVersion = initialSnapshotVersion;
3480
+ const snapshotCurrent = (session, rev) => this.isSnapshotCurrent(snapshotVersion, this.instanceId, session, rev);
2902
3481
  const touched = /* @__PURE__ */ new Set();
2903
3482
  let touchedAll = false;
2904
3483
  let operations = null;
2905
3484
  let fresh = [];
2906
3485
  const flush = () => {
2907
- if (operations) this.setOperations(operations, fresh);
3486
+ if (operations) this.setOperations(operations, fresh, current);
2908
3487
  operations = null;
2909
3488
  fresh = [];
2910
3489
  };
2911
3490
  for (const message of batch) {
3491
+ if (!current()) return;
2912
3492
  if (!isObject(message)) continue;
3493
+ const messageSession = message["session"];
3494
+ const existingSession = this.stateValue.get().session;
3495
+ if (typeof messageSession === "number" && existingSession !== null && messageSession < existingSession)
3496
+ continue;
2913
3497
  switch (message["type"]) {
2914
3498
  case "hello": {
2915
3499
  flush();
3500
+ if (!current()) return;
2916
3501
  const summary = message["session"];
3502
+ this.adoptInstance(message["instance"]);
3503
+ if (!current()) return;
2917
3504
  if (isObject(summary) && Number.isSafeInteger(summary["id"])) {
2918
- this.adoptSummary(summary);
3505
+ const id = summary["id"];
3506
+ const details = summary["variables"];
3507
+ const rev = isObject(details) ? positionOrNull(details["rev"]) : null;
3508
+ const applied = this.adoptSummary(summary, current, () => snapshotCurrent(id, rev));
3509
+ if (applied !== null && this.snapshotVersionValue === applied)
3510
+ snapshotVersion = applied;
2919
3511
  } else {
3512
+ if (this.stateValue.get().session !== null) break;
2920
3513
  this.enter(null);
3514
+ if (!current()) return;
2921
3515
  this.stateValue.set({ ...NO_VARIABLES, status: "off" });
2922
3516
  }
2923
3517
  touchedAll = true;
@@ -2926,10 +3520,16 @@ var VariablesFeed = class {
2926
3520
  case "session": {
2927
3521
  const summary = message["session"];
2928
3522
  const id = isObject(summary) ? summary["id"] : null;
3523
+ const existing = this.stateValue.get().session;
3524
+ if (typeof id === "number" && existing !== null && id < existing) break;
2929
3525
  if (Number.isSafeInteger(id) && id !== this.stateValue.get().session) {
2930
3526
  flush();
3527
+ if (!current()) return;
3528
+ const afterFlush = this.stateValue.get().session;
3529
+ if (afterFlush !== null && id < afterFlush) break;
2931
3530
  this.enter(id);
2932
- this.stateValue.set({ ...NO_VARIABLES, session: id });
3531
+ if (!current()) return;
3532
+ if (this.stateValue.get().session !== id) break;
2933
3533
  touchedAll = true;
2934
3534
  }
2935
3535
  break;
@@ -2937,12 +3537,30 @@ var VariablesFeed = class {
2937
3537
  case "variables": {
2938
3538
  const id = message["session"];
2939
3539
  if (!Number.isSafeInteger(id)) break;
2940
- if (id !== this.stateValue.get().session) {
3540
+ const details = message["variables"];
3541
+ const rev = isObject(details) ? positionOrNull(details["rev"]) : null;
3542
+ const existing = this.stateValue.get().session;
3543
+ if (existing !== null && id < existing) break;
3544
+ if (id !== existing) {
2941
3545
  flush();
2942
- this.enter(id);
2943
- touchedAll = true;
3546
+ if (!current()) return;
3547
+ const afterFlush = this.stateValue.get().session;
3548
+ if (afterFlush !== null && id < afterFlush) break;
3549
+ if (afterFlush !== id) {
3550
+ this.enter(id);
3551
+ if (!current()) return;
3552
+ if (this.stateValue.get().session !== id) break;
3553
+ touchedAll = true;
3554
+ }
3555
+ }
3556
+ if (snapshotCurrent(id, rev)) {
3557
+ const version2 = this.applySnapshot(
3558
+ readVariables2(details, id),
3559
+ id,
3560
+ rev
3561
+ );
3562
+ if (this.snapshotVersionValue === version2) snapshotVersion = version2;
2944
3563
  }
2945
- this.stateValue.set(readVariables2(message["variables"], id));
2946
3564
  break;
2947
3565
  }
2948
3566
  case "values": {
@@ -2961,8 +3579,13 @@ var VariablesFeed = class {
2961
3579
  break;
2962
3580
  }
2963
3581
  case "availability": {
2964
- if (message["session"] !== this.stateValue.get().session) break;
3582
+ const id = this.stateValue.get().session;
3583
+ if (message["session"] !== id || id === null) break;
3584
+ const rev = positionOrNull(message["rev"]);
3585
+ if (!snapshotCurrent(id, rev)) break;
3586
+ const version2 = this.markSnapshot(id, rev);
2965
3587
  if (this.takeAvailability(message["peers"])) touchedAll = true;
3588
+ if (this.snapshotVersionValue === version2) snapshotVersion = version2;
2966
3589
  break;
2967
3590
  }
2968
3591
  case "error": {
@@ -2975,7 +3598,8 @@ var VariablesFeed = class {
2975
3598
  }
2976
3599
  }
2977
3600
  flush();
2978
- if (touchedAll || touched.size > 0) this.publish(touchedAll ? null : touched);
3601
+ if (current() && (touchedAll || touched.size > 0))
3602
+ this.publish(touchedAll ? null : touched, current);
2979
3603
  }
2980
3604
  /** Returns whether any state changed. Only the availability table changes: `peers` keeps its identity. */
2981
3605
  takeAvailability(peers) {
@@ -2996,29 +3620,82 @@ var VariablesFeed = class {
2996
3620
  this.stateValue.set({ ...state, availability: next });
2997
3621
  return true;
2998
3622
  }
2999
- /** Applies the variables part of hello and of an HTTP summary (`session`). */
3000
- adoptSummary(summary) {
3001
- if (!isObject(summary) || !Number.isSafeInteger(summary["id"])) return;
3623
+ snapshotVersion() {
3624
+ return this.snapshotVersionValue;
3625
+ }
3626
+ /** Compare server capture order when available; legacy peers use the local best-effort watermark. */
3627
+ isSnapshotCurrent(version2, instance, session, rev) {
3628
+ if (session === null) return true;
3629
+ const source = this.serverRevision;
3630
+ if (source && source.instance === instance && source.session === session) {
3631
+ return rev !== null && rev >= source.rev;
3632
+ }
3633
+ if (rev !== null) return true;
3634
+ const identity = this.snapshotIdentity;
3635
+ return !identity || identity.instance !== instance || identity.session !== session || this.snapshotVersionValue <= version2;
3636
+ }
3637
+ markSnapshot(session, rev) {
3638
+ const version2 = ++this.snapshotVersionValue;
3639
+ this.snapshotIdentity = { instance: this.instanceId, session };
3640
+ if (rev !== null) this.serverRevision = { instance: this.instanceId, session, rev };
3641
+ return version2;
3642
+ }
3643
+ applySnapshot(state, session, rev) {
3644
+ const version2 = this.markSnapshot(session, rev);
3645
+ this.stateValue.set(state);
3646
+ return version2;
3647
+ }
3648
+ /** A reused numeric session on another server is a different run. */
3649
+ adoptInstance(value) {
3650
+ if (typeof value !== "string" || !value) return;
3651
+ const changed = this.instanceId !== null && this.instanceId !== value;
3652
+ this.instanceId = value;
3653
+ if (changed) this.enter(null, true);
3654
+ }
3655
+ /** Applies a summary: an older snapshot can still carry a terminal write result. */
3656
+ adoptSummary(summary, current = () => true, snapshotCurrent = current) {
3657
+ if (!isObject(summary) || !Number.isSafeInteger(summary["id"]) || !current()) return null;
3002
3658
  const id = summary["id"];
3659
+ const instance = this.instanceId;
3660
+ const existing = this.stateValue.get().session;
3661
+ if (existing !== null && id < existing) return null;
3003
3662
  const variables = summary["variables"];
3004
- if (id !== this.stateValue.get().session) {
3005
- this.enter(id);
3006
- this.publish(null);
3007
- } else if (variables === void 0) {
3008
- return;
3663
+ let applyState = snapshotCurrent();
3664
+ if (id !== existing) {
3665
+ const initial = this.enter(id);
3666
+ if (!current()) return null;
3667
+ if (this.stateValue.get() !== initial) applyState = applyState && snapshotCurrent();
3009
3668
  }
3010
- this.stateValue.set(readVariables2(variables, id));
3669
+ const sameIdentity = () => current() && this.instanceId === instance && this.stateValue.get().session === id;
3670
+ if (!sameIdentity() || variables === void 0) return null;
3671
+ applyState = applyState && snapshotCurrent();
3672
+ let notifyOperations = () => void 0;
3673
+ const listed = [];
3011
3674
  if (isObject(variables) && Array.isArray(variables["operations"])) {
3012
3675
  let operations = this.operationsValue.get();
3013
- const listed = [];
3014
3676
  for (const entry of variables["operations"]) {
3015
3677
  const operation = readOperation(entry, id);
3016
- if (operation) {
3678
+ if (operation && (applyState || operation.done)) {
3017
3679
  listed.push(operation);
3018
3680
  operations = this.withOperation(operations, operation);
3019
3681
  }
3020
3682
  }
3021
- this.setOperations(operations, listed);
3683
+ notifyOperations = this.prepareOperations(operations, listed, sameIdentity);
3684
+ }
3685
+ let next = null;
3686
+ let appliedVersion = null;
3687
+ if (applyState && snapshotCurrent() && sameIdentity()) {
3688
+ next = readVariables2(variables, id);
3689
+ appliedVersion = this.applySnapshot(
3690
+ next,
3691
+ id,
3692
+ isObject(variables) ? positionOrNull(variables["rev"]) : null
3693
+ );
3694
+ }
3695
+ notifyOperations();
3696
+ if (!sameIdentity() || appliedVersion === null || this.snapshotVersionValue !== appliedVersion || !next || this.stateValue.get() !== next)
3697
+ return appliedVersion;
3698
+ if (isObject(variables) && Array.isArray(variables["operations"])) {
3022
3699
  const fromSeq = variables["operations_from_seq"];
3023
3700
  const openOmitted = variables["operations_open_omitted"];
3024
3701
  this.forgetLost(id, {
@@ -3027,6 +3704,7 @@ var VariablesFeed = class {
3027
3704
  openOmitted: typeof openOmitted === "number" && openOmitted > 0
3028
3705
  });
3029
3706
  }
3707
+ return appliedVersion;
3030
3708
  }
3031
3709
  /**
3032
3710
  * With the summary after a reconnect (or from api/session), settles as "no answer came" (lost) the writes waiting for
@@ -3049,12 +3727,15 @@ var VariablesFeed = class {
3049
3727
  * are dropped with their memory, so they do not keep growing as the variables change from run to run). Writes
3050
3728
  * waiting for the previous run's result are failed, since the result will not come.
3051
3729
  */
3052
- enter(session) {
3053
- if (session === this.stateValue.get().session) return;
3730
+ enter(session, force = false) {
3731
+ if (!force && session === this.stateValue.get().session) return this.stateValue.get();
3054
3732
  this.readings.clear();
3055
3733
  this.histories.clear();
3056
3734
  this.historyReserved = 0;
3057
- this.operationsValue.set([]);
3735
+ const initial = { ...NO_VARIABLES, session };
3736
+ const notifyOperations = this.operationsValue.setDeferred([]);
3737
+ const notifyState = this.stateValue.setDeferred(initial);
3738
+ const notifyWatches = [...this.handles].map((handle) => handle.values.setDeferred({}));
3058
3739
  for (const pending of [...this.pending]) {
3059
3740
  if (pending.session !== session) {
3060
3741
  this.settle(
@@ -3066,6 +3747,10 @@ var VariablesFeed = class {
3066
3747
  );
3067
3748
  }
3068
3749
  }
3750
+ notifyOperations();
3751
+ notifyState();
3752
+ for (const notify of notifyWatches) notify();
3753
+ return initial;
3069
3754
  }
3070
3755
  takeValues(message, touched) {
3071
3756
  const peers = message["peers"];
@@ -3107,8 +3792,9 @@ var VariablesFeed = class {
3107
3792
  }
3108
3793
  }
3109
3794
  /** Rebuilds values of the watches that observe the changed variables (all watches if touched is null). */
3110
- publish(touched) {
3795
+ publish(touched, current = () => true) {
3111
3796
  for (const handle of this.handles) {
3797
+ if (!current()) return;
3112
3798
  if (touched !== null && handle.keys !== null) {
3113
3799
  let hit = false;
3114
3800
  for (const key of handle.keys) {
@@ -3141,7 +3827,7 @@ var VariablesFeed = class {
3141
3827
  // --- Operations -----------------------------------------------------------------------------
3142
3828
  withOperation(operations, operation) {
3143
3829
  const at = operations.findIndex((o) => o.seq === operation.seq);
3144
- if (at >= 0 && operations[at]?.done && !operation.done) return [...operations];
3830
+ if (at >= 0 && operations[at]?.done) return [...operations];
3145
3831
  const next = at >= 0 ? operations.map((o, i) => i === at ? operation : o) : [...operations, operation];
3146
3832
  return next.length > OPERATIONS_KEPT ? next.slice(next.length - OPERATIONS_KEPT) : next;
3147
3833
  }
@@ -3150,14 +3836,19 @@ var VariablesFeed = class {
3150
3836
  * just arrived (a batch of notifications, the list in a summary): the list is cut to OPERATIONS_KEPT entries, so
3151
3837
  * settled operations cut from the list are picked up from here.
3152
3838
  */
3153
- setOperations(operations, fresh = []) {
3154
- this.operationsValue.set(operations);
3839
+ setOperations(operations, fresh = [], current = () => true) {
3840
+ this.prepareOperations(operations, fresh, current)();
3841
+ }
3842
+ prepareOperations(operations, fresh, current) {
3843
+ if (!current()) return () => void 0;
3844
+ const notify = this.operationsValue.setDeferred(operations);
3155
3845
  for (const pending of [...this.pending]) {
3156
3846
  if (pending.seq === null) continue;
3157
3847
  const mine = (o) => o.done && o.seq === pending.seq && o.session === pending.session;
3158
3848
  const operation = fresh.find(mine) ?? operations.find(mine);
3159
3849
  if (operation) this.settle(pending, operation);
3160
3850
  }
3851
+ return notify;
3161
3852
  }
3162
3853
  settle(pending, outcome) {
3163
3854
  if (!this.pending.delete(pending)) return;
@@ -3580,6 +4271,7 @@ var VariableBinder = class {
3580
4271
  return entry;
3581
4272
  }
3582
4273
  send(entry, value) {
4274
+ const epoch = this.sources.connectionEpoch();
3583
4275
  const mine = { value };
3584
4276
  const { peer, name } = entry.ref;
3585
4277
  entry.sending = mine;
@@ -3587,7 +4279,6 @@ var VariableBinder = class {
3587
4279
  entry.shown = mine;
3588
4280
  entry.status = { kind: "sending" };
3589
4281
  entry.pending = value;
3590
- this.changed(entry);
3591
4282
  const accepted = (seq) => {
3592
4283
  if (entry.sending !== mine) return;
3593
4284
  entry.sending = null;
@@ -3622,6 +4313,11 @@ var VariableBinder = class {
3622
4313
  if (entry.shown === mine) entry.status = status;
3623
4314
  this.changed(entry);
3624
4315
  };
4316
+ this.changed(entry);
4317
+ if (this.sources.connectionEpoch() !== epoch || this.sources.session.get()?.id !== entry.session || this.sources.variables.state.get().session !== entry.session || this.block(entry.ref) !== null) {
4318
+ settled({ kind: "dropped", message: DROPPED_MESSAGE });
4319
+ return;
4320
+ }
3625
4321
  this.sources.variables.write(
3626
4322
  { [peer]: { [name]: value } },
3627
4323
  {
@@ -3782,6 +4478,10 @@ function defaultOrigin(baseUrl, runtime = globalThis) {
3782
4478
  function createClient(options) {
3783
4479
  return buildClient(options).client;
3784
4480
  }
4481
+ var clientErrorSinks = /* @__PURE__ */ new WeakMap();
4482
+ function clientErrorSink(client) {
4483
+ return clientErrorSinks.get(client);
4484
+ }
3785
4485
  function buildClient(options) {
3786
4486
  const token = typeof options.token === "function" ? options.token : () => options.token;
3787
4487
  const onError = options.onError ?? reportToConsole;
@@ -3808,18 +4508,30 @@ function buildClient(options) {
3808
4508
  });
3809
4509
  feed = new SessionFeed(connection, onError);
3810
4510
  const session = feed;
3811
- variablesFeed = new VariablesFeed(connection, http, onError, () => limits.get());
4511
+ variablesFeed = new VariablesFeed(
4512
+ {
4513
+ send: (message) => connection.send(message),
4514
+ onBatch: (listener) => session.onRawMessages(listener)
4515
+ },
4516
+ http,
4517
+ onError,
4518
+ () => limits.get()
4519
+ );
3812
4520
  const variables = variablesFeed;
4521
+ session.onSnapshotVersion(() => variables.snapshotVersion());
4522
+ session.onInstance((instance) => variables.adoptInstance(instance));
3813
4523
  const run = new RunControl(session, http, onError, () => longRequestMs(limits.get()));
3814
4524
  const time = new TimeControl(
3815
4525
  session.session,
3816
4526
  http,
4527
+ () => session.currentTarget(),
3817
4528
  options.answerTimeoutMs ?? ANSWER_TIMEOUT_MS,
3818
4529
  onError
3819
4530
  );
3820
4531
  const binder = new VariableBinder({
3821
4532
  variables,
3822
4533
  connection: connection.state,
4534
+ connectionEpoch: () => connection.batchEpoch(),
3823
4535
  session: session.session,
3824
4536
  onError
3825
4537
  });
@@ -3849,6 +4561,8 @@ function buildClient(options) {
3849
4561
  },
3850
4562
  session: {
3851
4563
  session: session.session,
4564
+ currentTarget: () => session.currentTarget(),
4565
+ currentInstance: () => session.currentInstance(),
3852
4566
  ready: session.ready,
3853
4567
  allowed: session.allowed,
3854
4568
  lastEventAt: session.lastEventAt,
@@ -3862,6 +4576,7 @@ function buildClient(options) {
3862
4576
  run: {
3863
4577
  starting: run.starting,
3864
4578
  stopping: run.stopping,
4579
+ currentStopping: run.currentStopping,
3865
4580
  stopWhileStarting: run.stopWhileStarting,
3866
4581
  error: run.error,
3867
4582
  start: (request) => run.start(request),
@@ -3938,25 +4653,48 @@ function buildClient(options) {
3938
4653
  },
3939
4654
  readConnections
3940
4655
  ),
3941
- fetchSession: () => new Promise(
3942
- (resolve, reject) => http({ method: "GET", path: "api/session" }, (outcome) => {
3943
- if (!outcome.ok) {
3944
- reject(outcome.error);
3945
- return;
3946
- }
3947
- try {
3948
- const summary = readSessionResponse(outcome.body);
3949
- session.adopt(summary);
3950
- session.adoptAllowed(readSessionAllowed(outcome.body));
3951
- variables.adoptSummary(outcome.body?.session);
3952
- resolve(summary);
3953
- } catch (error) {
3954
- reject(error);
3955
- }
3956
- })
3957
- )
4656
+ fetchSession: () => {
4657
+ const resyncFrom = session.currentInstance();
4658
+ const snapshotVersion = variables.snapshotVersion();
4659
+ return new Promise(
4660
+ (resolve, reject) => http({ method: "GET", path: "api/session" }, (outcome) => {
4661
+ if (!outcome.ok) {
4662
+ reject(outcome.error);
4663
+ return;
4664
+ }
4665
+ try {
4666
+ const summary = readSessionResponse(outcome.body);
4667
+ const instance = readSessionInstance(outcome.body);
4668
+ const adoption = session.adopt(summary, instance, resyncFrom);
4669
+ if (adoption !== null) {
4670
+ const rawSession = outcome.body?.session;
4671
+ const rev = rawSession?.variables?.rev;
4672
+ const current = () => variables.isSnapshotCurrent(
4673
+ snapshotVersion,
4674
+ adoption.instance,
4675
+ adoption.session,
4676
+ Number.isSafeInteger(rev) && rev >= 0 ? rev : null
4677
+ );
4678
+ if (session.sameRun(adoption)) session.adoptAllowed(readSessionAllowed(outcome.body));
4679
+ const sameRun = () => session.sameRun(adoption);
4680
+ if (sameRun()) variables.adoptInstance(instance);
4681
+ if (sameRun())
4682
+ variables.adoptSummary(
4683
+ outcome.body?.session,
4684
+ sameRun,
4685
+ current
4686
+ );
4687
+ }
4688
+ resolve(summary);
4689
+ } catch (error) {
4690
+ reject(error);
4691
+ }
4692
+ })
4693
+ );
4694
+ }
3958
4695
  };
3959
- return { client, http, onError };
4696
+ clientErrorSinks.set(client, onError);
4697
+ return { client, http, onError, runControl: run };
3960
4698
  }
3961
4699
 
3962
4700
  // ../client/src/token.ts
@@ -4044,7 +4782,7 @@ function runOf(s) {
4044
4782
  case "starting":
4045
4783
  return "starting";
4046
4784
  case "waiting":
4047
- return "waiting";
4785
+ return state?.holding === true ? "paused" : "waiting";
4048
4786
  case "stopping":
4049
4787
  return "stopping";
4050
4788
  case "ended":
@@ -4183,7 +4921,9 @@ function composeControls(s, run) {
4183
4921
  const serverStop = s.allowed?.stop;
4184
4922
  const stoppable = s.busy.has("start") || live || run === "starting" || serverStop?.ok === true;
4185
4923
  let stop;
4186
- if (s.busy.has("stop")) stop = control(false, busyReason("stop"));
4924
+ if (!s.busy.has("start") && s.allowed?.start.reason === "starting")
4925
+ stop = control(false, reason("starting", "wait until the new run can be identified"));
4926
+ else if (s.busy.has("stop")) stop = control(false, busyReason("stop"));
4187
4927
  else if (s.busy.has("start")) stop = control(true);
4188
4928
  else if (serverStop && !serverStop.ok && serverStop.reason !== "not-running")
4189
4929
  stop = fromServer(serverStop, "the server does not stop the run now");
@@ -4197,7 +4937,9 @@ function composeControls(s, run) {
4197
4937
  else stop = control(true);
4198
4938
  const serverForce = s.allowed?.force;
4199
4939
  let force;
4200
- if (s.busy.has("force_stop")) force = control(false, busyReason("force stop"));
4940
+ if (s.busy.has("start") || s.allowed?.start.reason === "starting")
4941
+ force = control(false, reason("starting", "wait until the new run can be identified"));
4942
+ else if (s.busy.has("force_stop")) force = control(false, busyReason("force stop"));
4201
4943
  else if (serverForce && !serverForce.ok && serverForce.reason !== "not-running")
4202
4944
  force = fromServer(serverForce, "the server does not force a stop now");
4203
4945
  else if (!stoppable)
@@ -4308,6 +5050,8 @@ var INTENT_FIELDS = /* @__PURE__ */ new Set([
4308
5050
  "params",
4309
5051
  "speed",
4310
5052
  "start_paused",
5053
+ "stop_at_ms",
5054
+ "late_tolerance_ms",
4311
5055
  "strict",
4312
5056
  "connect",
4313
5057
  "time_policy"
@@ -4354,7 +5098,8 @@ var FrontActions = class {
4354
5098
  if (request instanceof ActionError) return this.fail(request);
4355
5099
  const own = this.refusalOfStart();
4356
5100
  if (own) return this.fail(own);
4357
- return this.guarded("start", () => this.src.low.run.start(request).then(() => void 0));
5101
+ const start = this.src.low.run.start(request);
5102
+ return this.guarded("start", () => start.then(() => void 0));
4358
5103
  }
4359
5104
  /**
4360
5105
  * Checks what `intent` would start (`api/check`). Its failure is the caller's: it is not kept for `status.problem`.
@@ -4454,6 +5199,8 @@ var FrontActions = class {
4454
5199
  ...intent.params ? { params: intent.params } : {},
4455
5200
  ...intent.speed !== void 0 ? { speed: intent.speed } : {},
4456
5201
  ...intent.start_paused ? { start_paused: true } : {},
5202
+ ...intent.stop_at_ms !== void 0 ? { stop_at_ms: intent.stop_at_ms } : {},
5203
+ ...intent.late_tolerance_ms !== void 0 ? { late_tolerance_ms: intent.late_tolerance_ms } : {},
4457
5204
  ...intent.strict ? { strict: true } : {},
4458
5205
  ...intent.connect ? { connect: intent.connect } : {},
4459
5206
  ...intent.time_policy !== void 0 ? { time_policy: intent.time_policy } : {}
@@ -4493,19 +5240,66 @@ var FrontActions = class {
4493
5240
  ) : null;
4494
5241
  }
4495
5242
  stop() {
4496
- return this.once("stop", () => this.src.low.run.stop());
5243
+ return this.once("stop", false);
4497
5244
  }
4498
- forceStop() {
4499
- return this.once("force_stop", () => this.src.low.run.forceStop());
5245
+ forceStop(target) {
5246
+ const current = this.src.low.session.currentTarget();
5247
+ if (target && (current?.session !== target.session || current.instance !== target.instance))
5248
+ return this.fail(
5249
+ new ActionError("session-changed", "the confirmed run has changed", "refused")
5250
+ );
5251
+ if (this.src.low.run.starting.get())
5252
+ return this.fail(
5253
+ new ActionError("starting", "wait until the new run can be identified", "refused")
5254
+ );
5255
+ return this.once("force_stop", true);
5256
+ }
5257
+ /** Pending stop only affects controls of the run it was sent for. */
5258
+ busyForCurrent() {
5259
+ const busy = new Set(this.busyValue.get());
5260
+ const key = this.stopKey();
5261
+ for (const name of ["stop", "force_stop"]) {
5262
+ if (this.inFlight.get(name)?.key !== key) busy.delete(name);
5263
+ }
5264
+ return busy;
5265
+ }
5266
+ stopKey() {
5267
+ return this.src.captureStop().key;
4500
5268
  }
4501
- /** A stop asked again while its request is on its way is the same request (a double click sends nothing more). */
4502
- once(name, send) {
5269
+ /** Repeated requests for the same run share one operation. */
5270
+ once(name, force) {
5271
+ const capture = this.src.captureStop();
5272
+ const key = capture.key;
4503
5273
  const running = this.inFlight.get(name);
4504
- if (running) return running;
4505
- const promise = this.guarded(name, () => send().then(() => void 0)).finally(() => {
4506
- this.inFlight.delete(name);
5274
+ if (running?.key === key) return running.promise;
5275
+ let resolve;
5276
+ let reject;
5277
+ const promise = new Promise((ok, fail) => {
5278
+ resolve = ok;
5279
+ reject = fail;
4507
5280
  });
4508
- this.inFlight.set(name, promise);
5281
+ const entry = { key, promise };
5282
+ this.inFlight.set(name, entry);
5283
+ this.failureValue.set(null);
5284
+ const operation = capture.send(force);
5285
+ if (this.busyValue.get().has(name)) this.busyValue.set(new Set(this.busyValue.get()));
5286
+ else this.setBusy(name, true);
5287
+ operation.then(
5288
+ () => {
5289
+ if (this.inFlight.get(name) === entry) {
5290
+ this.inFlight.delete(name);
5291
+ this.setBusy(name, false);
5292
+ }
5293
+ resolve();
5294
+ },
5295
+ (error) => {
5296
+ if (this.inFlight.get(name) === entry) {
5297
+ this.inFlight.delete(name);
5298
+ this.setBusy(name, false);
5299
+ }
5300
+ reject(this.record(actionError(error)));
5301
+ }
5302
+ );
4509
5303
  return promise;
4510
5304
  }
4511
5305
  guarded(name, send) {
@@ -4520,13 +5314,13 @@ var FrontActions = class {
4520
5314
  );
4521
5315
  }
4522
5316
  // --- time --------------------------------------------------------------------------------------
4523
- pause() {
4524
- return this.time("pause", { command: "pause" }, 0);
5317
+ pause(target) {
5318
+ return this.time("pause", { command: "pause" }, 0, target);
4525
5319
  }
4526
- resume() {
4527
- return this.time("resume", { command: "resume" }, 0);
5320
+ resume(target) {
5321
+ return this.time("resume", { command: "resume" }, 0, target);
4528
5322
  }
4529
- step(ms) {
5323
+ step(ms, target) {
4530
5324
  if (!Number.isFinite(ms) || ms <= 0) {
4531
5325
  return this.fail(
4532
5326
  new ActionError(
@@ -4536,9 +5330,9 @@ var FrontActions = class {
4536
5330
  )
4537
5331
  );
4538
5332
  }
4539
- return this.time("step", { command: "step", ms }, ms);
5333
+ return this.time("step", { command: "step", ms }, ms, target);
4540
5334
  }
4541
- setSpeed(value) {
5335
+ setSpeed(value, target) {
4542
5336
  if (value !== "max" && !(Number.isFinite(value) && value > 0)) {
4543
5337
  return this.fail(
4544
5338
  new ActionError(
@@ -4548,9 +5342,9 @@ var FrontActions = class {
4548
5342
  )
4549
5343
  );
4550
5344
  }
4551
- return this.time("speed", { command: "speed", value }, 0);
5345
+ return this.time("speed", { command: "speed", value }, 0, target);
4552
5346
  }
4553
- runUntil(ms) {
5347
+ runUntil(ms, target) {
4554
5348
  if (!Number.isFinite(ms) || ms < 0) {
4555
5349
  return this.fail(
4556
5350
  new ActionError(
@@ -4560,26 +5354,32 @@ var FrontActions = class {
4560
5354
  )
4561
5355
  );
4562
5356
  }
4563
- return this.time("run_until", { command: "run_until", at_ms: ms }, ms);
5357
+ return this.time("run_until", { command: "run_until", at_ms: ms }, ms, target);
4564
5358
  }
4565
- time(op, body, amount) {
5359
+ time(op, body, amount, shownTarget) {
5360
+ const target = this.src.low.session.currentTarget();
4566
5361
  this.failureValue.set(null);
4567
5362
  const snapshot = this.src.snapshot();
4568
5363
  const link = linkOf(snapshot);
4569
5364
  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;
4570
5365
  if (own) return this.fail(new ActionError(own.code, own.message, "refused"));
5366
+ if (shownTarget !== void 0 && !sameRunTarget(shownTarget, target))
5367
+ return this.fail(
5368
+ new ActionError("session-changed", "the displayed run has changed", "refused")
5369
+ );
5370
+ if (!target)
5371
+ return this.fail(new ActionError("not-running", "there is no identified run", "refused"));
4571
5372
  const code = this.src.controls()[op === "pause" ? "pause" : "resume"].reason?.code;
4572
5373
  if (op === "pause" && code === "paused" || op === "resume" && code === "not-paused") {
4573
5374
  return Promise.resolve();
4574
5375
  }
4575
- const session = snapshot.session;
4576
5376
  const id = this.nextId++;
4577
5377
  return new Promise((resolve, reject) => {
4578
5378
  const waiting = {
4579
5379
  id,
4580
5380
  op,
4581
5381
  amount,
4582
- session: session?.id ?? -1,
5382
+ ...target,
4583
5383
  stage: "sent",
4584
5384
  target: 0,
4585
5385
  from: 0,
@@ -4600,9 +5400,12 @@ var FrontActions = class {
4600
5400
  )
4601
5401
  );
4602
5402
  }, this.src.answerTimeoutMs);
4603
- this.src.http({ method: "POST", path: "api/time", body: { ...body, id } }, (outcome) => {
4604
- if (!outcome.ok) this.settle(waiting, actionError(outcome.error));
4605
- });
5403
+ this.src.http(
5404
+ { method: "POST", path: "api/time", body: { ...body, id, ...target } },
5405
+ (outcome) => {
5406
+ if (!outcome.ok) this.settle(waiting, actionError(outcome.error));
5407
+ }
5408
+ );
4606
5409
  });
4607
5410
  }
4608
5411
  /** Ends a waiting command: with an error, or (null) as done. A command ended twice is ended once. */
@@ -4694,8 +5497,9 @@ var FrontActions = class {
4694
5497
  evaluate() {
4695
5498
  if (this.waiting.size === 0) return;
4696
5499
  const session = this.src.low.session.session.get();
5500
+ const instance = this.src.low.session.currentInstance();
4697
5501
  for (const w of [...this.waiting.values()]) {
4698
- if (!session || session.id !== w.session || !session.launcher.running || session.result) {
5502
+ if (!session || session.id !== w.session || instance !== w.instance || !session.launcher.running || session.result) {
4699
5503
  this.settle(
4700
5504
  w,
4701
5505
  new ActionError(
@@ -4991,7 +5795,7 @@ function makeVariable(low, ref, refuse, launcher) {
4991
5795
 
4992
5796
  // ../client/src/front.ts
4993
5797
  function makeFront(options, onClose) {
4994
- const { client: low, http, onError } = buildClient(options);
5798
+ const { client: low, http, onError, runControl } = buildClient(options);
4995
5799
  let counter = 0;
4996
5800
  const stamp = () => ++counter;
4997
5801
  const stamps = /* @__PURE__ */ new Map();
@@ -5012,7 +5816,7 @@ function makeFront(options, onClose) {
5012
5816
  session: low.session.session.get(),
5013
5817
  allowed: low.session.allowed.get(),
5014
5818
  limits: low.limits.get(),
5015
- busy: actions.busy.get()
5819
+ busy: actions.busyForCurrent()
5016
5820
  });
5017
5821
  const sources = [
5018
5822
  low.connection.state,
@@ -5034,6 +5838,7 @@ function makeFront(options, onClose) {
5034
5838
  actions = new FrontActions({
5035
5839
  low,
5036
5840
  http,
5841
+ captureStop: () => runControl.captureStop(),
5037
5842
  snapshot,
5038
5843
  controls: () => controls.get(),
5039
5844
  run,
@@ -5160,14 +5965,14 @@ function makeFront(options, onClose) {
5160
5965
  run: {
5161
5966
  start: (intent, startOptions) => actions.start(intent, startOptions),
5162
5967
  stop: () => actions.stop(),
5163
- forceStop: () => actions.forceStop()
5968
+ forceStop: (target) => actions.forceStop(target)
5164
5969
  },
5165
5970
  time: {
5166
- pause: () => actions.pause(),
5167
- resume: () => actions.resume(),
5168
- step: (ms) => actions.step(ms),
5169
- setSpeed: (value) => actions.setSpeed(value),
5170
- runUntil: (ms) => actions.runUntil(ms)
5971
+ pause: (target) => actions.pause(target),
5972
+ resume: (target) => actions.resume(target),
5973
+ step: (ms, target) => actions.step(ms, target),
5974
+ setSpeed: (value, target) => actions.setSpeed(value, target),
5975
+ runUntil: (ms, target) => actions.runUntil(ms, target)
5171
5976
  },
5172
5977
  variable: (ref) => {
5173
5978
  const named = refOf(ref);
@@ -5298,6 +6103,172 @@ function until(source, test, options = {}) {
5298
6103
  if (test(first)) finish(() => resolve(first));
5299
6104
  });
5300
6105
  }
6106
+
6107
+ // ../client/src/waveforms.ts
6108
+ function createWaveforms(client, options = {}) {
6109
+ const settings = { ...options, history: options.history ?? 600 };
6110
+ const series = new Writable([], Object.is, clientErrorSink(client));
6111
+ let historyTarget = client.session.currentTarget();
6112
+ let selection = [];
6113
+ let active = null;
6114
+ let unsubscribe;
6115
+ let closed = false;
6116
+ const setSignals = (refs) => {
6117
+ if (closed) return;
6118
+ const seen = /* @__PURE__ */ new Set();
6119
+ const next = refs.flatMap(({ peer, name }) => {
6120
+ const key = JSON.stringify([peer, name]);
6121
+ if (seen.has(key)) return [];
6122
+ seen.add(key);
6123
+ return [{ peer, name }];
6124
+ });
6125
+ if (next.length === selection.length && next.every((ref, i) => ref.peer === selection[i].peer && ref.name === selection[i].name))
6126
+ return;
6127
+ const previous = active;
6128
+ unsubscribe?.();
6129
+ const feed = next.length ? client.variables.watch(next, settings) : null;
6130
+ selection = next;
6131
+ active = feed;
6132
+ const refresh = () => {
6133
+ if (active !== feed || closed) return;
6134
+ historyTarget = client.session.currentTarget();
6135
+ const current = historyTarget && historyTarget.session === client.variables.state.get().session;
6136
+ series.set(
6137
+ next.map((ref) => ({ ref: { ...ref }, points: current && feed ? feed.history(ref) : [] }))
6138
+ );
6139
+ };
6140
+ unsubscribe = feed?.values.subscribe(refresh);
6141
+ previous?.close();
6142
+ refresh();
6143
+ };
6144
+ return {
6145
+ series: {
6146
+ subscribe: (listener) => series.subscribe(listener),
6147
+ get() {
6148
+ const target = client.session.currentTarget();
6149
+ if (target?.instance !== historyTarget?.instance || target?.session !== historyTarget?.session)
6150
+ return series.get().map(({ ref }) => ({ ref, points: [] }));
6151
+ return series.get();
6152
+ }
6153
+ },
6154
+ setSignals,
6155
+ close() {
6156
+ if (closed) return;
6157
+ closed = true;
6158
+ unsubscribe?.();
6159
+ active?.close();
6160
+ active = null;
6161
+ series.set([]);
6162
+ }
6163
+ };
6164
+ }
6165
+
6166
+ // ../client/src/variable-editor.ts
6167
+ var READBACK_MS = 500;
6168
+ function createVariableEditor(front, ref) {
6169
+ const client = front.low;
6170
+ const variable = front.variable(ref);
6171
+ const binding = client.variables.bind({ ...ref }, { visible: false });
6172
+ let requested = null;
6173
+ let awaiting = null;
6174
+ let timer;
6175
+ let target = client.session.currentTarget();
6176
+ let closed = false;
6177
+ let stopReading;
6178
+ let infoSource;
6179
+ let info;
6180
+ const read2 = (bound = binding.state.get()) => {
6181
+ const view = variable.get();
6182
+ if (bound.info !== infoSource) {
6183
+ infoSource = bound.info;
6184
+ info = infoSource && {
6185
+ ...infoSource,
6186
+ enum: infoSource.enum?.map((item) => ({ ...item })) ?? null
6187
+ };
6188
+ }
6189
+ const waiting = bound.pending !== null || view.writing || awaiting !== null;
6190
+ const current = client.session.currentTarget();
6191
+ return {
6192
+ info,
6193
+ view,
6194
+ shown: bound.pending ?? view.value,
6195
+ waiting,
6196
+ canWrite: !closed && client.session.ready.get() && current !== null && current.session === client.variables.state.get().session && view.can_write && bound.block === null && !waiting
6197
+ };
6198
+ };
6199
+ const state = new Writable(read2(), Object.is, clientErrorSink(client));
6200
+ const reset = () => {
6201
+ clearTimeout(timer);
6202
+ timer = void 0;
6203
+ requested = null;
6204
+ awaiting = null;
6205
+ };
6206
+ const refresh = () => {
6207
+ if (closed) return;
6208
+ const current = client.session.currentTarget();
6209
+ const bound = binding.state.get();
6210
+ const shown = read2(bound);
6211
+ if (closed) return;
6212
+ if (current?.instance !== target?.instance || current?.session !== target?.session || !shown.view.can_write) {
6213
+ reset();
6214
+ } else if (awaiting !== null && shown.view.value === awaiting) {
6215
+ reset();
6216
+ } else if (requested !== null && bound.writeStatus.kind === "applied") {
6217
+ if (shown.view.value !== requested) {
6218
+ awaiting = requested;
6219
+ timer = setTimeout(() => {
6220
+ reset();
6221
+ state.set(read2());
6222
+ }, READBACK_MS);
6223
+ }
6224
+ requested = null;
6225
+ } else if ("message" in bound.writeStatus) {
6226
+ reset();
6227
+ }
6228
+ target = current;
6229
+ state.set(read2());
6230
+ };
6231
+ const unsubscribe = binding.state.subscribe(refresh);
6232
+ const unsubscribeSession = client.session.session.subscribe(refresh);
6233
+ const unsubscribeReady = client.session.ready.subscribe(refresh);
6234
+ return {
6235
+ state: state.readonly(),
6236
+ write(value) {
6237
+ const { canWrite, info: info2 } = read2();
6238
+ if (!canWrite || !info2) return false;
6239
+ const valid = typeof value === "boolean" ? info2.type === "bool" : typeof value === "string" ? info2.type === "enum" && info2.enum?.some((item) => item.name === value) : Number.isFinite(value) && (info2.type === "real" || info2.type === "integer" && Number.isInteger(value) || info2.type === "enum" && info2.enum?.some((item) => item.value === value)) && (info2.min === null || value >= info2.min) && (info2.max === null || value <= info2.max);
6240
+ if (!valid) {
6241
+ binding.reject("the edit does not match the variable type or range");
6242
+ return false;
6243
+ }
6244
+ requested = typeof value === "boolean" ? value : null;
6245
+ binding.write(value);
6246
+ return true;
6247
+ },
6248
+ setVisible(visible) {
6249
+ if (closed || visible === !!stopReading) return;
6250
+ if (visible) {
6251
+ stopReading = variable.subscribe(refresh);
6252
+ } else {
6253
+ const stop = stopReading;
6254
+ stopReading = void 0;
6255
+ stop?.();
6256
+ }
6257
+ refresh();
6258
+ },
6259
+ close() {
6260
+ if (closed) return;
6261
+ closed = true;
6262
+ unsubscribe();
6263
+ unsubscribeSession();
6264
+ unsubscribeReady();
6265
+ stopReading?.();
6266
+ reset();
6267
+ binding.close();
6268
+ state.set(read2());
6269
+ }
6270
+ };
6271
+ }
5301
6272
  export {
5302
6273
  ANSWER_TIMEOUT_MS,
5303
6274
  ActionError,
@@ -5321,6 +6292,8 @@ export {
5321
6292
  connect,
5322
6293
  createClient,
5323
6294
  createFront,
6295
+ createVariableEditor,
6296
+ createWaveforms,
5324
6297
  errorMessage,
5325
6298
  fetchTransport,
5326
6299
  hasRange,