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

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
  };
@@ -1149,6 +1195,7 @@ var readSessionSummary = (value, path) => {
1149
1195
  const timePath = `${path}.time`;
1150
1196
  const summary = {
1151
1197
  id: field(f, path, "id", integer),
1198
+ ...f["snapshot_rev"] === void 0 ? {} : { snapshot_rev: field(f, path, "snapshot_rev", soft(nullable(integer), null, u)) },
1152
1199
  state: field(f, path, "state", string),
1153
1200
  launcher: field(f, path, "launcher", readSummaryLauncher),
1154
1201
  stop: field(f, path, "stop", string),
@@ -1231,6 +1278,7 @@ var readSessionSummary = (value, path) => {
1231
1278
  log: field(f, path, "log", soft(partlyRecord(readLogCounts, u), {}, u)),
1232
1279
  problems: field(f, path, "problems", items(readServerProblem, u)),
1233
1280
  problems_omitted: field(f, path, "problems_omitted", soft(integer, 0, u)),
1281
+ ...f["problem_seq"] === void 0 ? {} : { problem_seq: field(f, path, "problem_seq", soft(nullable(integer), null, u)) },
1234
1282
  scenario: field(
1235
1283
  f,
1236
1284
  path,
@@ -1277,6 +1325,11 @@ function partlyRecord(read2, u) {
1277
1325
  };
1278
1326
  }
1279
1327
  var readSessionResponse = (value) => field(object(value, "response"), "response", "session", nullable(readSessionSummary));
1328
+ var readSessionInstance = (value) => field(object(value, "response"), "response", "instance", (instance, path) => {
1329
+ if (typeof instance !== "string" || !instance)
1330
+ throw new ProtocolError(path, "a server instance ID. Use the GUI server from this release");
1331
+ return instance;
1332
+ });
1280
1333
  var readSessionAllowed = (value) => field(
1281
1334
  object(value, "response"),
1282
1335
  "response",
@@ -1351,6 +1404,7 @@ var readVariablesSummary = (value) => readVariables(value, "variables");
1351
1404
  var readVariables = (value, path) => {
1352
1405
  const f = object(value, path);
1353
1406
  return {
1407
+ ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", optional(nullable(integer), null)) },
1354
1408
  state: field(f, path, "state", string),
1355
1409
  reason: field(f, path, "reason", optional(nullable(string), null)),
1356
1410
  peers: field(
@@ -1561,6 +1615,7 @@ var readServerMessage = (value) => {
1561
1615
  return {
1562
1616
  type,
1563
1617
  session: field(f, path, "session", integer),
1618
+ ...f["rev"] === void 0 ? {} : { rev: field(f, path, "rev", optional(nullable(integer), null)) },
1564
1619
  peers: field(
1565
1620
  f,
1566
1621
  path,
@@ -1674,10 +1729,20 @@ var RunControl = class {
1674
1729
  this.startTimeoutMs = startTimeoutMs;
1675
1730
  this.startSending = new Writable(false, Object.is, onError);
1676
1731
  this.stopSending = new Writable(null, Object.is, onError);
1732
+ this.pendingRevision = new Writable(0, Object.is, onError);
1677
1733
  this.stopAskedWhileStarting = new Writable(false, Object.is, onError);
1678
1734
  this.failure = new Writable(null, Object.is, onError);
1679
1735
  this.starting = this.startSending.readonly();
1680
1736
  this.stopping = this.stopSending.readonly();
1737
+ this.currentStopping = derived(
1738
+ [this.pendingRevision, this.startSending, feed.session],
1739
+ () => {
1740
+ const key = this.startSending.get() ? this.startOperation : JSON.stringify(feed.currentTarget());
1741
+ return [...this.pendingStops].filter((pending) => pending.key === key).at(-1)?.action ?? null;
1742
+ },
1743
+ Object.is,
1744
+ onError
1745
+ );
1681
1746
  this.stopWhileStarting = this.stopAskedWhileStarting.readonly();
1682
1747
  this.error = derived(
1683
1748
  [this.failure, feed.session],
@@ -1695,66 +1760,180 @@ var RunControl = class {
1695
1760
  feed;
1696
1761
  transport;
1697
1762
  startTimeoutMs;
1763
+ startOperation = null;
1764
+ pendingStops = /* @__PURE__ */ new Set();
1765
+ pendingRevision;
1698
1766
  startSending;
1699
1767
  stopSending;
1700
1768
  stopAskedWhileStarting;
1701
1769
  failure;
1702
1770
  starting;
1703
1771
  stopping;
1772
+ currentStopping;
1704
1773
  stopWhileStarting;
1705
1774
  error;
1706
1775
  /** Starts a run. */
1707
1776
  start(request) {
1708
- this.startSending.set(true);
1777
+ if (this.startSending.get()) return Promise.reject(new Error("a start is already pending"));
1778
+ let resolveStart;
1779
+ let rejectStart;
1780
+ const operation = new Promise(
1781
+ (resolve, reject) => {
1782
+ resolveStart = resolve;
1783
+ rejectStart = reject;
1784
+ }
1785
+ );
1786
+ this.startOperation = operation;
1709
1787
  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);
1788
+ this.startSending.set(true);
1789
+ let instance = null;
1790
+ this.send(
1791
+ "api/run",
1792
+ request,
1793
+ this.startTimeoutMs() || void 0,
1794
+ () => {
1795
+ this.startSending.set(false);
1796
+ },
1797
+ (seen) => {
1798
+ instance = seen;
1717
1799
  }
1718
- });
1800
+ ).then((summary) => resolveStart({ summary, instance }), rejectStart);
1801
+ return operation.then(({ summary }) => summary);
1719
1802
  }
1720
1803
  /** Stops in order (waits for the participants to end). Asking again never turns it into a stop without waiting. */
1721
1804
  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));
1805
+ return this.requestStop(false);
1725
1806
  }
1726
1807
  /** Stops without waiting (kills the participants). */
1727
1808
  forceStop() {
1728
- this.stopSending.set("force");
1729
- return this.send("api/stop", { force: true }, void 0, () => this.stopSending.set(null));
1809
+ return this.requestStop(true);
1810
+ }
1811
+ captureStop() {
1812
+ const starting = this.startSending.get() ? this.startOperation : null;
1813
+ const target = starting ? null : this.feed.currentTarget();
1814
+ return {
1815
+ key: starting ?? JSON.stringify(target),
1816
+ send: (force) => this.requestStop(force, starting, target)
1817
+ };
1818
+ }
1819
+ requestStop(force, starting = this.startSending.get() ? this.startOperation : null, target = starting ? null : this.feed.currentTarget()) {
1820
+ const session = this.feed.session.get();
1821
+ const pending = {
1822
+ action: force ? "force" : "stop",
1823
+ starting: !!starting,
1824
+ key: starting ?? JSON.stringify(target)
1825
+ };
1826
+ this.pendingStops.add(pending);
1827
+ this.pendingRevision.update((n) => n + 1);
1828
+ this.stopSending.set(pending.action);
1829
+ const done = () => {
1830
+ this.pendingStops.delete(pending);
1831
+ this.pendingRevision.update((n) => n + 1);
1832
+ const remaining = [...this.pendingStops];
1833
+ this.stopAskedWhileStarting.set(remaining.some((p) => p.starting));
1834
+ this.stopSending.set(remaining.at(-1)?.action ?? null);
1835
+ };
1836
+ if (!starting) {
1837
+ if (!target) {
1838
+ const message = "no session and server instance are known: no stop was sent; reconnect and check the current run";
1839
+ this.failure.set({
1840
+ message,
1841
+ session: session?.id ?? null,
1842
+ running: session?.launcher.running ?? false
1843
+ });
1844
+ done();
1845
+ return Promise.reject(new Error(message));
1846
+ }
1847
+ return this.send("api/stop-session", { force, ...target }, void 0, done);
1848
+ }
1849
+ this.stopAskedWhileStarting.set(true);
1850
+ return starting.then(
1851
+ ({ summary, instance }) => {
1852
+ if (!summary || !instance) {
1853
+ const message = "the start answer did not identify the run; no stop was sent";
1854
+ const session2 = this.feed.session.get();
1855
+ this.failure.set({
1856
+ message,
1857
+ session: session2?.id ?? null,
1858
+ running: session2?.launcher.running ?? false
1859
+ });
1860
+ throw new Error(message);
1861
+ }
1862
+ pending.key = JSON.stringify({ session: summary.id, instance });
1863
+ this.pendingRevision.update((n) => n + 1);
1864
+ return this.send(
1865
+ "api/stop-session",
1866
+ { force, session: summary.id, instance },
1867
+ void 0,
1868
+ () => void 0
1869
+ );
1870
+ },
1871
+ (error) => {
1872
+ const message = `the start was not confirmed; no stop was sent: ${errorMessage(error)}`;
1873
+ const session2 = this.feed.session.get();
1874
+ this.failure.set({
1875
+ message,
1876
+ session: session2?.id ?? null,
1877
+ running: session2?.launcher.running ?? false
1878
+ });
1879
+ throw new Error(message);
1880
+ }
1881
+ ).finally(done);
1730
1882
  }
1731
1883
  /**
1732
1884
  * Sends and applies the summary in the answer. done is called after the answer (failures too), before the Promise
1733
1885
  * settles.
1734
1886
  */
1735
- send(path, body, timeoutMs, done) {
1887
+ send(path, body, timeoutMs, done, onInstance) {
1888
+ const incompatible = this.feed.incompatible.get();
1889
+ if (incompatible) {
1890
+ done();
1891
+ return Promise.reject(new Error(incompatible));
1892
+ }
1736
1893
  this.failure.set(null);
1737
1894
  return new Promise((resolve, reject) => {
1738
1895
  this.transport({ method: "POST", path, body, timeoutMs }, (outcome) => {
1739
1896
  if (!outcome.ok) {
1897
+ const failure = path === "api/stop-session" && outcome.error.status === 404 ? new HttpError(404, outcome.error.statusText, {
1898
+ code: "targeted-stop-unsupported",
1899
+ message: "the GUI server cannot stop a particular session: no stop was sent; use the GUI server of this release"
1900
+ }) : outcome.error;
1740
1901
  const session = this.feed.session.get();
1741
1902
  this.failure.set({
1742
- message: answerMissing(path, outcome.error) ?? errorMessage(outcome.error),
1903
+ message: answerMissing(path, failure) ?? errorMessage(failure),
1743
1904
  session: session?.id ?? null,
1744
1905
  running: session?.launcher.running ?? false
1745
1906
  });
1746
1907
  done();
1747
- reject(outcome.error);
1908
+ reject(failure);
1748
1909
  return;
1749
1910
  }
1750
1911
  let summary = null;
1751
1912
  try {
1913
+ const instance = path === "api/stop-session" ? body.instance : readSessionInstance(outcome.body);
1752
1914
  summary = readSessionResponse(outcome.body);
1753
- this.feed.adopt(summary);
1915
+ if (path === "api/stop-session" && (!summary || summary.id !== body.session)) {
1916
+ throw new Error("the stop answer did not identify the requested session");
1917
+ }
1918
+ onInstance?.(instance);
1919
+ this.feed.adopt(summary, instance);
1754
1920
  } catch (error) {
1755
1921
  this.feed.report(
1756
1922
  error instanceof ProtocolError ? `unreadable answer: ${error.message}` : String(error)
1757
1923
  );
1924
+ const missingInstance = error instanceof ProtocolError && error.path === "response.instance";
1925
+ if (path === "api/stop-session" || missingInstance) {
1926
+ const message = missingInstance ? `${error.message}. The run may have started. Check the current run before retrying` : "the stop answer was unreadable: check the session before trying again";
1927
+ const session = this.feed.session.get();
1928
+ this.failure.set({
1929
+ message,
1930
+ session: session?.id ?? null,
1931
+ running: session?.launcher.running ?? false
1932
+ });
1933
+ done();
1934
+ reject(new Error(message));
1935
+ return;
1936
+ }
1758
1937
  }
1759
1938
  done();
1760
1939
  resolve(summary);
@@ -1827,6 +2006,29 @@ function scenarioView(summary) {
1827
2006
  timelineUrl: summary.timeline_url
1828
2007
  };
1829
2008
  }
2009
+ function fullStepText(incoming, current) {
2010
+ if (incoming === null || current === null) return incoming;
2011
+ const cut = /^(.*)\.\.\. \((\d+) more characters\)$/s.exec(incoming);
2012
+ if (!cut) return incoming;
2013
+ const prefix = cut[1];
2014
+ return current.startsWith(prefix) && Array.from(current).length === Array.from(prefix).length + Number(cut[2]) ? current : incoming;
2015
+ }
2016
+ function mergeScenarioStep(current, incoming) {
2017
+ return {
2018
+ ...incoming,
2019
+ text: fullStepText(incoming.text, current.text) ?? incoming.text,
2020
+ message: fullStepText(incoming.message, current.message)
2021
+ };
2022
+ }
2023
+ var stepPositions = /* @__PURE__ */ new WeakMap();
2024
+ function mergeScenarioSteps(current, incoming, merge = (_old, next) => next) {
2025
+ const steps = new Map(current.map((step) => [step.index, step]));
2026
+ for (const step of incoming) {
2027
+ const old = steps.get(step.index);
2028
+ steps.set(step.index, old ? merge(old, step) : step);
2029
+ }
2030
+ return [...steps.values()].sort((a, b) => a.index - b.index);
2031
+ }
1830
2032
  function withStep(steps, step) {
1831
2033
  const i = steps.findIndex((s) => s.index >= step.index);
1832
2034
  if (i < 0) return [...steps, step];
@@ -1847,6 +2049,7 @@ function runOutcome(session) {
1847
2049
  function sessionFromSummary(summary) {
1848
2050
  const blank = {
1849
2051
  id: summary.id,
2052
+ ...summary.snapshot_rev == null ? {} : { snapshotRev: summary.snapshot_rev },
1850
2053
  lastSeq: -1,
1851
2054
  file: summary.file,
1852
2055
  disable: summary.disable,
@@ -1876,7 +2079,11 @@ function sessionFromSummary(summary) {
1876
2079
  droppedMarks: 0,
1877
2080
  scenario: null
1878
2081
  };
1879
- return applySummary(blank, summary, true);
2082
+ const adopted = applySummary(blank, summary, true);
2083
+ return summary.last_seq == null ? adopted : {
2084
+ ...adopted,
2085
+ pendingFindings: { through: summary.last_seq, keys: summary.findings.map(findingIdentity) }
2086
+ };
1880
2087
  }
1881
2088
  function addDropped(session, dropped) {
1882
2089
  const counts = Object.entries(dropped.log).filter(([, count2]) => count2 > 0);
@@ -1887,7 +2094,11 @@ function addDropped(session, dropped) {
1887
2094
  key: `dropped ${mark} ${source}`,
1888
2095
  source,
1889
2096
  line: "",
1890
- gap: { count: count2, atLeast: dropped.at_least.includes(source) }
2097
+ gap: {
2098
+ count: count2,
2099
+ atLeast: dropped.at_least.includes(source),
2100
+ ...dropped.reason === "not-kept" ? { notKept: true } : {}
2101
+ }
1891
2102
  }));
1892
2103
  const next = { ...appendLogs(session, gaps), droppedMarks: mark };
1893
2104
  const sources = { ...next.logSources };
@@ -1909,23 +2120,49 @@ function launcherOf(summary) {
1909
2120
  };
1910
2121
  }
1911
2122
  function applySummary(session, summary, force = false, controlOnly = false) {
1912
- const newer = force || (summary.last_seq ?? -1) > session.lastSeq;
2123
+ const incomingRev = summary.snapshot_rev ?? null;
2124
+ const currentRev = session.snapshotRev ?? null;
2125
+ const staleControl = currentRev !== null && (incomingRev === null || incomingRev < currentRev);
2126
+ const projectionRev = session.projectionRev ?? null;
2127
+ const staleProjection = projectionRev !== null && (incomingRev === null || incomingRev < projectionRev);
2128
+ if (staleControl && (staleProjection || !force && controlOnly)) return session;
2129
+ const newer = force || (summary.last_seq ?? -1) > Math.max(session.lastSeq, session.observedSeq ?? -1, session.projectionSeq ?? -1);
1913
2130
  const launcher = !force && !session.launcher.running && summary.launcher.running ? session.launcher : launcherOf(summary);
1914
2131
  const notLess = summary.problems.length + summary.problems_omitted >= session.problems.length + session.problemsOmitted;
1915
- const next = {
2132
+ const mergedProblems = [...summary.problems];
2133
+ let omitted = summary.problems_omitted;
2134
+ if (summary.problem_seq != null) {
2135
+ const included = new Set(mergedProblems.map((problem) => problem.problem_seq));
2136
+ for (const problem of session.problems) {
2137
+ if (problem.problem_seq === void 0 || included.has(problem.problem_seq)) continue;
2138
+ if (mergedProblems.length >= MAX_PROBLEMS) break;
2139
+ mergedProblems.push(problem);
2140
+ if (problem.problem_seq <= summary.problem_seq && omitted > 0) omitted--;
2141
+ }
2142
+ }
2143
+ if (mergedProblems.every((problem) => problem.problem_seq !== void 0))
2144
+ mergedProblems.sort((a, b) => a.problem_seq - b.problem_seq);
2145
+ const next = staleControl ? session : {
1916
2146
  ...session,
2147
+ ...incomingRev === null ? {} : { snapshotRev: incomingRev },
2148
+ ...summary.problem_seq == null ? {} : { problemSeq: Math.max(session.problemSeq ?? 0, summary.problem_seq) },
1917
2149
  launcher,
1918
2150
  stopRequests: Math.max(session.stopRequests, stopRequestsOf(summary.stop)),
1919
2151
  logSources: withSources(session.logSources, Object.keys(summary.log)),
1920
- ...force || notLess ? { problems: summary.problems, problemsOmitted: summary.problems_omitted } : {}
2152
+ ...summary.scenario?.timeline_url ? {
2153
+ scenario: session.scenario ? { ...session.scenario, timelineUrl: summary.scenario.timeline_url } : scenarioView(summary.scenario)
2154
+ } : {},
2155
+ ...force || notLess ? { problems: mergedProblems, problemsOmitted: omitted } : {}
1921
2156
  };
1922
- if (!newer || !force && controlOnly) {
2157
+ if (!newer || staleProjection || !force && controlOnly) {
1923
2158
  return next;
1924
2159
  }
1925
2160
  const phase = summary.phase ?? next.phase;
1926
2161
  const rank = phaseIndex(phase);
1927
- const check = summary.check ?? next.check ?? summary.result?.check ?? null;
1928
- const result = summary.result ?? next.result;
2162
+ const preserveEvents = force && controlOnly;
2163
+ const behind = (...kinds) => summary.last_seq !== null && kinds.some((kind) => (session.eventSeqs?.[kind] ?? -1) > summary.last_seq);
2164
+ const check = (preserveEvents ? next.check : null) ?? summary.check ?? next.check ?? summary.result?.check ?? null;
2165
+ const result = (preserveEvents ? next.result : null) ?? summary.result ?? next.result;
1929
2166
  const known = new Map(session.participants.map((p) => [p.name, p]));
1930
2167
  const participants = summary.participants.map((p) => ({
1931
2168
  name: p.name,
@@ -1935,34 +2172,66 @@ function applySummary(session, summary, force = false, controlOnly = false) {
1935
2172
  exitCode: p.exit_code,
1936
2173
  signal: p.signal,
1937
2174
  failure: p.reason,
1938
- message: p.message,
2175
+ message: p.message ?? (preserveEvents ? known.get(p.name)?.message ?? null : null),
1939
2176
  // A stop the launcher asked for is kept even in summaries of later states (ended and so on)
1940
2177
  stopRequested: p.stop_requested || p.state === "stop_requested" || !!known.get(p.name)?.stopRequested,
1941
2178
  omittedFields: p.omitted_fields,
1942
2179
  controlLink: p.control_link ?? known.get(p.name)?.controlLink ?? null,
1943
2180
  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 ?? {}
2181
+ commandLine: p.command_line ?? (preserveEvents ? known.get(p.name)?.commandLine ?? null : null),
2182
+ workingDirectory: p.working_directory ?? (preserveEvents ? known.get(p.name)?.workingDirectory ?? null : null),
2183
+ environment: p.environment ?? (preserveEvents ? known.get(p.name)?.environment ?? {} : {})
1947
2184
  }));
2185
+ const scenario = summary.scenario ? {
2186
+ ...scenarioView(summary.scenario),
2187
+ timelineUrl: next.scenario?.timelineUrl ?? summary.scenario.timeline_url
2188
+ } : next.scenario;
2189
+ let mergedScenario = preserveEvents && scenario && next.scenario ? {
2190
+ ...scenario,
2191
+ steps: mergeScenarioSteps(
2192
+ next.scenario.steps,
2193
+ scenario.steps,
2194
+ (old, step) => summary.last_seq !== null && (stepPositions.get(old) ?? -1) > summary.last_seq ? old : mergeScenarioStep(old, step)
2195
+ )
2196
+ } : scenario;
2197
+ if (mergedScenario && result?.scenario) {
2198
+ mergedScenario = {
2199
+ ...mergedScenario,
2200
+ steps: mergeScenarioSteps(mergedScenario.steps, result.scenario.steps)
2201
+ };
2202
+ }
2203
+ if (mergedScenario && scenario && mergedScenario !== scenario) {
2204
+ mergedScenario.stepsOmitted = Math.max(
2205
+ 0,
2206
+ scenario.stepsOmitted - (mergedScenario.steps.length - scenario.steps.length)
2207
+ );
2208
+ }
2209
+ const mergedParticipants = preserveEvents ? [
2210
+ ...participants,
2211
+ ...next.participants.filter(
2212
+ (p) => !participants.some((current) => current.name === p.name)
2213
+ )
2214
+ ] : participants;
1948
2215
  return {
1949
2216
  ...next,
1950
- unreadable: force ? summary.unreadable : union(next.unreadable, summary.unreadable),
1951
- phase,
1952
- phaseRank: rank >= 0 ? rank : next.phaseRank,
2217
+ ...incomingRev === null ? {} : { projectionRev: incomingRev },
2218
+ projectionSeq: Math.max(next.projectionSeq ?? -1, summary.last_seq ?? -1),
2219
+ unreadable: force && !behind("finding", "result", "participant") ? summary.unreadable : union(next.unreadable, summary.unreadable),
2220
+ phase: behind("phase", "result") ? next.phase ?? phase : phase,
2221
+ phaseRank: behind("phase", "result") ? next.phaseRank : rank >= 0 ? rank : next.phaseRank,
1953
2222
  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,
2223
+ simMs: behind("time") ? next.simMs ?? summary.sim_ms : summary.sim_ms ?? next.simMs,
2224
+ timeOmittedFields: behind("time") || summary.sim_ms === null ? next.timeOmittedFields : summary.time_omitted_fields,
2225
+ time: behind("time") && next.time ? next.time : summary.time ? timeView(summary.time) : next.time,
2226
+ lastCommand: behind("command") && next.lastCommand ? next.lastCommand : summary.last_command ? commandView(summary.last_command, summary.last_command.seq ?? -1) : next.lastCommand,
1958
2227
  launcherState: newerState(next.launcherState, summary.launcher_state ?? null),
1959
- findings: summary.findings,
2228
+ findings: preserveEvents ? mergeFindings(next.findings, summary.findings) : summary.findings,
1960
2229
  result,
1961
2230
  check,
1962
- scenario: summary.scenario ? scenarioView(summary.scenario) : next.scenario,
2231
+ scenario: mergedScenario,
1963
2232
  // Whether a participant is required or left out is in the check result (as is the order, that of the configuration
1964
2233
  // 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)
2234
+ participants: behind("participant", "result", CONTROL_EVENT) && next.participants.length > 0 ? next.participants : withResult(check ? mergeCheck(mergedParticipants, check) : mergedParticipants, result)
1966
2235
  };
1967
2236
  }
1968
2237
  function newerState(current, incoming) {
@@ -1980,20 +2249,101 @@ function withSources(sources, names) {
1980
2249
  return next;
1981
2250
  }
1982
2251
  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] };
2252
+ const seq = problem.problem_seq;
2253
+ if (seq !== void 0 && seq <= (session.problemEventSeq ?? 0)) return session;
2254
+ const updated = seq === void 0 ? session : { ...session, problemEventSeq: seq };
2255
+ if (seq !== void 0 && session.problems.some((item) => item.problem_seq === seq))
2256
+ return updated;
2257
+ if (updated.problems.length >= MAX_PROBLEMS) {
2258
+ const alreadyCounted2 = seq !== void 0 && seq <= (session.problemSeq ?? 0);
2259
+ return alreadyCounted2 ? updated : { ...updated, problemsOmitted: updated.problemsOmitted + 1 };
2260
+ }
2261
+ const alreadyCounted = seq !== void 0 && seq <= (session.problemSeq ?? 0);
2262
+ const problems = [...updated.problems, problem];
2263
+ if (problems.every((item) => item.problem_seq !== void 0))
2264
+ problems.sort((a, b) => a.problem_seq - b.problem_seq);
2265
+ return {
2266
+ ...updated,
2267
+ problems,
2268
+ problemsOmitted: alreadyCounted ? Math.max(0, updated.problemsOmitted - 1) : updated.problemsOmitted
2269
+ };
1987
2270
  }
1988
2271
  function phaseIndex(phase) {
1989
2272
  return phase === null ? -1 : PHASES.indexOf(phase);
1990
2273
  }
2274
+ function findingKey(finding) {
2275
+ return JSON.stringify([
2276
+ finding.severity,
2277
+ finding.code,
2278
+ finding.file,
2279
+ finding.line,
2280
+ finding.participant,
2281
+ finding.network,
2282
+ finding.message,
2283
+ finding.detail
2284
+ ]);
2285
+ }
2286
+ function findingIdentity(finding) {
2287
+ return finding.event_seq === void 0 ? `body:${findingKey(finding)}` : `seq:${finding.event_seq}`;
2288
+ }
2289
+ function mergeFindings(current, incoming) {
2290
+ const a = current.slice(0, MAX_FINDINGS);
2291
+ const b = incoming.slice(0, MAX_FINDINGS);
2292
+ if (a.every((finding) => finding.event_seq !== void 0) && b.every((finding) => finding.event_seq !== void 0)) {
2293
+ const bySeq = /* @__PURE__ */ new Map();
2294
+ for (const finding of [...b, ...a]) bySeq.set(finding.event_seq, finding);
2295
+ return [...bySeq.values()].sort((left, right) => left.event_seq - right.event_seq).slice(0, MAX_FINDINGS);
2296
+ }
2297
+ const ak = a.map(findingKey);
2298
+ const bk = b.map(findingKey);
2299
+ const sizes = Array.from({ length: a.length + 1 }, () => new Uint16Array(b.length + 1));
2300
+ for (let i2 = a.length - 1; i2 >= 0; --i2)
2301
+ for (let j2 = b.length - 1; j2 >= 0; --j2)
2302
+ sizes[i2][j2] = ak[i2] === bk[j2] ? 1 + sizes[i2 + 1][j2 + 1] : Math.max(sizes[i2 + 1][j2], sizes[i2][j2 + 1]);
2303
+ const merged = [];
2304
+ let i = 0, j = 0;
2305
+ while ((i < a.length || j < b.length) && merged.length < MAX_FINDINGS) {
2306
+ if (i < a.length && j < b.length && ak[i] === bk[j]) {
2307
+ merged.push(a[i++]);
2308
+ j++;
2309
+ } else if (j === b.length || i < a.length && sizes[i + 1][j] >= sizes[i][j + 1])
2310
+ merged.push(a[i++]);
2311
+ else merged.push(b[j++]);
2312
+ }
2313
+ return merged;
2314
+ }
1991
2315
  function applyEvents(session, events, countStale = false) {
1992
2316
  let next = session;
1993
2317
  const logs = [];
1994
2318
  let stale = 0;
1995
2319
  for (const event of events) {
1996
2320
  if (event.seq > next.lastSeq) {
2321
+ const tracked = [
2322
+ "time",
2323
+ "phase",
2324
+ "result",
2325
+ "finding",
2326
+ "participant",
2327
+ "command",
2328
+ CONTROL_EVENT
2329
+ ].includes(event.event);
2330
+ if (event.event === "scenario_step") stepPositions.set(event.step, event.seq);
2331
+ next = {
2332
+ ...next,
2333
+ observedSeq: Math.max(next.observedSeq ?? -1, event.seq),
2334
+ ...tracked ? { eventSeqs: { ...next.eventSeqs, [event.event]: event.seq } } : {}
2335
+ };
2336
+ const pending = next.pendingFindings;
2337
+ if (event.event === "finding" && pending && event.seq <= pending.through) {
2338
+ const numbered = pending.keys.indexOf(`seq:${event.seq}`);
2339
+ const index = numbered === -1 ? pending.keys.indexOf(`body:${findingKey(event.finding)}`) : numbered;
2340
+ if (index !== -1) {
2341
+ const keys = [...pending.keys];
2342
+ keys.splice(index, 1);
2343
+ next = { ...next, lastSeq: event.seq, pendingFindings: { ...pending, keys } };
2344
+ continue;
2345
+ }
2346
+ }
1997
2347
  next = applyOne(next, event, logs);
1998
2348
  if (event.unreadable)
1999
2349
  next = { ...next, unreadable: union(next.unreadable, event.unreadable) };
@@ -2013,6 +2363,37 @@ function applyEvents(session, events, countStale = false) {
2013
2363
  }
2014
2364
  return { ...next, logSources: sources };
2015
2365
  }
2366
+ function recoverReplayLogs(session, recovered, notKept) {
2367
+ if (!recovered.length) return session;
2368
+ const sources = Object.fromEntries(
2369
+ Object.entries(session.logSources).map(([name, source]) => [
2370
+ name,
2371
+ { lines: 0, dropped: source.dropped }
2372
+ ])
2373
+ );
2374
+ const restored = /* @__PURE__ */ new Map();
2375
+ for (const line of recovered) {
2376
+ const source = sources[line.source] ??= { lines: 0, dropped: 0 };
2377
+ if (line.gap) source.dropped += line.gap.count;
2378
+ else {
2379
+ const count2 = restored.get(line.source) ?? 0;
2380
+ if (count2 < (notKept.get(line.source) ?? 0)) {
2381
+ source.dropped--;
2382
+ restored.set(line.source, count2 + 1);
2383
+ }
2384
+ }
2385
+ }
2386
+ const logs = session.logs.flatMap((line) => {
2387
+ if (!line.gap?.notKept) return [line];
2388
+ const available = restored.get(line.source) ?? 0;
2389
+ const count2 = Math.max(0, line.gap.count - available);
2390
+ restored.set(line.source, Math.max(0, available - line.gap.count));
2391
+ return count2 > 0 ? [{ ...line, gap: { ...line.gap, count: count2 } }] : [];
2392
+ });
2393
+ logs.push(...recovered);
2394
+ logs.sort((a, b) => a.seq - b.seq);
2395
+ return appendLogs({ ...session, logs: [], logSources: sources }, logs);
2396
+ }
2016
2397
  function appendLogs(session, added) {
2017
2398
  const sources = {};
2018
2399
  for (const [source, counts] of Object.entries(session.logSources))
@@ -2106,7 +2487,10 @@ function applyOne(session, event, logs) {
2106
2487
  }
2107
2488
  return next;
2108
2489
  case "finding":
2109
- return next.findings.length >= MAX_FINDINGS ? next : { ...next, findings: [...next.findings, event.finding] };
2490
+ return next.findings.length >= MAX_FINDINGS ? next : {
2491
+ ...next,
2492
+ findings: next.findings.every((finding) => finding.event_seq !== void 0) ? mergeFindings(next.findings, [{ ...event.finding, event_seq: event.seq }]) : [...next.findings, { ...event.finding, event_seq: event.seq }]
2493
+ };
2110
2494
  case "time":
2111
2495
  return { ...next, simMs: event.sim_ms, timeOmittedFields: [], time: timeView(event) };
2112
2496
  case "command":
@@ -2253,6 +2637,12 @@ var SessionFeed = class {
2253
2637
  }
2254
2638
  connection;
2255
2639
  onError;
2640
+ rawListeners = /* @__PURE__ */ new Set();
2641
+ snapshotVersion = () => 0;
2642
+ instanceId = null;
2643
+ adoptionRevision = 0;
2644
+ instanceListener = () => void 0;
2645
+ stopTarget = null;
2256
2646
  current;
2257
2647
  synced;
2258
2648
  allowedValue;
@@ -2263,6 +2653,7 @@ var SessionFeed = class {
2263
2653
  messageListeners = /* @__PURE__ */ new Set();
2264
2654
  noticeId = 0;
2265
2655
  stoppedFlag = false;
2656
+ replayLogs = null;
2266
2657
  session;
2267
2658
  ready;
2268
2659
  allowed;
@@ -2281,8 +2672,7 @@ var SessionFeed = class {
2281
2672
  */
2282
2673
  resumeFields() {
2283
2674
  this.synced.set(false);
2284
- const session = this.current.get();
2285
- return session ? { session: session.id, from_seq: session.lastSeq + 1 } : {};
2675
+ return {};
2286
2676
  }
2287
2677
  onMessages(listener) {
2288
2678
  this.messageListeners.add(listener);
@@ -2296,15 +2686,56 @@ var SessionFeed = class {
2296
2686
  * request for the same run (the rest arrives in notifications). A summary of an earlier run never brings back an old
2297
2687
  * run over a new one.
2298
2688
  */
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
- );
2689
+ onRawMessages(listener) {
2690
+ this.rawListeners.add(listener);
2691
+ return () => this.rawListeners.delete(listener);
2692
+ }
2693
+ onSnapshotVersion(read2) {
2694
+ this.snapshotVersion = read2;
2695
+ }
2696
+ /** Called before a new server's session can be published. */
2697
+ onInstance(listener) {
2698
+ this.instanceListener = listener;
2699
+ }
2700
+ /** Instance associated with the current session, or null if its origin is not known. */
2701
+ currentInstance() {
2702
+ return this.instanceId;
2703
+ }
2704
+ currentTarget() {
2705
+ return this.stopTarget ? { ...this.stopTarget } : null;
2706
+ }
2707
+ adopt(summary, instance, resyncFrom) {
2708
+ const switching = this.instanceId !== null && instance !== this.instanceId;
2709
+ if (switching && (resyncFrom !== this.instanceId || this.connection.state.get() === "open"))
2710
+ return null;
2711
+ const previous = switching ? null : this.current.get();
2712
+ if (summary && previous && summary.id < previous.id) return null;
2713
+ if (!summary && instance === this.instanceId)
2714
+ return {
2715
+ revision: this.adoptionRevision,
2716
+ instance,
2717
+ session: previous?.id ?? null
2718
+ };
2719
+ const revision = ++this.adoptionRevision;
2720
+ const next = !summary ? null : previous?.id === summary.id ? applySummary(previous, summary, false, this.connection.state.get() === "open") : sessionFromSummary(summary);
2721
+ const changedInstance = instance !== this.instanceId;
2722
+ this.instanceId = instance;
2723
+ const adoption = { revision, instance, session: next?.id ?? null };
2724
+ this.stopTarget = next ? { session: next.id, instance } : null;
2725
+ const notifySession = this.current.setDeferred(next);
2726
+ const notifyAllowed = switching ? this.allowedValue.setDeferred(null) : () => void 0;
2727
+ if (changedInstance) this.instanceListener(instance, () => this.isCurrent(revision));
2728
+ notifySession();
2729
+ notifyAllowed();
2730
+ if (!this.sameRun(adoption)) return null;
2731
+ this.adoptAllowed(summary?.allowed ?? null);
2732
+ return this.sameRun(adoption) ? adoption : null;
2733
+ }
2734
+ sameRun(adoption) {
2735
+ return this.instanceId === adoption.instance && (this.current.get()?.id ?? null) === adoption.session;
2736
+ }
2737
+ isCurrent(revision) {
2738
+ return revision === this.adoptionRevision;
2308
2739
  }
2309
2740
  /**
2310
2741
  * Takes what the server accepts (an HTTP answer or a notification): the one with the larger `rev` wins (rev 0 is a
@@ -2323,7 +2754,12 @@ var SessionFeed = class {
2323
2754
  }
2324
2755
  /** Reads and applies a batch from the connection. */
2325
2756
  receive(raw) {
2757
+ const snapshotVersion = this.snapshotVersion();
2758
+ const epoch = this.connection.batchEpoch();
2759
+ let originInstance = this.instanceId;
2760
+ const currentOrigin = () => this.connection.batchEpoch() === epoch && this.instanceId === originInstance;
2326
2761
  const batch = [];
2762
+ const accepted = [];
2327
2763
  let stop = null;
2328
2764
  let incompatible = null;
2329
2765
  for (const value of raw) {
@@ -2334,6 +2770,7 @@ var SessionFeed = class {
2334
2770
  this.notify(
2335
2771
  error instanceof ProtocolError ? `unreadable message: ${error.message}` : String(error)
2336
2772
  );
2773
+ if (!currentOrigin()) return;
2337
2774
  const type = value?.type;
2338
2775
  if (type === "hello" && error instanceof ProtocolError && error.path === "message.vehicle_sil_gui") {
2339
2776
  const version2 = JSON.stringify(value.vehicle_sil_gui);
@@ -2349,26 +2786,73 @@ var SessionFeed = class {
2349
2786
  }
2350
2787
  if (message === null) continue;
2351
2788
  batch.push(message);
2789
+ accepted.push(value);
2352
2790
  if (message.type === "error" && message.code === "unauthorized") {
2353
2791
  stop = "unauthorized";
2354
2792
  break;
2355
2793
  }
2356
2794
  }
2795
+ let filtered = this.filterOlderRuns(batch, accepted);
2796
+ if (filtered.staleHello && stop === null) stop = "lost";
2357
2797
  if (stop === "unauthorized" || stop === "incompatible") {
2358
2798
  this.stoppedFlag = true;
2359
2799
  this.connection.close();
2360
2800
  }
2801
+ if (!currentOrigin()) {
2802
+ if (stop === "unauthorized" || stop === "incompatible") this.stoppedFlag = false;
2803
+ return;
2804
+ }
2361
2805
  if (stop === "lost") this.connection.restart();
2362
- this.apply(batch);
2806
+ if (!currentOrigin()) return;
2807
+ filtered = this.filterOlderRuns(filtered.batch, filtered.raw);
2808
+ this.apply(filtered.batch, filtered.raw, snapshotVersion, currentOrigin, (instance) => {
2809
+ originInstance = instance;
2810
+ });
2811
+ if (!currentOrigin()) return;
2363
2812
  if (stop === "lost" || stop === "incompatible") this.synced.set(false);
2364
2813
  if (stop === "unauthorized") this.rejectedValue.set(true);
2365
2814
  if (incompatible !== null) this.incompatibleValue.set(incompatible);
2366
2815
  }
2367
- apply(batch) {
2816
+ /** Keep messages at or after the run already observed over HTTP, within each server instance. */
2817
+ filterOlderRuns(batch, raw) {
2818
+ let instance = this.instanceId;
2819
+ let floor = this.current.get()?.id ?? null;
2820
+ let staleHello = false;
2821
+ const selected = [];
2822
+ const selectedRaw = [];
2823
+ batch.forEach((message, index) => {
2824
+ if (message.type === "hello") {
2825
+ const id = message.session?.id ?? null;
2826
+ if (instance === message.instance && floor !== null && (id === null || id < floor)) {
2827
+ staleHello = true;
2828
+ return;
2829
+ }
2830
+ if (instance !== message.instance) {
2831
+ instance = message.instance;
2832
+ floor = id;
2833
+ } else if (id !== null) floor = id;
2834
+ } else {
2835
+ const id = message.type === "session" ? message.session.id : "session" in message && typeof message.session === "number" ? message.session : null;
2836
+ if (id !== null && floor !== null && id < floor) return;
2837
+ if (message.type === "session" && (floor === null || message.session.id > floor))
2838
+ floor = message.session.id;
2839
+ }
2840
+ selected.push(message);
2841
+ selectedRaw.push(raw[index]);
2842
+ });
2843
+ return { batch: selected, raw: selectedRaw, staleHello };
2844
+ }
2845
+ apply(batch, raw, snapshotVersion, currentOrigin, commitOrigin) {
2368
2846
  if (batch.length === 0) return;
2847
+ const revision = ++this.adoptionRevision;
2369
2848
  const before = this.current.get();
2849
+ const originalInstance = this.instanceId;
2850
+ let instance = originalInstance;
2370
2851
  let session = before;
2852
+ let replayLogs = this.replayLogs?.instance === instance && this.replayLogs?.session === session?.id ? this.replayLogs : null;
2853
+ const unseenLogs = () => replayLogs?.logs.filter((line) => replayLogs?.unseen.has(line.seq)) ?? [];
2371
2854
  let events = [];
2855
+ const notices = [];
2372
2856
  let applied = false;
2373
2857
  let synced = this.synced.get();
2374
2858
  let allowedNow = this.allowedValue.get();
@@ -2393,16 +2877,46 @@ var SessionFeed = class {
2393
2877
  synced = false;
2394
2878
  replaying = true;
2395
2879
  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);
2880
+ const staleSnapshot = !!summary && instance === message.instance && session?.id === summary.id && session.snapshotRev != null && (summary.snapshot_rev == null || summary.snapshot_rev < session.snapshotRev);
2881
+ takeAllowed(message.allowed ?? summary?.allowed ?? null, !staleSnapshot);
2882
+ const sameRun2 = summary && instance === message.instance && session?.id === summary.id;
2883
+ const resumed = sameRun2 && replay?.from_seq != null;
2884
+ instance = message.instance;
2885
+ if (!sameRun2) replayLogs = null;
2886
+ if (!summary) {
2887
+ session = null;
2888
+ } else if (sameRun2 && session) {
2889
+ const kept = applySummary(session, summary, true, true);
2890
+ if (!resumed && instance) {
2891
+ const logs = replayLogs ? recoverReplayLogs(kept, unseenLogs(), replayLogs.notKept).logs : kept.logs;
2892
+ replayLogs = {
2893
+ instance,
2894
+ session: summary.id,
2895
+ logs: logs.filter((line) => !line.gap || line.gap.launcher),
2896
+ unseen: new Set(logs.map((line) => line.seq)),
2897
+ notKept: /* @__PURE__ */ new Map()
2898
+ };
2899
+ }
2900
+ session = resumed ? kept : { ...kept, lastSeq: -1, logs: [], logSources: {}, droppedMarks: 0 };
2901
+ } else {
2902
+ session = sessionFromSummary(summary);
2903
+ }
2399
2904
  break;
2400
2905
  }
2401
2906
  case "dropped": {
2402
- if (session && message.session === session.id) session = addDropped(session, message);
2907
+ if (session && message.session === session.id) {
2908
+ session = addDropped(session, message);
2909
+ if (message.reason === "not-kept" && replayLogs) {
2910
+ for (const [source, count2] of Object.entries(message.log))
2911
+ replayLogs.notKept.set(source, (replayLogs.notKept.get(source) ?? 0) + count2);
2912
+ }
2913
+ }
2403
2914
  break;
2404
2915
  }
2405
2916
  case "synced":
2917
+ if (session && replayLogs && replayLogs.instance === instance && replayLogs.session === session.id)
2918
+ session = recoverReplayLogs(session, unseenLogs(), replayLogs.notKept);
2919
+ replayLogs = null;
2406
2920
  synced = true;
2407
2921
  replaying = false;
2408
2922
  break;
@@ -2410,22 +2924,34 @@ var SessionFeed = class {
2410
2924
  takeAllowed(message.allowed);
2411
2925
  break;
2412
2926
  case "session":
2927
+ if (session?.id !== message.session.id) replayLogs = null;
2413
2928
  takeAllowed(message.session.allowed);
2414
- session = session?.id === message.session.id ? applySummary(session, message.session, true) : sessionFromSummary(message.session);
2929
+ session = session?.id === message.session.id ? applySummary(
2930
+ session,
2931
+ message.session,
2932
+ true,
2933
+ message.session.last_seq !== null && (session.observedSeq ?? session.lastSeq) >= message.session.last_seq
2934
+ ) : sessionFromSummary(message.session);
2415
2935
  break;
2416
2936
  case "event":
2417
- if (session?.id === message.session) events.push(message.event);
2937
+ if (session?.id === message.session) {
2938
+ if (message.event.event === "log" || message.event.event === "log_dropped")
2939
+ replayLogs?.unseen.delete(message.event.seq);
2940
+ events.push(message.event);
2941
+ }
2418
2942
  break;
2419
2943
  case "error":
2420
2944
  if (message.code === "unauthorized") {
2421
2945
  } 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
- );
2946
+ const { code, message: text3, skipped, problem_seq } = message;
2947
+ session = addProblem(session, {
2948
+ code,
2949
+ message: text3,
2950
+ ...skipped === void 0 ? {} : { skipped },
2951
+ ...problem_seq === void 0 ? {} : { problem_seq }
2952
+ });
2427
2953
  } else {
2428
- this.notify(message.message);
2954
+ notices.push(message.message);
2429
2955
  }
2430
2956
  break;
2431
2957
  case "resync":
@@ -2436,12 +2962,32 @@ var SessionFeed = class {
2436
2962
  }
2437
2963
  flush();
2438
2964
  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);
2965
+ if (!currentOrigin() || !this.isCurrent(revision)) return;
2966
+ this.instanceId = instance;
2967
+ commitOrigin(instance);
2968
+ this.replayLogs = replayLogs && replayLogs.session === session?.id && replayLogs.instance === instance ? replayLogs : null;
2969
+ this.stopTarget = session && instance ? { session: session.id, instance } : null;
2970
+ const sessionId = session?.id ?? null;
2971
+ const sameRun = () => currentOrigin() && this.instanceId === instance && (this.current.get()?.id ?? null) === sessionId;
2972
+ const notifySession = this.current.setDeferred(session);
2973
+ const notifyAllowed = this.allowedValue.setDeferred(allowedNow);
2974
+ const notifySynced = this.synced.setDeferred(synced);
2975
+ if (instance && instance !== originalInstance) this.instanceListener(instance, sameRun);
2976
+ notifySession();
2977
+ notifyAllowed();
2978
+ notifySynced();
2979
+ if (!sameRun()) return;
2980
+ for (const notice of notices) {
2981
+ this.notify(notice);
2982
+ if (!sameRun()) return;
2983
+ }
2442
2984
  if (applied) this.receivedAt.set(Date.now());
2985
+ if (!sameRun()) return;
2443
2986
  if (stale > 0) this.notify(STALE_EVENTS_NOTICE, stale);
2444
- callEach(this.messageListeners, [batch], this.onError);
2987
+ if (!sameRun()) return;
2988
+ callEach(this.rawListeners, [raw, sameRun, snapshotVersion], this.onError, sameRun);
2989
+ if (!sameRun()) return;
2990
+ callEach(this.messageListeners, [batch], this.onError, sameRun);
2445
2991
  }
2446
2992
  notify(message, count2 = 1) {
2447
2993
  this.noticeList.update((list) => {
@@ -2844,12 +3390,18 @@ var VariablesFeed = class {
2844
3390
  this.state = this.stateValue.readonly();
2845
3391
  this.operations = this.operationsValue.readonly();
2846
3392
  this.watchProblem = this.problemValue.readonly();
2847
- link.onBatch((batch) => this.receive(batch));
3393
+ link.onBatch(
3394
+ (batch, current, snapshotCurrent) => this.receive(batch, current, snapshotCurrent)
3395
+ );
2848
3396
  }
2849
3397
  link;
2850
3398
  http;
2851
3399
  onError;
2852
3400
  limits;
3401
+ instanceId = null;
3402
+ snapshotVersionValue = 0;
3403
+ snapshotIdentity = null;
3404
+ serverRevision = null;
2853
3405
  stateValue;
2854
3406
  operationsValue;
2855
3407
  handles = /* @__PURE__ */ new Set();
@@ -2898,26 +3450,43 @@ var VariablesFeed = class {
2898
3450
  }
2899
3451
  }
2900
3452
  // --- Notifications --------------------------------------------------------------------------
2901
- receive(batch) {
3453
+ receive(batch, current = () => true, initialSnapshotVersion = this.snapshotVersionValue) {
3454
+ let snapshotVersion = initialSnapshotVersion;
3455
+ const snapshotCurrent = (session, rev) => this.isSnapshotCurrent(snapshotVersion, this.instanceId, session, rev);
2902
3456
  const touched = /* @__PURE__ */ new Set();
2903
3457
  let touchedAll = false;
2904
3458
  let operations = null;
2905
3459
  let fresh = [];
2906
3460
  const flush = () => {
2907
- if (operations) this.setOperations(operations, fresh);
3461
+ if (operations) this.setOperations(operations, fresh, current);
2908
3462
  operations = null;
2909
3463
  fresh = [];
2910
3464
  };
2911
3465
  for (const message of batch) {
3466
+ if (!current()) return;
2912
3467
  if (!isObject(message)) continue;
3468
+ const messageSession = message["session"];
3469
+ const existingSession = this.stateValue.get().session;
3470
+ if (typeof messageSession === "number" && existingSession !== null && messageSession < existingSession)
3471
+ continue;
2913
3472
  switch (message["type"]) {
2914
3473
  case "hello": {
2915
3474
  flush();
3475
+ if (!current()) return;
2916
3476
  const summary = message["session"];
3477
+ this.adoptInstance(message["instance"]);
3478
+ if (!current()) return;
2917
3479
  if (isObject(summary) && Number.isSafeInteger(summary["id"])) {
2918
- this.adoptSummary(summary);
3480
+ const id = summary["id"];
3481
+ const details = summary["variables"];
3482
+ const rev = isObject(details) ? positionOrNull(details["rev"]) : null;
3483
+ const applied = this.adoptSummary(summary, current, () => snapshotCurrent(id, rev));
3484
+ if (applied !== null && this.snapshotVersionValue === applied)
3485
+ snapshotVersion = applied;
2919
3486
  } else {
3487
+ if (this.stateValue.get().session !== null) break;
2920
3488
  this.enter(null);
3489
+ if (!current()) return;
2921
3490
  this.stateValue.set({ ...NO_VARIABLES, status: "off" });
2922
3491
  }
2923
3492
  touchedAll = true;
@@ -2926,10 +3495,16 @@ var VariablesFeed = class {
2926
3495
  case "session": {
2927
3496
  const summary = message["session"];
2928
3497
  const id = isObject(summary) ? summary["id"] : null;
3498
+ const existing = this.stateValue.get().session;
3499
+ if (typeof id === "number" && existing !== null && id < existing) break;
2929
3500
  if (Number.isSafeInteger(id) && id !== this.stateValue.get().session) {
2930
3501
  flush();
3502
+ if (!current()) return;
3503
+ const afterFlush = this.stateValue.get().session;
3504
+ if (afterFlush !== null && id < afterFlush) break;
2931
3505
  this.enter(id);
2932
- this.stateValue.set({ ...NO_VARIABLES, session: id });
3506
+ if (!current()) return;
3507
+ if (this.stateValue.get().session !== id) break;
2933
3508
  touchedAll = true;
2934
3509
  }
2935
3510
  break;
@@ -2937,12 +3512,30 @@ var VariablesFeed = class {
2937
3512
  case "variables": {
2938
3513
  const id = message["session"];
2939
3514
  if (!Number.isSafeInteger(id)) break;
2940
- if (id !== this.stateValue.get().session) {
3515
+ const details = message["variables"];
3516
+ const rev = isObject(details) ? positionOrNull(details["rev"]) : null;
3517
+ const existing = this.stateValue.get().session;
3518
+ if (existing !== null && id < existing) break;
3519
+ if (id !== existing) {
2941
3520
  flush();
2942
- this.enter(id);
2943
- touchedAll = true;
3521
+ if (!current()) return;
3522
+ const afterFlush = this.stateValue.get().session;
3523
+ if (afterFlush !== null && id < afterFlush) break;
3524
+ if (afterFlush !== id) {
3525
+ this.enter(id);
3526
+ if (!current()) return;
3527
+ if (this.stateValue.get().session !== id) break;
3528
+ touchedAll = true;
3529
+ }
3530
+ }
3531
+ if (snapshotCurrent(id, rev)) {
3532
+ const version2 = this.applySnapshot(
3533
+ readVariables2(details, id),
3534
+ id,
3535
+ rev
3536
+ );
3537
+ if (this.snapshotVersionValue === version2) snapshotVersion = version2;
2944
3538
  }
2945
- this.stateValue.set(readVariables2(message["variables"], id));
2946
3539
  break;
2947
3540
  }
2948
3541
  case "values": {
@@ -2961,8 +3554,13 @@ var VariablesFeed = class {
2961
3554
  break;
2962
3555
  }
2963
3556
  case "availability": {
2964
- if (message["session"] !== this.stateValue.get().session) break;
3557
+ const id = this.stateValue.get().session;
3558
+ if (message["session"] !== id || id === null) break;
3559
+ const rev = positionOrNull(message["rev"]);
3560
+ if (!snapshotCurrent(id, rev)) break;
3561
+ const version2 = this.markSnapshot(id, rev);
2965
3562
  if (this.takeAvailability(message["peers"])) touchedAll = true;
3563
+ if (this.snapshotVersionValue === version2) snapshotVersion = version2;
2966
3564
  break;
2967
3565
  }
2968
3566
  case "error": {
@@ -2975,7 +3573,8 @@ var VariablesFeed = class {
2975
3573
  }
2976
3574
  }
2977
3575
  flush();
2978
- if (touchedAll || touched.size > 0) this.publish(touchedAll ? null : touched);
3576
+ if (current() && (touchedAll || touched.size > 0))
3577
+ this.publish(touchedAll ? null : touched, current);
2979
3578
  }
2980
3579
  /** Returns whether any state changed. Only the availability table changes: `peers` keeps its identity. */
2981
3580
  takeAvailability(peers) {
@@ -2996,29 +3595,82 @@ var VariablesFeed = class {
2996
3595
  this.stateValue.set({ ...state, availability: next });
2997
3596
  return true;
2998
3597
  }
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;
3598
+ snapshotVersion() {
3599
+ return this.snapshotVersionValue;
3600
+ }
3601
+ /** Compare server capture order when available; legacy peers use the local best-effort watermark. */
3602
+ isSnapshotCurrent(version2, instance, session, rev) {
3603
+ if (session === null) return true;
3604
+ const source = this.serverRevision;
3605
+ if (source && source.instance === instance && source.session === session) {
3606
+ return rev !== null && rev >= source.rev;
3607
+ }
3608
+ if (rev !== null) return true;
3609
+ const identity = this.snapshotIdentity;
3610
+ return !identity || identity.instance !== instance || identity.session !== session || this.snapshotVersionValue <= version2;
3611
+ }
3612
+ markSnapshot(session, rev) {
3613
+ const version2 = ++this.snapshotVersionValue;
3614
+ this.snapshotIdentity = { instance: this.instanceId, session };
3615
+ if (rev !== null) this.serverRevision = { instance: this.instanceId, session, rev };
3616
+ return version2;
3617
+ }
3618
+ applySnapshot(state, session, rev) {
3619
+ const version2 = this.markSnapshot(session, rev);
3620
+ this.stateValue.set(state);
3621
+ return version2;
3622
+ }
3623
+ /** A reused numeric session on another server is a different run. */
3624
+ adoptInstance(value) {
3625
+ if (typeof value !== "string" || !value) return;
3626
+ const changed = this.instanceId !== null && this.instanceId !== value;
3627
+ this.instanceId = value;
3628
+ if (changed) this.enter(null, true);
3629
+ }
3630
+ /** Applies a summary: an older snapshot can still carry a terminal write result. */
3631
+ adoptSummary(summary, current = () => true, snapshotCurrent = current) {
3632
+ if (!isObject(summary) || !Number.isSafeInteger(summary["id"]) || !current()) return null;
3002
3633
  const id = summary["id"];
3634
+ const instance = this.instanceId;
3635
+ const existing = this.stateValue.get().session;
3636
+ if (existing !== null && id < existing) return null;
3003
3637
  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;
3638
+ let applyState = snapshotCurrent();
3639
+ if (id !== existing) {
3640
+ const initial = this.enter(id);
3641
+ if (!current()) return null;
3642
+ if (this.stateValue.get() !== initial) applyState = applyState && snapshotCurrent();
3009
3643
  }
3010
- this.stateValue.set(readVariables2(variables, id));
3644
+ const sameIdentity = () => current() && this.instanceId === instance && this.stateValue.get().session === id;
3645
+ if (!sameIdentity() || variables === void 0) return null;
3646
+ applyState = applyState && snapshotCurrent();
3647
+ let notifyOperations = () => void 0;
3648
+ const listed = [];
3011
3649
  if (isObject(variables) && Array.isArray(variables["operations"])) {
3012
3650
  let operations = this.operationsValue.get();
3013
- const listed = [];
3014
3651
  for (const entry of variables["operations"]) {
3015
3652
  const operation = readOperation(entry, id);
3016
- if (operation) {
3653
+ if (operation && (applyState || operation.done)) {
3017
3654
  listed.push(operation);
3018
3655
  operations = this.withOperation(operations, operation);
3019
3656
  }
3020
3657
  }
3021
- this.setOperations(operations, listed);
3658
+ notifyOperations = this.prepareOperations(operations, listed, sameIdentity);
3659
+ }
3660
+ let next = null;
3661
+ let appliedVersion = null;
3662
+ if (applyState && snapshotCurrent() && sameIdentity()) {
3663
+ next = readVariables2(variables, id);
3664
+ appliedVersion = this.applySnapshot(
3665
+ next,
3666
+ id,
3667
+ isObject(variables) ? positionOrNull(variables["rev"]) : null
3668
+ );
3669
+ }
3670
+ notifyOperations();
3671
+ if (!sameIdentity() || appliedVersion === null || this.snapshotVersionValue !== appliedVersion || !next || this.stateValue.get() !== next)
3672
+ return appliedVersion;
3673
+ if (isObject(variables) && Array.isArray(variables["operations"])) {
3022
3674
  const fromSeq = variables["operations_from_seq"];
3023
3675
  const openOmitted = variables["operations_open_omitted"];
3024
3676
  this.forgetLost(id, {
@@ -3027,6 +3679,7 @@ var VariablesFeed = class {
3027
3679
  openOmitted: typeof openOmitted === "number" && openOmitted > 0
3028
3680
  });
3029
3681
  }
3682
+ return appliedVersion;
3030
3683
  }
3031
3684
  /**
3032
3685
  * With the summary after a reconnect (or from api/session), settles as "no answer came" (lost) the writes waiting for
@@ -3049,12 +3702,15 @@ var VariablesFeed = class {
3049
3702
  * are dropped with their memory, so they do not keep growing as the variables change from run to run). Writes
3050
3703
  * waiting for the previous run's result are failed, since the result will not come.
3051
3704
  */
3052
- enter(session) {
3053
- if (session === this.stateValue.get().session) return;
3705
+ enter(session, force = false) {
3706
+ if (!force && session === this.stateValue.get().session) return this.stateValue.get();
3054
3707
  this.readings.clear();
3055
3708
  this.histories.clear();
3056
3709
  this.historyReserved = 0;
3057
- this.operationsValue.set([]);
3710
+ const initial = { ...NO_VARIABLES, session };
3711
+ const notifyOperations = this.operationsValue.setDeferred([]);
3712
+ const notifyState = this.stateValue.setDeferred(initial);
3713
+ const notifyWatches = [...this.handles].map((handle) => handle.values.setDeferred({}));
3058
3714
  for (const pending of [...this.pending]) {
3059
3715
  if (pending.session !== session) {
3060
3716
  this.settle(
@@ -3066,6 +3722,10 @@ var VariablesFeed = class {
3066
3722
  );
3067
3723
  }
3068
3724
  }
3725
+ notifyOperations();
3726
+ notifyState();
3727
+ for (const notify of notifyWatches) notify();
3728
+ return initial;
3069
3729
  }
3070
3730
  takeValues(message, touched) {
3071
3731
  const peers = message["peers"];
@@ -3107,8 +3767,9 @@ var VariablesFeed = class {
3107
3767
  }
3108
3768
  }
3109
3769
  /** Rebuilds values of the watches that observe the changed variables (all watches if touched is null). */
3110
- publish(touched) {
3770
+ publish(touched, current = () => true) {
3111
3771
  for (const handle of this.handles) {
3772
+ if (!current()) return;
3112
3773
  if (touched !== null && handle.keys !== null) {
3113
3774
  let hit = false;
3114
3775
  for (const key of handle.keys) {
@@ -3141,7 +3802,7 @@ var VariablesFeed = class {
3141
3802
  // --- Operations -----------------------------------------------------------------------------
3142
3803
  withOperation(operations, operation) {
3143
3804
  const at = operations.findIndex((o) => o.seq === operation.seq);
3144
- if (at >= 0 && operations[at]?.done && !operation.done) return [...operations];
3805
+ if (at >= 0 && operations[at]?.done) return [...operations];
3145
3806
  const next = at >= 0 ? operations.map((o, i) => i === at ? operation : o) : [...operations, operation];
3146
3807
  return next.length > OPERATIONS_KEPT ? next.slice(next.length - OPERATIONS_KEPT) : next;
3147
3808
  }
@@ -3150,14 +3811,19 @@ var VariablesFeed = class {
3150
3811
  * just arrived (a batch of notifications, the list in a summary): the list is cut to OPERATIONS_KEPT entries, so
3151
3812
  * settled operations cut from the list are picked up from here.
3152
3813
  */
3153
- setOperations(operations, fresh = []) {
3154
- this.operationsValue.set(operations);
3814
+ setOperations(operations, fresh = [], current = () => true) {
3815
+ this.prepareOperations(operations, fresh, current)();
3816
+ }
3817
+ prepareOperations(operations, fresh, current) {
3818
+ if (!current()) return () => void 0;
3819
+ const notify = this.operationsValue.setDeferred(operations);
3155
3820
  for (const pending of [...this.pending]) {
3156
3821
  if (pending.seq === null) continue;
3157
3822
  const mine = (o) => o.done && o.seq === pending.seq && o.session === pending.session;
3158
3823
  const operation = fresh.find(mine) ?? operations.find(mine);
3159
3824
  if (operation) this.settle(pending, operation);
3160
3825
  }
3826
+ return notify;
3161
3827
  }
3162
3828
  settle(pending, outcome) {
3163
3829
  if (!this.pending.delete(pending)) return;
@@ -3580,6 +4246,7 @@ var VariableBinder = class {
3580
4246
  return entry;
3581
4247
  }
3582
4248
  send(entry, value) {
4249
+ const epoch = this.sources.connectionEpoch();
3583
4250
  const mine = { value };
3584
4251
  const { peer, name } = entry.ref;
3585
4252
  entry.sending = mine;
@@ -3587,7 +4254,6 @@ var VariableBinder = class {
3587
4254
  entry.shown = mine;
3588
4255
  entry.status = { kind: "sending" };
3589
4256
  entry.pending = value;
3590
- this.changed(entry);
3591
4257
  const accepted = (seq) => {
3592
4258
  if (entry.sending !== mine) return;
3593
4259
  entry.sending = null;
@@ -3622,6 +4288,11 @@ var VariableBinder = class {
3622
4288
  if (entry.shown === mine) entry.status = status;
3623
4289
  this.changed(entry);
3624
4290
  };
4291
+ this.changed(entry);
4292
+ 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) {
4293
+ settled({ kind: "dropped", message: DROPPED_MESSAGE });
4294
+ return;
4295
+ }
3625
4296
  this.sources.variables.write(
3626
4297
  { [peer]: { [name]: value } },
3627
4298
  {
@@ -3782,6 +4453,10 @@ function defaultOrigin(baseUrl, runtime = globalThis) {
3782
4453
  function createClient(options) {
3783
4454
  return buildClient(options).client;
3784
4455
  }
4456
+ var clientErrorSinks = /* @__PURE__ */ new WeakMap();
4457
+ function clientErrorSink(client) {
4458
+ return clientErrorSinks.get(client);
4459
+ }
3785
4460
  function buildClient(options) {
3786
4461
  const token = typeof options.token === "function" ? options.token : () => options.token;
3787
4462
  const onError = options.onError ?? reportToConsole;
@@ -3808,8 +4483,18 @@ function buildClient(options) {
3808
4483
  });
3809
4484
  feed = new SessionFeed(connection, onError);
3810
4485
  const session = feed;
3811
- variablesFeed = new VariablesFeed(connection, http, onError, () => limits.get());
4486
+ variablesFeed = new VariablesFeed(
4487
+ {
4488
+ send: (message) => connection.send(message),
4489
+ onBatch: (listener) => session.onRawMessages(listener)
4490
+ },
4491
+ http,
4492
+ onError,
4493
+ () => limits.get()
4494
+ );
3812
4495
  const variables = variablesFeed;
4496
+ session.onSnapshotVersion(() => variables.snapshotVersion());
4497
+ session.onInstance((instance) => variables.adoptInstance(instance));
3813
4498
  const run = new RunControl(session, http, onError, () => longRequestMs(limits.get()));
3814
4499
  const time = new TimeControl(
3815
4500
  session.session,
@@ -3820,6 +4505,7 @@ function buildClient(options) {
3820
4505
  const binder = new VariableBinder({
3821
4506
  variables,
3822
4507
  connection: connection.state,
4508
+ connectionEpoch: () => connection.batchEpoch(),
3823
4509
  session: session.session,
3824
4510
  onError
3825
4511
  });
@@ -3849,6 +4535,8 @@ function buildClient(options) {
3849
4535
  },
3850
4536
  session: {
3851
4537
  session: session.session,
4538
+ currentTarget: () => session.currentTarget(),
4539
+ currentInstance: () => session.currentInstance(),
3852
4540
  ready: session.ready,
3853
4541
  allowed: session.allowed,
3854
4542
  lastEventAt: session.lastEventAt,
@@ -3862,6 +4550,7 @@ function buildClient(options) {
3862
4550
  run: {
3863
4551
  starting: run.starting,
3864
4552
  stopping: run.stopping,
4553
+ currentStopping: run.currentStopping,
3865
4554
  stopWhileStarting: run.stopWhileStarting,
3866
4555
  error: run.error,
3867
4556
  start: (request) => run.start(request),
@@ -3938,25 +4627,48 @@ function buildClient(options) {
3938
4627
  },
3939
4628
  readConnections
3940
4629
  ),
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
- )
4630
+ fetchSession: () => {
4631
+ const resyncFrom = session.currentInstance();
4632
+ const snapshotVersion = variables.snapshotVersion();
4633
+ return new Promise(
4634
+ (resolve, reject) => http({ method: "GET", path: "api/session" }, (outcome) => {
4635
+ if (!outcome.ok) {
4636
+ reject(outcome.error);
4637
+ return;
4638
+ }
4639
+ try {
4640
+ const summary = readSessionResponse(outcome.body);
4641
+ const instance = readSessionInstance(outcome.body);
4642
+ const adoption = session.adopt(summary, instance, resyncFrom);
4643
+ if (adoption !== null) {
4644
+ const rawSession = outcome.body?.session;
4645
+ const rev = rawSession?.variables?.rev;
4646
+ const current = () => variables.isSnapshotCurrent(
4647
+ snapshotVersion,
4648
+ adoption.instance,
4649
+ adoption.session,
4650
+ Number.isSafeInteger(rev) && rev >= 0 ? rev : null
4651
+ );
4652
+ if (session.sameRun(adoption)) session.adoptAllowed(readSessionAllowed(outcome.body));
4653
+ const sameRun = () => session.sameRun(adoption);
4654
+ if (sameRun()) variables.adoptInstance(instance);
4655
+ if (sameRun())
4656
+ variables.adoptSummary(
4657
+ outcome.body?.session,
4658
+ sameRun,
4659
+ current
4660
+ );
4661
+ }
4662
+ resolve(summary);
4663
+ } catch (error) {
4664
+ reject(error);
4665
+ }
4666
+ })
4667
+ );
4668
+ }
3958
4669
  };
3959
- return { client, http, onError };
4670
+ clientErrorSinks.set(client, onError);
4671
+ return { client, http, onError, runControl: run };
3960
4672
  }
3961
4673
 
3962
4674
  // ../client/src/token.ts
@@ -4044,7 +4756,7 @@ function runOf(s) {
4044
4756
  case "starting":
4045
4757
  return "starting";
4046
4758
  case "waiting":
4047
- return "waiting";
4759
+ return state?.holding === true ? "paused" : "waiting";
4048
4760
  case "stopping":
4049
4761
  return "stopping";
4050
4762
  case "ended":
@@ -4183,7 +4895,9 @@ function composeControls(s, run) {
4183
4895
  const serverStop = s.allowed?.stop;
4184
4896
  const stoppable = s.busy.has("start") || live || run === "starting" || serverStop?.ok === true;
4185
4897
  let stop;
4186
- if (s.busy.has("stop")) stop = control(false, busyReason("stop"));
4898
+ if (!s.busy.has("start") && s.allowed?.start.reason === "starting")
4899
+ stop = control(false, reason("starting", "wait until the new run can be identified"));
4900
+ else if (s.busy.has("stop")) stop = control(false, busyReason("stop"));
4187
4901
  else if (s.busy.has("start")) stop = control(true);
4188
4902
  else if (serverStop && !serverStop.ok && serverStop.reason !== "not-running")
4189
4903
  stop = fromServer(serverStop, "the server does not stop the run now");
@@ -4197,7 +4911,9 @@ function composeControls(s, run) {
4197
4911
  else stop = control(true);
4198
4912
  const serverForce = s.allowed?.force;
4199
4913
  let force;
4200
- if (s.busy.has("force_stop")) force = control(false, busyReason("force stop"));
4914
+ if (s.busy.has("start") || s.allowed?.start.reason === "starting")
4915
+ force = control(false, reason("starting", "wait until the new run can be identified"));
4916
+ else if (s.busy.has("force_stop")) force = control(false, busyReason("force stop"));
4201
4917
  else if (serverForce && !serverForce.ok && serverForce.reason !== "not-running")
4202
4918
  force = fromServer(serverForce, "the server does not force a stop now");
4203
4919
  else if (!stoppable)
@@ -4308,6 +5024,8 @@ var INTENT_FIELDS = /* @__PURE__ */ new Set([
4308
5024
  "params",
4309
5025
  "speed",
4310
5026
  "start_paused",
5027
+ "stop_at_ms",
5028
+ "late_tolerance_ms",
4311
5029
  "strict",
4312
5030
  "connect",
4313
5031
  "time_policy"
@@ -4354,7 +5072,8 @@ var FrontActions = class {
4354
5072
  if (request instanceof ActionError) return this.fail(request);
4355
5073
  const own = this.refusalOfStart();
4356
5074
  if (own) return this.fail(own);
4357
- return this.guarded("start", () => this.src.low.run.start(request).then(() => void 0));
5075
+ const start = this.src.low.run.start(request);
5076
+ return this.guarded("start", () => start.then(() => void 0));
4358
5077
  }
4359
5078
  /**
4360
5079
  * Checks what `intent` would start (`api/check`). Its failure is the caller's: it is not kept for `status.problem`.
@@ -4454,6 +5173,8 @@ var FrontActions = class {
4454
5173
  ...intent.params ? { params: intent.params } : {},
4455
5174
  ...intent.speed !== void 0 ? { speed: intent.speed } : {},
4456
5175
  ...intent.start_paused ? { start_paused: true } : {},
5176
+ ...intent.stop_at_ms !== void 0 ? { stop_at_ms: intent.stop_at_ms } : {},
5177
+ ...intent.late_tolerance_ms !== void 0 ? { late_tolerance_ms: intent.late_tolerance_ms } : {},
4457
5178
  ...intent.strict ? { strict: true } : {},
4458
5179
  ...intent.connect ? { connect: intent.connect } : {},
4459
5180
  ...intent.time_policy !== void 0 ? { time_policy: intent.time_policy } : {}
@@ -4493,19 +5214,66 @@ var FrontActions = class {
4493
5214
  ) : null;
4494
5215
  }
4495
5216
  stop() {
4496
- return this.once("stop", () => this.src.low.run.stop());
5217
+ return this.once("stop", false);
4497
5218
  }
4498
- forceStop() {
4499
- return this.once("force_stop", () => this.src.low.run.forceStop());
5219
+ forceStop(target) {
5220
+ const current = this.src.low.session.currentTarget();
5221
+ if (target && (current?.session !== target.session || current.instance !== target.instance))
5222
+ return this.fail(
5223
+ new ActionError("session-changed", "the confirmed run has changed", "refused")
5224
+ );
5225
+ if (this.src.low.run.starting.get())
5226
+ return this.fail(
5227
+ new ActionError("starting", "wait until the new run can be identified", "refused")
5228
+ );
5229
+ return this.once("force_stop", true);
5230
+ }
5231
+ /** Pending stop only affects controls of the run it was sent for. */
5232
+ busyForCurrent() {
5233
+ const busy = new Set(this.busyValue.get());
5234
+ const key = this.stopKey();
5235
+ for (const name of ["stop", "force_stop"]) {
5236
+ if (this.inFlight.get(name)?.key !== key) busy.delete(name);
5237
+ }
5238
+ return busy;
4500
5239
  }
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) {
5240
+ stopKey() {
5241
+ return this.src.captureStop().key;
5242
+ }
5243
+ /** Repeated requests for the same run share one operation. */
5244
+ once(name, force) {
5245
+ const capture = this.src.captureStop();
5246
+ const key = capture.key;
4503
5247
  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);
5248
+ if (running?.key === key) return running.promise;
5249
+ let resolve;
5250
+ let reject;
5251
+ const promise = new Promise((ok, fail) => {
5252
+ resolve = ok;
5253
+ reject = fail;
4507
5254
  });
4508
- this.inFlight.set(name, promise);
5255
+ const entry = { key, promise };
5256
+ this.inFlight.set(name, entry);
5257
+ this.failureValue.set(null);
5258
+ const operation = capture.send(force);
5259
+ if (this.busyValue.get().has(name)) this.busyValue.set(new Set(this.busyValue.get()));
5260
+ else this.setBusy(name, true);
5261
+ operation.then(
5262
+ () => {
5263
+ if (this.inFlight.get(name) === entry) {
5264
+ this.inFlight.delete(name);
5265
+ this.setBusy(name, false);
5266
+ }
5267
+ resolve();
5268
+ },
5269
+ (error) => {
5270
+ if (this.inFlight.get(name) === entry) {
5271
+ this.inFlight.delete(name);
5272
+ this.setBusy(name, false);
5273
+ }
5274
+ reject(this.record(actionError(error)));
5275
+ }
5276
+ );
4509
5277
  return promise;
4510
5278
  }
4511
5279
  guarded(name, send) {
@@ -4991,7 +5759,7 @@ function makeVariable(low, ref, refuse, launcher) {
4991
5759
 
4992
5760
  // ../client/src/front.ts
4993
5761
  function makeFront(options, onClose) {
4994
- const { client: low, http, onError } = buildClient(options);
5762
+ const { client: low, http, onError, runControl } = buildClient(options);
4995
5763
  let counter = 0;
4996
5764
  const stamp = () => ++counter;
4997
5765
  const stamps = /* @__PURE__ */ new Map();
@@ -5012,7 +5780,7 @@ function makeFront(options, onClose) {
5012
5780
  session: low.session.session.get(),
5013
5781
  allowed: low.session.allowed.get(),
5014
5782
  limits: low.limits.get(),
5015
- busy: actions.busy.get()
5783
+ busy: actions.busyForCurrent()
5016
5784
  });
5017
5785
  const sources = [
5018
5786
  low.connection.state,
@@ -5034,6 +5802,7 @@ function makeFront(options, onClose) {
5034
5802
  actions = new FrontActions({
5035
5803
  low,
5036
5804
  http,
5805
+ captureStop: () => runControl.captureStop(),
5037
5806
  snapshot,
5038
5807
  controls: () => controls.get(),
5039
5808
  run,
@@ -5160,7 +5929,7 @@ function makeFront(options, onClose) {
5160
5929
  run: {
5161
5930
  start: (intent, startOptions) => actions.start(intent, startOptions),
5162
5931
  stop: () => actions.stop(),
5163
- forceStop: () => actions.forceStop()
5932
+ forceStop: (target) => actions.forceStop(target)
5164
5933
  },
5165
5934
  time: {
5166
5935
  pause: () => actions.pause(),
@@ -5298,6 +6067,172 @@ function until(source, test, options = {}) {
5298
6067
  if (test(first)) finish(() => resolve(first));
5299
6068
  });
5300
6069
  }
6070
+
6071
+ // ../client/src/waveforms.ts
6072
+ function createWaveforms(client, options = {}) {
6073
+ const settings = { ...options, history: options.history ?? 600 };
6074
+ const series = new Writable([], Object.is, clientErrorSink(client));
6075
+ let historyTarget = client.session.currentTarget();
6076
+ let selection = [];
6077
+ let active = null;
6078
+ let unsubscribe;
6079
+ let closed = false;
6080
+ const setSignals = (refs) => {
6081
+ if (closed) return;
6082
+ const seen = /* @__PURE__ */ new Set();
6083
+ const next = refs.flatMap(({ peer, name }) => {
6084
+ const key = JSON.stringify([peer, name]);
6085
+ if (seen.has(key)) return [];
6086
+ seen.add(key);
6087
+ return [{ peer, name }];
6088
+ });
6089
+ if (next.length === selection.length && next.every((ref, i) => ref.peer === selection[i].peer && ref.name === selection[i].name))
6090
+ return;
6091
+ const previous = active;
6092
+ unsubscribe?.();
6093
+ const feed = next.length ? client.variables.watch(next, settings) : null;
6094
+ selection = next;
6095
+ active = feed;
6096
+ const refresh = () => {
6097
+ if (active !== feed || closed) return;
6098
+ historyTarget = client.session.currentTarget();
6099
+ const current = historyTarget && historyTarget.session === client.variables.state.get().session;
6100
+ series.set(
6101
+ next.map((ref) => ({ ref: { ...ref }, points: current && feed ? feed.history(ref) : [] }))
6102
+ );
6103
+ };
6104
+ unsubscribe = feed?.values.subscribe(refresh);
6105
+ previous?.close();
6106
+ refresh();
6107
+ };
6108
+ return {
6109
+ series: {
6110
+ subscribe: (listener) => series.subscribe(listener),
6111
+ get() {
6112
+ const target = client.session.currentTarget();
6113
+ if (target?.instance !== historyTarget?.instance || target?.session !== historyTarget?.session)
6114
+ return series.get().map(({ ref }) => ({ ref, points: [] }));
6115
+ return series.get();
6116
+ }
6117
+ },
6118
+ setSignals,
6119
+ close() {
6120
+ if (closed) return;
6121
+ closed = true;
6122
+ unsubscribe?.();
6123
+ active?.close();
6124
+ active = null;
6125
+ series.set([]);
6126
+ }
6127
+ };
6128
+ }
6129
+
6130
+ // ../client/src/variable-editor.ts
6131
+ var READBACK_MS = 500;
6132
+ function createVariableEditor(front, ref) {
6133
+ const client = front.low;
6134
+ const variable = front.variable(ref);
6135
+ const binding = client.variables.bind({ ...ref }, { visible: false });
6136
+ let requested = null;
6137
+ let awaiting = null;
6138
+ let timer;
6139
+ let target = client.session.currentTarget();
6140
+ let closed = false;
6141
+ let stopReading;
6142
+ let infoSource;
6143
+ let info;
6144
+ const read2 = (bound = binding.state.get()) => {
6145
+ const view = variable.get();
6146
+ if (bound.info !== infoSource) {
6147
+ infoSource = bound.info;
6148
+ info = infoSource && {
6149
+ ...infoSource,
6150
+ enum: infoSource.enum?.map((item) => ({ ...item })) ?? null
6151
+ };
6152
+ }
6153
+ const waiting = bound.pending !== null || view.writing || awaiting !== null;
6154
+ const current = client.session.currentTarget();
6155
+ return {
6156
+ info,
6157
+ view,
6158
+ shown: bound.pending ?? view.value,
6159
+ waiting,
6160
+ canWrite: !closed && client.session.ready.get() && current !== null && current.session === client.variables.state.get().session && view.can_write && bound.block === null && !waiting
6161
+ };
6162
+ };
6163
+ const state = new Writable(read2(), Object.is, clientErrorSink(client));
6164
+ const reset = () => {
6165
+ clearTimeout(timer);
6166
+ timer = void 0;
6167
+ requested = null;
6168
+ awaiting = null;
6169
+ };
6170
+ const refresh = () => {
6171
+ if (closed) return;
6172
+ const current = client.session.currentTarget();
6173
+ const bound = binding.state.get();
6174
+ const shown = read2(bound);
6175
+ if (closed) return;
6176
+ if (current?.instance !== target?.instance || current?.session !== target?.session || !shown.view.can_write) {
6177
+ reset();
6178
+ } else if (awaiting !== null && shown.view.value === awaiting) {
6179
+ reset();
6180
+ } else if (requested !== null && bound.writeStatus.kind === "applied") {
6181
+ if (shown.view.value !== requested) {
6182
+ awaiting = requested;
6183
+ timer = setTimeout(() => {
6184
+ reset();
6185
+ state.set(read2());
6186
+ }, READBACK_MS);
6187
+ }
6188
+ requested = null;
6189
+ } else if ("message" in bound.writeStatus) {
6190
+ reset();
6191
+ }
6192
+ target = current;
6193
+ state.set(read2());
6194
+ };
6195
+ const unsubscribe = binding.state.subscribe(refresh);
6196
+ const unsubscribeSession = client.session.session.subscribe(refresh);
6197
+ const unsubscribeReady = client.session.ready.subscribe(refresh);
6198
+ return {
6199
+ state: state.readonly(),
6200
+ write(value) {
6201
+ const { canWrite, info: info2 } = read2();
6202
+ if (!canWrite || !info2) return false;
6203
+ 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);
6204
+ if (!valid) {
6205
+ binding.reject("the edit does not match the variable type or range");
6206
+ return false;
6207
+ }
6208
+ requested = typeof value === "boolean" ? value : null;
6209
+ binding.write(value);
6210
+ return true;
6211
+ },
6212
+ setVisible(visible) {
6213
+ if (closed || visible === !!stopReading) return;
6214
+ if (visible) {
6215
+ stopReading = variable.subscribe(refresh);
6216
+ } else {
6217
+ const stop = stopReading;
6218
+ stopReading = void 0;
6219
+ stop?.();
6220
+ }
6221
+ refresh();
6222
+ },
6223
+ close() {
6224
+ if (closed) return;
6225
+ closed = true;
6226
+ unsubscribe();
6227
+ unsubscribeSession();
6228
+ unsubscribeReady();
6229
+ stopReading?.();
6230
+ reset();
6231
+ binding.close();
6232
+ state.set(read2());
6233
+ }
6234
+ };
6235
+ }
5301
6236
  export {
5302
6237
  ANSWER_TIMEOUT_MS,
5303
6238
  ActionError,
@@ -5321,6 +6256,8 @@ export {
5321
6256
  connect,
5322
6257
  createClient,
5323
6258
  createFront,
6259
+ createVariableEditor,
6260
+ createWaveforms,
5324
6261
  errorMessage,
5325
6262
  fetchTransport,
5326
6263
  hasRange,