@vehicle-sil/gui-client 0.4.0 → 0.6.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.
Files changed (37) hide show
  1. package/README.ja.md +452 -730
  2. package/README.md +452 -728
  3. package/dist/elements.js +656 -47
  4. package/dist/empty.js +2 -0
  5. package/dist/index.js +3362 -1721
  6. package/package.json +13 -1
  7. package/timeline/vehicle-sil-timeline.d.ts +76 -0
  8. package/timeline/vehicle-sil-timeline.js +817 -139
  9. package/timeline/vehicle-sil-timeline.mjs +817 -139
  10. package/types/client.d.ts +24 -3
  11. package/types/connection.d.ts +10 -2
  12. package/types/elements/contracts.d.ts +112 -0
  13. package/types/elements/index.d.ts +5 -3
  14. package/types/elements/outside-parts.d.ts +5 -0
  15. package/types/elements/page-intent.d.ts +1 -1
  16. package/types/elements/part.d.ts +11 -4
  17. package/types/elements/run-parts.d.ts +19 -0
  18. package/types/elements/scenario-parts.d.ts +5 -1
  19. package/types/elements/variable-parts.d.ts +58 -11
  20. package/types/frameworks/all-contracts.d.ts +18 -0
  21. package/types/frameworks/react.d.ts +40 -0
  22. package/types/frameworks/svelte.d.ts +22 -0
  23. package/types/frameworks/vue.d.ts +35 -0
  24. package/types/front-actions.d.ts +18 -0
  25. package/types/front-types.d.ts +67 -6
  26. package/types/front-variable.d.ts +5 -0
  27. package/types/front.d.ts +11 -24
  28. package/types/http.d.ts +4 -0
  29. package/types/index.d.ts +5 -5
  30. package/types/protocol/launcher.d.ts +87 -1
  31. package/types/protocol/server.d.ts +44 -1
  32. package/types/session-state.d.ts +15 -1
  33. package/types/session.d.ts +8 -2
  34. package/types/time.d.ts +8 -0
  35. package/types/variable-binding.d.ts +9 -3
  36. package/types/variable-state.d.ts +5 -0
  37. package/types/variables.d.ts +113 -48
package/README.md CHANGED
@@ -1,310 +1,85 @@
1
- # gui/client
1
+ # gui/client (`@vehicle-sil/gui-client`)
2
2
 
3
3
  [日本語](README.ja.md)
4
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.
5
+ Zero-dependency TypeScript client library and custom elements for the `vehicle-sil-gui` server. Runs in browsers and Node.js 22+.
6
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/`).
7
+ Use this page for onboarding, choosing between `connect()` and `createFront()`, high-level recipes, and embedding the 12 `vsil-*` custom elements across Vanilla JS/TS, Angular, React, Vue, and Svelte. For the low-level `createClient()` API, `variables.bind()`, full export tables, wire-adjacent details, and contributor tests, see [docs/gui-client-low-level.md](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui-client-low-level.md).
8
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
- | What a screen shows and which buttons work: `connect()` | [The front door (`connect()`)](#the-front-door-connect) |
16
- | The elements to put in HTML, with no script | [Parts (custom elements)](#parts-custom-elements) |
17
- | Building sliders and lamps (the values of `condition` and `block`) | [Build widgets (`bind`)](#build-widgets-bind) |
18
- | What happens after `connect()` and `close()` | [Lifecycle](#lifecycle) |
19
- | Developing the library | [Coding rules](#coding-rules), [Tests](#tests) |
9
+ ## Contents
20
10
 
21
- ## Installing and importing
22
-
23
- The library is TypeScript source with no dependencies. Each release publishes it on the npm registry as `@vehicle-sil/gui-client` (the dist-tag `latest` is the newest release, `next` the newest pre-release) and attaches the same package to the release as `vehicle-sil-gui-client-<version>.tgz`. Install the version of your GUI server: the client refuses a server that speaks another version of the GUI protocol.
24
-
25
- | Use | How to get it | Import |
26
- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
27
- | A page that the GUI server serves (`--web`) | Nothing to copy: the server serves the files (below) | `import { connect } from '/vsil/vehicle-sil-gui-client.mjs'` |
28
- | Plain JavaScript, outside such a page | Put `vehicle-sil-gui-client.mjs`, the library bundled into one ESM file, next to your script | `import { connect } from './vehicle-sil-gui-client.mjs'` |
29
- | TypeScript and any framework | Run `npm install @vehicle-sil/gui-client@<version>` in your project (or `npm install <the release's .tgz>`) | `import { connect } from '@vehicle-sil/gui-client'` |
30
- | 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'` |
31
-
32
- Where to find the 3 files:
33
-
34
- | File | Prebuilt tools | Build in the repository (run in `gui/web`) |
35
- | -------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------- |
36
- | `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` |
37
- | `vehicle-sil-gui-elements.mjs` | `<tools>/client/vehicle-sil-gui-elements.mjs` | `npm run build:client` creates `build/gui-client/vehicle-sil-gui-elements.mjs` |
38
- | `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` |
39
-
40
- The releases page has the same `.tgz`. `build/` is the one at the top of the repository and is not tracked in Git.
41
-
42
- The GUI server also serves the two `.mjs` files, without the token, as `/vsil/vehicle-sil-gui-client.mjs` and `/vsil/vehicle-sil-gui-elements.mjs` (in the repository, from `build/gui-client/`; it says what to run when they are not built). A screen without a build can load them from there and copy nothing.
43
-
44
- - **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.
45
- - **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`). Its entry points are `.`, `./elements` and `./timeline` (`testing` and `internal` are not included).
46
-
47
- ## Entry points
48
-
49
- | Entry point | Name | Contents |
50
- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
- | `src/index.ts` | `@vehicle-sil/gui-client` | The public API ("Public API" below). This entry point and `./elements` are kept compatible |
52
- | `src/testing/index.ts` | `@vehicle-sil/gui-client/testing` | Test helpers (usable in tests of your own widgets) |
53
- | `src/internal.ts` | `@vehicle-sil/gui-client/internal` | **No compatibility guarantee.** Internal classes and functions; do not use them in apps |
54
- | `src/elements/index.ts` (in the package as `dist/elements.js`, which imports `dist/index.js`) | `@vehicle-sil/gui-client/elements` | The parts (custom elements `<vsil-status>` and 10 more), `pageIntent` and `setReasonText`: importing it defines them ("Parts (custom elements)" below). It needs a DOM; the main entry does not import it |
55
- | `../timeline/vehicle-sil-timeline.js` (in the package as `timeline/vehicle-sil-timeline.mjs`, with `export {}`) | `@vehicle-sil/gui-client/timeline` | The element `<vehicle-sil-timeline>`, with its types: importing it defines the element ("Putting a timeline on your own screen" in [docs/gui.md](../../docs/gui.md#putting-a-timeline-on-your-own-screen)) |
56
-
57
- - `testing` contains a fake WebSocket (`FakeWebSockets`), a fake HTTP (`FakeHttp`), loaders for `gui/protocol/examples/`, and `sessionViewFrom`, which builds a `SessionView` from a summary.
58
- - `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.
59
-
60
- 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.
61
-
62
- ## Live waveforms and variable editing
63
-
64
- `createWaveforms` returns live histories in selection order. Signals shared by two selections keep their history, and a new run clears the histories. It keeps up to 600 points per signal by default. The screen draws the points and handles cross-tab synchronization.
65
-
66
- `createVariableEditor` exposes the variable definition, display value and write outcome in `state`. It validates numeric, Boolean and enum edits against the definition. After a Boolean edit is applied, it waits for readback for up to 500 ms before accepting another edit. Set visibility to subscribe to values, and call `close()` on both parts when done.
67
-
68
- ```ts
69
- import { connect, createVariableEditor, createWaveforms } from '@vehicle-sil/gui-client';
70
-
71
- const front = await connect();
72
- const ref = { peer: 'Engine', name: 'engine.throttle' };
73
- const waves = createWaveforms(front.low, { periodMs: 20 });
74
- waves.setSignals([ref]);
75
- const editor = createVariableEditor(front, ref);
76
- editor.setVisible(true);
77
- // Render waves.series and editor.state. Call editor.write(value) on commit.
78
- ```
79
-
80
- ## Public API
81
-
82
- The names that `src/index.ts` exports, by group. Parentheses list the members of the object.
83
-
84
- ### Client
85
-
86
- | Kind | Name |
87
- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
88
- | Function | `createClient(options)` |
89
- | Type | `ClientOptions` (`baseUrl`, `token`, `origin`, `http`, `socket`, `answerTimeoutMs`, `onError`) |
90
- | Type | `GuiClient` (`connection`, `session`, `run`, `time`, `variables`, `app`, `limits`, `connect()`, `close()`, `loadApp()`, `configs()`, `config(file)`, `check()`, `describe()`, `saveConfig()`, `prepare()`, `connections()`, `dashboard(file)`, `scenarios(file)`, `recording()`) |
91
- | Constant | `DEFAULT_LIMITS` |
92
-
93
- ### Front door
94
-
95
- | Kind | Name |
96
- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
97
- | Function | `connect(options?)`, `createFront(options)`, `watch(source, fn)`, `until(source, test, options?)` |
98
- | Class | `ActionError` (`code`, `message`, `outcome`, `findings`) |
99
- | Type | `ConnectOptions` (`base_url`, `token`, `origin`, `http`, `socket`, `answer_timeout_ms`, `on_error`), `Front` (`low`, `status`, `clock`, `controls`, `scenario`, `runtime`, `outside`, `prepare()`, `configs()`, `recording()`, `run`, `time`, `variable()`, `scenarios()`, `connections()`, `check()`, `readConfig()`, `describeAgain()`, `saveConfig()`, `close()`), `FrontStatus`, `FrontResult`, `FrontClock`, `FrontControls`, `Control`, `Reason`, `FrontScenario`, `FrontRun`, `FrontTime`, `FrontVariable`, `VariableView`, `Intent`, `Outside`, `ConnectEntry`, `ConnectTarget`, `ConnectListError`, `Link`, `RunState`, `EndKind`, `Pacing`, `OperationName`, `RuntimeStatus` |
100
-
101
- ### Token
102
-
103
- | Kind | Name |
104
- | -------- | ------------------- |
105
- | Function | `takeToken(place)` |
106
- | Type | `TokenPlace` |
107
- | Constant | `TOKEN_STORAGE_KEY` |
108
-
109
- 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`. When connecting to a server started with `--no-auth`, `token` may be omitted or `null` (against a server with token authentication enabled, HTTP requests reject with 401 and WebSocket sets `rejected`).
110
-
111
- ### Connection (read-only)
112
-
113
- | Kind | Name |
114
- | -------- | -------------------------------------------------------------------------------------------------- |
115
- | Type | `ClientConnection` (`state`, `failures`, `lastClose`, `tryAgainReason`, `onBatch`, `onUnreadable`) |
116
- | Type | `ConnectionState`, `CloseInfo` |
117
- | Constant | `BATCH_MS`, `TRY_AGAIN_LATER` |
118
-
119
- ### Session copy
120
-
121
- | Kind | Name |
122
- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
123
- | Type | `ClientSession` (`session`, `currentTarget`, `currentInstance`, `ready`, `allowed`, `runtime`, `lastEventAt`, `notices`, `rejected`, `incompatible`, `onMessages`, `report`, `dismissNotice`) |
124
- | Type | `Notice`, `SessionView`, `ParticipantView`, `LauncherView`, `LogLine`, `LogSource`, `TimeView`, `CommandView`, `RunOutcome`, `LauncherAnswer` |
125
- | Function | `runOutcome`, `phaseIndex`, `isHolding`, `launcherAnswer` |
126
-
127
- `ClientSession.allowed` is what the GUI server accepts now (`start`, `stop`, `force` and `save`, each with `ok`, a `reason` code and a `message`; `null` until the server says). `SessionView.launcherState` is the launcher's last `state` event (where the run stands and what it accepts; the larger `rev` wins; `null` until one arrives). `launcherAnswer(launcherState, name)` reads what it says of one operation (`write`, `pause`, ...): `reason` (`null` when the launcher accepts it) and `caution`. A launcher that has not said (no `state` yet, or no entry for the operation) does not accept it (`unsupported`). The front door's `controls` and `variables.bind` read the launcher with it.
128
-
129
- Ordered notifications (`session`, `event`, `allowed`, `runtime`, `variables`, `availability`, `operation`, `error`, `dropped`, `synced`) arrive over the single WebSocket stream ordered by `(instance, run_id, stream_seq)`. HTTP mutation endpoints (`api/run`, `api/stop-session`, `api/prepare`, `api/time`, `api/write`) return lightweight acknowledgements while state updates arrive on the WebSocket stream.
130
-
131
- The `currentTarget()` method returns the current `{run_id, instance}` pair, or `null` when it is unknown. `currentInstance()` returns the last authenticated server instance even if no run exists, and retains it while disconnected. On reconnect to the same instance and run, the client sends `{instance, run_id, after_stream_seq}` so the server resends only log events after that cursor; when the server instance changes, it starts fresh from the new `hello`.
132
-
133
- ### Run control
134
-
135
- | Kind | Name |
136
- | ---- | ------------------------------------------------------------------------------------------------------------------- |
137
- | Type | `ClientRun` (`starting`, `stopping`, `currentStopping`, `stopWhileStarting`, `error`, `start`, `stop`, `forceStop`) |
138
- | Type | `StopAction` |
139
-
140
- `currentStopping` reports only pending stops of the current session or current start; `stopping` includes stops for earlier runs. Stop and force stop target the known session and instance. A confirmation can pass the captured pair to `front.run.forceStop(target)`; the action is refused if the target has changed or a new start is pending. A stop requested during this client’s start waits for its answer; if that answer is lost, the stop is not sent and the error says so. Check the current session before retrying. An old server without targeted stop is rejected; overlapping starts on one client are rejected.
141
-
142
- ### Time
143
-
144
- | Kind | Name |
145
- | -------- | ---------------------------------------------------------------------------------------- |
146
- | Type | `ClientTime` (`state`, `answerTimeoutMs`, `pause`, `resume`, `step`, `setSpeed`, `send`) |
147
- | Type | `TimeState`, `TimeFailure`, `Lateness`, `SendResult`, `NotSentReason` |
148
- | Constant | `ANSWER_TIMEOUT_MS` |
149
-
150
- Both `front.time` and `client.time` send commands with the known run ID and server instance. If the run is replaced, the server rejects the command before sending it to a launcher. Older servers that do not accept these fields reject the request.
151
-
152
- A screen can pass the `RunTarget` it captured when rendering a control to `front.time`. The client rejects the action if that target no longer matches the current run.
153
-
154
- ### ECU variable API
155
-
156
- | Kind | Name |
157
- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
158
- | Type | `ClientVariables` (`state`, `operations`, `watchProblem`, `watch`, `write`, `bind`) |
159
- | Type | `VariableWatch` (`values`, `value`, `history`, `close`) |
160
- | Type | `VariablesState`, `VariablesStatus`, `VariablePeer`, `VariableInfo`, `VariableRef`, `VariableValue`, `WatchOptions`, `WatchValues`, `VariableReading`, `HistoryPoint` |
161
- | Type | `WriteOptions`, `OperationView`, `OperationPeer`, `WatchProblem` |
162
- | Class | `WriteError` |
163
- | Constant | `WATCH_PERIOD_MS`, `WATCH_PERIODS_MS`, `WRITE_TIMEOUT_MS`, `HISTORY_MAX`, `HISTORY_TOTAL_MAX`, `OPERATIONS_KEPT` |
11
+ - [Installing and importing](#installing-and-importing)
12
+ - [Choosing `connect()`, `createFront()`, or `createClient()`](#choosing-connect-createfront-or-createclient)
13
+ - [The front door (`connect()`)](#the-front-door-connect)
14
+ - [Recipes](#recipes)
15
+ - [Parts (custom elements)](#parts-custom-elements)
16
+ - [Framework setup (5 frameworks)](#framework-setup-5-frameworks)
17
+ - [Low-level API and see also](#low-level-api-and-see-also)
164
18
 
165
- ### Binding variables to widgets (`bind`)
166
-
167
- | Kind | Name |
168
- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
169
- | Method | `client.variables.bind(ref, options)` |
170
- | Type | `BindOptions` (`periodMs`, `history`, `needsRange`, `needsValue`, `visible`) |
171
- | Type | `VariableBinding` (`ref`, `state`, `history()`, `write(value)`, `reject(message)`, `setVisible(visible)`, `close()`) |
172
- | Type | `BoundVariable` (`ref`, `info`, `reading`, `condition`, `block`, `launcherReason` (a `Reason`), `writeStatus`, `pending`) |
173
- | Type | `ValueCondition`, `WriteBlock`, `WriteStatus`, `WriteValue` |
174
- | Function | `isWriteError`, `hasRange` |
175
- | Function | `valueCondition` (`ConditionInput`), `writeBlock` (`WriteBlockInput`) |
176
- | Constant | `DROPPED_MESSAGE` |
177
-
178
- `valueCondition`, `writeBlock` and `hasRange` are the pure functions that `bind` builds its state with.
179
-
180
- ### `Readable` (read-only value)
181
-
182
- | Kind | Name |
183
- | ---- | ---------------------------------------- |
184
- | Type | `Readable<T>` (`get()`, `subscribe(fn)`) |
185
-
186
- ### APIs for substitution
187
-
188
- | Kind | Name |
189
- | -------- | ---------------------------------------------------------------------- |
190
- | Type | `SocketFactory`, `SocketHandlers`, `SocketLike` |
191
- | Type | `HttpTransport`, `HttpRequest`, `HttpOutcome`, `FetchTransportOptions` |
192
- | Function | `webSocketFactory`, `fetchTransport` |
193
- | Constant | `DEFAULT_TIMEOUT_MS` |
194
-
195
- ### Errors
196
-
197
- | Kind | Name |
198
- | -------- | ----------------------------------------------------------- |
199
- | Class | `HttpError` (`status`, `statusText`, `problem`, `timedOut`) |
200
- | Class | `ProtocolError` |
201
- | Function | `errorMessage` |
202
-
203
- ### Server API types and parsing
204
-
205
- Types for the shapes that `gui/protocol` defines, and the parsers to use when you read the server API yourself.
206
-
207
- | Subject | Name |
208
- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
209
- | Types of the `gui/protocol` shapes | `SessionSummary`, `ServerMessage`, `LauncherEvent`, `CheckResult`, `RunResult`, `AppInfo` and others |
210
- | Constants and functions | `PROTOCOL_VERSION`, `PHASES`, `severityRank` |
211
- | Parsers | `readServerMessage`, `readAppInfo`, `readConfigList`, `readConfigText`, `readSavedConfig`, `readCheckResponse`, `readConnections`, `readSessionResponse`, `readTimeResponse`, `readWriteResponse`, `readVariablesSummary`, `readDashboardResponse`, `readScenarioList`, `readRecording` |
212
- | Shapes of the variable API | `VariablesSummary`, `VariableSummary`, `ValuesMessage`, `OperationReport`, `WatchMessage`, `WriteAnswer` |
213
- | Dashboard files (`dashboard(file)`) | `DashboardResponse`, `DashboardFile`, `DashboardFileSection`, `DashboardFileItem`, `DashboardFileError`, `DashboardPanelModule`, `DashboardVariable` |
214
- | Scenarios (`--scenario`, `scenarios(file)`, `recording()`) | `ScenarioStep`, `ScenarioStepStatus`, `ScenarioStatus`, `CheckScenario`, `ScenarioResult`, `SummaryScenario`, `ScenarioList`, `ScenarioFile`, `Recording` |
215
- | Request shapes | `CheckRequest`, `CheckTextRequest`, `DescribeRequest`, `SaveConfigRequest`, `RunRequest`, `ConnectionsRequest`, `Speed`, `StopRequest`, `TimeCommand` |
216
- | List of configuration files | `ConfigList`, `ConfigFile`, `ConfigText`, `SavedConfig` |
217
- | Error shape | `ServerProblem` |
218
- | Findings | `Finding`, `Severity` |
219
- | The launcher's keys and traffic | `FromLauncher`, `LauncherFields`, `RunTraffic`, `TrafficNetwork`, `TrafficParticipant`, `TrafficUnplaced`, `ParticipantRole`, `OutsideState` |
220
- | `SessionView.scenario` of the session copy | `ScenarioView` |
221
-
222
- ## Basic usage
223
-
224
- This is the lower door of the library, `createClient`, which the front door is built on (it is `client.low` there). A screen starts with `connect()` and the parts ("The front door (`connect()`)" and "Parts (custom elements)" below) and uses this door for what they do not cover: events, logs, findings, participants and `bind`.
225
-
226
- ```ts
227
- import { createClient, takeToken } from '@vehicle-sil/gui-client';
228
-
229
- // 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.
230
- // A Node tool takes baseUrl and the token out of that URL itself and passes them (examples/gui_client, in a clone of the repository).
231
- const client = createClient({
232
- baseUrl: new URL('/', location.href).href,
233
- token: takeToken(window),
234
- });
235
- await client.loadApp(); // the server's information (the start-up file, the limits, whether variables are available)
236
- client.connect();
237
- const stop = client.session.session.subscribe((session) => {
238
- if (session?.result) console.log(session.result.result);
239
- });
240
- await client.run.start({ file: 'simulation.yaml', disable: [] });
241
- ```
242
-
243
- ### Read state (`Readable`)
244
-
245
- Every state is a `Readable` (a read-only value).
246
-
247
- | Call | What it does |
248
- | --------------------- | ------------------------------------------------------------------ |
249
- | `get()` | Returns the current value |
250
- | `subscribe(fn)` | Notifies `fn` of later changes (not called with the current value) |
251
- | The returned function | Ends the subscription |
19
+ ## Installing and importing
252
20
 
253
- - Notifications are synchronous: they arrive inside the code that changed the value.
254
- - A subscriber that unsubscribes during a notification still receives that notification.
255
- - If a subscriber changes the same value, every subscriber receives the new value, and the old value does not arrive afterward.
256
- - A framework wrapper takes the first value with `get()` and converts later values into its own state with `subscribe()` (an Angular signal is shown in "[A project with a framework](../../examples/gui_starter/README.md#a-project-with-a-framework)"; the package has no framework code).
257
- - 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`).
258
- - `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.
21
+ Each release publishes `@vehicle-sil/gui-client` on npm (`latest` for releases, `next` for pre-releases) and attaches `vehicle-sil-gui-client-<version>.tgz` to the release and prebuilt tools archive. Install the same version as your GUI server: the client refuses a server speaking another GUI protocol version.
259
22
 
260
- ### Rejections and timeouts
23
+ | Use | How to get it | Import |
24
+ | ---------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------ |
25
+ | A page served by `vehicle-sil-gui --web` | Nothing to copy: served by the GUI server under `/vsil/` | `import { connect } from '/vsil/vehicle-sil-gui-client.mjs'` |
26
+ | Plain JavaScript outside `--web` (or Node 22+) | Copy `vehicle-sil-gui-client.mjs` next to your script | `import { connect } from './vehicle-sil-gui-client.mjs'` |
27
+ | TypeScript or any framework build | `npm install @vehicle-sil/gui-client@<version>` (or `npm install <path>.tgz`) | `import { connect } from '@vehicle-sil/gui-client'` |
261
28
 
262
- - 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.
263
- - 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`).
264
- - 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).
265
- - 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.
266
- - 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.
267
- - Redirects are not followed.
29
+ Where to find the built artifacts:
268
30
 
