@vehicle-sil/gui-client 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,547 @@
1
- # Temporary Holding Version
1
+ # gui/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [日本語](README.ja.md)
4
+
5
+ Reference for the client library of the GUI server (`vehicle-sil-gui`), written in TypeScript and published as `@vehicle-sil/gui-client`. It covers how to get and import the library, the public API, basic usage, reading and writing ECU variables, and the lifecycle.
6
+
7
+ The library handles the connection (token, reconnection), the session copy (a copy of the run state, built from the server's summary and events), run and time control, ECU variables (list, watching values, writes and their results), and the types and parsers of the server API. It depends on no other package, not even Angular or RxJS. The sample screens (`gui/web`) use only this library, through a thin Angular wrapper (`gui/web/src/app/core/session/`).
8
+
9
+ | To find | See |
10
+ | ------------------------------------------------------------------ | -------------------------------------------------------- |
11
+ | Where to get the library and how to import it | [Installing and importing](#installing-and-importing) |
12
+ | Which names are public | [Entry points](#entry-points), [Public API](#public-api) |
13
+ | The code to connect and start a run | [Basic usage](#basic-usage) |
14
+ | Reading and writing variable values | [ECU variables](#ecu-variables) |
15
+ | Building sliders and lamps (the values of `condition` and `block`) | [Build widgets (`bind`)](#build-widgets-bind) |
16
+ | What happens after `connect()` and `close()` | [Lifecycle](#lifecycle) |
17
+ | Developing the library | [Coding rules](#coding-rules), [Tests](#tests) |
18
+
19
+ ## Installing and importing
20
+
21
+ The library is TypeScript source with no dependencies. It is not published to the npm registry.
22
+
23
+ | Use | How to get it | Import |
24
+ | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
25
+ | Plain JavaScript, no build step | Put `vehicle-sil-gui-client.mjs`, the library bundled into one ESM file, in the screen's directory | `import { createClient } from './vehicle-sil-gui-client.mjs'` |
26
+ | TypeScript and any framework | Get the package `vehicle-sil-gui-client-<version>.tgz` and run `npm install <that .tgz>` in your project | `import { createClient } from '@vehicle-sil/gui-client'` |
27
+ | A TypeScript app in this repository (`gui/web`) | Point the entry point names to `src/` with `paths` in `tsconfig.json` | `import { createClient } from '@vehicle-sil/gui-client'` |
28
+
29
+ Where to find the 2 files:
30
+
31
+ | File | Prebuilt tools | Build in the repository (run in `gui/web`) |
32
+ | -------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------- |
33
+ | `vehicle-sil-gui-client.mjs` | `<tools>/client/vehicle-sil-gui-client.mjs` | `npm run build:client` creates `build/gui-client/vehicle-sil-gui-client.mjs` |
34
+ | `vehicle-sil-gui-client-<version>.tgz` | `<tools>/client/vehicle-sil-gui-client-<version>.tgz` | `npm run pack:client` creates `build/gui-client/vehicle-sil-gui-client-<version>.tgz` |
35
+
36
+ The releases page has the same `.tgz`. `build/` is the one at the top of the repository and is not tracked in Git.
37
+
38
+ - **Bundled file**: loads in the browser and in Node (22 or later). `scripts/verify-gui.py` runs an example that uses this file from Node against the replay launcher.
39
+ - **Package**: contains the bundled ESM, `.d.ts` files, `exports`, the README and the LICENSE (`pack.mjs` builds it). Its version is the same as the GUI server's. Its types use the browser types (`DOM` in `lib`). The only entry point is `.` (`testing` and `internal` are not included).
40
+
41
+ ## Entry points
42
+
43
+ | Entry point | Name | Contents |
44
+ | ---------------------- | ---------------------------------- | --------------------------------------------------------------------------------------- |
45
+ | `src/index.ts` | `@vehicle-sil/gui-client` | The public API ("Public API" below). Only this entry point is kept compatible |
46
+ | `src/testing/index.ts` | `@vehicle-sil/gui-client/testing` | Test helpers (usable in tests of your own widgets) |
47
+ | `src/internal.ts` | `@vehicle-sil/gui-client/internal` | **No compatibility guarantee.** Internal classes and functions; do not use them in apps |
48
+
49
+ - `testing` contains a fake WebSocket (`FakeWebSockets`), a fake HTTP (`FakeHttp`), loaders for `gui/protocol/examples/`, and `sessionViewFrom`, which builds a `SessionView` from a summary.
50
+ - `internal` contains the internal classes, the functions that apply a summary, and the parsers. They are public for tests only, and change or disappear without notice.
51
+
52
+ The public API is kept small, because adding to it keeps compatibility and removing from it breaks compatibility. If the public entry point lacks something you need, do not reach into `internal`; decide whether to add it to the public API.
53
+
54
+ ## Public API
55
+
56
+ The names that `src/index.ts` exports, by group. Parentheses list the members of the object.
57
+
58
+ ### Client
59
+
60
+ | Kind | Name |
61
+ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
62
+ | Function | `createClient(options)` |
63
+ | Type | `ClientOptions` (`baseUrl`, `token`, `origin`, `http`, `socket`, `answerTimeoutMs`, `onError`) |
64
+ | Type | `GuiClient` (`connection`, `session`, `run`, `time`, `variables`, `app`, `limits`, `connect()`, `close()`, `loadApp()`, `configs()`, `check()`, `fetchSession()`, `dashboard(file)`, `scenarios(file)`, `recording()`) |
65
+ | Constant | `DEFAULT_LIMITS` |
66
+
67
+ ### Token
68
+
69
+ | Kind | Name |
70
+ | -------- | ------------------- |
71
+ | Function | `takeToken(place)` |
72
+ | Type | `TokenPlace` |
73
+ | Constant | `TOKEN_STORAGE_KEY` |
74
+
75
+ In the browser, call `takeToken(window)`. It reads `#token=` from the URL, removes it from the URL and stores it in sessionStorage. If the URL has no token, it returns the one in sessionStorage; if neither has one, it returns `null`.
76
+
77
+ ### Connection (read-only)
78
+
79
+ | Kind | Name |
80
+ | -------- | -------------------------------------------------------------------------------------------------- |
81
+ | Type | `ClientConnection` (`state`, `failures`, `lastClose`, `tryAgainReason`, `onBatch`, `onUnreadable`) |
82
+ | Type | `ConnectionState`, `CloseInfo` |
83
+ | Constant | `BATCH_MS`, `TRY_AGAIN_LATER` |
84
+
85
+ ### Session copy
86
+
87
+ | Kind | Name |
88
+ | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
89
+ | Type | `ClientSession` (`session`, `ready`, `lastEventAt`, `notices`, `rejected`, `incompatible`, `onMessages`, `report`, `dismissNotice`) |
90
+ | Type | `Notice`, `SessionView`, `ParticipantView`, `LauncherView`, `LogLine`, `LogSource`, `TimeView`, `CommandView`, `RunOutcome` |
91
+ | Function | `runOutcome`, `phaseIndex` |
92
+
93
+ ### Run control
94
+
95
+ | Kind | Name |
96
+ | ---- | ------------------------------------------------------------------------------------------------ |
97
+ | Type | `ClientRun` (`starting`, `stopping`, `stopWhileStarting`, `error`, `start`, `stop`, `forceStop`) |
98
+ | Type | `StopAction` |
99
+
100
+ ### Time
101
+
102
+ | Kind | Name |
103
+ | -------- | ---------------------------------------------------------------------------------------- |
104
+ | Type | `ClientTime` (`state`, `answerTimeoutMs`, `pause`, `resume`, `step`, `setSpeed`, `send`) |
105
+ | Type | `TimeState`, `TimeFailure`, `Lateness`, `SendResult`, `NotSentReason` |
106
+ | Constant | `ANSWER_TIMEOUT_MS`, `FEATURE_SPEED`, `FEATURE_START_PAUSED`, `FEATURE_TIME_COMMANDS` |
107
+
108
+ ### ECU variable API
109
+
110
+ | Kind | Name |
111
+ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
112
+ | Type | `ClientVariables` (`state`, `operations`, `watchProblem`, `watch`, `write`, `bind`) |
113
+ | Type | `VariableWatch` (`values`, `value`, `history`, `close`) |
114
+ | Type | `VariablesState`, `VariablesStatus`, `VariablePeer`, `VariableInfo`, `VariableRef`, `VariableValue`, `WatchOptions`, `WatchValues`, `VariableReading`, `HistoryPoint` |
115
+ | Type | `WriteOptions`, `OperationView`, `OperationPeer`, `WatchProblem` |
116
+ | Class | `WriteError` |
117
+ | Constant | `WATCH_PERIOD_MS`, `WATCH_PERIODS_MS`, `WRITE_TIMEOUT_MS`, `HISTORY_MAX`, `HISTORY_TOTAL_MAX`, `OPERATIONS_KEPT` |
118
+
119
+ ### Binding variables to widgets (`bind`)
120
+
121
+ | Kind | Name |
122
+ | -------- | -------------------------------------------------------------------------------------------------------------------- |
123
+ | Method | `client.variables.bind(ref, options)` |
124
+ | Type | `BindOptions` (`periodMs`, `history`, `needsRange`, `needsValue`, `visible`) |
125
+ | Type | `VariableBinding` (`ref`, `state`, `history()`, `write(value)`, `reject(message)`, `setVisible(visible)`, `close()`) |
126
+ | Type | `BoundVariable` (`ref`, `info`, `reading`, `condition`, `block`, `writeStatus`, `pending`) |
127
+ | Type | `ValueCondition`, `WriteBlock`, `WriteStatus`, `WriteValue` |
128
+ | Function | `isWriteError`, `hasRange` |
129
+ | Function | `valueCondition` (`ConditionInput`), `writeBlock` (`WriteBlockInput`) |
130
+ | Constant | `DROPPED_MESSAGE` |
131
+
132
+ `valueCondition`, `writeBlock` and `hasRange` are the pure functions that `bind` builds its state with.
133
+
134
+ ### `Readable` (read-only value)
135
+
136
+ | Kind | Name |
137
+ | ---- | ---------------------------------------- |
138
+ | Type | `Readable<T>` (`get()`, `subscribe(fn)`) |
139
+
140
+ ### APIs for substitution
141
+
142
+ | Kind | Name |
143
+ | -------- | ---------------------------------------------------------------------- |
144
+ | Type | `SocketFactory`, `SocketHandlers`, `SocketLike` |
145
+ | Type | `HttpTransport`, `HttpRequest`, `HttpOutcome`, `FetchTransportOptions` |
146
+ | Function | `webSocketFactory`, `fetchTransport` |
147
+ | Constant | `DEFAULT_TIMEOUT_MS` |
148
+
149
+ ### Errors
150
+
151
+ | Kind | Name |
152
+ | -------- | ----------------------------------------------------------- |
153
+ | Class | `HttpError` (`status`, `statusText`, `problem`, `timedOut`) |
154
+ | Class | `ProtocolError` |
155
+ | Function | `errorMessage` |
156
+
157
+ ### Server API types and parsing
158
+
159
+ Types for the shapes that `gui/protocol` defines, and the parsers to use when you read the server API yourself.
160
+
161
+ | Subject | Name |
162
+ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
163
+ | Types of the `gui/protocol` shapes | `SessionSummary`, `ServerMessage`, `LauncherEvent`, `CheckResult`, `RunResult`, `AppInfo` and others |
164
+ | Constants and functions | `PROTOCOL_VERSION`, `PHASES`, `severityRank` |
165
+ | Parsers | `readServerMessage`, `readAppInfo`, `readConfigList`, `readCheckResponse`, `readSessionResponse`, `readTimeResponse`, `readWriteResponse`, `readVariablesSummary`, `readDashboardResponse`, `readScenarioList`, `readRecording` |
166
+ | Shapes of the variable API | `VariablesSummary`, `VariableSummary`, `ValuesMessage`, `OperationReport`, `WatchMessage`, `WriteAnswer` |
167
+ | Dashboard files (`dashboard(file)`) | `DashboardResponse`, `DashboardFile`, `DashboardFileSection`, `DashboardFileItem`, `DashboardFileError`, `DashboardPanelModule`, `DashboardVariable` |
168
+ | Scenarios (`--scenario`, `scenarios(file)`, `recording()`) | `ScenarioStep`, `ScenarioStepStatus`, `ScenarioStatus`, `CheckScenario`, `ScenarioResult`, `SummaryScenario`, `ScenarioList`, `ScenarioFile`, `Recording`, `FEATURE_SCENARIO`, `FEATURE_SCENARIO_CONTROL` |
169
+ | Request shapes | `CheckRequest`, `RunRequest`, `Speed`, `StopRequest`, `TimeCommand` |
170
+ | List of configuration files | `ConfigList`, `ConfigFile` |
171
+ | Error shape | `ServerProblem` |
172
+ | Findings | `Finding`, `Severity` |
173
+ | Participants you start yourself (`manual`) | `FEATURE_MANUAL` |
174
+ | `SessionView.scenario` of the session copy | `ScenarioView` |
175
+
176
+ ## Basic usage
177
+
178
+ ```ts
179
+ import { createClient, takeToken } from '@vehicle-sil/gui-client';
180
+
181
+ // A screen opened from the URL the server printed (http://127.0.0.1:<port>/#token=<token>): take #token= from the URL and remove it.
182
+ // A Node tool takes baseUrl and the token out of that URL itself and passes them (examples/gui_client).
183
+ const client = createClient({
184
+ baseUrl: new URL('/', location.href).href,
185
+ token: takeToken(window),
186
+ });
187
+ await client.loadApp(); // the launcher's features (whether it has time commands, and so on)
188
+ client.connect();
189
+ const stop = client.session.session.subscribe((session) => {
190
+ if (session?.result) console.log(session.result.result);
191
+ });
192
+ await client.run.start({ file: 'simulation.yaml', disable: [], speed: null, start_paused: false });
193
+ ```
194
+
195
+ ### Read state (`Readable`)
196
+
197
+ Every state is a `Readable` (a read-only value).
198
+
199
+ | Call | What it does |
200
+ | --------------------- | ------------------------------------------------------------------ |
201
+ | `get()` | Returns the current value |
202
+ | `subscribe(fn)` | Notifies `fn` of later changes (not called with the current value) |
203
+ | The returned function | Ends the subscription |
204
+
205
+ - Notifications are synchronous: they arrive inside the code that changed the value.
206
+ - A subscriber that unsubscribes during a notification still receives that notification.
207
+ - If a subscriber changes the same value, every subscriber receives the new value, and the old value does not arrive afterward.
208
+ - A framework wrapper takes the first value with `get()` and converts later values into its own state with `subscribe()` (Angular uses `readableSignal`).
209
+ - If a subscriber (a function passed to `subscribe`, `onBatch`, `onMessages` or `onUnreadable`) throws, the other subscribers are still notified and the library carries on (disconnecting when rejected, rebuilding and so on). The thrown value goes to `onError` (default `console.error`).
210
+ - `client.session.ready` tells whether the session copy is complete (connected, and `hello` and the replay have arrived). Other features (values, for example) have their own ready state.
211
+
212
+ ### Rejections and timeouts
213
+
214
+ - If the token is rejected (for example, because the server was restarted), `client.session.rejected` becomes true (WebSocket), and HTTP requests are rejected with an `HttpError` of status 401.
215
+ - When an operation is rejected, its Promise rejects with an `HttpError`, and the same reason appears in the state (`client.run.error`, `failure` in `client.time.state`).
216
+ - A request waits for its response for up to `DEFAULT_TIMEOUT_MS`. After that it fails with an `HttpError` whose `timedOut` is true (status 0).
217
+ - Start (`run.start()`) and check (`check()`) wait up to twice the check limit (`limits.check_timeout_s`) plus `DEFAULT_TIMEOUT_MS`. The server runs checks one at a time, and both the wait in the queue and the check itself can take up to the check limit; a start also checks the configuration file again if it changed.
218
+ - A timeout is not a rejection: no response came. For a start, the server may have started the run; the session copy (WebSocket) shows whether it did, and `client.run.error` says so.
219
+ - Redirects are not followed.
220
+
221
+ ### Handling unreadable notifications
222
+
223
+ The library parses each part separately.
224
+
225
+ - If part of a summary or an event cannot be read, the library uses the readable parts and adds the names of the unreadable parts to `SessionView.unreadable`.
226
+ - Unknown notifications and events pass through without changing the state (`client.connection.onBatch` receives everything, before parsing).
227
+ - A notification that is not valid JSON raises a notice, and the library receives everything again from `hello`.
228
+
229
+ ### Use from Node, or replace the transport
230
+
231
+ - In Node, the library sends the server's own origin as `Origin` (`createClient` builds it from `baseUrl`).
232
+ - In the browser and in Web Workers, do not pass `origin`: the browser sets it (a Worker's WebSocket cannot set handshake headers).
233
+ - To replace the HTTP implementation, pass `http` (`HttpTransport`); to replace the WebSocket, pass `socket` (`SocketFactory`).
234
+
235
+ For the rules the library does not enforce for you (request fields that match the launcher's `features`, whether a variable is writable, whether a value is stale), see "Rules for building a screen" in [docs/gui.md](../../docs/gui.md#rules-for-building-a-screen).
236
+
237
+ ## ECU variables
238
+
239
+ ```ts
240
+ const watch = client.variables.watch([{ peer: 'Engine', name: 'engine.speed' }], {
241
+ periodMs: 100,
242
+ history: 600,
243
+ });
244
+ watch.values.subscribe((values) => console.log(values['Engine']?.['engine.speed']));
245
+ try {
246
+ const operation = await client.variables.write({ Engine: { 'engine.throttle': 50 } });
247
+ console.log(operation.peers['Engine'].appliedAtMs);
248
+ } catch (error) {
249
+ if (error instanceof WriteError) console.log(error.kind, error.message);
250
+ }
251
+ watch.close();
252
+ ```
253
+
254
+ ### List and state (`client.variables.state`)
255
+
256
+ | `status` | Meaning |
257
+ | ------------ | ---------------------------------------- |
258
+ | `unknown` | Not known yet |
259
+ | `off` | This run has no variables |
260
+ | `connecting` | Connecting |
261
+ | `ready` | Variables can be read and written |
262
+ | `failed` | Could not connect, or was refused |
263
+ | `ended` | The run ended (values are the last ones) |
264
+
265
+ - For `off`, `connecting` and `failed`, `reason` gives the reason, as text from the server (not localized).
266
+ - Before you start a run, `variables` in `client.app` (`available`, `reason`) tells whether variables are available.
267
+ - The variable definitions are `peers[].variables[]` (`type`, `role`, `writable`, `unit`, `min`, `max`, `step`, `description`, `enum`).
268
+
269
+ ### Read values (`watch`)
270
+
271
+ `watch` receives the last values of the given variables (`'all'` for every variable). Always call `close()` when you are done.
272
+
273
+ **Values**: in `values` (a `Readable`), `values[peer]?.[name]` is a `VariableReading` (`value`, `sampleMs`, `simMs`, `paused`). Each value carries the time it belongs to.
274
+
275
+ | `paused` | What the value is |
276
+ | -------- | --------------------------------------------------------------------------------------------------------- |
277
+ | True | The value at the paused time `simMs` (it includes the values of every step that started before that time) |
278
+ | False | The last value while the simulation runs |
279
+
280
+ **Subscriptions**:
281
+
282
+ - However many watches look at a variable, the server has one subscription per variable. A variable joins the subscription with the shortest period requested (periods are rounded to one of 20, 50, 100, 200, 500 ms …).
283
+ - `close()` also ends the server subscription if no other watch looks at the variable.
284
+ - After a reconnection, the library subscribes again automatically.
285
+ - A watch continues across runs; the values and history of the previous run are discarded.
286
+ - Values are kept only for variables that someone is watching.
287
+
288
+ **History** (when you ask for `history`):
289
+
290
+ - For each variable, the library keeps up to that many points (`sampleMs`, `value`) in a ring buffer. The limit per variable is `HISTORY_MAX`; the oldest points are dropped first.
291
+ - Memory is allocated as points arrive, not when you ask.
292
+ - The history of all variables together holds up to `HISTORY_TOTAL_MAX` points (about 34 MB). Once that is reached, no history grows further: each keeps its current size and drops its oldest points (`history(ref)` returns fewer points than you asked for).
293
+ - Values of the same step are one point. If a changed value arrives for the same step, it replaces that point.
294
+ - When the run changes, the history starts empty.
295
+ - `watch.history(ref)` returns a new array on every call.
296
+ - Notifications arrive in batches about every 100 ms (`BATCH_MS`), so `values` notifies at that rate, but the history also holds the values in between.
297
+
298
+ **When a limit is near**:
299
+
300
+ - If you list many long names and one subscription message would exceed the server's limit (256 KiB), the library switches the subscription for that period to "all" (and uses only the watched variables from what arrives).
301
+ - If the server rejects a watch (a server with different limits), the problem appears in `client.variables.watchProblem`.
302
+
303
+ ### Write values (`write`)
304
+
305
+ `write(writes, options)` sends the writes to the run that was current when you called it (`session` in `client.variables.state`, sent as `session` in the body).
306
+
307
+ - The server rejects the writes if that run is no longer running (`session-changed`). A write sent while one run ends and the next starts is therefore never written to the next run.
308
+ - If the run is not known yet, the library does not send and rejects with `refused` (`not-running`).
309
+ - The server checks type and range, then passes the writes to the launcher.
310
+ - The Promise resolves with the operation (`OperationView`) once the writes are applied (`applied`); otherwise it rejects with a `WriteError`.
311
+ - The library never resends a write automatically.
312
+
313
+ The `kind` of a `WriteError`:
314
+
315
+ | `kind` | Meaning | Safe to resend? |
316
+ | ----------- | ------------------------------------------------------------------- | -------------------------------------------------- |
317
+ | `refused` | The server did not accept the write (it did not reach the launcher) | Yes, after you fix it |
318
+ | `failed` | Accepted, but not applied | Yes, after you fix the reason (it was not applied) |
319
+ | `no-answer` | **Unknown whether it was applied** | **Do not resend as is** (see below) |
320
+ | `closed` | `close()` was called before the result | Same as above |
321
+
322
+ - The `code` of `refused` is `unknown-variable`, `not-writable`, `invalid-field`, `not-running`, `session-changed`, `variables-not-ready`, `write-busy` or similar.
323
+ - The `operation` of `failed` holds the state and reason for each participant (`late`, `rejected`, `invalid` and others).
324
+ - `no-answer` happens in any of these cases:
325
+ - No result came within `timeoutMs` (`operation` holds the last known state).
326
+ - There was no HTTP response.
327
+ - The server failed midway (500).
328
+ - The server gave up waiting for the Control Server's response (`code` is `write-timeout`) or was disconnected midway (`write-failed`).
329
+ - The run changed before the response.
330
+ - The operation completed during a reconnection and the result was lost ("Reconnection" below).
331
+ - The server could not keep track of all open operations and stopped following this one.
332
+
333
+ **Avoid writing twice**: after `no-answer`, check before you resend.
334
+
335
+ - If `error.operation` is set, follow the operation with that number in `client.variables.operations`. If it is `queued`, it is applied once the simulation reaches that step (the wait was only too short).
336
+ - If there is no number, look in `operations` for a new operation that looks like your write, and look at the variable's value (watch).
337
+ - Resend only once you know that the write was not applied.
338
+ - This matters most for writes that add to a value (writing twice gives a different result). Writing the same value twice gives the same result.
339
+
340
+ **Reconnection**: if the connection drops while you wait for a result, the summary after reconnecting (`hello`, `fetchSession()`) tells how it went on. The summary holds every open operation the server keeps, and every operation whose number is `operations_from_seq` or higher.
341
+
342
+ | Your operation | What the library does |
343
+ | ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
344
+ | In the list | Uses its state (if still open, keeps waiting) |
345
+ | Not in the list, number below `operations_from_seq` | Treats it as completed while disconnected with its result lost: `no-answer` |
346
+ | Not in the list, and the server could not keep all open operations | Sets the old operations to `no-answer` |
347
+
348
+ - A write that has not been applied yet (for example, a write while paused) never becomes `no-answer` however many operations follow it.
349
+ - "The server could not keep all open operations" means more than 256 open operations (`operations_open_omitted` in the summary). The server no longer follows them, so the library reports `no-answer`, and the error message says why.
350
+
351
+ **Options and related state**:
352
+
353
+ - `onAccepted` (a function that receives `{session, seq}`) is called once, when the server has received the write and returned the operation number. This is before the result. It is not called when the write is rejected or no response comes.
354
+ - Use `onAccepted` to show "accepted, waiting to be applied", and to know when you may send the next write. Writes through `bind` use it: a next value that comes before the server has received the previous write is kept instead of sent, and only the last value is sent once the server has it.
355
+ - `timeoutMs` (default `WRITE_TIMEOUT_MS`) counts from the HTTP response. `Infinity` sets no time limit (the write waits until the run changes or `close()` is called). Values above 2^31-1 ms (about 24.8 days) are capped there. Non-numbers and values of 0 or less mean the default.
356
+ - A write is applied in the step at the given virtual time (`atMs`; if omitted, the next step), so it does not complete while the simulation is paused. To write while paused, wait for `queued` in `client.variables.operations` before you advance (`examples/gui_client/variables.mjs`).
357
+ - `client.variables.operations` lists recent operations, including writes from other clients.
358
+
359
+ ### Write before the first step
360
+
361
+ A run started paused (`start_paused`) waits before the first step if the launcher can read and write variables. Meanwhile `beforeStart` in `client.time.state` is true, and you can resume and step (written values are applied in the step at time 0).
362
+
363
+ ## Build widgets (`bind`)
364
+
365
+ For a widget that shows and writes one variable, such as a slider, a switch or a lamp, use `client.variables.bind(ref, options)` instead of combining `watch` and `write` yourself. It puts the value condition, whether the variable can be written and why not, and the write status into one `Readable` (`state`).
366
+
367
+ ```ts
368
+ const throttle = client.variables.bind(
369
+ { peer: 'Engine', name: 'engine.throttle' },
370
+ { needsRange: true, needsValue: true },
371
+ );
372
+ throttle.state.subscribe(({ info, reading, pending, block, writeStatus, condition }) => {
373
+ slider.disabled = block !== null; // block: why it cannot be written now; null if it can
374
+ slider.value = String(pending ?? reading?.value ?? info?.min ?? 0); // pending: the value sent and waiting for its result
375
+ status.textContent = isWriteError(writeStatus) ? writeStatus.message : writeStatus.kind;
376
+ stale.hidden = condition.kind === 'live';
377
+ });
378
+ slider.onchange = () => throttle.write(Number(slider.value));
379
+ // when you are done
380
+ throttle.close();
381
+ ```
382
+
383
+ Always call `close()` when you are done (it cleans up the watch and the subscriptions).
384
+
385
+ ### Fields of `state` (`BoundVariable`)
386
+
387
+ | Field | Contents |
388
+ | ------------- | ------------------------------------------------------------------------------------------------ |
389
+ | `info` | The variable definition (`undefined` if the current run does not have the variable) |
390
+ | `reading` | The last value (`VariableReading`; `undefined` if there is none yet or while `visible` is false) |
391
+ | `condition` | The value condition ("Value condition (`condition`)" below) |
392
+ | `block` | Why the variable cannot be written now ("Why a write is blocked (`block`)" below) |
393
+ | `writeStatus` | The status of the last write ("Write status (`writeStatus`, `pending`)" below) |
394
+ | `pending` | The value sent and still waiting for its result (`null` if none) |
395
+
396
+ - `subscribe` is called only on changes (get the first state with `state.get()`).
397
+ - `get()` always builds the state from the current values. So if you call `get()` during a notification of another `Readable` (such as `client.variables.state`), it may notify this `state`'s subscribers of a new state right there.
398
+
399
+ ### Value condition (`condition`)
400
+
401
+ Switch on `condition.kind`.
402
+
403
+ | `kind` | Meaning |
404
+ | ------------- | -------------------------------------------------------------------------------------------- |
405
+ | `unavailable` | The variable feature is not available (`status` holds the state of `client.variables.state`) |
406
+ | `missing` | The current run does not have the variable |
407
+ | `waiting` | The current run has the variable, but no value has arrived yet |
408
+ | `live` | The last value while the simulation runs |
409
+ | `paused` | The value at the paused time |
410
+ | `stale` | A value that may be stale (the reason is in `why`) |
411
+ | `ended` | The last value read in a run that ended |
412
+
413
+ The `status` of `unavailable` is one of: not running, this run has no variables, connecting, cannot connect. The values of `why` for `stale`:
414
+
415
+ | `why` | Meaning |
416
+ | -------------- | -------------------------------------------------------- |
417
+ | `connection` | The connection between the client and the server dropped |
418
+ | `reconnecting` | The server is reconnecting to the launcher |
419
+ | `peer` | The ECU is disconnected |
420
+ | `reading` | Reading values keeps failing |
421
+
422
+ ### Why a write is blocked (`block`)
423
+
424
+ `null` if the variable can be written. If several reasons apply, `block` is the one highest in the table.
425
+
426
+ | `block` | Meaning |
427
+ | ------------------- | ---------------------------------------------------------------------------------------------------------------------- |
428
+ | `read-only` | A read-only variable (`role` is `output`) |
429
+ | `disconnected` | The connection between the client and the server is down |
430
+ | `ended` | The run ended |
431
+ | `not-ready` | The variable feature is not available (not running, connecting, cannot connect) |
432
+ | `missing` | The current run does not have the variable |
433
+ | `peer-disconnected` | The ECU is not connected to the Control Server |
434
+ | `parameter` | A `parameter` can be written only before the first step of a run started paused (`beforeStart` in `client.time.state`) |
435
+ | `scenario` | A scenario is running (view only) |
436
+ | `no-range` | `needsRange` is set, but the variable has no range (`min` and `max`) |
437
+ | `no-value` | `needsValue` is set, and there is no value yet (neither read nor sent) |
438
+
439
+ ### Write status (`writeStatus`, `pending`)
440
+
441
+ `writeStatus` is the status of the last write.
442
+
443
+ | `writeStatus` | Meaning |
444
+ | ------------------------------------------ | -------------------------------------------------------------- |
445
+ | `idle` | Empty (no last write) |
446
+ | `sending` | Sent |
447
+ | `queued` | The server received it (`seq` is the operation number) |
448
+ | `applied` | Applied (`atMs`) |
449
+ | `invalid` | The text passed to `reject(message)` (not sent) |
450
+ | `dropped` | A kept value was not sent ("How `write(value)` behaves" below) |
451
+ | `refused`, `failed`, `no-answer`, `closed` | The `kind` of a `WriteError` (has `message` and `code`) |
452
+
453
+ - `isWriteError(writeStatus)` picks out the statuses that have a `message` (the ones that did not succeed).
454
+ - `message` is not localized. To show it in the screen's language, build the text from `kind`.
455
+ - If `pending` is set, show it instead of the read value (so a switch you clicked does not appear to flip back while it waits for the result).
456
+
457
+ ### How `write(value)` behaves
458
+
459
+ - If the variable cannot be written (`block`), it does nothing.
460
+ - It returns no Promise; the result appears in `writeStatus`.
461
+ - It waits for the operation's result with no time limit (a write while paused stays `queued` until the simulation advances).
462
+ - While the server has not yet received the previous write (`sending`), it keeps only the last of the next values instead of sending them, and sends it once the previous write is received (so a dragged slider or repeated keys do not pile up writes).
463
+ - Before it sends a kept value, it checks again that the run is the same and the variable is still writable; if not, it does not send and sets `dropped`.
464
+ - If the previous write is rejected before it is received, the kept value is not sent either.
465
+ - A write that got no result (`no-answer`) is never resent automatically.
466
+ - `reject(message)` reports an error that the widget found before sending (not a number, out of range) as `invalid`. It does not touch the write in flight, the kept value or `pending`.
467
+
468
+ ### One state per variable
469
+
470
+ - However many places `bind` the same variable, they all see the same `writeStatus` and `pending`, and writes do not overlap.
471
+ - The state survives closing a `bind` and creating it again.
472
+ - The state belongs to the run: when the run changes, it starts empty (`idle`, `null`) and shows no results of writes from the previous run.
473
+
474
+ ### Watch only while visible
475
+
476
+ `bind` receives values from the moment you create it (as with `watch`, the server has one subscription per variable). On a screen with many widgets, create it with `{ visible: false }`, call `setVisible(true)` when it becomes visible (IntersectionObserver or similar) and `setVisible(false)` when it is hidden. While `visible` is false:
477
+
478
+ | Field | While `visible` is false |
479
+ | ------------------------ | --------------------------------------------------------------------------------------------------- |
480
+ | `reading` | `undefined` |
481
+ | `condition` | `waiting` |
482
+ | `writeStatus`, `pending` | Reported as usual |
483
+ | `block` | Reported as usual (a `bind` with `needsValue` reports `no-value` unless there is a `pending` value) |
484
+
485
+ ### History
486
+
487
+ If you create it with `{ history: 600 }`, `history()` returns the points, oldest first. `state` notifies every time a point is added; read the history again there.
488
+
489
+ ### What is not checked, and after `close()`
490
+
491
+ - `write(value)` sends without checking the value's type and range. The server rejects a value that does not fit, and `writeStatus` becomes `refused`. To check first and show a message, check in the widget and call `reject(message)`.
492
+ - After `close()`, `write`, `reject` and `setVisible` do nothing.
493
+ - `close()` does not cancel writes already sent or the kept value. The kept value is sent once the previous write is received (the state belongs to the variable, so the next `bind` of the same variable sees it).
494
+
495
+ ## Lifecycle
496
+
497
+ | Call | What it does |
498
+ | --------------------------------------------------- | ----------------------------------------------------------------------------- |
499
+ | `createClient()` | Only creates the client; does not connect |
500
+ | `connect()` | Connects over WebSocket (does nothing without a token) |
501
+ | `connect()` while connected | Does nothing (also while waiting to reconnect) |
502
+ | `close()` | Disconnects and does not reconnect (what it cleans up is below) |
503
+ | `connect()` after `close()` | Connects again and subscribes the remaining watches again |
504
+ | HTTP requests after `close()` | Work (`loadApp()`, `run.start()` and others can be sent without a connection) |
505
+ | `connect()` after a rejection or a version mismatch | Does nothing (`session.rejected` and `session.incompatible` do not reset) |
506
+
507
+ - `close()` stops pending timers, stops waiting for responses to time commands, and rejects writes waiting for results with a `WriteError` (`closed`). Notifications in a batch being collected are discarded. Variable watches remain.
508
+ - After `close()` and `connect()`, the session copy is still there, and the library receives again from where its copy ends.
509
+ - To connect with another token or version, create a new client.
510
+
511
+ ## Coding rules
512
+
513
+ - Import nothing outside this library's own files (`eslint.config.js` blocks it; it also blocks dynamic `import()` except in the test helpers; `rootDir` in `tsconfig.json` blocks anything outside `src/`).
514
+ - Do not use anything that exists only in the browser (`window`, `document`, `localStorage` and so on). Take what you need through the options (`ClientOptions`).
515
+ - Human-readable text (such as `TimeFailure.message`) is in English. Turning it into the screen's language is the wrapper's job (built from machine-readable fields such as `kind`).
516
+ - When you add to the public API, add it to `src/index.ts` and to the "Public API" tables above, and update [Build your own screen for the browser GUI](../../docs/howto/gui-screen.md) to match.
517
+
518
+ ## Tests
519
+
520
+ The tools (TypeScript, ESLint, Prettier, Vitest, esbuild) are the ones in `node_modules` of `gui/web`. Run these in `gui/web` (`scripts/verify-web.py` runs them too):
521
+
522
+ | Command | What it does |
523
+ | ---------------------- | ----------------------------------------------------------------------------------------------- |
524
+ | `npm run test:client` | Type check (`tsc -p ../client`) and unit tests (Vitest; runs on Node, without Angular or a DOM) |
525
+ | `npm run build:client` | Bundles into one ESM file (esbuild, the copy that comes with the Angular build tools) |
526
+ | `npm run lint` | `gui/web`, and this directory with its `eslint.config.js` |
527
+ | `npm run format:check` | Formatting of `gui/web` and this directory (`gui/.prettierrc`) |
528
+
529
+ The unit tests feed the examples in `gui/protocol/examples/` instead of building server notifications by hand (`testing/protocol-examples.ts`).
530
+
531
+ ## See also
532
+
533
+ | To find | Document |
534
+ | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
535
+ | How to build your own screen and have the GUI server serve it | [Build your own screen for the browser GUI](../../docs/howto/gui-screen.md) |
536
+ | The server API (HTTP and WebSocket shapes, versioning and compatibility rules, authentication) | [gui/protocol](../protocol/README.md) |
537
+ | The rules the library does not enforce for you | "Rules for building a screen" in [docs/gui.md](../../docs/gui.md#rules-for-building-a-screen) |
538
+ | Files to start your own screen from | The screen template [examples/gui_starter](../../examples/gui_starter/) |
539
+ | An example that uses the library from Node, without a screen | [examples/gui_client](../../examples/gui_client/) |
540
+
541
+ `examples/gui_client` exists only in the repository (the prebuilt tools archive contains `gui_starter/` and `client/`).
542
+
543
+ | File | What it does |
544
+ | ---------------------- | ---------------------------------------------------------- |
545
+ | `run.mjs` | Calls the server API without the library |
546
+ | `run-with-library.mjs` | Uses the bundled library file from plain JavaScript (Node) |
547
+ | `variables.mjs` | Also uses the library, to read and write ECU variables |