269
- ### The launcher's keys (`raw`)
31
+ | File | Prebuilt tools | Build in the repository (`gui/web`) |
32
+ | -------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------- |
33
+ | `vehicle-sil-gui-client.mjs` | `<tools>/client/vehicle-sil-gui-client.mjs` | `npm run build:client` -> `build/gui-client/vehicle-sil-gui-client.mjs` |
34
+ | `vehicle-sil-gui-elements.mjs` | `<tools>/client/vehicle-sil-gui-elements.mjs` | `npm run build:client` -> `build/gui-client/vehicle-sil-gui-elements.mjs` |
35
+ | `vehicle-sil-gui-client-<version>.tgz` | `<tools>/client/vehicle-sil-gui-client-<version>.tgz` | `npm run pack:client` -> `build/gui-client/vehicle-sil-gui-client-<version>.tgz` |
270
36
 
271
- The check result, the run result, findings and launcher events come from the launcher, and the library passes on every key of them. The typed fields (for example `traffic` of the run result, `participants[].log`, and `role` of a check participant) follow the launcher's format versions (`vehicle_sil_check`, `vehicle_sil_run`, `vehicle_sil_events`), not the version of this library. Every object read from the launcher also has `raw`: the launcher's object as it arrived, with the keys the types do not name. `raw` is read-only and not enumerable (`JSON.stringify` and spreading leave it out). Its values are unchecked JSON: check their type, and show them as text, never as HTML.
37
+ Package subpaths (`package.json` `exports`):
272
38
 
273
- ```ts
274
- const result = client.session.session.get()?.result; // RunResult | null
275
- for (const network of result?.traffic?.networks ?? []) console.log(network.name, network.delivered);
276
- const strict = result?.raw?.['strict']; // a key without a typed field: unknown
277
- ```
39
+ | Import path | Purpose |
40
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
41
+ | `@vehicle-sil/gui-client` | High-level `connect()` / `createFront()`, low-level `createClient()`, `watch()`, `until()`, `ActionError`, `WriteError`, and protocol types |
42
+ | `@vehicle-sil/gui-client/elements` | Registers the 12 `vsil-*` custom elements; exports `pageIntent`, `setReasonText`, element classes, `VsilElementContracts`, and write-event detail types (`WriteQueuedInfo`, `WriteOutcome`, `WriteSuccess`, `WriteFailure`) |
43
+ | `@vehicle-sil/gui-client/timeline` | Registers `<vehicle-sil-timeline>` and exports its element and event types |
44
+ | `@vehicle-sil/gui-client/react` | Type-only JSX intrinsic element types for React 18 and 19 (no runtime dependency on `react`) |
45
+ | `@vehicle-sil/gui-client/vue` | Type-only `GlobalComponents` types for Vue 3 (no runtime dependency on `vue`) |
46
+ | `@vehicle-sil/gui-client/svelte` | Type-only `SvelteHTMLElements` types for Svelte 5 (no runtime dependency on `svelte`) |
278
47
 
279
- ### Handling unreadable notifications
48
+ - **Development server (Vite, `ng serve`, etc.)**: proxy `/api/`, `/vsil/`, and `/ws` to `vehicle-sil-gui` and start the server with `--dev-origin http://127.0.0.1:<port>` (optionally `--no-auth` for local development; see "[Use a development server](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md#use-a-development-server)" in `docs/gui.md`).
280
49
 
281
- The library parses each part separately.
50
+ ## Choosing `connect()`, `createFront()`, or `createClient()`
282
51
 
283
- - 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`.
284
- - Unknown notifications and events pass through without changing the state, and `onMessages` does not get them (`client.connection.onBatch` receives everything, before parsing: read an event that the library does not know there).
285
- - A notification that is not valid JSON raises a notice, and the library receives everything again from `hello`.
52
+ | Entry point | Connects immediately? | Shared page connection? | Best for |
53
+ | ------------------------------------------ | ------------------------------------------------------------------ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
54
+ | `await connect()` (no options, browser) | Yes (`connect()` + `loadApp()`) | Yes (shared with all `<vsil-*>` parts on the page) | Custom screens served by `--web`, scripts alongside `<vsil-*>` parts |
55
+ | `await connect(options)` (browser or Node) | Yes (`connect()` + `loadApp()`) | No (dedicated connection; call `close()`) | Node.js scripts/automation, second connection, or explicit `batchMs` / `watchPeriodMs` |
56
+ | `createFront(options)` | No (call `front.low.connect()` and `front.low.loadApp()` yourself) | No (dedicated connection; call `close()`) | Apps that must render UI before the server answers or while offline (e.g., `gui/web`) |
57
+ | `createClient(options)` | No (call `client.connect()` and `client.loadApp()` yourself) | No | Low-level access to raw session/events/logs, multi-variable atomic writes, or `variables.bind()` ([docs/gui-client-low-level.md](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui-client-low-level.md)) |
286
58
 
287
- ### Use from Node, or replace the transport
59
+ All three option objects use camelCase keys (`ConnectOptions` is `ClientOptions`):
288
60
 
289
- - In Node, the library sends the server's own origin as `Origin` (`createClient` builds it from `baseUrl`).
290
- - In the browser and in Web Workers, do not pass `origin`: the browser sets it (a Worker's WebSocket cannot set handshake headers).
291
- - To replace the HTTP implementation, pass `http` (`HttpTransport`); to replace the WebSocket, pass `socket` (`SocketFactory`).
61
+ | Option | Type / range | Default | Purpose |
62
+ | --------------------------- | ------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
63
+ | `baseUrl` | `string` (required when options are passed) | Server root in `connect()` | GUI server root URL (`http://127.0.0.1:<port>/`, without `#token=...`) |
64
+ | `token` | `string \| null \| (() => string \| null)` | `takeToken(window)` in `connect()` | Bearer/WS token from `#token=...`; omit or pass `null` for `--no-auth` |
65
+ | `origin` | `string` | Origin of `baseUrl` in Node; unset in browsers/Workers | Override `Origin` header (do not pass in browsers or Web Workers) |
66
+ | `answerTimeoutMs` | finite `number > 0` | `5000` (`ANSWER_TIMEOUT_MS`) | Timeout waiting for a time command reply and initial WS sync on `run`/`time`/`write` |
67
+ | `batchMs` | finite `number` `0..1000` | `100` (`BATCH_MS`) | Coalescing interval for incoming WebSocket notifications (`0` flushes on a microtask; control frames `synced`, `operation`, `error`, and `command` always flush immediately) |
68
+ | `watchPeriodMs` | finite `number` `20..60_000` | `100` (`WATCH_PERIOD_MS`) | Default polling interval for variable watches (rounded down to `WATCH_PERIODS_MS` and clamped to server limits) |
69
+ | `http`, `socket`, `onError` | transport / error sink | `fetch`, `WebSocket`, `console.error` | Custom transports or subscriber error handler |
292
70
 
293
- For the rules the library does not enforce for you (the fields of check and start requests, 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).
71
+ Unknown or legacy snake_case keys (such as `base_url` or `timeout_ms`) are rejected immediately with `ActionError('unknown-field', ..., 'refused')`.
294
72
 
295
73
  ## The front door (`connect()`)
296
74
 
297
- `connect()` returns the front door of the library: what a screen shows (`status`, `clock`, `controls`, `scenario`), the operations as Promises (`run`, `time`) and one variable at a time (`variable()`). It is built on the client described above and changes nothing in it: `front.low` is the same `GuiClient` (events, logs, findings, participants), and `createClient` still works as before. Use the front door for what a screen needs to decide ("which state is this", "may this button be pressed now, and if not, why"); use `low` for the rest.
298
-
299
- An app that must show its screens before the server answers, and while it cannot be reached (the standard screens), uses `createFront(options)` instead: it makes the front door without connecting, as `createClient` does, and the app calls `front.low.connect()` and `front.low.loadApp()` itself. Until `loadApp()` has answered, the front knows no start-up file, and the ranges in `controls` are the defaults (`DEFAULT_LIMITS`).
75
+ `connect()` returns a `Front`: reactive `Readable` state (`status`, `clock`, `controls`, `scenario`, `runtime`, `outside`), Promise-based actions (`run`, `time`, `check`, `scenarios`, `connections`, `configs`, `recording`, `prepare`, `readConfig`, `describeAgain`, `saveConfig`), and per-variable handles (`variable(ref)`). The underlying low-level client is always available as `front.low`.
300
76
 
301
77
  ```ts
302
- import { ActionError, connect, until, watch } from '@vehicle-sil/gui-client';
78
+ import { ActionError, connect, watch } from '@vehicle-sil/gui-client';
303
79
 
304
- // A page that the GUI server served, opened from the URL it printed: no options. The first call connects; the next calls
305
- // (another part of the page) get the same connection. In Node, or for a second connection, pass the server's URL and the token.
80
+ // In a page served by --web, omit options to share the connection with <vsil-*> parts.
81
+ // In Node.js, pass { baseUrl, token } (omit token for --no-auth).
306
82
  const client = await connect();
307
- // const client = await connect({ base_url: 'http://127.0.0.1:8765/', token });
308
83
 
309
84
  const stop = watch([client.status, client.controls], (status, controls) => {
310
85
  startButton.disabled = !controls.start.ok;
@@ -313,178 +88,223 @@ const stop = watch([client.status, client.controls], (status, controls) => {
313
88
  });
314
89
 
315
90
  try {
316
- await client.time.pause(); // a step needs a paused run (or start it paused: `run.start({ start_paused: true })`)
91
+ await client.time.pause();
317
92
  await client.time.step(100); // resolves when time has arrived and the run is paused again
318
93
  } catch (error) {
319
94
  if (error instanceof ActionError) console.log(error.code, error.message, error.outcome);
320
95
  }
321
96
  ```
322
97
 
323
- | Name | What it is |
324
- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
325
- | `status` | The one state to show: `link`, `run`, `file`, `result` and `problem` (below). Discrete values only |
326
- | `clock` | `sim_ms` (the virtual time in ms; `null` before a run), `speed`, `actual_speed` (the speed over about the last second; `null` while paused and right after the start) and `pacing` (`not-paced`, `on-time` or `late`). It changes often, so it is apart from `status` |
327
- | `controls` | Whether each operation can be used now: `start`, `stop`, `force_stop`, `pause`, `resume`, `step` (with `min_ms` and `max_ms`), `run_until`, `speed` (with `min`, `max` and `fastest`: whether `'max'` is accepted besides the numbers), and `save` |
328
- | `scenario` | The scenario of the current (or last) run: `file`, `name`, `status`, `steps`, `timeline_url`; `null` for a run without one |
329
- | `runtime` | Persistent hot / cold runtime status: `mode`, `state`, `config`, `reason`, `message` |
330
- | `prepare(options?)` | Pre-warms a persistent launcher for `file` (`POST api/prepare`) when eligible, or returns `cold` with `reason` |
331
- | `configs()` | Lists configuration files under the server root (`GET api/configs`) |
332
- | `recording()` | Returns applied writes of the current or last run as scenario YAML (`GET api/recording`), or `null` if none |
333
- | `outside` | The networks that the run's `connect` connected to a real bus ("Connecting a network outside" below) |
334
- | `connections({ network }, { file }?)`, `check(intent?, { file }?)` | Where a network can be connected, and the check of an intent without starting it ("Connecting a network outside" below) |
335
- | `readConfig({ file }?)` | The text of a configuration file as it is saved, with its `stamp` ("Editing the text of a configuration file" below) |
336
- | `check(intent?, { file, text }?)` | With `text`, the check of an unsaved text of the file (the same section) |
337
- | `describeAgain({ file, variant }?)` | Describes the participants of the saved file again, and returns that check (the same section) |
338
- | `saveConfig({ file, text, stamp })` | Saves a text as the file, with the `stamp` it was read with (`null`: a new file), and returns the new `stamp` (the same section) |
339
- | `run` | `start(intent?, { file, onStarted }?)`, `stop()` and `forceStop()` |
340
- | `time` | `pause()`, `resume()`, `step(ms)`, `setSpeed(value)` and `runUntil(ms)` |
341
- | `variable(ref)` | One variable, by `"ECU.variable"` (cut at the first dot) or `{ peer, name }` (for an ECU whose name has a dot) |
342
- | `low`, `close()` | The `GuiClient` of the same connection; `close()` disconnects (a shared connection is made again by the next `connect()`) |
343
- | `watch(source, fn)`, `until(source, test, options)` | `watch` calls `fn` now and on every change (several sources: `watch([a, b], (a, b) => ...)`) and returns the function that stops it. `until` resolves with the first value that satisfies `test`; it rejects with an `ActionError` (`timeout` or `aborted`, both `unknown`) |
98
+ Data fields use the wire's snake_case names (`force_stop`, `sim_ms`, `can_write`); methods and JS options use camelCase (`forceStop`, `runUntil`, `timeoutMs`). Every `Readable` returns the same reference while unchanged and has unbound `get` / `subscribe` methods (compatible directly with React `useSyncExternalStore`).
344
99
 
345
- Data fields use the wire's names (`force_stop`, `sim_ms`); functions use JavaScript's (`forceStop`, `runUntil`). Every state is a `Readable`; `get()` returns the same object while nothing changed, and `get` and `subscribe` work without `this` (they can be passed to `useSyncExternalStore` as they are).
100
+ ### `status`, `clock`, and `controls`
346
101
 
347
- ### `status`
102
+ - **`status`**: `{ link, run, file, result, problem }`.
103
+ - `link`: `'connecting' | 'online' | 'offline' | 'rejected' | 'incompatible'`.
104
+ - `run`: `'none' | 'starting' | 'waiting' | 'running' | 'paused' | 'stopping' | 'ended' | 'crashed'`.
105
+ - `result`: `{ end, scenario, ok, message }` while `run` is `'ended'` or `'crashed'`.
106
+ - `problem`: `{ code, message } | null` — connection errors first, otherwise the newest of launcher crash, failed run, or last failed action (variable write errors appear on `variable.get().problem` instead).
107
+ - **`clock`**: `{ sim_ms, speed, actual_speed, pacing }` (`pacing`: `'not-paced' | 'on-time' | 'late'`). Separated from `status` because `sim_ms` updates frequently.
108
+ - **`controls`**: `{ start, stop, force_stop, pause, resume, step, run_until, speed, save }`. Each entry is `{ ok, reason, caution }` where `reason` and `caution` are `{ code, message } | null`. Branch on `code` rather than matching the English `message`. For the complete table of every `controls.*.reason.code` and `caution.code` (plus `--time-policy` precedence and `free` default speed), see "[Control reason codes, caution codes, and `--time-policy`](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md#control-reason-codes-caution-codes-and---time-policy)" in `docs/gui.md`.
348
109
 
349
- | Field | Values |
350
- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
351
- | `link` | `connecting`, `online`, `offline`, `rejected` (the token was refused) or `incompatible` (another protocol version). `online` means the copy matches the server |
352
- | `run` | `none`, `starting` (a start is on its way, from this page or another), `waiting` (the launcher waits for the participants to join), `running`, `paused`, `stopping`, `ended` (there is a result) or `crashed` (the launcher ended without one) |
353
- | `file` | The configuration file of the run (the last one if none is running); the server's start-up file before the first run. `null` until the first answer from the server (the type is `string \| null`), and when there is no start-up file |
354
- | `result` | While `run` is `ended` or `crashed`: `end` (`completed`, `stopped`, `interrupted`, `failed`, `setup_failed` or `crashed`; `null` when nothing was started: the check failed, or the file or the command line could not be used), `scenario`, `ok` and `message` (one English sentence). A stop by the operator is `ok`, except when it stopped a scenario before its end |
355
- | `problem` | The one problem to tell the user now (`{ code, message }`), or `null` |
110
+ ### `run`, `time`, and `until()`
356
111
 
357
- `problem` is chosen in this order: the connection first (the token refused, another protocol version, offline); otherwise the newest of the launcher's crash, the failure of the last operation and a failed run (`result.ok` is false). A crash and a failed run go when the next run begins. The failure of an operation goes at the next operation or when `status.run` changes. A stop by the operator is not a problem, except when it stopped a scenario before its end (`result.ok` is false then, and the message says that the scenario has no verdict). The failure of a variable write is in the variable's own `problem`, not here. The server's notices (`low.session.session` `problems`) and `notices` stay in `low`.
112
+ - **`run.start(intent?, { file?, onStarted? }?)`**: starts a run. `intent` uses the keys of `schema/run-request.schema.json` (`variant`, `params`, `scenario`, `case`, `after_scenario`, `disable`, `enable`, `manual`, `strict`, `speed`, `start_paused`, `stop_at_ms`, `late_tolerance_ms`, `connect`, `time_policy`); omit unset keys rather than sending `null`. To re-run the current or last session with the exact same options, pass `session.intent` directly: `await front.run.start(session.intent, { file: session.file })` (`session.intent.scenario` is already root-relative). Resolves once the server accepts the start — wait for `status.run !== 'starting'` with `until()` before reading the new run state.
113
+ - **`run.stop()` / `run.forceStop(target?)`**: stops the run. If called right after `await connect()` while `link === 'connecting'`, `run.stop()`, `run.forceStop()`, `time.*()`, and `variable().enqueue()` / `write()` automatically wait for the initial WebSocket sync (up to `answerTimeoutMs`) instead of failing on a not-yet-synced state.
114
+ - **`time.pause()` / `resume()` / `step(ms)` / `runUntil(ms)` / `setSpeed(value)`**: `step` and `runUntil` resolve once virtual time reaches the target and the run is paused again; another sender's command before arrival rejects with `ActionError('interrupted', ..., 'unknown')`.
115
+ - **`until(source, test, { timeoutMs?, signal? })`**: resolves with the first value matching `test` (checking the current value immediately), or rejects with `ActionError('timeout' | 'aborted', ..., 'unknown')`. Options are strictly camelCase (`timeoutMs`, `signal`); unknown keys reject with `unknown-field`.
358
116
 
359
- `result.end`, `result.ok` and `result.message` are the launcher's: it writes them into its result (`end`, `ok` and `message`; see "How a run ended" in [simulation-run.md](../../docs/simulation-run.md#how-a-run-ended-end-ok-message)), and the library passes them on. The library has no table of result names. Only `crashed` is the library's own (`ok` is false, with a sentence of its own), because a launcher that ended without a result wrote nothing.
117
+ ### One variable (`client.variable(ref)`)
360
118
 
361
- ### `controls`
119
+ Pass `"ECU.variable"` (split at the first dot) or `{ peer, name }` (when the ECU name contains a dot).
362
120
 
363
- Each entry is `{ ok, reason, caution }`: `reason` is `{ code, message }` when `ok` is false, `caution` is the same shape for an operation that is accepted with something to know first. The codes stay the same (a new code may be added; the meaning of one does not change); the sentence is English, written by the owner of the rule.
121
+ ```ts
122
+ const throttle = client.variable('Engine.engine.throttle');
364
123
 
365
- | Entry | Comes from |
366
- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
367
- | `start` | The GUI server's `allowed.start` (`starting`, `already-running`, `launcher-unusable`, `shutting-down`), with its sentence |
368
- | `stop`, `force_stop` | The GUI server's `allowed.stop` and `allowed.force`. `stop` is `ok` for the last known run (or a start on its way), also offline, and while the server says the launcher still runs after its result. `force_stop` is `ok` only after a first stop (`not-stopping` before) |
369
- | `pause`, `resume`, `step`, `speed`, `run_until` | The launcher's `state.allowed` (reason, sentence and `caution` as the launcher wrote them; the ranges of `step` and `speed`; `fastest` is false when `min` equals `max`, as the launcher promises). No run in the copy: `not-running`; the launcher has not said yet (no `state` yet at the start of a run, or no entry for the operation): `unsupported` |
370
- | `pause`, `resume` (what would change nothing) | `pause` is not `ok` while the run is paused (`paused`), `resume` is not `ok` while it is not (`not-paused`): the launcher accepts both, but a button has nothing to do. While a step or a run_until is on its way (accepted, and not yet seen to arrive: virtual time at its `at_ms` and the launcher's `state` paused), neither is claimed |
371
- | `save` | The GUI server's `allowed.save` (`save-disabled`: started with `--no-save`; `shutting-down`), with its `caution` (`command-changes-allowed`: started with `--allow-command-changes`, so it also saves edits that change the commands that run). Whether one edit is saved is the answer to `saveConfig()` |
372
- | All of them | The connection: `rejected`, `incompatible`, `offline` or `connecting` turn them off (`stop` and `force_stop` stay as above); `busy` while the same operation of this page has not been answered |
124
+ // Subscribe with an optional per-subscriber polling period (20..60_000 ms)
125
+ const stop = throttle.subscribe(
126
+ (view) => {
127
+ slider.value = String(view.value ?? 0);
128
+ slider.disabled = !view.can_write;
129
+ slider.title = view.why?.message ?? view.note ?? '';
130
+ },
131
+ { periodMs: 20 },
132
+ );
373
133
 
374
- ### Operations
134
+ // Single-step write (stages 1-4 combined)
135
+ const result = await throttle.write(40);
136
+ console.log(result.appliedAtMs, result.late);
137
+ stop();
138
+ ```
375
139
 
376
- `run.start(intent, { file })` takes the intent: `vehicle_sil_run_request` (1, optional), `variant`, `params`, `scenario`, `disable`, `enable`, `manual`, `strict`, `speed`, `start_paused`, `connect` and `time_policy`, as the launcher's request file names them (`scenario` is a `path` that `scenarios()` gave, relative to the GUI server's root; the request file's own `scenario` is relative to the configuration file's directory, and the server rewrites the path, so do not compose it) (any other field is refused with `unknown-field`; a choice that is not made is a key that is left out, never `null`); `file` defaults to the server's start-up file (`scenarios({ file })` and `connections()` default to it too: give the same `file` to each when a run uses another file). Every operation is a Promise. It rejects with an `ActionError`: `code`, a sentence (`message`), `findings` (for `check-failed`) and `outcome`: `refused` (the owner said no; nothing happened) or `unknown` (it may have been done: look at `status` and `clock` before you send it again).
140
+ **Four-stage write API (`enqueue()` + `applied()` / `write()`)**:
377
141
 
378
- | Operation | Resolves when | Rejects with |
379
- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
380
- | `run.start` | The server took the request. Whether the run began is `status.run` (wait with `until(client.status, s => s.run !== 'starting')`, then read `run`) | The refusal (`check-failed` with the `findings`, `already-running`, ...). No answer in time: `no-answer` (`unknown`: it may have started) |
381
- | `run.stop`, `run.forceStop` | The server took the request. Sent whatever the state of the connection (HTTP may reach the server when the WebSocket is down); asking again while one is on its way is the same request | The same |
382
- | `time.pause`, `resume`, `setSpeed` | The launcher answered. `pause` while paused and `resume` while running send nothing and resolve, only when the connection is `online` and a run takes the operation | The launcher's `reason` and sentence (`refused`); no answer within 5 seconds: `no-answer` (`unknown`); the run ended before the answer: `not-running` (`unknown`) |
383
- | `time.step`, `time.runUntil` | Time has arrived and the run is paused again, so `clock` can be read after `await`. `runUntil(t)` arrives at `t` (a `t` the paused run has already passed resolves at once and time does not move); `step(ms)` at the `at_ms` the launcher writes in the answer (older launcher: the time it was accepted plus the `ms` it rounded to, an estimate) | As above; and `interrupted` (`unknown`) when a resume or a pause of another sender (another page or stdin) comes before it arrives (a pause or resume of this page, or a stop, rejects it the same way but is not shown in `status.problem`). Another step sent meanwhile does not end it |
142
+ - **`enqueue(value, options?): Promise<QueuedWrite>`**: completes stages 1 + 2 — the GUI server validates the write, registers it in FIFO `seq` order, and waits on the launcher Control Server (`WAIT_FOR_QUEUED`) until the ECU has queued it (or settled it immediately). Rejects immediately with `ActionError` if refused or terminally failed (`invalid`, `busy`, `late`, `rejected`, `cancelled`, ...).
143
+ - **`queued.applied(waitOptions?): Promise<WriteResult>`**: completes stages 3 + 4 — resolves with `{ session, seq, peer, name, value, appliedAtMs, late }` once the ECU applies the write in a step, or rejects with `ActionError`.
144
+ - **`write(value, options?): Promise<WriteResult>`**: shorthand for `enqueue(value, options).then((q) => q.applied({ timeoutMs, signal }))`.
145
+ - **`FrontWriteOptions`**: `{ atMs?, late?: 'reject' | 'apply', timeoutMs?, keepalive?, signal? }`. Unknown keys reject immediately with `ActionError('unknown-field', ..., 'refused')`.
146
+ - **Virtual-time-aware watchdog (`timeoutMs`)**: default `WRITE_TIMEOUT_MS` (10,000 ms). Must be a finite number `> 0` (`Infinity` is rejected with `invalid-argument`). While the connection is healthy, the target ECU is connected, and the run is `paused` or `holding`, the watchdog is **suspended** (so paused writes and multi-rate scheduled `atMs` writes never false-timeout); pass `signal: AbortSignal.timeout(ms)` if you need a wall-clock cap while paused. While running, the watchdog scales for slow playback (`speed < 1`) and resets as `sim_ms` advances, while still rejecting in finite time if the WebSocket drops, the ECU disconnects, or virtual time freezes.
147
+ - **Polling rate and boundary**: the first `subscribe()` starts watching the variable and the last unsubscribe stops it (there is no `close()`). Passing `{ periodMs }` temporarily promotes the variable to the shortest active interval among subscribers and restores the slower interval when that subscriber unsubscribes. Lowering `watchPeriodMs` / `periodMs` to `20` ms (with `batchMs: 16` or `0`) improves live UI responsiveness, but latest-value polling does **not** guarantee capturing pulses shorter than 20 ms; use `--timeline` or `Spy` for deterministic step-accurate capture (see "[Live polling vs deterministic capture](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md#live-polling-vs-deterministic-capture)" in `docs/gui.md`).
148
+ - **Held inputs and reentrancy**: pass `{ keepalive: true }` from a `pagehide` handler for held-control release writes, and avoid triggering unguarded reentrant writes inside `subscribe()`. See "[Held inputs, reconnect recovery, and bus observation](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md#held-inputs-reconnect-recovery-and-bus-observation)" in `docs/gui.md`.
384
149
 
385
- The client refuses before sending only what it owns: the connection (`rejected`, `incompatible`), the same operation still waiting for its answer (`busy`; this includes `start()`) and the shape of an argument (`invalid-argument`). Anything else is sent even if `controls` says no, and the owner's answer comes back (the copy may be old). The 5 seconds are the front door's own (they do not apply to the wait for arrival, which ends when the run ends or another command interrupts it).
150
+ ### Connecting outside and editing configuration files
386
151
 
387
- A time command carries a request number (`id`) that the page chose, and the answer is the launcher's `command` event with the same `id`; an answer to another page's or stdin's command with the same name is not taken for it.
152
+ - **External buses**: call `await client.connections({ network })` when the user opens a target picker (starts that network's bridge on the server host), check an intent with `await client.check({ connect: { ETH_EXT: target }, time_policy: 'free' })`, start with `client.run.start(intent)`, and observe live bridge health on `client.outside`.
153
+ - **Configuration text editing**: read saved text and its SHA-256 stamp with `await client.readConfig({ file })`, validate unsaved edits without starting ECUs via `await client.check({ variant }, { file, text })`, refresh cached `--describe` metadata after rebuilding ECUs with `await client.describeAgain({ file, variant })`, and save atomically with `await client.saveConfig({ file, text, stamp })`.
388
154
 
389
- ### Connecting a network outside
155
+ ## Recipes
390
156
 
391
- A `can` or `ethernet` network can be connected to a real bus through the launcher's bridge ("Connecting a network outside" in [gui/protocol/README.md](../protocol/README.md#connecting-a-network-outside-connect-time_policy-apiconnections)). The front door adds three things for it, with no rule of its own.
157
+ ### 1. Discover variables before starting a run (`client.check()`)
158
+
159
+ `client.check()` runs `vehicle_sil_launch check --json` before any run starts and returns each participant's `--describe` variable metadata, including `builtin` (`true` for automatic variables such as `ecu.connected`, `peer.*`, `j1939.*`, `can.*`, `lin.*`, `eth.*`; `false` for variables declared by your ECU).
392
160
 
393
161
  ```ts
394
- const entries = await client.connections({ network: 'ETH_EXT' }); // when the user opens the choice
395
- const intent = { connect: { ETH_EXT: 'fake0' }, time_policy: 'free' as const };
396
- const result = await client.check(intent); // the launcher's findings, before anything starts
397
- await client.run.start(intent);
398
- const stop = watch(client.outside, (rows) => console.log(rows.map((r) => r.condition)));
399
- ```
162
+ import { connect } from '@vehicle-sil/gui-client';
400
163
 
401
- - **`connections({ network }, { file }?)`** asks `POST api/connections` and lays the answer out as one list, in its order: `{ backend, value, label, detail, usable, reason }` for each target, and `{ backend, error }` (the launcher's sentence) for a backend whose bridge could not list, or for an error of the file. Tell the two apart with `'error' in entry`. A list that lacks a backend (exit code 1) is not a failure. It starts that network's bridge on the computer of the GUI server (on Windows, Npcap may ask to raise the rights there), so call it when the user opens the choice, not when the page opens. The list is that computer's, not the browser's. It rejects with an `ActionError` (`check-busy`, `unknown-network`, ...).
402
- - **`intent.connect`** maps a network to a `value` that the list gave with `usable: true`, as written there; `'none'` keeps it on SIL Kit only, the same as leaving it out. The server refuses a value that its last list of that network did not give (`target-not-listed`): list the network again. **`intent.time_policy`** is `realtime` (the launcher's default: a connected run keeps real time) or `free`.
403
- - **`check(intent?, { file, signal }?)`** returns the launcher's check result of what `run.start(intent)` would start (`findings`; `time_lock` and `networks[].outside` are in `raw`), or rejects with an `ActionError`. Its failure is not put into `status.problem`. It sends one check at a time: the next is sent after the answer to the one before (the server runs checks one at a time and refuses with `check-busy` when too many wait). A check of the same intent and file as one that waits or is on its way shares it, so the parts and the screen of a page that check the same page intent make one check. A check that waits is not sent when `signal` has aborted for every caller of it; it rejects with the signal's reason. A check on its way is shared too, and its answer reads the file as it was when it was sent: pass `fresh: true` when the user asks to check again (it shares only a check that waits). After `close()`, a check that waits is not sent and rejects with `closed`.
404
- - **`outside`** has one row for each network that the run's `connect` connected: `network`, `target`, `participant`, `link` (Ethernet) or `bus` (CAN), `condition` (`ok`, `interrupted`, `degraded`), `reasons` (codes, in the launcher's order), `nothing_received` (apart from `condition`), and `to_outside` and `from_outside` (`null` until an `outside` event has arrived on this page). It is empty while no run is going, and in a run that a `role: bridge` participant of the file connects: do not read from it whether the run is connected outside (`time_lock.because` of the check says what makes the run keep real time). How the run ended, `connect-failed` and `connect-lost` included, is in `status`.
164
+ const client = await connect({ baseUrl: 'http://127.0.0.1:8765/', token });
165
+ try {
166
+ const checked = await client.check();
167
+ for (const participant of checked.participants) {
168
+ const vars = participant.variables ?? [];
169
+ const appVars = vars.filter((v) => !v.builtin);
170
+ const builtinVars = vars.filter((v) => v.builtin);
171
+ console.log(participant.name, {
172
+ app: appVars.map((v) => `${v.name} (${v.type}, ${v.causality}, ${v.unit})`),
173
+ builtin: builtinVars.map((v) => v.name),
174
+ });
175
+ }
176
+ } finally {
177
+ client.close();
178
+ }
179
+ ```
405
180
 
406
- ### Editing the text of a configuration file
181
+ ### 2. Wait through `starting` state after `run.start()`
407
182
 
408
- A screen that edits a configuration file reads it, checks the text before it is saved, saves it, and asks for the participants to be described again after an executable was built again ("The text of a configuration file" and "Saving a text" in [gui/protocol/README.md](../protocol/README.md#the-text-of-a-configuration-file-apiconfig-text-of-apicheck-apidescribe)). The client does not read YAML: the text is a string to it.
183
+ `client.run.start()` resolves as soon as the server accepts the request, while `status.run` is still `'starting'`. Wait with `until()` using camelCase `timeoutMs`, then inspect `status.run` and `status.result`.
409
184
 
410
185
  ```ts
411
- const { text } = await client.readConfig({ file: 'simulation.yaml' }); // the file as it is saved
412
- const edited = text + '\n# edited on the screen\n'; // the screen's own edit
413
- const result = await client.check({ variant: 'fast' }, { file: 'simulation.yaml', text: edited });
414
- console.log(result.findings.map((f) => `${f.severity}: ${f.message}`));
415
- const open = result.participants.filter((p) => p.status === 'not_described');
416
- if (open.length > 0) {
417
- console.log(`${open.length} participants need describeAgain before they are compared`);
418
- await client.describeAgain({ file: 'simulation.yaml', variant: 'fast' }); // then check the text again
186
+ import { connect, until } from '@vehicle-sil/gui-client';
187
+
188
+ const client = await connect({ baseUrl: 'http://127.0.0.1:8765/', token });
189
+ try {
190
+ await client.run.start({ start_paused: true });
191
+ const settled = await until(client.status, (s) => s.run !== 'starting' && s.run !== 'waiting', {
192
+ timeoutMs: 30_000,
193
+ });
194
+ if (settled.run !== 'paused') {
195
+ throw new Error(`Run did not pause: ${settled.run} (${settled.result?.message ?? ''})`);
196
+ }
197
+ } finally {
198
+ client.close();
419
199
  }
420
200
  ```
421
201
 
422
- Saving sends the `stamp` that was read. When the file changed meanwhile, the server refuses with `config-changed`: read it again and make the edit on that text.
202
+ ### 3. Deterministic writes while paused (`enqueue()` -> `step()` / `runUntil()` -> `applied()`)
203
+
204
+ Because `enqueue()` waits until the ECU has actually queued the command (`WAIT_FOR_QUEUED`), you never need fixed `sleep()` delays or infinite timeouts before calling `step()` or `runUntil()`.
423
205
 
424
206
  ```ts
425
- const read = await client.readConfig({ file: 'simulation.yaml' });
426
- const edited = read.text.replace('kind: can', 'kind: can\n external: true'); // the screen's own edit
207
+ import { connect, until } from '@vehicle-sil/gui-client';
208
+
209
+ const client = await connect({ baseUrl: 'http://127.0.0.1:8765/', token });
427
210
  try {
428
- const saved = await client.saveConfig({
429
- file: 'simulation.yaml',
430
- text: edited,
431
- stamp: read.stamp,
432
- });
433
- console.log(`saved; the next save sends ${saved.stamp}`);
434
- } catch (error) {
435
- if (error instanceof ActionError && error.code === 'config-changed') {
436
- // the file changed since it was read: read it again, edit that text, save again
437
- } else if (error instanceof ActionError && error.code === 'commands-changed') {
438
- console.log(error.message); // the edit changes the commands that run: the launcher's finding says what
439
- } else {
440
- throw error;
441
- }
211
+ await client.run.start({ start_paused: true });
212
+ await until(client.status, (s) => s.run === 'paused', { timeoutMs: 30_000 });
213
+
214
+ const throttle = client.variable('Engine.engine.throttle');
215
+
216
+ // Queue a rising and falling pulse while paused (zero sleep required)
217
+ const rise = await throttle.enqueue(80, { atMs: 100 });
218
+ const fall = await throttle.enqueue(20, { atMs: 250 });
219
+
220
+ // Advance virtual time deterministically to apply both writes
221
+ await client.time.runUntil(300);
222
+
223
+ const [r1, r2] = await Promise.all([rise.applied(), fall.applied()]);
224
+ console.log('applied at:', r1.appliedAtMs, r2.appliedAtMs);
225
+ } finally {
226
+ await client.run.stop().catch(() => undefined);
227
+ client.close();
442
228
  }
443
229
  ```
444
230
 
445
- - **`readConfig({ file }?)`** asks `GET api/config` and returns `{ file, text, stamp }`: the bytes as UTF-8 as they are, and the SHA-256 of those bytes (`stamp` is what `saveConfig` sends). `file` defaults to the start-up file (`no-file` if there is none). It rejects with an `ActionError` (`not-a-configuration`, `config-too-large`, `config-unreadable`, ...).
446
- - **`check(intent?, { file, text }?)`** with `text` checks that text as the content of `file`, which must exist; no process starts. The intent takes only `variant`, `strict` and `vehicle_sil_run_request`; the types say so, and any other field rejects with `unknown-field` before anything is sent. The check waits its turn in the same line as the other checks, but it is never shared: a check of a text is not the check of the page, and the parts and `status` do not see its answer. A refusal (`text-too-large`, `check-busy`, `check-timeout`, ...) is the caller's, as for a check without `text`. A check can pass while a participant is `not_described`: that participant was not compared with its executable. Tell them apart in `result.participants[].status === 'not_described'` (in `raw.participants[].status` if you read the raw check).
447
- - **`describeAgain({ file, variant }?)`** asks `POST api/describe`: it checks the saved file, saves the descriptions of its participants again, and returns that check. After it, the check of a text compares those participants; a participant that only the text has needs the file saved first. It waits in the same line. A describe of the same file and variant that waits or is on its way is shared (pressing again starts the executables once). Its answer is the caller's alone, and its failure is not put into `status.problem`.
448
- - **`saveConfig({ file, text, stamp })`** asks `POST api/config` and resolves with `{ file, stamp }`, the stamp of the saved content (send it with the next save). `stamp` is the one `readConfig` gave, or `null` to make a new file. By default the server saves only an edit that keeps the commands that run, as the launcher's check of the text says (the networks, their mapping, `external`); `controls.save` tells whether the server saves at all, and its `caution` when it also saves edits that change the commands. The text is written as it is (a BOM and the line ends stay). It rejects with an `ActionError`: `save-disabled`, `commands-changed` (`findings` are the launcher's; also a new file to a server started without `--allow-command-changes`), `config-changed` (the file changed since it was read, or a new file is there already), `config-busy` (the file could not be replaced: another program has it open, say), `config-unreadable` (the launcher cannot read the text as a configuration; `findings`), `text-too-large`, `check-busy`, .... It waits in the server's line of the checks, not in this page's. Its failure is not put into `status.problem`. After a save, the next check of a text describes the saved file first (its executables start with `--describe`).
231
+ ### 4. Record manual writes and replay with handover (`recording()` + `end_ms` + `after_scenario: 'pause'`)
449
232
 
450
- ### One variable
233
+ After stopping a run that applied variable writes, `client.recording()` returns scenario YAML (`vehicle_sil_scenario: 1`) with a finalized top-level `end_ms` equal to the recorded run's end virtual time (mid-run calls omit `end_ms` so replay ends at the last `set` step). Save that YAML under `scenarios/` next to the configuration file and replay it with `after_scenario: 'pause'` to inspect or continue manually on the same run without restarting ECUs.
451
234
 
452
235
  ```ts
453
- const throttle = client.variable('Engine.engine.throttle');
454
- const stop = throttle.subscribe((view) => {
455
- slider.value = String(view.value ?? 0);
456
- slider.disabled = !view.can_write;
457
- slider.title = view.why?.message ?? view.note ?? '';
458
- });
459
- await throttle.write(40); // resolves when it was applied in an ECU step
460
- stop(); // the last unsubscribe stops asking the server for values
236
+ import { writeFileSync } from 'node:fs';
237
+ import { connect, until } from '@vehicle-sil/gui-client';
238
+
239
+ const client = await connect({ baseUrl: 'http://127.0.0.1:8765/', token });
240
+ try {
241
+ // 1. After a recorded run has ended, export its scenario YAML (includes finalized end_ms)
242
+ const rec = await client.recording();
243
+ if (!rec?.yaml || rec.writes === 0) throw new Error('No applied writes recorded');
244
+ console.log(`recorded ${rec.writes} writes, end_ms=${rec.end_ms}`);
245
+ writeFileSync('scenarios/recorded.yaml', rec.yaml, 'utf8');
246
+
247
+ // 2. Discover the saved scenario via the server and replay it with handover to manual pause
248
+ const list = await client.scenarios();
249
+ const saved = list.find((s) => s.path.endsWith('recorded.yaml'));
250
+ if (!saved) throw new Error('recorded.yaml not listed under scenarios/');
251
+
252
+ await client.run.start({ scenario: saved.path, after_scenario: 'pause' });
253
+ await until(client.scenario, (sc) => sc?.handed_over === true, { timeoutMs: 30_000 });
254
+ console.log('handed over at ms:', client.scenario.get()?.over_at_ms);
255
+
256
+ // 3. Writes and time controls are now unlocked on the same run
257
+ const q = await client.variable('Engine.engine.throttle').enqueue(0);
258
+ await client.time.step(100);
259
+ await q.applied();
260
+ } finally {
261
+ await client.run.stop().catch(() => undefined);
262
+ client.close();
263
+ }
461
264
  ```
462
265
 
463
- The view has `value`, `text` (an enum shows the item's name), `unit`, `min`, `max`, `step`, `sim_ms`, `stale`, `note` (a sentence when the value is not a live one), `availability` (`unknown`, `active` or `inactive`: whether the ECU uses the variable now; information only, so `can_write`, `why` and `note` do not look at it, and a lost connection does not change it; `unknown` until the run's summary has the variable, then `active` with a GUI server that does not send it), `can_write` (the variable's own conditions and what the launcher accepts: `state.allowed.write`), `why` (a `{ code, message }` for what cannot be written: the variable's own reason first, then the launcher's), `writing`, `problem` (why the last write of this page did not go through), and the values of `client.low.variables.bind` (`condition`, `block`, `write_status`).
266
+ ### 5. Tune live polling cadence (`watchPeriodMs`, `batchMs`, `subscribe({ periodMs })`)
464
267
 
465
- - The first subscription asks the server for the value, and the last unsubscribe stops it. There is no `close()`.
466
- - `write(value)` needs no subscription (it sends that one write). It rejects with an `ActionError`; `no-answer` is `unknown`, and a write whose answer did not come is not sent again.
467
- - The binding (`client.low.variables.bind`) holds back and merges writes while one is on its way (for sliders); `write()` of the front door sends each call.
268
+ The default 100 ms polling and 100 ms batching keep background overhead low. For higher-responsiveness gauges or animations, lower `watchPeriodMs` / `batchMs` on `connect()`, or promote only specific variables while subscribed:
468
269
 
469
- ## Parts (custom elements)
270
+ ```ts
271
+ import { connect } from '@vehicle-sil/gui-client';
272
+
273
+ const client = await connect({
274
+ baseUrl: 'http://127.0.0.1:8765/',
275
+ token,
276
+ watchPeriodMs: 100, // default for most variables
277
+ batchMs: 16, // flush incoming WebSocket frames ~60 Hz
278
+ });
470
279
 
471
- `@vehicle-sil/gui-client/elements` defines 11 custom elements that draw what `connect()` returns, so that a screen can be written as HTML without a script. They use native controls in the light DOM and have no styles of their own: your CSS styles them, and they work in plain HTML and in the templates of Angular, React, Vue and Svelte. Importing the module defines them (a name that is defined already is skipped).
280
+ // Promote only engine.speed to 20 ms while this panel is mounted
281
+ const stop = client.variable('Engine.engine.speed').subscribe(
282
+ (view) => {
283
+ if (view.value !== null) console.log(view.sim_ms, view.text, view.unit);
284
+ },
285
+ { periodMs: 20 },
286
+ );
287
+ // Calling stop() restores the slower watch period automatically
288
+ ```
472
289
 
473
- | Element | What it shows or does | Attributes and properties |
474
- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
475
- | `<vsil-status>` | The connection, the run, the virtual time (marked when it falls behind real time) and the one problem | none |
476
- | `<vsil-run-controls>` | Start (with the page's selection), Stop and, after a first stop, Stop without waiting | property `intent` (what the next run starts with); `label-start`, `label-stop`, `label-force-stop` (the button texts) |
477
- | `<vsil-time-controls>` | Pause, Resume, Step, Run until and the speed | `speeds` (the speeds to choose from, separated by spaces; default `0.5 1 5 max`; a speed outside the range of `controls.speed` cannot be chosen, and `max` is not offered while `fastest` is false; the part does not say why, so a page that wants to say it reads the range from `client.controls`), `step-ms` (the size of a step in ms; default `10`); `label-pause`, `label-resume`, `label-step`, `label-run-until` (the button texts) |
478
- | `<vsil-value>` | The value and its unit, and a sentence when it is not live. A bool shows as the `on` and `off` text | `variable`; `on`, `off` (the text for a bool's true and false); `no-unit` (leave the unit out) |
479
- | `<vsil-slider>` | A number in the variable's range; it is written when the knob is released | `variable` |
480
- | `<vsil-write>` | A button that writes one value (not usable when the variable already has it) | `variable`; `value` (what to write: JSON such as `false` or `3`, otherwise text); `label` (the button text) |
481
- | `<vsil-scenario-select>` | The scenario of the next run, among those next to the run's configuration file (the first choice is none) | none |
482
- | `<vsil-scenario-result>` | The status and the steps of the run's scenario | none |
483
- | `<vsil-timeline>` | The timeline of the run's scenario, in the `<vehicle-sil-timeline>` that you put inside it | none; the attributes of that element are yours (see below) |
484
- | `<vsil-connect>` | Where one network of the next run is connected: SIL Kit only first, then the targets of the list ("Connecting a network outside with the parts" below) | `network` (a `can` or `ethernet` network of the configuration file) |
485
- | `<vsil-outside>` | One row for each network that the run connected, with its condition and counts | none |
290
+ ## Parts (custom elements)
486
291
 
487
- A variable is written `ECU.variable` (cut at the first dot), as for `client.variable()`.
292
+ `@vehicle-sil/gui-client/elements` defines 12 light-DOM custom elements built on `connect()` with no styles of their own. Every HTML attribute has a matching camelCase JS property (including boolean `noUnit`, falsy `value={false}` / `value={0}`, and numeric `stepMs`) so they bind cleanly in plain HTML and in Angular, React, Vue, and Svelte templates.
293
+
294
+ | Element | What it shows or does | Attributes / JS properties | Custom events |
295
+ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
296
+ | `<vsil-status>` | Connection, run state, virtual time (marked when late), and active problem | `client` (prop) | — |
297
+ | `<vsil-run-controls>` | Start (with page intent), Stop, and Force stop | `label-start` (`labelStart`), `label-stop` (`labelStop`), `label-force-stop` (`labelForceStop`), `intent` (prop), `client` (prop) | — |
298
+ | `<vsil-time-controls>` | Pause, Resume, Step, Run until, and speed selector | `speeds`, `step-ms` (`stepMs`), `label-pause` (`labelPause`), `label-resume` (`labelResume`), `label-step` (`labelStep`), `label-run-until` (`labelRunUntil`), `client` (prop) | — |
299
+ | `<vsil-value>` | Value with unit and non-live note; bool renders `on`/`off` text | `variable`, `on`, `off`, `no-unit` (`noUnit`), `client` (prop) | — |
300
+ | `<vsil-slider>` | Numeric slider in variable's range; writes on release with single-slot coalescing | `variable`, `client` (prop) | `vsil-write-queued`, `vsil-write-result` |
301
+ | `<vsil-write>` | Button writing one value (disabled when variable already equals value) | `variable`, `value` (`string \| number \| boolean \| null`), `label`, `client` (prop) | `vsil-write-queued`, `vsil-write-result` |
302
+ | `<vsil-scenario-select>` | Scenario selector for the next run | `client` (prop) | — |
303
+ | `<vsil-case-select>` | Case selector for the next run's scenario when it defines multiple cases (disables cases restricted by the active `variant` via `only`) | `client` (prop) | — |
304
+ | `<vsil-scenario-result>` | Scenario status, case, resolved parameters, and step table (including failed step `file:line` and template `call_stack`) | `client` (prop) | — |
305
+ | `<vsil-timeline>` | Ties an inner `<vehicle-sil-timeline>` to the run's `timeline_url` | `client` (prop) | — |
306
+ | `<vsil-connect>` | External bus target picker (`SIL Kit only` + bridge targets) | `network`, `file`, `client` (prop) | — |
307
+ | `<vsil-outside>` | Live rows of externally connected networks, condition, and frame counts | `client` (prop) | — |
488
308
 
489
309
  ```html
490
310
  <script type="module" src="/vsil/vehicle-sil-gui-elements.mjs"></script>
@@ -501,6 +321,7 @@ A variable is written `ECU.variable` (cut at the first dot), as for `client.vari
501
321
  </p>
502
322
  <vsil-time-controls speeds="0.5 1 5 max"></vsil-time-controls>
503
323
  <label>Scenario of the next run <vsil-scenario-select></vsil-scenario-select></label>
324
+ <label>Case <vsil-case-select></vsil-case-select></label>
504
325
  <vsil-scenario-result></vsil-scenario-result>
505
326
  <script src="/timeline/vehicle-sil-timeline.js"></script>
506
327
  <vsil-timeline>
@@ -508,362 +329,265 @@ A variable is written `ECU.variable` (cut at the first dot), as for `client.vari
508
329
  </vsil-timeline>
509
330
  ```
510
331
 
511
- `<vsil-timeline>` only ties the element to the run: it sets `src` (the run's `timeline_url`, from the server's root) and `hidden` (when the run has no timeline) of the `<vehicle-sil-timeline>` inside it, and nothing else of it. It adds a default element when you put none, and removes only that one. The part does not load the element's script: the page does (`<script src="/timeline/vehicle-sil-timeline.js">`, or `import '@vehicle-sil/gui-client/timeline'`); an element that is defined later works too. The element sends the token that the page keeps in the tab; for a part with another connection (`client`), give the element its `token` property. It sets `data-timeline` (`shown` or `none`) on itself. The attributes and events of the element are in "Putting a timeline on your own screen" in [docs/gui.md](../../docs/gui.md#putting-a-timeline-on-your-own-screen).
512
-
513
- ### What the parts promise
514
-
515
- - **The page's connection.** A part calls `connect()` without options, so the page's own script and all the parts share one connection (one WebSocket), and a refusal of your own button shows in `<vsil-status>`. To give a part another connection, set its `client` property (a part that is in the document binds again).
516
- - **One set of files.** Use the package, the copies of the single files, or the GUI server's `/vsil/` files, not a mix. The parts import the main entry by its file name; they do not carry a copy of it. In a project (the package) the parts and your script both import `@vehicle-sil/gui-client`. With copies, put `vehicle-sil-gui-elements.mjs` next to `vehicle-sil-gui-client.mjs` and import the client from that same file. With the server, load the parts from `/vsil/vehicle-sil-gui-elements.mjs` and the client from `/vsil/vehicle-sil-gui-client.mjs` (the parts' own import resolves to it). A second copy of the library, such as a copy of the client next to the page and the parts from `/vsil/`, makes a second connection.
517
- - **Your markup and your CSS.** There is no shadow DOM. A part draws into one `<span class="vsil">` that it adds, and the children you put in the element stay. It sets `data-*` attributes for CSS: `data-link`, `data-run`, `data-pacing` (`<vsil-status>`), `data-stale`, `data-can-write`, `data-availability` and `data-on` (the variable parts; `data-availability` never disables a part; to dim an unused variable, write `[data-availability="inactive"] { opacity: .45; }`), `data-error` (every part that could not connect, the code of the error when it has one, else `error`; removed when it binds again), `data-status` (`<vsil-scenario-result>` and its steps), `data-network`, `data-chosen` and `data-reverted` (`<vsil-connect>`; its `data-error` is also the code of a list that failed), `data-network`, `data-condition` and `data-nothing-received` (each row of `<vsil-outside>`), and on each button of `<vsil-run-controls>` and `<vsil-time-controls>`, and on the speed select, `data-reason` and `data-caution` (the code, when there is one).
518
- - **A button that cannot be used** is not `disabled`: it has `aria-disabled="true"` (so it keeps the focus), pressing it does nothing, and the reason is a sentence in an element that `aria-describedby` points to (the speed select is described the same way). A reason that only says there is nothing to do (`not-running`, `offline`) is in that element too, but the element is `hidden`: a screen reader reads it, and the page does not repeat it beside every button (`<vsil-status>` shows the state). The same goes for `<vsil-write>` when the variable already has the value ("already false"). A slider that cannot be written, or has no range, is `disabled`, and the reason is next to it.
519
- - **Life.** A part subscribes when it enters the document and stops everything when it leaves. When it leaves while it waits for the connection, it draws nothing. When `variable` or another attribute changes, it binds again. `<vsil-connect>` takes its network out of `pageIntent.connect` when it leaves or its `network` or `file` changes, so that no run is connected by a choice that is not on the page (a part drawn again starts at SIL Kit only).
520
- - **A part that could not connect** (no token, the server is not there) fails together with the other parts of the page, because they share one connection. The page shows the error sentence once: in `<vsil-status>`, or in the first part in document order when the page has no `<vsil-status>` (if that part leaves, another one shows it). Every such part gets `data-error`, so CSS and scripts see the failure; the mark goes when the part binds again and succeeds. A part that was given its own connection in `client`, or that fails while it draws (a missing `variable` attribute), shows its own sentence.
521
- - **A failed action** (an `ActionError`) is not thrown at the page: `status.problem` shows it in `<vsil-status>`, and a failed write shows next to its variable.
522
- - **No more than these 11.** Graphs, tables and the layout are the screen's work. For a graph of a variable over time, keep its history with `client.low.variables.bind(ref, { history: 600 })` and draw the points yourself ("[History](#history)" below).
523
-
524
- ### Words and the next run
525
-
526
- The words are English. Attributes rename the buttons (`label-start` and the others in the table, and `label` of `<vsil-write>`). The sentences of reasons (a button that cannot be used, `caution`, the problem, why a variable cannot be written) come from the owner of the reason, in English; `setReasonText(fn)` replaces them: `fn(reason)` returns the sentence, or `null` or `undefined` to keep the English one, and `setReasonText(null)` removes it. Call it before the parts are in the page. The other words of the parts (`ready`, `writing…`, `(no scenario)`, `fastest`, `behind real time`, `Step (ms)`, `Until (ms)`, `Speed`, `-`, the default `on` and `off`, `SIL Kit only (not connected)`, the sentence of a choice taken back to SIL Kit only, and `link`, `bus`, `to outside`, `from outside` and `nothing received` of `<vsil-outside>`) cannot be changed.
527
-
528
- The choosing parts and the start button are separate elements, so the module keeps what the page selected for the next run in `pageIntent` (`get()`, `subscribe(fn)` and `update(patch)`; a field set to `''` or `undefined` is removed). `<vsil-scenario-select>` writes `scenario`; `<vsil-run-controls>` starts with `{ ...pageIntent.get(), ...intent }`, so its `intent` property wins, and it starts the file that `status.file` names, the same file whose scenarios `<vsil-scenario-select>` lists (the server's start-up file when no run has been started). A screen that starts a run with its own code passes the intent to `client.run.start(intent)` itself; it writes the choices that the check sees into `pageIntent` too, so that `<vsil-connect>` checks what the screen will start.
529
-
530
- Start the GUI server with a configuration file (`vehicle-sil-gui --web my-screen simulation.yaml`). Without one the server has no start-up file, and a screen made of parts alone cannot start a run: `<vsil-status>` shows the refusal (`no-file`). Only your own code can name the file then: `client.run.start(intent, { file })`.
332
+ `<vsil-timeline>` only sets `src` and `hidden` on the `<vehicle-sil-timeline>` inside it (adding a default element if you omit one) and sets `data-timeline` (`shown` or `none`). Load the timeline script separately (`<script src="/timeline/vehicle-sil-timeline.js">` or `import '@vehicle-sil/gui-client/timeline'`).
531
333
 
532
334
  ```ts
533
- import '@vehicle-sil/gui-client/elements'; // defines the parts
335
+ import '@vehicle-sil/gui-client/elements'; // defines the 12 parts
534
336
  import { pageIntent, setReasonText } from '@vehicle-sil/gui-client/elements';
535
337
 
536
- setReasonText((reason) => (reason.code === 'running' ? 'A run is going.' : null));
537
- pageIntent.update({ variant: 'winter' }); // what the next start uses, with the scenario that was chosen
538
- const controls = document.querySelector('vsil-run-controls'); // typed: the parts are in HTMLElementTagNameMap
539
- if (controls) controls.intent = { speed: 'max' };
540
- ```
541
-
542
- The parts need a DOM, so Node does not load them (the main entry does not import them).
543
-
544
- ### Connecting a network outside with the parts
545
-
546
- `<vsil-connect network="ETH_EXT">` is a plain `<select>`. Its first choice is `none` (SIL Kit only). It asks for the list (`connections()`) only when the user opens it: a press, or a key other than Tab, Shift, Escape and the modifiers alone (passing it by with Tab asks for nothing, and neither does opening the page). It asks again each time, with `aria-busy` while it waits. The targets come in the list's order, under the name of their backend (`<optgroup>`). A target that cannot be used is a `disabled` option whose text is its label, its detail and the launcher's reason; a backend that has no list is a line in the element that describes the select (`aria-describedby`). The choice goes into `pageIntent.connect` (`none` takes the network out). A choice that the page put into `pageIntent` itself is shown as written. The part lists and checks the configuration file that its `file` attribute names (default: the start-up file, as `run.start`): a page that starts another file sets `file` to it.
547
-
548
- While the network has a choice, the part checks the page intent (`check()`) about 200 ms after it last changed, whichever part or script changed it; the parts and the screen of a page that check the same intent share one check (`check()` shares it). It shows, as the launcher wrote them, the findings `connect-*` and `outside-*` of its network, the `connect-*` findings of the other networks of `connect` after their name (`CAN1: ...`; a finding about two networks names one of them), and the `outside-*` findings of the run when the check says that this network makes the run keep real time (`time_lock.because`). Each line has `data-code` and `data-severity`. These lines are a guide before the start: what the run does is decided when it starts, by the GUI server and the launcher. A refusal is shown as the server wrote it. After `target-not-listed`, a part that the user has opened lists the network again, once, and checks again if the choice is still listed. When a new list does not offer the choice, or offers it as one that cannot be used, the choice goes back to `none`: a line in the description says which value and why (`'<value>' is not in the list of this computer: back to SIL Kit only`, or `'<value>' cannot be used (<reason>): back to SIL Kit only`), and `data-reverted` holds the value until the user chooses again. The part does not keep a choice from one page load to the next, and it has no choice of `time_policy`: the page sets it with `pageIntent.update({ time_policy: 'free' })`.
549
-
550
- `<vsil-outside>` draws the rows of `client.outside` in words (not only in colour; the counts are not a live region, since they change every second), and nothing when there are none.
551
-
552
- ## ECU variables
553
-
554
- ```ts
555
- const watch = client.variables.watch([{ peer: 'Engine', name: 'engine.speed' }], {
556
- periodMs: 100,
557
- history: 600,
558
- });
559
- watch.values.subscribe((values) => console.log(values['Engine']?.['engine.speed']));
560
- try {
561
- const operation = await client.variables.write({ Engine: { 'engine.throttle': 50 } });
562
- console.log(operation.peers['Engine'].appliedAtMs);
563
- } catch (error) {
564
- if (error instanceof WriteError) console.log(error.kind, error.message);
338
+ setReasonText((reason) => (reason.code === 'busy' ? 'Wait a moment.' : null));
339
+ pageIntent.update({ variant: 'winter' }); // applied to the next Start alongside <vsil-scenario-select>
340
+ const controls = document.querySelector('vsil-run-controls'); // typed via HTMLElementTagNameMap
341
+ if (controls) {
342
+ controls.intent = { speed: 'max' };
343
+ controls.labelStart = 'Run';
565
344
  }
566
- watch.close();
567
345
  ```
568
346
 
569
- ### List and state (`client.variables.state`)
570
-
571
- | `status` | Meaning |
572
- | ------------ | ---------------------------------------- |
573
- | `unknown` | Not known yet |
574
- | `off` | This run has no variables |
575
- | `connecting` | Connecting |
576
- | `ready` | Variables can be read and written |
577
- | `failed` | Could not connect, or was refused |
578
- | `ended` | The run ended (values are the last ones) |
579
-
580
- - For `off`, `connecting` and `failed`, `reason` gives the reason, as text from the server (not localized).
581
- - Before you start a run, `variables` in `client.app` (`available`, `reason`) tells whether variables are available.
582
- - The variable definitions are `peers[].variables[]` (`type`, `role`, `writable`, `unit`, `min`, `max`, `step`, `description`, `enum`).
583
-
584
- ### Read values (`watch`)
585
-
586
- `watch` receives the last values of the given variables (`'all'` for every variable). Always call `close()` when you are done.
587
-
588
- **Values**: in `values` (a `Readable`), `values[peer]?.[name]` is a `VariableReading` (`value`, `sampleMs`, `simMs`, `paused`). Each value carries the time it belongs to.
589
-
590
- | `paused` | What the value is |
591
- | -------- | --------------------------------------------------------------------------------------------------------- |
592
- | True | The value at the paused time `simMs` (it includes the values of every step that started before that time) |
593
- | False | The last value while the simulation runs |
594
-
595
- **Subscriptions**:
596
-
597
- - 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 …).
598
- - `close()` also ends the server subscription if no other watch looks at the variable.
599
- - After a reconnection, the library subscribes again automatically.
600
- - A watch continues across runs; the values and history of the previous run are discarded.
601
- - Values are kept only for variables that someone is watching.
602
-
603
- **History** (when you ask for `history`):
604
-
605
- - 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.
606
- - Memory is allocated as points arrive, not when you ask.
607
- - 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).
608
- - Values of the same step are one point. If a changed value arrives for the same step, it replaces that point.
609
- - When the run changes, the history starts empty.
610
- - `watch.history(ref)` returns a new array on every call.
611
- - 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.
612
-
613
- **When a limit is near**:
614
-
615
- - 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).
616
- - If the server rejects a watch (a server with different limits), the problem appears in `client.variables.watchProblem`.
617
-
618
- ### Write values (`write`)
619
-
620
- `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).
621
-
622
- - 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.
623
- - If the run is not known yet, the library does not send and rejects with `refused` (`not-running`).
624
- - The server checks type and range, then passes the writes to the launcher.
625
- - The Promise resolves with the operation (`OperationView`) once the writes are applied (`applied`); otherwise it rejects with a `WriteError`.
626
- - The library never resends a write automatically.
627
-
628
- The `kind` of a `WriteError`:
629
-
630
- | `kind` | Meaning | Safe to resend? |
631
- | ----------- | ------------------------------------------------------------------- | -------------------------------------------------- |
632
- | `refused` | The server did not accept the write (it did not reach the launcher) | Yes, after you fix it |
633
- | `failed` | Accepted, but not applied | Yes, after you fix the reason (it was not applied) |
634
- | `no-answer` | **Unknown whether it was applied** | **Do not resend as is** (see below) |
635
- | `closed` | `close()` was called before the result | Same as above |
636
-
637
- - The `code` of `refused` is `unknown-variable`, `not-writable`, `invalid-field`, `not-running`, `session-changed`, `variables-not-ready`, `write-busy` or similar.
638
- - The `operation` of `failed` holds the state and reason for each participant (`late`, `rejected`, `invalid` and others).
639
- - `no-answer` happens in any of these cases:
640
- - No result came within `timeoutMs` (`operation` holds the last known state).
641
- - There was no HTTP response.
642
- - The server failed midway (500).
643
- - The server gave up waiting for the Control Server's response (`code` is `write-timeout`) or was disconnected midway (`write-failed`).
644
- - The run changed before the response.
645
- - The operation completed during a reconnection and the result was lost ("Reconnection" below).
646
- - The server could not keep track of all open operations and stopped following this one.
647
-
648
- **Avoid writing twice**: after `no-answer`, check before you resend.
649
-
650
- - 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).
651
- - 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).
652
- - Resend only once you know that the write was not applied.
653
- - 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.
654
-
655
- **Reconnection**: if the connection drops while you wait for a result, the summary after reconnecting (`hello`) 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 (of those the server receives: the operations of a scenario's own writes never come).
347
+ ### What the parts promise
656
348
 
657
- | Your operation | What the library does |
658
- | ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
659
- | In the list | Uses its state (if still open, keeps waiting) |
660
- | Not in the list, number below `operations_from_seq` | Treats it as completed while disconnected with its result lost: `no-answer` |
661
- | Not in the list, and the server could not keep all open operations | Sets the old operations to `no-answer` |
349
+ - **Shared page connection**: by default every part calls `connect()` without options, sharing one WebSocket with your script. Set `element.client = front` to bind a part to another `Front`. Never mix `/vsil/` files with local copies of the library (a second module copy opens a second connection).
350
+ - **Light DOM and `data-*` styling hooks**: parts draw inside a `<span class="vsil">` with no shadow DOM. Style them via `[aria-disabled="true"]`, `[data-link]`, `[data-run]`, `[data-pacing]`, `[data-stale="true"]`, `[data-can-write]`, `[data-availability="inactive"]`, `[data-on]`, `[data-error]`, `[data-cases]` (`<vsil-case-select>`: `none` or `available`), `[data-status]` and `[data-case]` (`<vsil-scenario-result>`, plus `data-status` on its steps), `[data-reason]`, `[data-caution]`, and `[data-write-status]`.
351
+ - **Write lifecycle events (`vsil-write-queued` & `vsil-write-result`)**: `<vsil-slider>` and `<vsil-write>` dispatch two bubbling, composed (`bubbles: true, composed: true`) lowercase custom events (never fired after disconnect or rebind):
352
+ - `vsil-write-queued`: `CustomEvent<WriteQueuedInfo>` (`{ session, seq, peer, name, value }`) when the write reaches the ECU queue.
353
+ - `vsil-write-result`: `CustomEvent<WriteOutcome>` — either `WriteSuccess` (`{ ok: true, session, seq, peer, name, value, appliedAtMs, late }`) or `WriteFailure` (`{ ok: false, peer, name, value, error: ActionError, seq? }`).
354
+ - Both elements also reflect the latest initiated write lifecycle on `data-write-status` (`idle`, `sending`, `queued`, `applied`, `failed`), resetting automatically across run boundaries.
355
+ - **Accessible, uncluttered reason display (`.vsil-why`, `.vsil-note`, `QUIET`)**: disabled buttons stay focusable with `aria-disabled="true"`, `data-reason`, and an `aria-describedby` link to `<small class="vsil-why">` (or `<small class="vsil-note">` on variable parts). Empty descriptions and self-evident `QUIET` codes (`not-running`, `offline`, `connecting`, `already-running`, `paused`, `not-paused`, `not-stopping`, `already-stopping`, `starting`, plus `already` on `<vsil-write>`) set `hidden` so they stay readable to screen readers without cluttering layout. When styling `.vsil-why` or `.vsil-note` in CSS, target `:not([hidden])` so your `display` rule does not unhide hidden notes. See "[Styling parts and subscribing to write events](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md#styling-parts-and-subscribing-to-write-events)" in `docs/gui.md`.
356
+ - **Failure deduplication**: if the shared connection fails (e.g., missing token), every part gets `data-error` while the error sentence appears once (`<vsil-status>` first, otherwise the first part in document order).
662
357
 
663
- - A write that has not been applied yet (for example, a write while paused) never becomes `no-answer` however many operations follow it.
664
- - "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.
358
+ ### Words and the next run
665
359
 
666
- **Options and related state**:
360
+ `setReasonText(fn)` replaces English reason sentences (`fn(reason)` returns a string, or `null`/`undefined` to keep English; `setReasonText(null)` resets). Call it before inserting parts. Built-in part labels (such as `ready`, `writing…`, `(no scenario)`, `(no cases)`, `(choose a case)`, `fastest`, `behind real time`) are fixed English strings. `pageIntent` (`get()`, `subscribe(fn)`, `update(patch)`) stores the intent for the **next** run (never overwritten by the currently running session): `<vsil-scenario-select>` writes `scenario` and clears `case` when the scenario changes; `<vsil-case-select>` reads `scenario` and `variant` from `pageIntent`, checks the scenario to list its cases, and writes `case`; `<vsil-run-controls>` merges `{ ...pageIntent.get(), ...controls.intent }`.
667
361
 
668
- - `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.
669
- - 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.
670
- - `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.
671
- - 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`, in a clone of the repository).
672
- - `client.variables.operations` lists recent operations, including writes from other clients, but not a scenario's own writes.
362
+ ### Connecting a network outside with the parts
673
363
 
674
- ### Write before the first step
364
+ `<vsil-connect network="ETH_EXT">` fetches `connections()` lazily when opened (never on page load or Tab focus), puts the choice into `pageIntent.connect`, debounces `check()` (~200 ms), and reverts unlisted targets to `none` with `data-reverted`. Set `time_policy` from script via `pageIntent.update({ time_policy: 'free' })`. `<vsil-outside>` renders `client.outside` rows with `data-network`, `data-condition`, and `data-nothing-received`.
675
365
 
676
- A run started paused (`start_paused`) waits before the first step if the launcher can read and write variables. Meanwhile `isHolding(session)` is true (`holding` in the launcher's `state`, `launcherState` of the session copy), and you can resume and step (written values are applied in the step at time 0).
366
+ ## Framework setup (5 frameworks)
677
367
 
678
- ## Build widgets (`bind`)
368
+ All 5 environments below are compiled and smoke-tested against the real packed `.tgz` in CI (`npm --prefix gui/web run verify:consumers`).
679
369
 
680
- 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`).
370
+ ### Vanilla JS / TypeScript
681
371
 
682
372
  ```ts
683
- const throttle = client.variables.bind(
684
- { peer: 'Engine', name: 'engine.throttle' },
685
- { needsRange: true, needsValue: true },
686
- );
687
- throttle.state.subscribe(({ info, reading, pending, block, writeStatus, condition }) => {
688
- slider.disabled = block !== null; // block: why it cannot be written now; null if it can
689
- slider.value = String(pending ?? reading?.value ?? info?.min ?? 0); // pending: the value sent and waiting for its result
690
- status.textContent = isWriteError(writeStatus) ? writeStatus.message : writeStatus.kind;
691
- stale.hidden = condition.kind === 'live';
373
+ import '@vehicle-sil/gui-client/elements';
374
+ import type {
375
+ VsilSliderElement,
376
+ VsilWriteElement,
377
+ WriteOutcome,
378
+ WriteQueuedInfo,
379
+ } from '@vehicle-sil/gui-client/elements';
380
+
381
+ const slider: VsilSliderElement | null = document.querySelector('vsil-slider');
382
+ slider?.addEventListener('vsil-write-queued', (e) => {
383
+ const info: WriteQueuedInfo = e.detail;
384
+ console.log(`queued seq=${info.seq} value=${info.value}`);
385
+ });
386
+ slider?.addEventListener('vsil-write-result', (e) => {
387
+ const outcome: WriteOutcome = e.detail;
388
+ if (outcome.ok) console.log(`applied at ${outcome.appliedAtMs} ms`);
389
+ else console.error(`failed (${outcome.error.code}): ${outcome.error.message}`);
692
390
  });
693
- slider.onchange = () => throttle.write(Number(slider.value));
694
- // when you are done
695
- throttle.close();
391
+
392
+ const cut: VsilWriteElement = document.createElement('vsil-write');
393
+ cut.variable = 'Engine.ecu.connected';
394
+ cut.value = false;
395
+ cut.label = 'Cut engine';
396
+ document.body.append(cut);
696
397
  ```
697
398
 
698
- Always call `close()` when you are done (it cleans up the watch and the subscriptions).
699
-
700
- ### Fields of `state` (`BoundVariable`)
701
-
702
- | Field | Contents |
703
- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
704
- | `info` | The variable definition (`undefined` if the current run does not have the variable) |
705
- | `reading` | The last value (`VariableReading`; `undefined` if there is none yet or while `visible` is false) |
706
- | `condition` | The value condition ("Value condition (`condition`)" below) |
707
- | `block` | Why the variable cannot be written now ("Why a write is blocked (`block`)" below) |
708
- | `launcherReason` | When `block` is `launcher`: the launcher's reason (`code` and an English `message`, as `launcherAnswer` reads it); `null` otherwise |
709
- | `writeStatus` | The status of the last write ("Write status (`writeStatus`, `pending`)" below) |
710
- | `pending` | The value sent and still waiting for its result (`null` if none) |
399
+ ### Angular
711
400
 
712
- - `subscribe` is called only on changes (get the first state with `state.get()`).
713
- - `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.
401
+ Add `CUSTOM_ELEMENTS_SCHEMA` to the component and import `@vehicle-sil/gui-client/elements` (and `@vehicle-sil/gui-client/timeline` if using `<vehicle-sil-timeline>`):
714
402
 
715
- ### Value condition (`condition`)
403
+ ```ts
404
+ import { CUSTOM_ELEMENTS_SCHEMA, Component } from '@angular/core';
405
+ import type { Front, Intent } from '@vehicle-sil/gui-client';
406
+ import '@vehicle-sil/gui-client/elements';
407
+ import type { WriteOutcome, WriteQueuedInfo } from '@vehicle-sil/gui-client/elements';
408
+
409
+ @Component({
410
+ selector: 'app-bench',
411
+ standalone: true,
412
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
413
+ template: `
414
+ <vsil-status [client]="front"></vsil-status>
415
+ <vsil-run-controls [client]="front" [intent]="intent" label-start="Run"></vsil-run-controls>
416
+ <vsil-slider
417
+ [client]="front"
418
+ variable="Engine.engine.throttle"
419
+ (vsil-write-queued)="onQueued($event)"
420
+ (vsil-write-result)="onResult($event)"
421
+ ></vsil-slider>
422
+ <vsil-write
423
+ [client]="front"
424
+ variable="Engine.ecu.connected"
425
+ [value]="false"
426
+ label="Cut"
427
+ ></vsil-write>
428
+ `,
429
+ })
430
+ export class BenchComponent {
431
+ front: Front | null = null;
432
+ intent: Intent = { speed: 'max' };
433
+ onQueued(event: Event): void {
434
+ const detail = (event as CustomEvent<WriteQueuedInfo>).detail;
435
+ console.log(detail.seq, detail.value);
436
+ }
437
+ onResult(event: Event): void {
438
+ const detail = (event as CustomEvent<WriteOutcome>).detail;
439
+ console.log(detail.ok ? detail.appliedAtMs : detail.error.code);
440
+ }
441
+ }
442
+ ```
716
443
 
717
- Switch on `condition.kind`.
444
+ ### React 18 and 19
445
+
446
+ Import `@vehicle-sil/gui-client/react` once (for example in `src/main.tsx` or `src/env.d.ts`) to register JSX types for all 12 `vsil-*` parts and `<vehicle-sil-timeline>`.
447
+
448
+ ```tsx
449
+ import { useEffect, useRef } from 'react';
450
+ import type { Front } from '@vehicle-sil/gui-client';
451
+ import '@vehicle-sil/gui-client/elements';
452
+ import '@vehicle-sil/gui-client/react';
453
+ import '@vehicle-sil/gui-client/timeline';
454
+ import type { VsilSliderElement, WriteOutcome } from '@vehicle-sil/gui-client/elements';
455
+
456
+ // React 19: lowercase `on<event>` JSX props delegate directly via addEventListener.
457
+ export function BenchReact19({ front }: { front: Front }) {
458
+ return (
459
+ <div>
460
+ <vsil-status client={front} />
461
+ <vsil-run-controls client={front} intent={{ speed: 'max' }} labelStart="Run" />
462
+ <vsil-value client={front} variable="Engine.engine.speed" noUnit={false} />
463
+ <vsil-slider
464
+ client={front}
465
+ variable="Engine.engine.throttle"
466
+ onvsil-write-queued={(e) => console.log(e.detail.seq)}
467
+ onvsil-write-result={(e) =>
468
+ console.log(e.detail.ok ? e.detail.appliedAtMs : e.detail.error.code)
469
+ }
470
+ />
471
+ <vsil-write client={front} variable="Engine.ecu.connected" value={false} label="Cut" />
472
+ <vehicle-sil-timeline
473
+ compact={true}
474
+ variables={['Engine.*']}
475
+ onload={(e) => console.log(e.detail.status)}
476
+ onerror={(e) => console.error(e.detail.message)}
477
+ />
478
+ </div>
479
+ );
480
+ }
718
481
 
719
- | `kind` | Meaning |
720
- | ------------- | -------------------------------------------------------------------------------------------- |
721
- | `unavailable` | The variable feature is not available (`status` holds the state of `client.variables.state`) |
722
- | `missing` | The current run does not have the variable |
723
- | `waiting` | The current run has the variable, but no value has arrived yet |
724
- | `live` | The last value while the simulation runs |
725
- | `paused` | The value at the paused time |
726
- | `stale` | A value that may be stale (the reason is in `why`) |
727
- | `ended` | The last value read in a run that ended |
728
-
729
- The `status` of `unavailable` is one of: not running, this run has no variables, connecting, cannot connect. The values of `why` for `stale`:
482
+ // React 18 (also works in React 19): attach custom element listeners and object props via ref + useEffect.
483
+ export function BenchSliderReact18({ front }: { front: Front }) {
484
+ const ref = useRef<VsilSliderElement>(null);
485
+ useEffect(() => {
486
+ const el = ref.current;
487
+ if (!el) return;
488
+ el.client = front;
489
+ const onResult = (e: CustomEvent<WriteOutcome>) => console.log(e.detail);
490
+ el.addEventListener('vsil-write-result', onResult);
491
+ return () => el.removeEventListener('vsil-write-result', onResult);
492
+ }, [front]);
493
+ return <vsil-slider ref={ref} variable="Engine.engine.throttle" />;
494
+ }
495
+ ```
730
496
 
731
- | `why` | Meaning |
732
- | -------------- | -------------------------------------------------------- |
733
- | `connection` | The connection between the client and the server dropped |
734
- | `reconnecting` | The server is reconnecting to the launcher |
735
- | `peer` | The ECU is disconnected |
736
- | `reading` | Reading values keeps failing |
497
+ > **React 19 `onload` / `onerror` note**: React intercepts PascalCase `onLoad` / `onError` as synthetic React events that never fire for custom-element `CustomEvent`s (our `./react` types omit `onLoad` / `onError` on `<vehicle-sil-timeline>` to catch this at compile time). Use lowercase `onload` / `onerror` in React 19, or `ref` + `addEventListener` when supporting both React 18 and React 19.
737
498
 
738
- ### Why a write is blocked (`block`)
499
+ ### Vue 3
739
500
 
740
- `null` if the variable can be written. If several reasons apply, `block` is the one highest in the table.
501
+ Configure Vue's template compiler so `vsil-*` and `vehicle-sil-timeline` are treated as native custom elements (for example in `vite.config.ts`: `vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('vsil-') || tag === 'vehicle-sil-timeline' } } })`), and import `@vehicle-sil/gui-client/vue` for `vue-tsc` types:
741
502
 
742
- The facts of the variable and the run come first, then the launcher's answer (`launcher`), then the client's prediction (`parameter`), then what the widget needs. Only `launcher` comes from the launcher; the other values are the client's own. The client has no rule of its own about what the launcher accepts: when the launcher takes a write during a scenario, `bind` lets it through. It reads the launcher's answer with `launcherAnswer(launcherState, 'write')`, as `controls` of the front door read theirs.
503
+ ```vue
504
+ <script setup lang="ts">
505
+ import type { Front, Intent } from '@vehicle-sil/gui-client';
506
+ import '@vehicle-sil/gui-client/elements';
507
+ import type { WriteOutcome, WriteQueuedInfo } from '@vehicle-sil/gui-client/elements';
508
+ import '@vehicle-sil/gui-client/vue';
743
509
 
744
- | `block` | Meaning |
745
- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
746
- | `read-only` | A read-only variable (`role` is `output`) |
747
- | `disconnected` | The connection between the client and the server is down |
748
- | `ended` | The run ended |
749
- | `not-ready` | The variable feature is not available (not running, connecting, cannot connect) |
750
- | `missing` | The current run does not have the variable |
751
- | `peer-disconnected` | The ECU is not connected to the Control Server |
752
- | `launcher` | The launcher does not take a write now (`allowed.write` of its `state`; `launcherReason` has its code and sentence, for example `scenario-running` while a scenario plays), or has not said yet that it does: until a `state` with `allowed.write` arrives, `unsupported` |
753
- | `parameter` | A `parameter` can be written only before the first step of a run started paused (`isHolding(session)`: `holding` in the launcher's `state`). The client's prediction of the ECU's rule: the launcher does not say it for each variable |
754
- | `no-range` | `needsRange` is set, but the variable has no range (`min` and `max`) |
755
- | `no-value` | `needsValue` is set, and there is no value yet (neither read nor sent) |
510
+ const props = defineProps<{ front: Front | null }>();
511
+ const intent: Intent = { speed: 'max' };
756
512
 
757
- ### Write status (`writeStatus`, `pending`)
513
+ function onWriteQueued(event: CustomEvent<WriteQueuedInfo>) {
514
+ console.log(event.detail.seq, event.detail.value);
515
+ }
516
+ function onWriteResult(event: CustomEvent<WriteOutcome>) {
517
+ console.log(event.detail.ok ? event.detail.appliedAtMs : event.detail.error.code);
518
+ }
519
+ </script>
520
+
521
+ <template>
522
+ <vsil-status :client="props.front" />
523
+ <vsil-run-controls :client="props.front" :intent="intent" label-start="Run" />
524
+ <vsil-value :client="props.front" variable="Engine.engine.speed" :noUnit="true" />
525
+ <vsil-slider
526
+ :client="props.front"
527
+ variable="Engine.engine.throttle"
528
+ @vsil-write-queued="onWriteQueued"
529
+ @vsil-write-result="onWriteResult"
530
+ />
531
+ <vsil-write
532
+ :client="props.front"
533
+ variable="Engine.ecu.connected"
534
+ :value="false"
535
+ label="Cut"
536
+ @vsil-write-queued="onWriteQueued"
537
+ @vsil-write-result="onWriteResult"
538
+ />
539
+ </template>
540
+ ```
758
541
 
759
- `writeStatus` is the status of the last write.
760
-
761
- | `writeStatus` | Meaning |
762
- | ------------------------------------------ | -------------------------------------------------------------- |
763
- | `idle` | Empty (no last write) |
764
- | `sending` | Sent |
765
- | `queued` | The server received it (`seq` is the operation number) |
766
- | `applied` | Applied (`atMs`) |
767
- | `invalid` | The text passed to `reject(message)` (not sent) |
768
- | `dropped` | A kept value was not sent ("How `write(value)` behaves" below) |
769
- | `refused`, `failed`, `no-answer`, `closed` | The `kind` of a `WriteError` (has `message` and `code`) |
770
-
771
- - `isWriteError(writeStatus)` picks out the statuses that have a `message` (the ones that did not succeed).
772
- - `message` is not localized. To show it in the screen's language, build the text from `kind`.
773
- - 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).
774
-
775
- ### How `write(value)` behaves
776
-
777
- - If the variable cannot be written (`block`), it does nothing.
778
- - It returns no Promise; the result appears in `writeStatus`.
779
- - It waits for the operation's result with no time limit (a write while paused stays `queued` until the simulation advances).
780
- - 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).
781
- - 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`.
782
- - If the previous write is rejected before it is received, the kept value is not sent either.
783
- - A write that got no result (`no-answer`) is never resent automatically.
784
- - `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`.
785
-
786
- ### One state per variable
787
-
788
- - However many places `bind` the same variable, they all see the same `writeStatus` and `pending`, and writes do not overlap.
789
- - The state survives closing a `bind` and creating it again.
790
- - 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.
791
-
792
- ### Watch only while visible
793
-
794
- `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:
795
-
796
- | Field | While `visible` is false |
797
- | ------------------------ | --------------------------------------------------------------------------------------------------- |
798
- | `reading` | `undefined` |
799
- | `condition` | `waiting` |
800
- | `writeStatus`, `pending` | Reported as usual |
801
- | `block` | Reported as usual (a `bind` with `needsValue` reports `no-value` unless there is a `pending` value) |
802
-
803
- ### History
804
-
805
- 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.
806
-
807
- ### What is not checked, and after `close()`
808
-
809
- - `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)`.
810
- - After `close()`, `write`, `reject` and `setVisible` do nothing.
811
- - `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).
812
-
813
- ## Lifecycle
814
-
815
- | Call | What it does |
816
- | --------------------------------------------------- | ----------------------------------------------------------------------------- |
817
- | `createClient()` | Only creates the client; does not connect |
818
- | `connect()` | Connects over WebSocket (does nothing without a token) |
819
- | `connect()` while connected | Does nothing (also while waiting to reconnect) |
820
- | `close()` | Disconnects and does not reconnect (what it cleans up is below) |
821
- | `connect()` after `close()` | Connects again and subscribes the remaining watches again |
822
- | HTTP requests after `close()` | Work (`loadApp()`, `run.start()` and others can be sent without a connection) |
823
- | `connect()` after a rejection or a version mismatch | Does nothing (`session.rejected` and `session.incompatible` do not reset) |
824
-
825
- - `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.
826
- - After `close()` and `connect()`, the session copy is still there, and the library receives again from where its copy ends.
827
- - To connect with another token or version, create a new client.
542
+ ### Svelte 5
828
543
 
829
- ## Coding rules
830
-
831
- - 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/`).
832
- - Do not use anything that exists only in the browser (`window`, `document`, `localStorage` and so on). Take what you need through the options (`ClientOptions`).
833
- - 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`).
834
- - 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.
544
+ Import `@vehicle-sil/gui-client/svelte` for `svelte-check` element and event typing:
835
545
 
836
- ## Tests
546
+ ```svelte
547
+ <script lang="ts">
548
+ import type { Front, Intent } from '@vehicle-sil/gui-client';
549
+ import '@vehicle-sil/gui-client/elements';
550
+ import type { WriteOutcome, WriteQueuedInfo } from '@vehicle-sil/gui-client/elements';
551
+ import '@vehicle-sil/gui-client/svelte';
837
552
 
838
- 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):
553
+ let { front }: { front: Front | null } = $props();
554
+ const intent: Intent = { speed: 'max' };
839
555
 
840
- | Command | What it does |
841
- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
842
- | `npm run test:client` | Type check (`tsc -p ../client`) and unit tests (Vitest; the library runs on Node, without Angular; the parts in `src/elements` run in a headless Chromium) |
843
- | `npm run build:client` | Bundles into one ESM file, and the parts into a second one that imports it (esbuild, the copy that comes with the Angular build tools) |
844
- | `npm run lint` | `gui/web`, and this directory with its `eslint.config.js` |
845
- | `npm run format:check` | Formatting of `gui/web` and this directory (`gui/.prettierrc`) |
846
-
847
- The tests of the parts need Playwright's Chromium (`npx playwright install --only-shell chromium` in `gui/web`; `scripts/doctor.py` says whether it starts). They run headless; to watch them, run `npx vitest --config ../client/vitest.config.mjs --project browser --browser.headless=false` in `gui/web`.
848
-
849
- The unit tests feed the examples in `gui/protocol/examples/` instead of building server notifications by hand (`testing/protocol-examples.ts`).
850
-
851
- ## See also
556
+ function onWriteQueued(event: CustomEvent<WriteQueuedInfo>) {
557
+ console.log(event.detail.seq, event.detail.value);
558
+ }
559
+ function onWriteResult(event: CustomEvent<WriteOutcome>) {
560
+ console.log(event.detail.ok ? event.detail.appliedAtMs : event.detail.error.code);
561
+ }
562
+ </script>
563
+
564
+ <vsil-status client={front}></vsil-status>
565
+ <vsil-run-controls client={front} {intent} label-start="Run"></vsil-run-controls>
566
+ <vsil-time-controls client={front} speeds="0.5 1 max" stepMs={25}></vsil-time-controls>
567
+ <vsil-value client={front} variable="Engine.engine.speed" noUnit={true}></vsil-value>
568
+ <vsil-slider
569
+ client={front}
570
+ variable="Engine.engine.throttle"
571
+ onvsil-write-queued={onWriteQueued}
572
+ onvsil-write-result={onWriteResult}
573
+ ></vsil-slider>
574
+ <vsil-write
575
+ client={front}
576
+ variable="Engine.ecu.connected"
577
+ value={false}
578
+ label="Cut"
579
+ onvsil-write-queued={onWriteQueued}
580
+ onvsil-write-result={onWriteResult}
581
+ ></vsil-write>
582
+ ```
852
583
 
853
- | To find | Document |
854
- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
855
- | Which way to add your own code to the GUI: a custom panel, your own screen or a tool | "Build your own screen" in [docs/gui.md](../../docs/gui.md#build-your-own-screen) |
856
- | 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) |
857
- | The server API (HTTP and WebSocket shapes, versioning and compatibility rules, authentication) | [gui/protocol](../protocol/README.md) |
858
- | 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) |
859
- | Files to start your own screen from | The screen template [examples/gui_starter](../../examples/gui_starter/) |
860
- | An example that uses the library from Node, without a screen | [examples/gui_client](../../examples/gui_client/) |
861
-
862
- `examples/gui_client` exists only in the repository (the prebuilt tools archive contains `gui_starter/` and `client/`).
584
+ ## Low-level API and see also
863
585
 
864
- | File | What it does |
865
- | ---------------------- | ---------------------------------------------------------- |
866
- | `run.mjs` | Calls the server API without the library |
867
- | `run-with-library.mjs` | Uses the bundled library file from plain JavaScript (Node) |
868
- | `front.mjs` | Uses the front door (`connect()`, `status`) from Node |
869
- | `variables.mjs` | Also uses the library, to read and write ECU variables |
586
+ | To find | Document |
587
+ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
588
+ | Low-level `createClient()`, full `Public API`, `variables.bind()`, `createWaveforms()`, `createVariableEditor()`, `raw` keys, lifecycle, and contributor tests | [docs/gui-client-low-level.md](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui-client-low-level.md) |
589
+ | Control `reason.code` / `caution.code` tables, CSP restrictions, live polling vs `--timeline`/`Spy`, and screen rules | [docs/gui.md](https://github.com/rahanahu/vehicle-sil/blob/main/docs/gui.md) |
590
+ | Step-by-step guide to build and serve your own screen | [Build your own screen for the browser GUI](https://github.com/rahanahu/vehicle-sil/blob/main/docs/howto/gui-screen.md) |
591
+ | Server HTTP and WebSocket protocol specification | [gui/protocol/README.md](https://github.com/rahanahu/vehicle-sil/blob/main/gui/protocol/README.md) |
592
+ | No-build HTML/CSS/JS screen starter template | [examples/gui_starter](https://github.com/rahanahu/vehicle-sil/tree/main/examples/gui_starter) |
593
+ | Node.js headless client examples (`run.mjs`, `front.mjs`, `variables.mjs`) | [examples/gui_client](https://github.com/rahanahu/vehicle-sil/tree/main/examples/gui_client) |