sygnal 7.0.0 → 7.2.0-preview.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 (343) hide show
  1. package/CHANGELOG.md +632 -0
  2. package/dist/agent-ui.cjs.js +592 -0
  3. package/dist/agent-ui.cjs.js.map +1 -0
  4. package/dist/agent-ui.esm.js +582 -0
  5. package/dist/agent-ui.esm.js.map +1 -0
  6. package/dist/api.cjs.js +63 -0
  7. package/dist/api.cjs.js.map +1 -0
  8. package/dist/api.esm.js +2 -0
  9. package/dist/api.esm.js.map +1 -0
  10. package/dist/astro/index.cjs.js +968 -4
  11. package/dist/astro/index.cjs.js.map +1 -1
  12. package/dist/astro/index.mjs +968 -4
  13. package/dist/astro/index.mjs.map +1 -1
  14. package/dist/astro/server.cjs.js +73 -45
  15. package/dist/astro/server.cjs.js.map +1 -1
  16. package/dist/astro/server.mjs +73 -45
  17. package/dist/astro/server.mjs.map +1 -1
  18. package/dist/canvas.cjs.js +2919 -0
  19. package/dist/canvas.cjs.js.map +1 -0
  20. package/dist/canvas.esm.js +2866 -0
  21. package/dist/canvas.esm.js.map +1 -0
  22. package/dist/devtools.cjs.js +38 -6
  23. package/dist/devtools.cjs.js.map +1 -1
  24. package/dist/devtools.esm.js +38 -6
  25. package/dist/devtools.esm.js.map +1 -1
  26. package/dist/diagnostics.cjs.js +224 -20
  27. package/dist/diagnostics.cjs.js.map +1 -1
  28. package/dist/diagnostics.esm.js +224 -20
  29. package/dist/diagnostics.esm.js.map +1 -1
  30. package/dist/guide/accessibility.md +1 -1
  31. package/dist/guide/ai-compose.md +150 -0
  32. package/dist/guide/behaviors.md +2 -1
  33. package/dist/guide/collaborative-state.md +265 -0
  34. package/dist/guide/element-commands.md +36 -2
  35. package/dist/guide/forms-reference.md +5 -5
  36. package/dist/guide/forms.md +3 -2
  37. package/dist/guide/http.md +28 -1
  38. package/dist/guide/islands.md +240 -0
  39. package/dist/guide/recipes/code-editor.md +1 -1
  40. package/dist/guide/renderers/agent-ui.md +138 -0
  41. package/dist/guide/renderers/custom-targets.md +126 -0
  42. package/dist/guide/renderers/overview.md +120 -0
  43. package/dist/guide/renderers/react-native.md +128 -0
  44. package/dist/guide/renderers/terminal.md +306 -0
  45. package/dist/guide/renderers/three.md +332 -0
  46. package/dist/guide/renderers/write-once.md +137 -0
  47. package/dist/guide/resources.md +2 -0
  48. package/dist/guide/sandboxed-components.md +223 -0
  49. package/dist/guide/timers.md +32 -5
  50. package/dist/guide/typed-apis.md +442 -0
  51. package/dist/guide/ui/accordion.md +11 -0
  52. package/dist/guide/ui/combobox.md +112 -8
  53. package/dist/guide/ui/dialog.md +96 -20
  54. package/dist/guide/ui/menu.md +57 -5
  55. package/dist/guide/ui/overview.md +8 -4
  56. package/dist/guide/ui/popover.md +69 -9
  57. package/dist/guide/ui/select.md +54 -4
  58. package/dist/guide/ui/tabs.md +1 -1
  59. package/dist/guide/ui/tooltip.md +7 -5
  60. package/dist/guide/virtual-collections.md +3 -0
  61. package/dist/guide/widgets.md +90 -1
  62. package/dist/host.cjs.js +2181 -0
  63. package/dist/host.cjs.js.map +1 -0
  64. package/dist/host.esm.js +2146 -0
  65. package/dist/host.esm.js.map +1 -0
  66. package/dist/index.cjs.js +3948 -586
  67. package/dist/index.cjs.js.map +1 -1
  68. package/dist/index.d.ts +584 -44
  69. package/dist/index.esm.js +3918 -586
  70. package/dist/index.esm.js.map +1 -1
  71. package/dist/primitives.cjs.js +143 -0
  72. package/dist/primitives.cjs.js.map +1 -0
  73. package/dist/primitives.esm.js +133 -0
  74. package/dist/primitives.esm.js.map +1 -0
  75. package/dist/react-native.cjs.js +248 -0
  76. package/dist/react-native.cjs.js.map +1 -0
  77. package/dist/react-native.esm.js +244 -0
  78. package/dist/react-native.esm.js.map +1 -0
  79. package/dist/replay.cjs.js +39 -0
  80. package/dist/replay.cjs.js.map +1 -0
  81. package/dist/replay.esm.js +2 -0
  82. package/dist/replay.esm.js.map +1 -0
  83. package/dist/sandbox-build.cjs.js +140 -0
  84. package/dist/sandbox-build.cjs.js.map +1 -0
  85. package/dist/sandbox-build.esm.js +137 -0
  86. package/dist/sandbox-build.esm.js.map +1 -0
  87. package/dist/sandbox-kernel.esm.js +212 -0
  88. package/dist/sandbox-kernel.esm.js.map +1 -0
  89. package/dist/sandbox-worker.cjs.js +857 -0
  90. package/dist/sandbox-worker.cjs.js.map +1 -0
  91. package/dist/sandbox-worker.esm.js +854 -0
  92. package/dist/sandbox-worker.esm.js.map +1 -0
  93. package/dist/sandbox.cjs.js +1425 -0
  94. package/dist/sandbox.cjs.js.map +1 -0
  95. package/dist/sandbox.esm.js +1406 -0
  96. package/dist/sandbox.esm.js.map +1 -0
  97. package/dist/sygnal.min.js +1 -1
  98. package/dist/sygnal.min.js.map +1 -1
  99. package/dist/terminal.cjs.js +1314 -0
  100. package/dist/terminal.cjs.js.map +1 -0
  101. package/dist/terminal.esm.js +1304 -0
  102. package/dist/terminal.esm.js.map +1 -0
  103. package/dist/three.cjs.js +1111 -0
  104. package/dist/three.cjs.js.map +1 -0
  105. package/dist/three.esm.js +1079 -0
  106. package/dist/three.esm.js.map +1 -0
  107. package/dist/ui-combobox.cjs.js +256 -18
  108. package/dist/ui-combobox.cjs.js.map +1 -1
  109. package/dist/ui-combobox.esm.js +256 -18
  110. package/dist/ui-combobox.esm.js.map +1 -1
  111. package/dist/ui-menu.cjs.js +150 -16
  112. package/dist/ui-menu.cjs.js.map +1 -1
  113. package/dist/ui-menu.esm.js +151 -17
  114. package/dist/ui-menu.esm.js.map +1 -1
  115. package/dist/ui-select.cjs.js +95 -9
  116. package/dist/ui-select.cjs.js.map +1 -1
  117. package/dist/ui-select.esm.js +95 -9
  118. package/dist/ui-select.esm.js.map +1 -1
  119. package/dist/ui.cjs.js +679 -173
  120. package/dist/ui.cjs.js.map +1 -1
  121. package/dist/ui.esm.js +679 -175
  122. package/dist/ui.esm.js.map +1 -1
  123. package/dist/vike/config/package.json +1 -1
  124. package/dist/vite/plugin.cjs.js +968 -4
  125. package/dist/vite/plugin.cjs.js.map +1 -1
  126. package/dist/vite/plugin.mjs +968 -4
  127. package/dist/vite/plugin.mjs.map +1 -1
  128. package/dist/worker-page.cjs.js +669 -0
  129. package/dist/worker-page.cjs.js.map +1 -0
  130. package/dist/worker-page.esm.js +665 -0
  131. package/dist/worker-page.esm.js.map +1 -0
  132. package/dist/worker.cjs.js +377 -0
  133. package/dist/worker.cjs.js.map +1 -0
  134. package/dist/worker.esm.js +374 -0
  135. package/dist/worker.esm.js.map +1 -0
  136. package/dist/yjs-testing.cjs.js +98 -0
  137. package/dist/yjs-testing.cjs.js.map +1 -0
  138. package/dist/yjs-testing.esm.js +77 -0
  139. package/dist/yjs-testing.esm.js.map +1 -0
  140. package/dist/yjs.cjs.js +923 -0
  141. package/dist/yjs.cjs.js.map +1 -0
  142. package/dist/yjs.esm.js +900 -0
  143. package/dist/yjs.esm.js.map +1 -0
  144. package/dist/zag.cjs.js +11 -1
  145. package/dist/zag.cjs.js.map +1 -1
  146. package/dist/zag.esm.js +11 -1
  147. package/dist/zag.esm.js.map +1 -1
  148. package/llms/ai.md +65 -0
  149. package/llms/collaboration.md +5 -0
  150. package/llms/graphics.md +10 -0
  151. package/llms/renderers.md +7 -0
  152. package/llms/replay.md +5 -0
  153. package/llms/sandbox.md +5 -0
  154. package/llms/typed-apis.md +5 -0
  155. package/llms/ui.md +10 -0
  156. package/llms-full.txt +444 -0
  157. package/llms.txt +37 -35
  158. package/package.json +139 -3
  159. package/src/agent-ui/mcp.ts +152 -0
  160. package/src/agent-ui/snapshot.ts +212 -0
  161. package/src/agent-ui.d.ts +106 -0
  162. package/src/agent-ui.ts +249 -0
  163. package/src/ai.d.ts +95 -2
  164. package/src/api.d.ts +303 -0
  165. package/src/api.ts +9 -0
  166. package/src/canvas/Canvas.ts +585 -0
  167. package/src/canvas/backend.ts +627 -0
  168. package/src/canvas/geometry.ts +187 -0
  169. package/src/canvas/gesture.ts +23 -0
  170. package/src/canvas/image.ts +197 -0
  171. package/src/canvas/kit.ts +130 -0
  172. package/src/canvas/paint.ts +260 -0
  173. package/src/canvas/pointer.ts +25 -0
  174. package/src/canvas/snap.ts +68 -0
  175. package/src/canvas/svg.ts +99 -0
  176. package/src/canvas.d.ts +373 -0
  177. package/src/canvas.ts +46 -0
  178. package/src/core/actions.ts +14 -3
  179. package/src/core/cell.ts +12 -4
  180. package/src/core/debug.ts +8 -3
  181. package/src/core/hooks.ts +16 -2
  182. package/src/core/hosts/collection.ts +1 -1
  183. package/src/core/hosts/switchable.ts +26 -8
  184. package/src/core/instance.ts +98 -45
  185. package/src/core/markers/portal.ts +4 -0
  186. package/src/core/registry.ts +4 -0
  187. package/src/core/runtime.ts +34 -25
  188. package/src/core/statics.ts +5 -5
  189. package/src/cycle/dom/EventDelegator.ts +37 -33
  190. package/src/cycle/dom/MainDOMSource.ts +16 -14
  191. package/src/cycle/dom/enrichEventStream.ts +13 -9
  192. package/src/cycle/dom/fromEvent.ts +6 -10
  193. package/src/cycle/dom/index.ts +11 -7
  194. package/src/cycle/dom/isolate.ts +13 -6
  195. package/src/cycle/dom/makeDOMDriver.ts +6 -2
  196. package/src/cycle/dom/utils.ts +9 -2
  197. package/src/cycle/run/adapt.ts +4 -12
  198. package/src/devtools.d.ts +9 -0
  199. package/src/devtools.ts +2 -1
  200. package/src/extra/ai/compose/catalog.ts +2 -1
  201. package/src/extra/ai/compose/decisions.ts +1 -2
  202. package/src/extra/ai/compose/generated.ts +234 -0
  203. package/src/extra/ai/compose/index.ts +6 -2
  204. package/src/extra/ai/compose/layout.ts +3 -1
  205. package/src/extra/ai/compose/llm.ts +7 -3
  206. package/src/extra/ai/compose/types.ts +2 -2
  207. package/src/extra/ai/transports/shared.ts +3 -1
  208. package/src/extra/api/contract.ts +485 -0
  209. package/src/extra/api/index.ts +26 -0
  210. package/src/extra/behaviors.ts +3 -3
  211. package/src/extra/controlled.ts +44 -0
  212. package/src/extra/copyAsTest.ts +22 -0
  213. package/src/extra/devtools.ts +5 -3
  214. package/src/extra/devtoolsActions.ts +8 -0
  215. package/src/extra/devtoolsNext.ts +1 -1
  216. package/src/extra/diagnostics/checks/actionLog.ts +8 -3
  217. package/src/extra/diagnostics/checks/behaviors.ts +25 -0
  218. package/src/extra/diagnostics/checks/elementCommands.ts +17 -5
  219. package/src/extra/diagnostics/checks/index.ts +1 -1
  220. package/src/extra/diagnostics/checks/next.ts +78 -4
  221. package/src/extra/diagnostics/checks/props.ts +6 -1
  222. package/src/extra/diagnostics/checks/replies.ts +11 -7
  223. package/src/extra/diagnostics/checks/timers.ts +8 -2
  224. package/src/extra/diagnostics/checks/virtual.ts +11 -0
  225. package/src/extra/diagnostics/codes.ts +51 -1
  226. package/src/extra/elementCommands.ts +20 -4
  227. package/src/extra/fetchDriver.ts +4 -1
  228. package/src/extra/fetchEventSource.ts +6 -2
  229. package/src/extra/field.ts +29 -0
  230. package/src/extra/form.ts +42 -16
  231. package/src/extra/frame.ts +54 -0
  232. package/src/extra/keymap.ts +41 -0
  233. package/src/extra/pager.ts +2 -0
  234. package/src/extra/persist.ts +2 -1
  235. package/src/extra/pointer.ts +262 -0
  236. package/src/extra/processForm.ts +34 -1
  237. package/src/extra/replay/address.ts +49 -0
  238. package/src/extra/replay/entropy.ts +99 -0
  239. package/src/extra/replay/format.ts +263 -0
  240. package/src/extra/replay/index.ts +8 -0
  241. package/src/extra/replay/inert.ts +22 -0
  242. package/src/extra/replay/recorder.ts +247 -0
  243. package/src/extra/replay/replayer.ts +234 -0
  244. package/src/extra/replay/report.ts +126 -0
  245. package/src/extra/replay/schema.ts +52 -0
  246. package/src/extra/replay/version.ts +3 -0
  247. package/src/extra/router.ts +7 -3
  248. package/src/extra/selection.ts +2 -0
  249. package/src/extra/socketDriver.ts +51 -6
  250. package/src/extra/ssr.ts +128 -42
  251. package/src/extra/testing.ts +295 -39
  252. package/src/extra/timers.ts +96 -7
  253. package/src/extra/undo.ts +2 -0
  254. package/src/extra/virtual.ts +25 -2
  255. package/src/extra/widget.ts +106 -17
  256. package/src/host/actions.ts +383 -0
  257. package/src/host/delegation.ts +101 -0
  258. package/src/host/dom.ts +553 -0
  259. package/src/host/driver.ts +185 -0
  260. package/src/host/selector.ts +119 -0
  261. package/src/host/style.ts +51 -0
  262. package/src/host.d.ts +298 -0
  263. package/src/host.ts +46 -0
  264. package/src/index.d.ts +302 -38
  265. package/src/index.ts +15 -3
  266. package/src/pragma/blocks.ts +211 -0
  267. package/src/pragma/index.ts +44 -10
  268. package/src/primitives.d.ts +54 -0
  269. package/src/primitives.ts +136 -0
  270. package/src/react-native.d.ts +57 -0
  271. package/src/react-native.ts +285 -0
  272. package/src/react-peers.d.ts +21 -3
  273. package/src/replay.d.ts +185 -0
  274. package/src/replay.ts +6 -0
  275. package/src/sandbox/build.ts +119 -0
  276. package/src/sandbox/create.ts +187 -0
  277. package/src/sandbox/engine.ts +267 -0
  278. package/src/sandbox/generated.ts +195 -0
  279. package/src/sandbox/kernel.ts +180 -0
  280. package/src/sandbox/mirror.ts +269 -0
  281. package/src/sandbox/protocol.ts +128 -0
  282. package/src/sandbox/quickjs.ts +74 -0
  283. package/src/sandbox/ssr.ts +41 -0
  284. package/src/sandbox/widget.ts +60 -0
  285. package/src/sandbox/worker-entry.ts +59 -0
  286. package/src/sandbox/worker.ts +137 -0
  287. package/src/sandbox-build.d.ts +12 -0
  288. package/src/sandbox-build.ts +6 -0
  289. package/src/sandbox.d.ts +299 -0
  290. package/src/sandbox.ts +25 -0
  291. package/src/shared.ts +12 -0
  292. package/src/terminal/paint.ts +712 -0
  293. package/src/terminal.d.ts +167 -0
  294. package/src/terminal.ts +530 -0
  295. package/src/three/assets.ts +170 -0
  296. package/src/three/host.ts +36 -0
  297. package/src/three/scene.ts +217 -0
  298. package/src/three/target.ts +252 -0
  299. package/src/three.d.ts +221 -0
  300. package/src/three.ts +30 -0
  301. package/src/ui/accordion.ts +21 -7
  302. package/src/ui/dialog.ts +192 -90
  303. package/src/ui/disclosure.ts +2 -0
  304. package/src/ui/dom.ts +30 -0
  305. package/src/ui/layers.ts +132 -0
  306. package/src/ui/popover.ts +120 -21
  307. package/src/ui/shared.ts +98 -12
  308. package/src/ui/stack.ts +18 -0
  309. package/src/ui/tabs.ts +2 -0
  310. package/src/ui/toaster.ts +16 -15
  311. package/src/ui/tooltip.ts +24 -8
  312. package/src/ui/tooltips.ts +26 -14
  313. package/src/ui/zag/combobox.ts +180 -13
  314. package/src/ui/zag/menu.ts +97 -17
  315. package/src/ui/zag/select.ts +15 -4
  316. package/src/ui/zag/shared.ts +60 -8
  317. package/src/ui-combobox.d.ts +16 -1
  318. package/src/ui-menu.d.ts +22 -7
  319. package/src/ui-zag-types.d.ts +13 -5
  320. package/src/ui.d.ts +62 -7
  321. package/src/ui.ts +2 -2
  322. package/src/vite/api.ts +186 -0
  323. package/src/vite/compile.ts +280 -0
  324. package/src/vite/plugin.d.ts +34 -0
  325. package/src/vite/plugin.ts +78 -4
  326. package/src/vite/sandbox.ts +16 -0
  327. package/src/worker/page.ts +396 -0
  328. package/src/worker/protocol.ts +48 -0
  329. package/src/worker/target.ts +282 -0
  330. package/src/worker-page.d.ts +42 -0
  331. package/src/worker-page.ts +12 -0
  332. package/src/worker.d.ts +65 -0
  333. package/src/worker.ts +16 -0
  334. package/src/yjs/driver.ts +253 -0
  335. package/src/yjs/mapping.ts +389 -0
  336. package/src/yjs/shared.ts +138 -0
  337. package/src/yjs/testing.ts +91 -0
  338. package/src/yjs-testing.d.ts +34 -0
  339. package/src/yjs-testing.ts +7 -0
  340. package/src/yjs.d.ts +109 -0
  341. package/src/yjs.ts +18 -0
  342. package/src/zag.d.ts +2 -0
  343. package/src/zag.ts +8 -1
package/llms-full.txt ADDED
@@ -0,0 +1,444 @@
1
+ # Sygnal
2
+
3
+ > Reactive component framework (Cycle.js Model-View-Intent, JSX views, xstream streams). `npm i sygnal`; Vite: `import sygnal from 'sygnal/vite'`, `plugins: [sygnal()]`; entry: `run(App)`. This file shows only the canonical forms. Strict mode (`sygnal-check --strict`, runtime `strict: true`) flags other forms as SYG5xx; forms 6.0 removed (positional views, `'A | SINK'` keys, `CHILD.select('Name')`, `.components`, `.peers`, `component()`) are SYG612: https://sygnal.js.org/guide/migrating-to-6/. 7.0 changes reducer timing (outputs see the state after STATE) and child lifetimes: https://sygnal.js.org/guide/migrating-to-7/
4
+
5
+ ## Topic files
6
+ Read the one you need before writing that feature. They sit next to this file (`node_modules/sygnal/llms/`, https://sygnal.js.org/llms/); `llms-full.txt` is this file plus all of them.
7
+ - [llms/ai.md](llms/ai.md): `sygnal/ai`: chat, one-off LLM requests, the `agent` static (tools for an LLM), decisions, pages and chat cards a model composes from your parts
8
+ - [llms/ui.md](llms/ui.md): dialog, popover, tooltip, tabs, accordion, disclosure, toasts (`sygnal/ui`), Menu / Select / Combobox, `fromReact` / `fromZag`, `sortable`, `<VirtualCollection>`, the `browser` static, library recipes (charts, editors, grids, icons, i18n)
9
+ - [llms/graphics.md](llms/graphics.md): widget islands, three.js scenes (`sygnal/three`), 2D editors and whiteboards (`sygnal/canvas`)
10
+ - [llms/typed-apis.md](llms/typed-apis.md): requests typed by the server's contract (`sygnal/api`: oRPC, OpenAPI, Hono, `*.server.ts` functions)
11
+ - [llms/collaboration.md](llms/collaboration.md): several users editing one state (`sygnal/yjs`)
12
+ - [llms/renderers.md](llms/renderers.md): terminal, LLM agent over MCP, React Native, primitives, your own target, a whole app in a Web Worker
13
+ - [llms/sandbox.md](llms/sandbox.md): untrusted or model-written components (`sygnal/sandbox`)
14
+ - [llms/replay.md](llms/replay.md): record a session, replay it as a test (`sygnal/replay`)
15
+
16
+ ## 1. Mental model
17
+ - A component is a pure view function plus static properties: `.intent` (WHEN: sources → named action streams), `.model` (WHAT: action → one reducer per sink), `.initialState`.
18
+ - There is one state tree. A child sees its parent's whole state, or a slice with `state="key"` (or a path: `state="settings.rules"`, `"boards[0].title"`). A Collection item sees one array element.
19
+ - A child belongs to the record its `state` points at (Sygnal 7): when a path or `byId()` target changes, or its record is deleted, the old child is disposed (its DISPOSE gets its last state; its requests, timers and subscriptions are cancelled) and a new one mounts with fresh local state and new DOM (focus and typing inside it are lost). So `<Workspace state={byId('projects', selected.id)} />` needs no key. Same for Collection/VirtualCollection `from` and Switchable `state`. A stable `key` doesn't keep a child across a target change (keep that state in the parent); a custom lens needs `key={record.id}`. Sygnal 6 fixes bindings at mount: use `key={selected.id}` there (SYG454).
20
+ - Every side effect is a sink of a model entry (STATE, EVENTS, PARENT, EFFECT, custom drivers). JSX never has event handlers (`onClick`).
21
+ - Streams are xstream, not RxJS: `import { xs } from 'sygnal'` (not `import xs from 'xstream'`, the module object under Node ESM / Vite 8: SYG302). An intent's DOM selectors only see the component's own JSX, never a child component's.
22
+
23
+ ## 2. Component anatomy
24
+ ```jsx
25
+ import { ABORT } from 'sygnal'
26
+ function Counter({ state, context, label }) { // 1st arg: parent props + state, context, children, slots
27
+ return (
28
+ <div className="counter">
29
+ <span>{label} {state.count} (x2 = {state.double})</span>
30
+ <button className="inc">+</button>
31
+ <button className="reset">reset</button>
32
+ </div>
33
+ )
34
+ }
35
+ Counter.initialState = { count: 0 } // root only: a child gets state from its parent (SYG405)
36
+ Counter.calculated = { double: state => state.count * 2 } // or [['count'], fn]; read as state.double
37
+ Counter.context = { total: state => state.count } // itself + descendants: ({ context }) => context.total
38
+ Counter.intent = ({ DOM }) => ({ // sources: DOM STATE EVENTS CHILD props$ commands$ dispose$ + drivers
39
+ INC: DOM.click('.inc'),
40
+ RESET: DOM.click('.reset'),
41
+ })
42
+ Counter.model = {
43
+ INC: (state, data, next, props) => ({ ...state, count: state.count + 1 }),
44
+ RESET: (state) => (state.count === 0 ? ABORT : { ...state, count: 0 }),
45
+ }
46
+ Counter.onError = (error, { componentName }) => <div className="error">{componentName} failed</div>
47
+ export default Counter
48
+ ```
49
+ - Reducer `(state, data, next, props)`. `data` is the action stream's value. `next('ACTION', data?, delayMs = 10)` dispatches another action of this component only (a child's `next('X')` never reaches a parent's `X`: SYG117; send it up with `PARENT` / `EVENTS`) `delayMs` after the call, whenever it is called: also later, from a timer or callback in an EFFECT (HTTP goes through `makeFetchDriver`, not `fetch` + `next()`). `props` holds the parent's props plus `state`, `context`, `children`, `slots`.
50
+ - Model entry: a function is the STATE reducer. An object `{ STATE, EVENTS, PARENT, EFFECT, LOG, <DRIVER>: fn }` maps each sink to a `(state, data, next, props)` function whose return value goes to that sink. `<SINK>: true` forwards `data` as-is.
51
+ - **STATE runs first in every entry (Sygnal 7)**; every other sink gets the committed state, calculated fields included: `INC: { STATE: s => ({ ...s, n: s.n + 1 }), PARENT: s => ({ n: s.n }) }` (`s.n + 1` would count twice). The state from before the action is `props.previousState` (4th argument): read it for a value STATE cleared or deleted, and in a guard that admits the action: `HTTP: (s, d, next, { previousState }) => (previousState.status === 'working' ? ABORT : { url: '/api/work', ok: 'DONE' })` (`s.status` is already `'working'` there; keep the guard, since STATE's `ABORT` doesn't cancel other sinks; SYG256). The tradeoff: payloads read `state`, guards read `previousState`. When STATE removes the component's own state (`() => undefined`), its other sinks get its last state. Behaviors: the slice and `props.state` are after STATE, the old slice is `props.previousState[key]`. Code for 6 and 7 reads old values as `props.previousState ?? state`. Upgrading 6.x code (every reducer saw the old state): turn on the timing audit, `renderComponent(C, { timingAudit: true })` or `sygnal({ diagnostics: { timingAudit: true } })`, and decide each SYG257. Guide: `node_modules/sygnal/dist/guide/migrating-to-7.md` **The clock and randomness** come from the handler's 4th argument, never the globals: `ADD_TASK: (state, title, next, { now, uuid }) => ({ ...state, tasks: [...state.tasks, { id: uuid(), title, created: now() }] })` (also `random()`; EFFECTs too, also after an `await`). They are `Date.now()` / `Math.random()` / `crypto.randomUUID()`, but tests fix them (`renderComponent(C, { now: Date.parse('2026-01-01'), random: 1, uuid: true })`: fixed clock, seeded random, ids `00000000-0000-4000-8000-000000000001`, `…002`) and a replay supplies the recorded values. `Date.now()` / `new Date()` / `Math.random()` / `crypto.randomUUID()` in a STATE reducer is SYG258 (any handler: SYG509, strict); `sygnal-check --fix` rewrites them. A prop named `now` / `random` / `uuid` shadows them.
52
+ - Built-in actions (model only): `BOOTSTRAP` (once, just after mount), `INITIALIZE` (automatic: sets initialState), `DISPOSE` (unmount). `HYDRATE` is not built in (6.0): SSR data comes from Vike `+data` / `hydrateState`. Declaration statics (`connections`, `resources`, `route`, `head`) are computed from state, with or without a model; a root that declares one needs `initialState` (SYG132). Also reserved as statics: `timers`, `uses`, `persist`, `viewTransitions` (§3).
53
+
54
+ ## 3. Canonical examples
55
+ ### State update, ABORT, set / toggle, controlled input
56
+ ```jsx
57
+ import { ABORT, set, toggle } from 'sygnal'
58
+ function AddTodo({ state }) {
59
+ return (
60
+ <div>
61
+ <input className="draft" aria-label="New todo" value={state.draft} />
62
+ <button className="add">Add</button>
63
+ <button className="help">?</button>
64
+ {state.showHelp && <p className="hint">Type, then Add</p>}
65
+ </div>
66
+ )
67
+ }
68
+ AddTodo.initialState = { draft: '', todos: [], nextId: 1, showHelp: false }
69
+ AddTodo.intent = ({ DOM }) => ({
70
+ DRAFT: DOM.input('.draft').value(), // a bound value={...} needs an input listener (SYG111)
71
+ ADD: DOM.click('.add'),
72
+ HELP: DOM.click('.help'),
73
+ })
74
+ AddTodo.model = {
75
+ DRAFT: set((state, draft) => ({ draft })), // merges: ({ ...state, draft }); never set('draft') (SYG221)
76
+ ADD: (state) => {
77
+ const text = state.draft.trim()
78
+ if (!text) return ABORT // "no change" (returning the same `state` works too)
79
+ return { ...state, draft: '', nextId: state.nextId + 1, todos: [...state.todos, { id: state.nextId, text }] }
80
+ },
81
+ HELP: toggle('showHelp'),
82
+ }
83
+ ```
84
+ ### Multi-sink entry + EVENTS between non-adjacent components
85
+ ```jsx
86
+ import { event } from 'sygnal'
87
+ function SaveButton({ state }) {
88
+ return <button className="save">{state.saving ? 'Saving' : 'Save'}</button>
89
+ }
90
+ SaveButton.intent = ({ DOM }) => ({ SAVE: DOM.click('.save') })
91
+ SaveButton.model = {
92
+ SAVE: {
93
+ STATE: (state) => ({ ...state, saving: true }),
94
+ EVENTS: event('DOC_SAVED', (state) => ({ id: state.id })), // or event('RESET'), event('MODE', 'dark'); return ABORT to send nothing
95
+ },
96
+ }
97
+ function Toast({ state }) { // anywhere in the tree: EVENTS is a global bus
98
+ return <p className="toast">{state.lastSaved}</p>
99
+ }
100
+ Toast.intent = ({ EVENTS }) => ({ SAVED: EVENTS.select('DOC_SAVED') }) // emits the payload only
101
+ Toast.model = { SAVED: (state, payload) => ({ ...state, lastSaved: payload.id }) }
102
+ ```
103
+ ### Child → parent (PARENT + CHILD.select), Collection, item removal
104
+ ```jsx
105
+ import { Collection } from 'sygnal'
106
+ function TaskItem({ state }) {
107
+ return (
108
+ <li className="task" data={{ id: state.id }}>
109
+ {state.title} <button className="pick">pick</button> <button className="remove">x</button>
110
+ </li>
111
+ )
112
+ }
113
+ TaskItem.intent = ({ DOM }) => ({ PICK: DOM.click('.pick'), REMOVE: DOM.click('.remove') })
114
+ TaskItem.model = {
115
+ PICK: { PARENT: (state) => ({ taskId: state.id }) }, // the parent receives exactly this value
116
+ REMOVE: () => undefined, // a Collection item removes itself
117
+ }
118
+ function TaskList({ state }) {
119
+ return (
120
+ <div>
121
+ <p className="picked">{state.picked}</p>
122
+ <ul className="tasks">
123
+ <Collection of={TaskItem} from="tasks" />
124
+ </ul>
125
+ </div>
126
+ )
127
+ }
128
+ TaskList.initialState = { picked: null, tasks: [{ id: 1, title: 'Write' }, { id: 2, title: 'Test' }] }
129
+ TaskList.intent = ({ CHILD }) => ({ PICKED: CHILD.select(TaskItem) }) // the function, not a string
130
+ TaskList.model = { PICKED: (state, { taskId }) => ({ ...state, picked: taskId }) }
131
+ ```
132
+ - `from` names an array field (or a path to one: `from="board.cards"`). Items are keyed by `.id` (by index if they have none). `filter={t => !t.done}`; `sort="title"`, `{ title: 'desc' }`, an array of those, or a compare function. Sorting and filtering only change what renders: the state array keeps its order, and an item's edit (`{ ...state, done: true }`) is written back to its element by key. Items render directly into the parent element, with no wrapper (`<Collection className>` is SYG612: put the class on your own `<ul>`). Switchable: `<Switchable of={{ home: Home, settings: Settings }} current={state.tab} />` (optional `state="slice"`); hidden pages stay alive, and `instance={key}` re-creates the current page with fresh state when the key changes (a router: `instance={state.route.path}`).
133
+ ### Behaviors (`uses`): shared state + actions
134
+ - `TaskList.uses = { pager: pager({ pageSize: 10, next: '.newer', prev: '.older' }) }` adds `state.pager` (`{ page, pageSize, total }` + calculated `offset`, `pages`, `hasPrev`, `hasNext`) and the actions `pager.NEXT`, `pager.PREV`, `pager.GOTO`, `pager.SET_TOTAL`; a click on what `next`/`prev` name triggers them. Options set the slice's start values; the key must not also be in `initialState` (SYG127). Also from `'sygnal'`: `selection({ multi: true, item: '.pick', from: 'mails' })` (`data-id` on each item; `isSelected(state.sel, id)`) and `undo({ key: 'doc', undo: '.undo', redo: '.redo' })` (`state.history.canUndo`/`canRedo`; `coalesce: ['TYPE'], coalesceMs: 500` groups only typing, each other action is its own step; `key: ['todo', 'done']` records several keys as one step; `node_modules/sygnal/dist/guide/undo.md`).
135
+ - Your own: `const disclosure = defineBehavior({ initialState: { open: false }, intent: ({ DOM }, { toggle }) => ({ TOGGLE: DOM.click(toggle) }), model: { TOGGLE: (slice) => ({ ...slice, open: !slice.open }) } })`, used as `uses = { more: disclosure({ toggle: '.more' }) }`. Its reducers and `calculated` get and return the slice (`state.more`), its action names have no key, and any sink works. Options: `persist: false` (UI state `persist()` never saves), `undoStep: ['DONE']` (its other actions form one gesture: one undo entry when `DONE` completes it).
136
+ - The host names behavior actions with the key: an intent action `'more.TOGGLE': DOM.keydown(…)` replaces the behavior's trigger (its `toggle` clicks stop, SYG118: list more elements in the option, or an `EFFECT` calls `next('more.TOGGLE')`); a model entry `'more.TOGGLE': (state) => …` runs after the behavior's, on the full state; tests use `t.simulateAction('more.TOGGLE')`. Guide: `node_modules/sygnal/dist/guide/behaviors.md`
137
+ ### Forms with validation (the `form` behavior)
138
+ - `Signup.uses = { form: form(schema, { values: { email: '', addresses: [{ id: 1, city: '' }] }, request: { url: '/api/signup' } }) }` (`form` from `'sygnal'`), any Standard Schema (zod, valibot, or `{ '~standard': { version: 1, vendor, validate } }`). Fields inside the `<form>` are matched by `name`, a path in `values` (array rows by id: `addresses.7.city`): no intent per field (SYG230: a name not in `values`). TypeScript: `type State = { … } & UsesState<typeof uses>`, `type Actions = UsesActions<typeof uses>` (a `submit` action's data: `FormOutput<typeof uses.form>`) (behaviors' slices and namespaced actions); a typed schema (zod, valibot, arktype) types `state.form.values` and `fields.email.value` and checks `values`. File fields: `<input type="file" name="avatar" key={'avatar' + state.form.resets} />` (never bind `value`) with `avatar: null` in values gives the `File` (`multiple`: File[]), validated by the schema (`z.file()`); `request: { url }` sends it as multipart, `state.form.progress?.fraction`.
139
+ - View: `const f = state.form.fields`; `<input id={uid('email')} name="email" value={f.email.value} aria-invalid={f.email.invalid} aria-describedby={uid('email-error')} />`, `<p id={uid('email-error')}>{f.email.error}</p>`, a `<label for={uid('email')}>`. `f.x.error` is what to show (after blur or a submit); also `state.form.submitting`, `state.form.valid`, `state.form.error` (form-level).
140
+ - An invalid submit shows every error and focuses the first invalid field; a valid one sends `request` with the schema's output (the form adds `json: data`, or `multipart` + `progress: 'form.PROGRESS'` when a value is a File (`progress: true` asks for it on JSON; progress goes over XMLHttpRequest), `ok: 'form.DONE'`, `error: 'form.ERRORS'`; `request: (data, state) => ({ url: '/api/users/' + state.id, method: 'PUT' })` for state); `state.form.submitting` is `true` until the reply (a second submit meanwhile is dropped); a submit that sends nothing names a host action instead, `submit: 'NEXT'` with `NEXT: { PARENT: … }` (a wizard step), done at once, no `form.DONE` needed; `form.ERRORS` puts a 422's `{ errors: { field: msg } }` or `{ errors: [{ path: ['items', 0, 'qty'], message }] }` (an index is the row's position in what was sent) on the fields and focuses the first; a reply with no field message shows in `state.form.error` (`Request failed (500)`); a host entry `'form.DONE': (state, body) => …` runs after the form's. Two forms in one component: `form: '.login'` on each (SYG237).
141
+ - **The `form` slice lives in the host's state**, and a Switchable page (no `state=`) shares its parent's, so the values survive leaving the page and coming back, even when `instance=` re-creates it. When the form must start empty on each visit, say so: `form(schema, { values: EMPTY, submit: 'SAVE', resetOnShow: true })` starts over (start values; touched, errors and the submit cleared) each time the form is shown: the page shown again, the component mounted again. Off by default (a wizard step keeps its values). A start value that comes from state (a default category from the settings) goes in a `values` function of the host's state, called at each start: `values: (state) => ({ ...EMPTY, category: state.settings.defaultCategory })`. When removing a feature that fed a start value, keep `resetOnShow`.
142
+ - Rows, inline (no child component): `state.form.values.addresses.map((row, i) => …)` with `const c = f['addresses.' + row.id + '.city']`, `name={c.name} value={c.value}`, ids `uid('city-' + row.id)`, `<button type="button" className="remove" data-id={row.id}>`; `'form.ADD': DOM.click('.add').mapTo({ field: 'addresses', value: { city: '' } })`, `'form.REMOVE': DOM.click('.remove').map((e) => ({ field: 'addresses', id: e.target.dataset.id }))`. Rows as components: `<Collection of={Row} from={{ get: (s) => s.form.values.addresses }} fields={f} />`, Row `REMOVE: { PARENT: (s) => ({ field: 'addresses', id: s.id }) }` + host `'form.REMOVE': CHILD.select(Row)`.
143
+ - Async check: `check: { email: { request: (email) => ({ url: '/api/email-free', query: { email } }), error: (body) => !body.free && 'Taken' } }` (on blur; a submit waits for it; `f.email.pending`). Tests: `t.simulateEvent('[name="email"]', 'input', { value })`, `'focusout'`, `'submit'` on the form; `t.state.form.fields.email.error`. Guide (recipe first): `node_modules/sygnal/dist/guide/forms.md`; details `forms-reference.md`
144
+ ### Commands (parent → child), element commands, timers, persistence
145
+ - `const player = createCommand()` (from `'sygnal'`); the parent passes it as a prop, `<Player commands={player} state="player" />`, and calls it from an EFFECT (side effect only, returns nothing): `PLAY: { EFFECT: () => player.send('play', data) }`. The child's intent listens with `PLAY: commands$.select('play')`, which emits `send()`'s data.
146
+ - **ELEMENT** (built in, no driver) calls a method on an element of the sending instance's own view, after the render the action causes: `SUBMIT: { STATE: (s) => ({ ...s, errors: validate(s) }), ELEMENT: (s) => (validate(s).email ? { focus: '.email' } : ABORT) }`. The first key is the method (`focus blur select click scrollIntoView showModal show close showPopover hidePopover togglePopover`) and its value the target (a selector); other keys are options (`{ scrollIntoView: '.row', block: 'nearest' }`, `{ close: '.help', returnValue: 'done' }`); an array sends several; `{ focus: focusWithin('.title') }` (from `'sygnal'`) reaches into children and Collection items; an ancestor's element: emit `EVENTS`, send ELEMENT there. `DOM.close('.help')` hears a dialog close. SYG640: no target; SYG641: unknown method. Tests: `t.commands('ELEMENT')`; `dom: 'real'` also runs them. TypeScript: a command built outside the return (`const top = { scrollIntoView: '.page', block: 'start' }`) widens `'start'` to `string`: annotate it `const top: ElementCommand = …` (or `satisfies ElementCommand`). Guide: `node_modules/sygnal/dist/guide/element-commands.md`
147
+ - **Timers**, from state like `connections` (falsy stops, a changed spec restarts): `Clock.timers = (state) => ({ tick: state.running && { every: 1000, action: 'TICK' } })` (also `{ after: ms, action }`, `{ frame: 'FRAME' }`; a game: `{ frame: 'STEP', step: 1000 / 60, keys: { jump: 'Space' } }` → `{ held, pressed }`, tests `await t.frames(n)`); `TICK` gets `{ n, t }`. Needs `run(App, { TIMER: makeTimerDriver() })` (SYG643 without it); no `setInterval`. Tests need no driver: fake timers, `await vi.advanceTimersByTimeAsync(ms)`, `t.timers()`. Guide: `node_modules/sygnal/dist/guide/timers.md`
148
+ - **Persistence** (root only, SYG224): `App.persist = persist({ key: 'todo-app', pick: ['todos', 'filter'] })` (also `version`, `migrate: (old, fromVersion) => keys`, `omit`, `storage: 'local' | 'session' | { getItem, setItem, removeItem }`, `sync: true`, `debounceMs`) restores those keys into `initialState` before the first render and saves them after each change (100 ms debounce) as JSON `{ version, state }` (`format: 'plain'`: the picked keys alone, no `version`/`migrate`); `PERSIST: { clear: true }` in an entry removes the copy. Tests: `renderComponent(App, { storage: { 'todo-app': { version: 1, state: { todos: [] } } } })`, `await t.settle()`, `t.storage('todo-app')`. Guide: `node_modules/sygnal/dist/guide/persistence.md`
149
+ ### Third-party widgets (`defineWidget`) and web components
150
+ - `defineWidget({ tag, mount(el, props, dispatch), update(instance, props), unmount(instance), events, commands })` (from `'sygnal'`) makes a JSX tag: `const DatePicker = defineWidget({ tag: 'input', mount: (el, props, dispatch) => flatpickr(el, { defaultDate: props.value, onChange: ([d]) => dispatch('pick', d) }), update: (fp, props) => fp.setDate(props.value, false), unmount: (fp) => fp.destroy(), events: ['pick'], commands: { open: (fp) => fp.open() } })`. Also `fallback` (SSR content), `hostProps` / `ownProps` (props on / kept off the host), `mount`'s 4th argument `error(e)` (a failure the library reports later). `update` runs only when a prop is a different value (shallow `===`): give a chart a new array (`points: [...s.points, p]`), never the same one changed in place, or it won't redraw. Islands (a three.js scene, a 2D editor or whiteboard, a map: parts as JSX children; `sygnal/three`, `sygnal/canvas`): read `llms/graphics.md` first. Experimental controlled value (an editor's text): `value: { write(instance, v), read?, equals?, strict? }` in the definition; the widget reports the user's changes with `dispatch('change', v)`; `write` runs only for the app's own changes to the `value` prop (no echoes); `strict` writes back an edit the model ABORTed. A form field (a date picker in a form): `field: { event: 'pick' }` + `name="due"` on the tag: the `form` behavior reads its value and blur like a native input.
151
+ - View: `<label>Due <DatePicker className="due" value={state.due} /></label>` (the host element; the widget owns its content and keeps its instance across renders). Intent: `DUE: DOM.select('.due').events('pick').detail()` (`.detail(fn?)` = e.detail). Model: `OPEN: { ELEMENT: { open: '.due' } }` runs the widget's command (it wins over a native method of the same name).
152
+ - List every dispatched name in `events` and name them yourself (`'pick'`, not `'change'`: SYG140/144); `update` gets the newest props when they change (without it, a change remounts); a throwing `mount`/`update` renders the component's `onError` fallback in its place (`onError` phase `'widget'`). Never `DOM.select(DatePicker)`: select its class (SYG143).
153
+ - Tests: `t.widget('.due').dispatch('pick', date)`, `t.widget('.due').props.value`, `t.commands('ELEMENT')`; `dom: 'real'` mounts it (`.instance`). Guide: `node_modules/sygnal/dist/guide/widgets.md`
154
+ - Web components (Web Awesome, Shoelace) are elements, no wrapper: render the tag (`<wa-rating className="food" label="Food" value={state.food} />`; props set properties: `withClear`, not `with-clear`; attributes via `attrs={{ name: 'stars' }}`) and select it by class: `DOM.select('.food').events('change').value(Number)`, library events with any name: `DOM.select('.food').events('wa-hover').detail()`. Guide: `node_modules/sygnal/dist/guide/web-components.md`
155
+ ### HTTP (makeFetchDriver + reply actions), latest response only
156
+ ```jsx
157
+ import { ABORT, debounce } from 'sygnal'
158
+ function Search({ state }) {
159
+ return <div><input className="q" aria-label="Search" value={state.query} /><p className="status">{state.status}</p><ul>{state.results.map(r => <li>{r.title}</li>)}</ul></div>
160
+ }
161
+ Search.initialState = { query: '', status: '', results: [] }
162
+ Search.intent = ({ DOM }) => ({ // no intent line for the reply
163
+ TYPE: DOM.input('.q').value(),
164
+ SEARCH: DOM.input('.q').value().compose(debounce(300)).filter(q => q !== ''),
165
+ })
166
+ Search.model = {
167
+ TYPE: {
168
+ STATE: (state, query) => (query === '' ? { ...state, query, status: '', results: [] } : { ...state, query }),
169
+ HTTP: (state, query) => (query === '' ? { abort: 'RESULTS' } : ABORT), // clearing cancels the request in flight
170
+ },
171
+ SEARCH: {
172
+ STATE: (state) => ({ ...state, status: 'Searching…' }),
173
+ HTTP: (state, q) => ({ url: '/api/search', query: { q }, ok: 'RESULTS', error: 'FAILED', latest: true }),
174
+ },
175
+ RESULTS: (state, body) => ({ ...state, status: '', results: body.results }), // ok: the parsed body
176
+ FAILED: (state, { status, error }) => ({ ...state, status: status === 404 ? 'Not found.' : 'Search failed.', results: [] }),
177
+ }
178
+ ```
179
+ - main.js: `run(Search, { HTTP: makeFetchDriver() })` (import both from `'sygnal'`; options `baseUrl headers init timeoutMs`). Request: `{ url, ok, error, key, query, json, multipart, body, method (POST with json/multipart/body, else GET), headers, latest, timeoutMs, parse: 'auto' | 'json' | 'text' | 'response', init: { credentials, mode, cache, ... } }`; other keys (an id) aren't sent and come back on `request`. The `ok` action gets the parsed body; the `error` action gets `{ error, status, body, request }` (non-2xx: `status` + parsed `body`; network error or timeout: `status` undefined, a timeout has `error.name === 'TimeoutError'`). The reply reaches exactly the instance that sent it (two `<Search>`es, every Collection item; never an ancestor), so no request ids. Shared loader: a tagged resource + `{ invalidate: tag }`. Never `HTTP.select`/`HTTP.errors` for your own request (SYG508), never `then`/`catch` keys (SYG610: not sent); an `ok`/`error` name with no model entry is SYG112. Don't call `fetch` in a component, intent or EFFECT. Upload/download progress: `progress: 'UPLOADING'` on the request (`multipart: { file: state.file, title }` builds the multipart/form-data body, never `new FormData()` in a model; the file from `DOM.select('.file').events('change').map(e => e.target.files[0])`) sends `{ phase: 'upload' | 'download', loaded, total, fraction }` steps as that action (`true`: `HTTP.progress(category)`); it goes over XMLHttpRequest; tests: `await t.progress('HTTP', { loaded: 50, total: 100 }, 'UPLOADING')`. Guide: `node_modules/sygnal/dist/guide/http.md` (online: https://sygnal.js.org/guide/http/). **Typed API calls** from a server contract (oRPC, OpenAPI, Hono, function-first `*.server.ts`; `sygnal/api`, dev preview): `llms/typed-apis.md`.
180
+ - `latest: true`: a newer request in the same lane (`key`: a constant name, never an id or URL; default the `ok` action) from the same instance aborts the older ones once it is sent: their replies never arrive after that, but one that lands before it (while the newer input still waits out a debounce) does. `{ abort: 'RESULTS' }` (it names the lane: with a custom `key`, abort that key; or `{ abort: true, key }`) cancels without sending; a removed instance's requests are aborted. **The request sees what STATE stored**: `SHOW: { STATE: (s, id) => ({ ...s, id }), HTTP: (s) => ({ url: '/api/q/' + s.id, ok: 'LOADED' }) }` (or build it from `id`).
181
+ - Other promise APIs: `driverFromAsync(fn)` takes the same reply actions: `{ value, ok: 'DONE', error: 'FAILED' }` calls `fn(value)`; `DONE` gets the result, `FAILED` `{ error, request }` (no `latest`/abort). One-off async work: `EFFECT: async (state, data, next, { signal }) => { ...; next('DONE', result) }` (rejection: SYG214; `signal` aborts on unmount; no concurrency control). A driver is any function `sink$ => source`; to answer with reply actions (several per request: progress, then ok), `const { replies, reply } = makeReplies(onStop)`, `reply(senderOf(req), req.ok, value)`, return `{ ...replies }` (custom-drivers.md). Page-wide events: `DOM.select('document' | 'body').events(type)`, CSS-filtered with `DOM.select('document').select('.overlay').events('click')`.
182
+ ### WebSocket / SSE (makeSocketDriver + connections)
183
+ ```jsx
184
+ import { ABORT } from 'sygnal'
185
+ function Chat({ state }) {
186
+ return <div><p className="status">{state.status}</p><ul>{state.messages.map(m => <li>{m.text}</li>)}</ul><input className="draft" aria-label="Message" value={state.draft} /><button className="send">Send</button><button className="leave">Leave</button></div>
187
+ }
188
+ Chat.initialState = { room: 'general', status: 'connecting', messages: [], draft: '' }
189
+ Chat.connections = (state) => ({ // from state, diffed by name: new opens, falsy/removed closes, changed URL reconnects
190
+ room: state.room && { socket: `/ws/rooms/${state.room}`, message: 'RECEIVED', open: 'CONNECTED', close: 'DROPPED',
191
+ reconnect: { delayMs: 1000, maxDelayMs: 1000, jitter: false } }, // fixed 1 s retry (default: 500 ms doubling to 10 s, ±20%)
192
+ })
193
+ Chat.intent = ({ DOM }) => ({ DRAFT: DOM.input('.draft').value(), SEND: DOM.click('.send'), LEAVE: DOM.click('.leave') })
194
+ Chat.model = {
195
+ DRAFT: (state, draft) => ({ ...state, draft }),
196
+ SEND: {
197
+ STATE: (state) => (state.draft.trim() ? { ...state, draft: '' } : ABORT),
198
+ WS: (state, data, next, { previousState }) => (previousState.draft.trim() ? { to: 'room', json: { text: previousState.draft } } : ABORT), // queued while (re)connecting
199
+ },
200
+ LEAVE: (state) => ({ ...state, room: null, status: 'offline', messages: [] }), // closes it: no DROPPED
201
+ RECEIVED: (state, msg) => ({ ...state, messages: [...state.messages, msg] }), // the JSON-parsed frame
202
+ CONNECTED: (state) => ({ ...state, status: 'online' }), // data: { reconnected }
203
+ DROPPED: (state, { willReconnect }) => ({ ...state, status: willReconnect ? 'reconnecting' : 'offline' }), // { code, reason, willReconnect }
204
+ }
205
+ ```
206
+ - main.js: `run(Chat, { WS: makeSocketDriver() })` (options `baseUrl reconnect queueLimit`). Without it the static opens nothing and nothing reports it. Spec keys: `socket` (a path gets ws:/wss: from the page) or `sse` (read-only; `events: { 'price-update': 'PRICE' }` for named events), `message open close error` (all optional reply actions, to this instance only), `reconnect` (`false` = never), `share` (default true: one socket per URL, ref-counted), `protocols`, `withCredentials`, SSE `headers: { authorization: `Bearer ${state.token}` }` (EventSource can't send headers, so the driver reads such a stream with fetch; keep the token in state: a changed header reconnects); SSE `meta: true` (actions get `{ data, id, event }`), `resume: true | 'param'` (a driver reconnect resumes from the last event id), `staleAfterMs` (silence = a drop that reconnects; `close` gets `stale: true`; heartbeat comments count over fetch). `close` fires only for drops the app didn't cause; leaving, a URL change, unmount and dispose close silently, so no connection-generation ids. A room switch must `ABORT` when the room is unchanged (an unchanged connection fires no new `open`). `error` gets `{ error }`. `{ to, json | text | binary }` on a name this instance didn't declare, a closed-for-good or an SSE connection is SYG611. Use the static OR a model-sent `{ connections }`, never both (each is the whole set). Guide: https://sygnal.js.org/guide/sockets/
207
+ ### Reads that follow state: `resources`
208
+ ```jsx
209
+ function Quote({ state }) {
210
+ const { status, data, error, refreshing } = state.quote // status: 'idle' | 'loading' | 'success' | 'error'
211
+ const text = status === 'loading' ? 'Loading…' : status === 'error' ? `Failed (${error.status ?? 'network'})` : refreshing ? 'Updating…' : ''
212
+ return <div><button className="next">Next</button><button className="refresh">Refresh</button><p className="status">{text}</p><p className="text">{data?.text}</p></div>
213
+ }
214
+ Quote.initialState = { id: 1 }
215
+ Quote.resources = { quote: (state) => state.id && `/api/quotes/${state.id}` } // a URL or a request ({ url, query, … }); falsy = idle
216
+ Quote.intent = ({ DOM }) => ({ NEXT: DOM.click('.next'), REFRESH: DOM.click('.refresh') })
217
+ Quote.model = {
218
+ NEXT: (state) => ({ ...state, id: state.id + 1 }), // new request: 'loading' without data; the old one is aborted
219
+ REFRESH: { HTTP: { refresh: 'quote' } }, // same request: data kept, refreshing: true
220
+ }
221
+ ```
222
+ - `resources` is the form for data a component shows (reads derived from state); writes and click-triggered one-off requests keep reply actions (above). Needs `run(Quote, { HTTP: makeFetchDriver() })`. The core keeps `state.quote` (named by the resource; don't set it in initialState: it reads as `{ status: 'idle' }`) and writes it with the built-in `RESOURCE` action. When the request changes (by value) it is fetched and the older one aborted, so a stale reply is never shown: no ids, `latest`, ok/error actions or loading flags to write. `data` is the parsed body; `error` is the Error (`error.status`, `error.body` for a non-2xx). Falsy aborts and goes idle. TS: `quote: Resource<Quote>` in the state type.
223
+ - **A component that reads `state.items` declares `items` in its own `.resources`**, even when another page (or its parent) declares the same request: without it `state.items` is undefined on a direct visit (or holds whatever another page loaded last), and a test that starts on the declaring page hides this. Each declaration fetches; with a `queryCache()` the repeat shows the cached data at once and identical requests in flight share one fetch.
224
+ - **Refetch rule**: a new request (another id) is `'loading'` with no data; a refetch of the same request (`{ refresh: 'quote' }`, an invalidation, focus, polling) keeps `status`, `data` and `error` with `refreshing: true`, and a failed refetch keeps `data`. When the old value must not show (Refresh shows "Loading…"), treat `refreshing` as loading. `keepPrevious: true` on the request keeps the old data across a request change too (pagination). `ok: 'FOUND'` / `error: 'FAILED'` on the request also dispatch those actions after the write (append a page, fill a field).
225
+ - Invalidation: tag reads `{ url, tags: ['quotes'] }`; a write with `invalidates: ['quotes']` (tags, a `'/api/quotes'` URL prefix, or a predicate) refetches the matching mounted reads after a 2xx, keeping their data; `{ invalidate: 'quotes' }` on the HTTP sink does it at once. Works with or without the cache. The refetch aborts the read already in flight, so a reply sent before the write never lands (no sequence numbers); a shared cache fetch from before never writes the cache.
226
+ - `updates: 'item'` on a write (React Query's `setQueryData`): after a 2xx, before the `ok` action and `invalidates`, the reply becomes `state.item.data` and its cache entry at once, and the item's read in flight is aborted; `updates: { items: (list, reply) => newList }` derives the data. With `invalidates` the read then refetches keeping the written data (`refreshing`). An idle resource is skipped; the `ok` action still gets the reply.
227
+ - Query cache (opt-in, its own export): `run(App, { HTTP: makeFetchDriver({ cache: queryCache({ staleTime: 30000, gcTime: 300000 }) }) })`. A request fetched before shows its cached data at once (`'success'`, `refreshing: true` while it revalidates; nothing is sent while younger than `staleTime`, default 0), identical requests in flight share one fetch, and stale mounted resources refetch on window focus and reconnect. Reply-action GETs use it with `cache: true` or `staleTime`. Per request: `retry: 3` or `{ count, delayMs }` (default 0; network errors, 408, 429, 5xx), `validate: schema` (Standard Schema: zod, valibot), `refetchEvery: 10000` (polling). `{ prefetch: '/api/quotes/2' }` on the sink warms the cache. SSR: `cache.set(request, data)`, `renderToString(App, { cache })`, `cache.dehydrate()` → `queryCache({ initial: snapshot })` (Vike: `pageContext.queryCache` from `+data`). Guide and recipes (list/detail + save, optimistic update, pagination, infinite list, save status): `node_modules/sygnal/dist/guide/resources.md` (online: https://sygnal.js.org/guide/resources/)
228
+ - List/detail + save, cached: `items: (s) => s.view === 'list' && { url: '/api/items', staleTime: 2000 }`, `item: (s) => s.view === 'detail' && { url: '/api/items/' + s.id, staleTime: 2000 }` (declared only while shown; shown again: cached data at once, refetched once stale), `makeFetchDriver({ cache: queryCache() })` in main.js **and** `renderComponent(App, { http: { cache: queryCache() } })` in every test (a `staleTime` without a queryCache is SYG635), the save `{ url, method: 'PUT', json, ok: 'SAVED', error: 'SAVE_FAILED', updates: 'item', invalidates: '/api/items' }`, status `r?.status === 'loading' ? 'Loading…' : r?.refreshing ? 'Updating…' : ''`.
229
+ - In a hidden Switchable page, resources and `connections` pause (fetches abort, sockets close) and resume on show; an entry with `background: true` (`{ url, background: true }`, `{ socket, background: true }`) stays live. Per-page slices: `state={{ projects: 'pages.projects', settings: byId('teams', state.teamId) }}` (key, path, lens or byId per page; each page follows its own binding: another target remakes only that page; unlisted pages share the owner's state; a key that names no page is SYG429). Every page starts at mount (BOOTSTRAP too); with entry side effects pass one: `key={page} of={{ [page]: PAGES[page] }}`.
230
+ ### Router (makeRouter + route) and HEAD
231
+ ```jsx
232
+ // src/routes.js: one module the views import
233
+ import { makeRouter } from 'sygnal'
234
+ export const router = makeRouter({ routes: { home: '/', task: '/tasks/:id', admin: '/admin', notFound: '*' } }) // first match wins
235
+ export const { href } = router // href('task', { id: 2 }, { tab: 'notes' }) → '/tasks/2?tab=notes'
236
+ ```
237
+ ```jsx
238
+ // src/App.jsx; main.js: run(App, { ROUTER: router.driver, HEAD: makeHeadDriver({ titleTemplate: '%s · Tasks' }) })
239
+ import { ABORT, Switchable } from 'sygnal'
240
+ import { router, href } from './routes.js'
241
+ function App({ state }) {
242
+ return <main><nav><a href={href('home')}>All</a></nav><Switchable of={{ home: Home, task: TaskPage, admin: Admin, notFound: NotFound }} current={state.route.name} instance={state.route.path} /></main>
243
+ }
244
+ App.route = 'ROUTE' // ROUTE gets { name, params, query, hash, path } on start and every change
245
+ App.initialState = { route: router.current(), user: null, draft: '', leaving: null } // seeded: the first paint shows the right page
246
+ App.head = (state) => ({ title: state.route.name === 'task' ? `Task ${state.route.params.id}` : 'Tasks' }) // { title, meta, link }
247
+ App.model = {
248
+ ROUTE: { // a guard: refuse the route and redirect
249
+ STATE: (state, route) => (route.name === 'admin' && !state.user ? ABORT : { ...state, route, draft: '', leaving: null }),
250
+ ROUTER: (state, route) => (route.name === 'admin' && !state.user ? { to: 'home', replace: true } : ABORT),
251
+ },
252
+ }
253
+ TaskPage.model = { // a page shares the parent's state: no initialState (SYG405)
254
+ EDIT: { STATE: (state, draft) => ({ ...state, draft }), ROUTER: () => ({ block: 'CONFIRM_LEAVE' }) }, // unsaved changes
255
+ CONFIRM_LEAVE: (state, { proceed }) => ({ ...state, leaving: proceed }), // a blocked attempt: { to, route, proceed }
256
+ LEAVE: { STATE: (state) => ({ ...state, leaving: null }), ROUTER: (state, data, next, { previousState }) => ({ ...previousState.leaving, block: false }) },
257
+ DONE: { ROUTER: () => ({ to: 'home', block: false }) },
258
+ }
259
+ ```
260
+ - Links are plain `<a href={href(...)}>`, never click handlers: the driver intercepts same-origin left clicks at the document (not modified clicks, `target`, `download`, `rel="external"`, `data-router-ignore`, other origins). `params` and `query` values are strings; `href()` is typed from the route table (an unknown name or a missing param is a type error; SYG130/SYG131 at run time). `instance={state.route.path}` re-creates the page for `/tasks/1` → `/tasks/2`. Pages derive `resources` from `state.route.params`. Pages read the route from context (`App.context = { route: (s) => s.route }`), and every declaration static (`resources timers connections head browser`) gets `(state, context)`: `TaskPage.resources = { task: (s, { route }) => `/api/tasks/${route.params.id}` }` (recomputed when the context changes).
261
+ - ROUTER commands: `{ to, params, query, hash, replace, scroll }`, `{ url }`, `{ back: true }`, `{ forward: true }`, `{ go: n }`, `{ block: 'ACTION' | false }` (also stops back/forward; `proceed` navigates anyway and clears the block it overrode). A block belongs to the component that set it (only its own `{ block: false }` clears it): put CONFIRM_LEAVE and LEAVE next to the `block`, `{ prefetch: 'task', params }` (calls `makeRouter({ prefetch })`). `route` is reserved for the declaration. A bad command is SYG620. The first declarer (the root) gets each route first, so keep guards there.
262
+ - Options: `makeRouter({ routes, base: '/app', mode: 'hash', scroll, focus })`. SSR: `router.current(req.url)` in the seeded state; `renderToString(App, { head: list })` + `renderHead(list)`. Vike: `makeRouter({ routes, navigate })` with `navigate` from `'vike/client/router'`, registered in `pages/+drivers.js`. HEAD: a later-mounted component's title wins; `meta`/`link` merge; a model entry can also send `HEAD: (state, data) => ({ title })`. Guides: https://sygnal.js.org/guide/router/, https://sygnal.js.org/guide/head/
263
+ ### AI (`sygnal/ai`): chat, agents, decisions, composed UI
264
+ - **A chat conversation** is the `chat` behavior, never hand-rolled: `Chat.uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop', regenerate: '.retry' }) }` → `state.chat` (`messages`, `prompt`, `draft`, `status`, `error`); `run(App, { LLM: makeChatDriver({ transport }) })`; tests `await t.stream('LLM', ['Hel', 'lo'])`. **Never put a provider API key in browser code** (SYG670): the browser calls your server (`uiMessageStream('/api/chat')`).
265
+ - One-off LLM requests, the `agent` static (tools an LLM may call), decisions (`decide()`), pages and chat cards a model composes from your parts (`defineCatalog`, `compose`, `chat({ ask })`): read `llms/ai.md` first.
266
+
267
+ ## 4. API facts
268
+ - **Child props**: `<Rating name="food" value={state.food} />` → `function Rating({ state, name, value })`; reducers read `props.name` (4th arg); intent gets the `props$` stream. Reserved: `state` (`"key"`, a path `"a.b"` / `"a[0].b"` (writes copy only the levels on it; for list items use `byId`), or a `{ get, set }` lens), `children`, `slots`, `context`, `uid` (SYG106; an error in strict mode). `key={…}` is a child's identity (not a prop; else its `id` prop, else its place in the view): a new key re-creates it. Without `state=` a child shares its parent's whole state. A child rendered by tag (`<Stopwatch state="stopwatch" />`) has no `initialState`: its start values go in the parent's (`stopwatch: { ms: 0 }`); its own throws SYG405 and the parent renders its error fallback (a test rendering the child as the root doesn't show it). Test a child alone with `renderComponent(Child, { initialState, context: { lang: 'fr' } })` (the ancestors' context). `uid(name?)` (a view prop, also on reducers' `props`) is a stable per-instance id for `id`/`for`/`aria-*` pairs: `<label for={uid('email')}>`, `<input id={uid('email')} />`.
269
+ - **A sliced child with its own start values**: `Editor.isolatedState = true` lets `<Editor state="draft" />` keep an `initialState`, used only while `state.draft` is `undefined` (an existing slice is kept; SYG425 warns when it lacks keys the `initialState` has). To start it from its `initialState` on every mount: `<Editor state="draft" resetState />`.
270
+ - **CHILD.select(Comp)** emits exactly what the child's `PARENT` function returned, for every instance (Collection items too). Put an id in the payload.
271
+ - **Extract a component without changing markup**: snapshot `t.html()` on the unchanged code first; move the elements verbatim into the child (a component adds no wrapper element and no attributes, so the HTML stays identical); props in, `PARENT` out; the parent drops its old selectors and uses `CHILD.select(Child)`; the snapshot must still match. Recipe: https://sygnal.js.org/guide/parent-child/#recipe-extract-a-component-without-changing-the-markup
272
+ - **run(App, drivers = {}, { mountPoint = '#root', diagnostics, onError })** returns `{ sources, sinks, dispose, hmr }`. `onError: (error, { componentName, action, phase }) => …` reports every error to a tracker (reporting only; a component's `.onError` still picks the fallback). Phase `'patch'`: a DOM patch threw, the app's DOM stops updating and the mount point gets `data-sygnal-error="patch"` (show a reload banner). DOM, EVENTS, LOG and STATE are built in. `app.sources.STATE.stream` is the state stream; `app.dispose()` fires DISPOSE.
273
+ - **ABORT**: from a STATE reducer, the state is unchanged (returning the identical `state` object also is: no emission, no render; except for an action triggered by an `input`/`change` event, which re-renders so a refused controlled field shows the state's value again); from any other sink, nothing is sent.
274
+ - **React to a state change** (save a draft, reload when a filter changes): `SAVE: STATE.watch(state => state.text).compose(debounce(1000))` in intent emits the selected value each time it changes (compared structurally; `{ immediate: true }` emits the current one first; a Collection item watches its own state). Not `STATE.stream` + `dropRepeats()`.
275
+ - **Shorthands**: `DOM.<event>('.sel')` = `DOM.select('.sel').events('<event>')` for every real DOM event name (`DOM.key`, `DOM.enter` never fire: SYG115). `blur`/`focus` don't bubble, but `DOM.blur('.field')` / `DOM.focus('.field')` work (listener on the element); for any field inside a container use the bubbling `DOM.focusout('.form')` / `DOM.focusin`. Escape anywhere: `DOM.keydown('document').key().filter(k => k === 'Escape')`. `preventDefault`: `DOM.select('form').events('submit', { preventDefault: true })` (or `DOM.submit('form', { preventDefault: true })`); a function picks the events: `DOM.select('document').events('keydown', { preventDefault: (e) => e.ctrlKey && e.key === 'z' })`. Shortcuts: `...keymap(DOM, { 'mod+z': 'UNDO', 'shift+mod+z': 'REDO', delete: 'DELETE', left: ['NUDGE', { dx: -1 }] })` (from `'sygnal'`) spreads one action stream per name (`mod` = ⌘ or Ctrl; default prevented; never while typing in a field); merge with a button: `UNDO: xs.merge(DOM.click('.undo'), keys.UNDO)`. **Enriched streams** (chainable, optional mapper): `.value(fn?)` e.target.value; `.checked(fn?)` boolean; `.key(fn?)` e.key; `.target(fn?)`; `.data('id', Number)` reads `data-id` on the target or its nearest ancestor that has it (JSX: `data={{ id: 7 }}`). camelCase names map to kebab-case attributes: `.data('taskId')` reads `data-task-id` (`data={{ taskId }}`); a `data-task-id="1"` attribute works too, but a kebab key in the prop (`data={{ 'task-id': 1 }}`) throws a DOMException (SYG421).
276
+ - **TypeScript**: `const intent = ({ DOM }: IntentSources<State>) => ({ ... })`, then `const C: Component<State, Props, {}, ActionsOf<typeof intent>, Calculated, Context, { PARENT: Payload }> = ({ state, context }) => ...` (root: `RootComponent<State, {}, Actions>`; unused parameters `{}`). Without `{ PARENT: Payload }` the parent's `CHILD.select(C)` is a `Stream<unknown>`. In JSX pass `state="slice"`, a lens, or nothing, plus the declared props. Register EVENTS names in `declare module 'sygnal' { interface SygnalEvents { DOC_SAVED: { id: string } } }` in a file that keeps `export {}` (without it the block replaces the 'sygnal' types: "has no exported member"): with an empty registry no event names are type-checked. Guide: https://sygnal.js.org/integration/typescript/
277
+ - **xstream**: `xs.merge/combine/of/periodic/never/fromPromise`; methods `map mapTo filter startWith fold take drop last endWhen flatten compose remember replaceError debug`. From `'sygnal'`, used with `.compose(...)`: `debounce(ms) throttle(ms) delay(ms) dropRepeats() sampleCombine(other$) flattenConcurrently flattenSequentially`; plus `concat(a$, b$)`. **RxJS → xstream**: `pipe(a, b)` → chain `.a().b()` / `.compose(op)`; `switchMap(f)` → `.map(f).flatten()`; `mergeMap(f)` → `.map(f).compose(flattenConcurrently)`; `concatMap(f)` → `.map(f).compose(flattenSequentially)`; `debounceTime(ms)` → `.compose(debounce(ms))`; `throttleTime(ms)` → `.compose(throttle(ms))`; `distinctUntilChanged()` → `.compose(dropRepeats())`; `withLatestFrom(b$)` → `.compose(sampleCombine(b$))`; `combineLatest(a$, b$)` → `xs.combine(a$, b$)`; `merge` → `xs.merge`; `scan(f, seed)` → `.fold(f, seed)`; `skip(n)` / `first()` → `.drop(n)` / `.take(1)`; `takeUntil(b$)` → `.endWhen(b$)`; `tap(f)` → `.debug(f)`; `catchError(f)` → `.replaceError(f)`; `shareReplay(1)` → `.remember()`.
278
+ - More (guides): View Transitions (`viewTransitions = ['MOVE']` + `makeViewTransitionDOMDriver`; `<Collection viewTransitionName="card" />` names each item `card-<id>`, so moves and reorders animate, also across Collections with the same prefix) https://sygnal.js.org/guide/view-transitions/; SSR: the first client render adopts the server's elements (focus and typed text kept) `node_modules/sygnal/dist/guide/ssr.md`; a component as a custom element (`defineElement`, `'sygnal/element'`) https://sygnal.js.org/reference/api/#sygnalelement; DevTools action log and "Copy as test" https://sygnal.js.org/integration/debugging/; app-level error reporting `node_modules/sygnal/dist/guide/error-boundaries.md`; Testing Library https://sygnal.js.org/integration/testing/#testing-with-testing-library; `controls()` element tokens, an alternative to class selectors https://sygnal.js.org/guide/controls/; compiled views (experimental, Vite 8: `sygnal({ compile: true })` compiles JSX at build time: the same DOM and vnodes, nothing to change in components; form fields, SVG, components and spreads stay JSX) https://sygnal.js.org/integration/compiled-views/; other renderer targets (terminal, an LLM agent over MCP, React Native, Web Worker; `sygnal/terminal`, `sygnal/agent-ui`, `sygnal/react-native`, `sygnal/primitives`, `sygnal/host`, `sygnal/worker`): `llms/renderers.md`. Several users editing one state live (`sygnal/yjs`, experimental): `llms/collaboration.md`.
279
+ - **UI parts, lists, browser input: never hand-roll these**, read `llms/ui.md` first: dialog, popover, tooltip, tabs, accordion, disclosure, toasts (`sygnal/ui` behaviors in `uses` + `<Toaster />`); Menu / Select / Combobox (`sygnal/ui/menu|select|combobox` widget tags); one React or Zag component (`fromReact`, `fromZag`); drag to reorder (`sortable`); 1,000+ rows (`<VirtualCollection>`); visibility, media queries, resize, clipboard (`browser` static + `makeBrowserDriver()`), `lazy(…, { when: 'visible' })`; tested recipes for charts, rich text, code editors, carousels, data grids, TanStack Table, icons, i18n.
280
+ - Untrusted or model-written components in a QuickJS sandbox (`sygnal/sandbox`, dev preview): `llms/sandbox.md`.
281
+
282
+ ## 5. Wiring rules (silent failures, and what catches them)
283
+ - **Selectors are scoped to the component's own JSX.** A parent's `DOM.click('.remove')` never fires for `.remove` rendered by a child or a Collection item. Handle the event in the child and send it up with `PARENT` (read with `CHILD.select(Child)`) or `EVENTS`. Caught as SYG104; a selector the view never renders is SYG110. Events still bubble like in the browser: a listener on an element the parent rendered itself (`<div className="slot"><Child /></div>` with `DOM.click('.slot')`) hears clicks from inside the child, after the child's own listeners.
284
+ - **Every intent action needs a model entry (SYG101), and every model entry needs a trigger (SYG102)**: an intent action, a built-in, or `next('X')`.
285
+ - **EVENTS types must match exactly** between `event('X')` and `EVENTS.select('X')` (SYG105). `event()` is the sink entry itself: `EVENTS: () => event('X')` sends a function, which nothing receives (SYG116).
286
+ - **Collection `from` must name an array field of the state** (SYG401). Over a calculated field it is read-only (item writes and removal are discarded): use `from="items"` with `sort=`/`filter=`.
287
+ - **A controlled input needs an input listener**: `value={state.x}` plus `DOM.input('.x').value()`, otherwise a re-render resets the text (SYG111). `value={null}` clears the field; leaving `value` out makes it uncontrolled.
288
+ - Also: reducers return the complete new state (`{ ...state, ... }`); never mutate (a mutated `state` returned as-is is ignored: SYG222); no side effects in views or STATE reducers (use EFFECT or a driver).
289
+
290
+ ## 6. Diagnostics
291
+ - Format: `[Sygnal SYG104] Lane: <what is wrong>. <how to fix> https://sygnal.js.org/reference/errors#syg104`. Severities error/warn/info. 1xx wiring, 2xx model/state, 3xx streams (SYG301: RxJS operator on an xstream stream), 4xx components (Collection, Switchable, context), 5xx strict, 6xx drivers and setup, 7xx accessibility (static, in `sygnal-check` and the Vite dev checker: a clicked `div`, a form field without a label, `<img>` without `alt`, a button with no name; warn, also under `--strict`; `--a11y=error` makes them errors), 9xx internal.
292
+ - `npx --no-install sygnal-check` runs the locally installed checker, never a download (a `create-sygnal-app` project already has the `sygnal-check` dev dependency; elsewhere `npm i -D sygnal-check`; still not installed? skip it and rely on the runtime diagnostics in the tests). It checks `src` statically; pass other paths instead, e.g. `npx --no-install sygnal-check pages --strict` (Vike). Use `--strict` for canonical forms, `--fix` to apply the mechanical rewrites (implies `--strict`), and `--json` / `--verbose` for output. `npx --no-install sygnal-check explain SYG104` explains a code and its fix. Suppress one line with `// sygnal-ignore SYG110`.
293
+ - App graph: `npx --no-install sygnal-check --graph --json` (static), `t.inspect()` (test), `getDevTools()?.inspect()` (running dev app with `sygnal/devtools`, injected by `sygnal/vite`). All return the same `InspectGraph`: components, actions and their triggers, selectors (`matched`, `isolationHit`), EVENTS emitters/selectors, diagnostics.
294
+ - Vite plugin in dev (`vite`, never `vite build`): runtime checks print warnings to the console; when `sygnal-check` is installed, the plugin also runs it on start and on every save (terminal + browser console). Stricter: `sygnal({ diagnostics: { mode: 'error', strict: true }, check: { strict: true } })`.
295
+ - Without the plugin: `run(App, drivers, { diagnostics: 'warn' })` (`'collect'` → `getDiagnostics()`; `'error'` throws) and `import 'sygnal/diagnostics'` for the full checks. Runtime strict: `run(App, drivers, { diagnostics: { strict: true } })`, `configureStrict(true)` from `'sygnal/diagnostics'`, or `renderComponent(C, { strict: true })` (all need `'sygnal/diagnostics'`).
296
+
297
+ ## 7. Testing your change
298
+ ```js
299
+ import { it, expect, afterEach } from 'vitest'
300
+ import { renderComponent } from 'sygnal'
301
+ import TaskList from './TaskList.jsx'
302
+ let t
303
+ afterEach(() => t?.dispose())
304
+ it('picks, then removes a task', async () => {
305
+ t = renderComponent(TaskList, { strict: true }) // also: initialState, context, drivers, mockConfig, diagnostics, timeoutMs, settleMs, eventWaitMs
306
+ t.simulateEvent('.pick', 'click') // first match; bubbles; reaches child components too
307
+ await t.next(s => s.picked === 1) // a state emitted after this call
308
+ await t.simulateEvent('.task[data-id="2"] .remove', 'click')
309
+ expect(t.state.tasks.length).toBe(1)
310
+ await t.settle() // nothing pending anywhere in the tree
311
+ expect(t.html()).not.toContain('Test')
312
+ t.expectNoDiagnostics() // throws on any warn/error diagnostic
313
+ })
314
+ ```
315
+ - `simulateEvent(sel, type, init?)`: init `{ value }`, `{ checked }`, `{ files: [file] }` (a FileList), `{ key: 'Enter' }`, `{ data: { id: 2 } }`; `'document'` targets `DOM.select('document')` listeners. Calls made before the component is ready are buffered (`await t.ready()` is optional). `sel` matches the rendered tree like the real DOM (`:nth-child(n)`, `:not()`, `>`, `+`, `~`: `.list:nth-child(2) .card:first-child .next`). Delivered later: await it (resolves once rendered) before `t.query`. If it matches nothing (after waiting up to 300ms for a render), the test fails with an error naming the selector (check `t.html()`, or select by attribute: `[data-id="3"]`); `{ allowMissing: true }` drops the event instead. `:has()` throws. `t.queryAll('.a, .b')`: document order. `sel` is always a selector string, never an element (`t.query()` returns snapshots: select by attribute, `'.remove[data-id="2"]'`). With `dom: 'real'`, simulated inputs wait for a quiet, patched tree between deliveries (10 ms), so a large queued batch may exceed `timeoutMs` without losing writes. Use native button `.click()` calls for a synchronous burst test, or give serialized tests a larger timeout. `eventWaitMs` is the target-readiness budget, not a quiet-window switch; wait timeouts report queued input counts.
316
+ - `t.next(pred)` matches only future states (right after `await t.ready()`, also those of the buffered calls). `t.waitForState(pred)` also matches states already recorded (e.g. the initial one), so use it only for a state that can't already exist. Both resolve after the whole tree has rendered. `await t.respond(…)` / `t.fail(…)` / `t.settle()` resolve once the state is there: assert on `t.state` next; a `t.next(pred)` after them waits for a further state and times out ("a state recorded before this next() call already matches"). `t.settle()` doesn't wait out a model `next('X', data, ms)` longer than its 20ms window: `await t.next(pred)` instead (timeout errors name the pending `next()`). `t.state` is the latest state (`t.states.at(-1)`), with current calculated fields (also after a child or Collection item writes); `t.states`, `t.emitted` (EVENTS sent) and `t.sinkValues('PARENT')` / `t.sinkValues('API')` (any sink, children's too) are live arrays. `t.html()` is serialised like `innerHTML` (text `Couldn't`, not `&#39;`) and throws before the first render: `await t.ready()` (or a `t.next`) first. Timer tests (debounce/delay): `vi.useFakeTimers()` before `renderComponent`, then `await t.ready()`; `await vi.advanceTimersByTimeAsync(ms)` moves time (e.g. 299 ms: nothing sent yet), and `t.next`/`t.waitForState`/`t.settle`/`t.ready` advance the fake clock themselves until they resolve, so no real waiting. Use it instead of sleeping out a real debounce. Each wait fails after 2000 ms of clock time (fake time too): for a state a longer timer brings, pass more, `t.next(pred, 6000)` (or `renderComponent(C, { timeoutMs })`). `vi.useRealTimers()` in `afterEach`.
317
+ - `t.actions` logs every action of the tree, `{ type, data, component, instance, sinks, cause, at }` (`cause`: `'intent' | 'next' | 'reply' | 'built-in' | 'simulateAction' | 'behavior' | 'agent'`; `sinks`: those that produced a value): when "nothing happened", it shows whether the action ran and what it produced. `t.explain(s => s.count === 5)` returns the action that produced a state.
318
+ - `t.simulateAction('LOADED', data)` pushes an action straight into intent → model (all sinks run) of the rendered component only; a child's: `{ component: Child }` (3rd arg); a name it doesn't handle fails the test. Use it for actions without a DOM trigger. **Drivers need no wiring in tests**: the HTTP fake is the real `makeFetchDriver` over an in-memory fetch, so every request stays pending until the test answers it. `t.requests('HTTP')` lists the requests as objects (a string URL is `{ url }`; never `{ abort }`/`{ refresh }`/`{ resources }` values). `await t.respond('HTTP', body, 'RESULTS')` delivers `body` as that request's `ok` action and resolves once it is reduced and rendered; `await t.fail('HTTP', 404 | error, target?)` sends `{ error, status, body, request }` to its `error` action. Target: an action or key name, a resource name, a URL, a partial request (`{ url: '/items/2' }`), or a predicate; none = the newest pending. A request superseded by `latest: true`, aborted or already answered isn't pending, and answering it **throws at the call**: `expect(() => t.respond('HTTP', {}, { query: { q: 'du' } })).toThrow()`. Identical requests (a resource refetch, a second click) match the same targets: `{ nth: 0 }` answers exactly `t.requests('HTTP')[0]` (`-1` the newest; with `request`, counting only its matches), and throws if it isn't pending. A call made while earlier input is still queued (a debounce) waits up to 1s for its request instead. Each send is its own request. The fake can't see `makeFetchDriver({ latest: true })` from main.js: write `latest: true` on the request.
319
+ - Sockets need no driver either: a component with `connections` gets a fake `WS` sink running the real driver on in-memory sockets (`{ socketSink: 'SOCKET' }` for another name). Connections open by themselves; `renderComponent(C, { autoConnect: false })` holds them in `'connecting'` until `await t.open('WS')`. `await t.push('WS', { text: 'hi' })` is a server frame (SSE named event: `t.push('WS', data, { event: 'price-update' })`); `await t.drop('WS', { code: 1011 })` is a close the app didn't make (`close` fires, the retry runs on the test's timers: `await vi.advanceTimersByTimeAsync(1000)`); `t.sent('WS')` lists the `{ to, json }` values; `t.connections('WS')` the declared connections (`name`, `url`, `state`). They throw too when nothing matches.
320
+ - Resources: each fetch is listed as `{ url, ...request, resource: 'quote' }` and answered by resource name, URL or partial request: `await t.respond('HTTP', { text: 'Hi' }, 'quote')`, `await t.fail('HTTP', 500, 'quote')`. A resource request is sent after the state changes; `t.respond` by resource name right after the `simulate*` call that changes it waits for that fetch. Cache: `renderComponent(C, { http: { cache: queryCache({ staleTime: 2000 }) } })` (any driver options); `t.cache('HTTP')` lists `{ key, age, stale, subscribers, data, tags }`; `t.focus()` / `t.online()` fire the refetch triggers; retries and `refetchEvery` run on the test's timers.
321
+ - Router: `renderComponent(App, { router, url: '/tasks/2' })` (the first render is already on `url`: its route goes through the root's route STATE reducer first) runs the router's real driver over an in-memory history (a component that declares `route` needs the `router` option). `await t.navigate('/admin')` (as a link click) or `await t.navigate({ to: 'task', params: { id: 1 } })`, `await t.back()` / `t.forward()`, `t.location` (`{ path, search, hash, href }`), `t.sent('ROUTER')` (the commands, not the declarations); a `simulateEvent` click on an `<a>` goes through the router's link handling; `{ block }` stops all of them. HEAD: `t.head()` returns the merged `{ title, meta, link }` (`{ titleTemplate }` option).
322
+ - TypeScript tests: `renderComponent` infers the state type; for a handle assigned in `beforeEach`, declare `let t: RenderResult<State>` (import the type from `'sygnal'`), not `any`. With the Vite plugin, Vitest gets `sygnal/diagnostics` in its setupFiles automatically; otherwise `import 'sygnal/diagnostics'` in the test.
323
+ - Real DOM (state the user typed or clicked, focus, refs, any CSS selector): `renderComponent(C, { dom: 'real' })` (`'real'`, not `'jsdom'`) in a jsdom test (`// @vitest-environment jsdom`, `npm i -D jsdom`), same `t.*` API in ONE suite (no separate `run()` + jsdom suite). `simulateEvent` then dispatches real events on any CSS selector (`{ value }` types, `'click'` toggles a checkbox/radio and skips disabled buttons, `'focus'`/`'blur'` move focus). Record a session and replay it as a test (`sygnal/replay`, dev preview): `llms/replay.md`.
324
+ - Assert on elements: `t.query<HTMLInputElement>(sel)` / `t.queryAll<HTMLInputElement>(sel)` (or typed control tokens; generic types are assertions, and a single query is nullable) also work on the default mock DOM, as read-only snapshots of what the view rendered (`textContent`, `value`, `checked`, `disabled`, `getAttribute`, `classList`, `dataset`, `querySelector`, `closest`; `focus()` throws): `expect(t.query('input[name="plan"]:checked').value).toBe('team')`, `t.query('.save').disabled`, `t.queryAll('.row')`; with `dom: 'real'` they are real elements (`document.activeElement === t.query('input[name="city"]')`). Every wait (`ready`, `next`, `waitForState`, `settle`) resolves once its state is rendered, so query right after the `await` (before the first render, `t.query` throws: `await t.ready()`). `await t.next(a); await t.next(b)` also sees a `b` that arrived while the DOM showed `a`.
325
+
326
+ # Sygnal: AI (`sygnal/ai`): chat, one-off requests, agent tools, decisions, composed UI, chat cards
327
+
328
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
329
+
330
+ ## In short
331
+ - **AI** (`sygnal/ai`): a chat conversation is the `chat` behavior, never hand-rolled: `uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop', regenerate: '.retry' }) }` → `state.chat` (`messages`, `prompt`, `draft`, `status`, `error`; Stop keeps the partial reply, Retry doesn't repeat the question); a one-off request (summary, structured `output`) is an `LLM` sink request `{ messages: [{ role: 'user', content: text }], delta: 'DELTA', ok: 'DONE', error: 'FAILED' }`; both need `makeChatDriver({ transport })` (tests: `t.stream('LLM', ['Hi'])`); what agents may run is the `agent` static `{ name, description, read, actions, queries }` (only declared actions; `read` is all they see; `queries: { find: { description, input, run: (state, input) => result } }` are read-only lookups, pure and synchronous; an action that starts a fetch answers once it lands with `until: 'resourceName'`; tests: `t.callTool(name, args)`); typed answers: `decide()` + `choice` / `noul` / `score` as a resource. No provider API key in the browser: `uiMessageStream('/api/chat')` to your server.
332
+
333
+ ## Details
334
+ - **A chat conversation** (send, streaming draft, Stop keeping the partial reply, Retry) is the `chat` behavior with no tools; don't hand-roll it: `Chat.uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop', regenerate: '.retry' }) }` → `state.chat` (`messages`, `prompt` (bind `<input className="prompt" value={state.chat.prompt} />`), `draft`, `status`: `'ready' | 'submitted' | 'streaming' | 'error'`, `error`), the markup in the host's own view (SYG104), `next('chat.SEND', text)` to send from code, a host entry `'chat.DONE'` after a reply; options and slice: agent.md "Options and state". **One-off requests** (a summary, structured `output`, or your own state shape) are a driver request, like HTTP: `SEND: { STATE: (s) => ({ ...s, messages: [...s.messages, { role: 'user', content: s.prompt }], prompt: '' }), LLM: (s) => ({ messages: s.messages, key: 'reply', delta: 'DELTA', ok: 'DONE', error: 'FAILED' }) }` (STATE runs first: the LLM sink sends the list it stored), `DELTA: (s, { text }) => ({ ...s, draft: text })` (all the text so far), `DONE: (s, { message }) => ({ ...s, messages: [...s.messages, message], draft: '' })` (also `text`, `toolCalls`, and `value` for `output: schema`), `FAILED` gets `{ error }`; `{ abort: 'reply' }` stops it (nothing more arrives; `latest` is on: a new request with the same key aborts the old); render with `messageText(m)`. main.js, a local Ollama: `run(App, { LLM: makeChatDriver({ transport: openResponses({ baseURL: 'http://localhost:11434/v1', model: 'llama3.2' }) }) })`; production: `transport: uiMessageStream('/api/chat')` (an AI SDK route on your server; the JSON it POSTs: ai-chat.md, "What uiMessageStream sends"). Tests need no driver: `await t.stream('LLM', ['Hel', 'lo'])` (then `ok`), `t.respond('LLM', text)`, `t.fail('LLM', 429)`, `t.requests('LLM')`.
335
+ - **`agent` static**: what an LLM may do in the app: `TodoApp.agent = { name: 'todos', description: 'The todo list', read: (state) => ({ todos: state.todos.map(({ id, text, done }) => ({ id, text, done })) }), actions: { ADD: { description: 'Add a todo', input: z.string().min(1) }, CLEAR_DONE: { description: 'Delete the done todos', consequential: true } } }` → tools `todos_add`, `todos_clear_done`, `todos_read`. **Only declared actions are tools, and `read` is all agents see** (a projection: keep ids, leave out secrets; `untrusted: true` when it holds text users typed). Per action: `input` (a Standard Schema with JSON Schema: zod 4.2+, or `jsonSchema({ type: 'string' })`; the reducer's data is the parsed input, so `z.object({ packed: z.boolean() })` gives `(state, { packed })`, never `(state, packed)`), `consequential` (the user confirms), `when: (state) => bool`, `idempotent`, `until: 'search'` (the call answers once that resource has loaded, with the `read`, not `loading`; or `until: (state) => bool` for a reply action; `timeout` → `{ ok: true, pending: true }`); an entry counts as a trigger (SYG102); a Collection item's `agent` (+ `label: (s) => s.text`) gives one tool per action with an `id` parameter. Data too large for `read` (a long list, one record): `queries: { find: { description, input, run: (state, input) => state.todos.filter(…) } }` → read-only tool `todos_find`, `{ ok: true, result }`, nothing dispatched; `run` is pure and synchronous (async is SYG246: load data with an action + `until`). A reducer refuses with `abort('reason')` (from `'sygnal'`). Tests: `t.tools()`, `await t.callTool('todos_add', { value: 'milk' })` → `{ ok: true, state }` (a consequential tool needs `{ confirm: true }`), `t.agentContext()`.
336
+ - **Decisions** (typed answers from a decision model; a fetch-driver request, `HTTP: makeFetchDriver()`): `const questions = { topic: choice('What is this ticket about?', { billing: 'Payments, invoices', bug: 'Something is broken' }), urgent: noul('Does it need handling today?'), mood: score('How upset is the customer?', ['calm', 'annoyed', 'angry']) }`, as a resource: `Ticket.resources = { triage: (state) => state.text && decide({ model: 'jev-latest', state: state.text, questions }) }` → `state.triage.data.answers.topic.choice` (`.confidence`: below ~0.6, ask a chat model), `answers.urgent.noul` (0–1), `answers.mood.score`; a click-triggered one is an `HTTP` sink `decide({ …, ok, error })`. Tests: `await t.respond('HTTP', answers(questions, { topic: 'bug', urgent: true }), 'triage')`.
337
+ - **A page a model composes from your parts** (a dashboard the user describes in words; the model only picks parts, params and places, never markup): `const catalog = defineCatalog({ parts: { revenue: { component: Kpi, props: { metric: 'revenue' }, description: 'Revenue (KPI card: the total this month)' }, orders: { component: OrdersTable, description: 'Orders (table of recent orders)', params: { status: { default: 'any', options: { any: 'orders of every status', pending: 'pending orders (not paid yet)' } } } }, tasks: { component: Checklist, state: 'tasks', description: "Tasks (the user's checklist)" } } })` (`description` is all a model sees: "Noun (what it shows)", no overlap between parts; params arrive as props; `state` is a key, a lens, or for a record param (`{ from: (state) => records }`) `(node) => byId('customers', node.params.id)` with `byId` from `'sygnal'`; `containers: { tabs: { slots, render: ({ slots, control }) => … } }` are view functions, never components (SYG161)), `Dashboard.uses = { page: compose(catalog, { backend: compose.decisions({ model: 'jev-latest' }), form: '.ask', prompt: '.prompt' }) }` (or `compose.llm()` on the `LLM` sink: same app, same tests) → `state.page` (`status`: `'composing' | 'preview' | 'done' | 'unavailable' | 'error'`, `layout`, `decisions`, `error`), rendered in the host's view as `{catalog.render(state.page, state)}` or `<Composed catalog={catalog} from="page" />`: the parts are the host's children (lenses, `CHILD.select`) keyed by identity, so a follow-up `next('page.COMPOSE', 'Move the orders to the top')` edits the page and keeps the untouched parts' instances (`{ prompt, fresh: true }` starts over; `persist` the slice to keep the page); for an agent: `actions: { ...compose.action('page') }`, `read: (s) => ({ page: compose.summary(s.page) })`. Tests (either backend): `t.simulateAction('page.COMPOSE', 'Pending orders')`, then `await composeWith(t, catalog, [{ part: 'orders', params: { status: 'pending' } }])`.
338
+ - **Cards in a chat** (the assistant asks with your parts; the user clicks the answer): `uses = { assistant: chat({ form: '.ask', prompt: '.prompt', ask: { catalog } }) }` gives the model the tool `ask_user({ need })`; the card composes from the catalog (`compose.llm()` on the chat's sink by default, or `ask: { catalog, backend: compose.decisions({ model: 'jev-latest' }) }`) and lives on the tool part as `part.ui` (`status`: `'composing' | 'open' | 'answered' | 'failed' | 'cancelled'`; persisted with the chat): render it where the view renders a `tool-ask_user` message part, `askCard(catalog, state, part) ?? <p>Composing…</p>`. A part with `result: true` answers it: `PICK: { PARENT: (state, id, next, props) => compose.answer(props, id) }` → the call's output is `{ part, answer }` and the chat goes on (no result part in the catalog: SYG686). Tools the app answers itself: `clientTools: { confirm: { description, inputSchema } }`, listed by `openToolCalls(state.assistant)`, answered with `next('assistant.TOOL_OUTPUT', { toolCallId, output })`. `chat({ model: (state) => state.chatModel })` picks the model per request. Tests: `await t.stream('LLM', [{ toolCall: { id: 'c1', name: 'ask_user', input: { need: 'Pick a plan' } } }])`, then `await composeWith(t, catalog, [{ part: 'plans' }])`.
339
+ - **Never put a provider API key in browser code**: the browser calls your server (`uiMessageStream('/api/chat')`, the default `/api/decide` of `decide()` and `compose.decisions()`), which adds the key, fixes the model and instructions, and rate-limits; an auth header to another origin is refused (SYG670). Strict provider schemas: `openResponses({ baseURL, model, strict: strictSchemas })` (an import; `strict: true` is SYG672). Every request sends the whole conversation (models are stateless); never `fetch` a provider from a component.
340
+ - Guides: `node_modules/sygnal/dist/guide/ai-chat.md` (transports, structured `output`, tools, shipping), `ai-decisions.md` (escalation, `decide.openai()`), `ai-compose.md` (catalogs, containers, edits, `byId`), `ai-cards.md` (`chat({ ask })`, client tools), `agent.md` (the in-app assistant `uses = { assistant: chat({ form: '.ask', prompt: '.prompt', instructions }) }`, `commandBar`, security), `webmcp.md` (`experimentalExposeWebMcp(app)`, `form(schema, { tool: formTool({ name, description }) })`: experimental, outside semver), `mcp-apps.md` (`makeMcpAppDriver()`: the app inside Claude or ChatGPT); online https://sygnal.js.org/guide/ai-chat/ (and `/guide/ai-decisions/`, `/guide/ai-compose/`, `/guide/ai-cards/`, `/guide/agent/`, `/guide/webmcp/`, `/guide/mcp-apps/`)
341
+
342
+ ## A composed page, end to end
343
+ A model builds a page (or a card in a chat) from parts the app prepared: it only picks parts, params and places, never markup. Guides: `ai-compose.md`, `ai-cards.md`.
344
+ ```jsx
345
+ import { defineCatalog, compose, Composed } from 'sygnal/ai'
346
+ import { OrdersTable, Checklist } from './parts.jsx'
347
+
348
+ export const catalog = defineCatalog({
349
+ parts: {
350
+ orders: {
351
+ component: OrdersTable,
352
+ description: 'Orders (table of recent orders)', // all a model sees: "Noun (what it shows)"
353
+ params: { status: { default: 'any', options: { any: 'orders of every status', pending: 'pending orders (not paid yet)' } } },
354
+ },
355
+ tasks: { component: Checklist, state: 'tasks', description: "Tasks (the user's checklist)" }, // a lens into app state
356
+ },
357
+ })
358
+
359
+ export function Dashboard({ state }) {
360
+ return (
361
+ <main>
362
+ <form className="ask">
363
+ <input className="prompt" aria-label="The page you want" value={state.page.prompt} />
364
+ <button type="submit">Compose</button>
365
+ </form>
366
+ <Composed catalog={catalog} from="page" />
367
+ </main>
368
+ )
369
+ }
370
+ Dashboard.initialState = { tasks: [] }
371
+ Dashboard.uses = { page: compose(catalog, { backend: compose.decisions({ model: 'jev-latest' }), form: '.ask', prompt: '.prompt' }) }
372
+ ```
373
+ ```js
374
+ import { it, expect } from 'vitest'
375
+ import { renderComponent } from 'sygnal'
376
+ import { composeWith } from 'sygnal/ai'
377
+ import { catalog, Dashboard } from './Dashboard.jsx'
378
+
379
+ it('composes the pending orders', async () => {
380
+ const t = renderComponent(Dashboard)
381
+ t.simulateAction('page.COMPOSE', 'Pending orders')
382
+ await composeWith(t, catalog, [{ part: 'orders', params: { status: 'pending' } }]) // answers either backend
383
+ await t.waitForState((s) => s.page.status === 'done')
384
+ expect(t.state.page.layout.nodes.orders.params).toEqual({ status: 'pending' })
385
+ t.dispose()
386
+ })
387
+ ```
388
+ - `backend: compose.llm()` (the `LLM` sink, a streamed preview) takes the same catalog, view and tests. `compose.decisions()` posts to your `/api/decide` route, which holds the API key. `state.page`: `status` (`'composing' | 'preview' | 'done' | 'unavailable' | 'error'`), `layout` (plain JSON), `decisions`, `error`.
389
+ - Parts are the host's children, keyed by their node key: params arrive as props, `CHILD.select(Part)` hears their `PARENT`, a `state` lens edits app state. A follow-up `next('page.COMPOSE', 'Move the orders to the top')` edits the page and keeps the untouched parts' instances; `{ prompt, fresh: true }` starts over. One part per record: a param `{ from: (state) => records }` + `state: (node) => byId('customers', node.params.id)` (`byId` from `'sygnal'`). Containers (`containers: { tabs: { slots, render: (view) => … } }`) are view functions, never components (SYG161). `{catalog.render(state.page, state)}` is the view-call form of `<Composed>`. An agent composes with `actions: { ...compose.action('page') }` and reads `compose.summary(state.page)`.
390
+ - **Chat cards**: `chat({ form: '.ask', prompt: '.prompt', ask: { catalog } })` under `assistant` gives the model `ask_user({ need })`; render each `tool-ask_user` message part with `askCard(catalog, state, part)` (null while composing; the card is `part.ui`, `status` `'composing' | 'open' | 'answered' | 'failed' | 'cancelled'`). A part with `result: true` answers it: `PICK: { PARENT: (state, id, next, props) => compose.answer(props, id) }` → the call's output `{ part, answer }` (no result part: SYG686). Tools the app answers itself: `clientTools: { confirm: { description, inputSchema } }`, `openToolCalls(state.assistant)`, `next('assistant.TOOL_OUTPUT', { toolCallId, output })`. Tests: `await t.stream('LLM', [{ toolCall: { id: 'c1', name: 'ask_user', input: { need: 'Pick a plan' } } }])`, then `await composeWith(t, catalog, [{ part: 'plans' }])`.
391
+
392
+ # Sygnal: UI parts (`sygnal/ui`), Menu / Select / Combobox, sortable lists, long lists, browser sources, library recipes
393
+
394
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
395
+
396
+ - Browser sources: `Card.browser = (state) => ({ seen: !state.seen && { intersection: '.cover', action: 'SEEN' }, dark: { media: '(prefers-color-scheme: dark)', action: 'DARK' } })` + `run(App, { BROWSER: makeBrowserDriver() })` (also `resize`, `storage`, `visibility`, `online`, `geolocation`; clipboard: `{ BROWSER: (s) => ({ copy: s.url, ok: 'COPIED', error: 'COPY_FAILED' }) }`; tests need no driver: `t.browser.intersect('.cover', true)`, `t.browser.media(query, true)`); `lazy(() => import('./Chart'), { when: 'visible' })` (or `'idle'`) defers the import. Guide: `node_modules/sygnal/dist/guide/browser-sources.md`
397
+ - Long lists (from ~1,000 rows): `<VirtualCollection of={Row} from="rows" className="rows" estimateSize={32} aria-label="Rows" />` (Collection's props; it is itself the scroll container, a `div` with `role="list"`: give `.rows` a bounded height in CSS and put `className`, `role`, `aria-label` on it, never wrap it in your own scrolling `<ul>`; SYG430 means fix that height; `estimateSize` is the rows' real height in px (too low: blank space at the end of a fast scroll, SYG436); only rows in view have components, so keep row state in the array); jump with `ELEMENT: (s, index) => ({ scrollToIndex: '.rows', index })` or `{ scrollToId: '.rows', id }`. Guide: `node_modules/sygnal/dist/guide/virtual-collections.md`
398
+ - Reorderable list: `List.uses = { sort: sortable({ from: 'tasks', item: '.task', handle: '.grip' }) }` (mouse, touch, keyboard); items `<li className="task" data-id={state.id}><button className="grip" aria-label=… aria-describedby={context.sort.helpId}>` (context `sort: (s) => s.sort`; style from `context.sort.dragging` / `over` / `after`), host `<p id={state.sort.helpId} hidden>` instructions and `<p role="status" aria-live="assertive">{state.sort.message}</p>` (English defaults: "Dropped X at position 2 of 5.", "Reorder cancelled. X is back at position…"; a spec's exact wording: `messages: { lift, move, drop, cancel, stay }`, each `(label, position, count) => text`), save in `'sort.DROPPED': (state, { id, index, fromIndex }) => …` (the list is already reordered); two lists `from: ['todo', 'done']` + `data-list="todo"` on each container. HTML5 / file drops: `makeDragDriver`. Guide: `node_modules/sygnal/dist/guide/drag-and-drop.md`
399
+ - UI parts (`import { dialog, dialogAttrs, popover, popoverAttrs, tooltip, tooltips, tabs, tabsAttrs, accordion, accordionAttrs, disclosure, disclosureAttrs, Toaster } from 'sygnal/ui'`; native HTML, unstyled): behaviors over your own markup in `uses` (`Profile.uses = { profile: dialog({ dialog: '.profile', trigger: '.edit', close: '.cancel' }) }` → `state.profile.open`, `'profile.CLOSED'`; spread `dialogAttrs(state.profile, uid).trigger` / `.dialog` / `.title` / `.description` (ARIA, ids; `role="alertdialog"` on the dialog for an alert); for tabs/accordion/disclosure spread `tabsAttrs(state.tabs, uid).tab('general')` etc. for roles, ids and ARIA), every slice is the source of truth (Radix-style controlled): a reducer may write `{ ...state.faq, expanded: [id] }` or `{ ...state.profile, open: true }` and the element follows; start values through options (`dialog({ …, open: true })`), never the same key in `initialState`; refuse a close with a host entry returning `previousState` (`'profile.CANCEL': (state, e, next, { previousState }) => (state.dirty ? previousState : state)`; also `'profile.CLOSE'` for the close button / `method="dialog"` form); pass `open` (even `open: false`) to make a dialog / popover controlled: the browser never dismisses it, the behavior does (Escape, a press or focus outside → `'profile.CANCEL'` / `'filters.DISMISS'`, one per interaction, top layer first; an open Menu / Select / Combobox inside is the top layer), so a refused dismiss never flickers; a popover's own button: `popover({ popover: '.share', trigger: '.share-button' })` + spread `popoverAttrs(state.share, uid).trigger` / `.popover` (ARIA, ids; clicks → `'share.TOGGLE'`); add another opener by listing it in the option (`trigger: '.edit, .avatar'`), never with an intent action named `'profile.OPEN'` (it replaces the trigger, SYG118); `tooltips({ trigger: '.term', tip: '.term-tip' })` serves many triggers with one slice (each trigger's `aria-describedby` names its tip), and `<Toaster />` once + `EVENTS: event('TOAST', { text, kind, timeoutMs })` from anywhere (needs `makeTimerDriver()`). Guides: `node_modules/sygnal/dist/guide/ui/overview.md` (and `ui/dialog.md`, `popover`, `tooltip`, `tabs`, `accordion`, `disclosure`, `toaster`)
400
+ - Menu / Select / Combobox: `import { Select } from 'sygnal/ui/select'` (`sygnal/ui/menu`, `sygnal/ui/combobox`; each needs `@zag-js/vanilla` + its machine, e.g. `@zag-js/select@~1.45.0`): widget tags, `<Select className="size" label="Size" items={['S', 'M']} value={state.size} />` + `SIZE: DOM.select('.size').events('value-change').detail()` (Menu: `'select'`; Combobox also `'input-change'`), commands `{ open: '.size' }`; never `events('change')` (a native select's habit: no detail; SYG141); with `name` in a form they are form fields (the `form` behavior reads value and blur: `value={state.form.values.size}`); in a `<Portal>` listen through `DOM.select('document').select('.size')`. Groups: `items={[{ group: 'Fruit', items: ['Apple'] }]}`. Combobox: `multiple` renders chips (a grid, one tab stop: Left at the input's start, Left / Right / Home / End, Delete / Backspace on a chip, Backspace in the empty input or `{ remove: '.tags', value }` remove one; removals announced, `removedMessage={(l) => …}`), `empty="No results"`, `allowCustomValue` commits the typed text on blur / Enter as the value (`loading` while async items load, so the value isn't shown as raw text first). Menu items: `{ type: 'checkbox' | 'radio', value, label, checked }` (event `checked-change` `{ value, checked, type }`; keep `checked` in state), `{ href, value, label }`, a submenu `{ value, label, items }` (ArrowRight / ArrowLeft). Lists are `position: fixed` by default (`positioning={{ strategy: 'absolute' }}` inside a transformed ancestor). Escape hatch for one React/Preact component or a Zag machine: `fromReact(Comp, { events: { rate: 'onChange' } })` (`sygnal/react`) / `fromZag(menu, (api, props) => …, { events })` (`sygnal/zag`, `import * as menu from '@zag-js/menu'`) return widget tags; test them with `dom: 'real'`. Guides: `node_modules/sygnal/dist/guide/ui/menu.md` (`ui/select.md`, `ui/combobox.md`), `node_modules/sygnal/dist/guide/adapters.md`
401
+ - Third-party libraries (tested recipes): charts (Chart.js, ECharts), rich text (Tiptap), code editor (CodeMirror), carousel (Embla), data grid (AG Grid) are `defineWidget` tags; TanStack Table v9 runs in the view as a pure function of state (`constructTable` per render, settings in state); icons: `lucide` data → SVG vnodes with a helper called in the view (`{icon(Plus)}`, not a component); i18n: i18next `getFixedT(locale)` once per locale in `App.context = { t }`, the locale in state saved with `persist()` (never `changeLanguage()`). Recipes: `node_modules/sygnal/dist/guide/recipes/overview.md` (and `recipes/charts.md`, `code-editor`, `rich-text`, `carousel`, `data-table`, `data-grid`, `icons`, `i18n`)
402
+
403
+ # Sygnal: Islands, three.js scenes (`sygnal/three`), 2D canvas editors (`sygnal/canvas`)
404
+
405
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
406
+
407
+ ## In short
408
+ - **Imperative island** (three.js scene, canvas, map with markers as JSX children): `defineWidget({ children: true, mount, sync })`; the children are elements the widget reads in `sync` and draws; it dispatches DOM events on them (raycast / hit test → `click` on `v.elm`), so each child component's intent uses `DOM.click('.cube')`. Per-frame motion is computed in the widget from props, not in state (`islands.md`). A three.js scene: `<Scene>` from `sygnal/three` (`npm install three`): meshes, geometries, materials, lights and cameras as lowercase tags, raycast hits as `click` / `pointerover` on the mesh's element with `event.point`, `animate={{ rotation: (t) => [0, t, 0] }}` for motion, `<Model src="/tree.glb" />` / `<Texture src="/wood.jpg" />` for loaded assets (with `<Suspense>`; a failed load renders `onError`), `capture="xz"` to drag a mesh along the floor (`pointermove` with `event.captured` and `event.delta`), `draggable` for `processDrag`, tests with `sceneOf(el).click(meshEl)` / `.drag(meshEl, [x, y])` under `dom: 'real'` (`renderers/three.md`).
409
+
410
+ ## Details
411
+ - Islands (a three.js scene, a canvas, a map: parts as JSX children): `defineWidget({ children: true, mount, sync(instance, childrenVnode, el), focus(instance, child) })`. The tag's children render (by Sygnal, as elements: components, `<Collection>`, intents work) into a visually hidden, accessible container; `sync` reads them (`v.sel`, `v.data.props` / `v.data.attrs`, `v.elm`) and draws them; the widget turns raycasts / hit tests into DOM events on `v.elm` (`el.dispatchEvent(new MouseEvent('click', { bubbles: true }))`), so `DOM.click('.cube')` works in the child's intent. Enter / Space on a focused child (`role`, a name, `tabIndex={0}`) is its click. `tags: ['marker']` stops the pragma treating the widget's tags as SVG. Per-frame values: compute them in the widget's own loop from props, never through state; a `timers` `{ frame: 'ACTION' }` only for state that changes every frame. Guide: `islands.md`. three.js ready-made: `import { Scene } from 'sygnal/three'` (`npm install three`, an optional peer): `<Scene className="viewport" width={640} height={400}><ambientLight /><Collection of={Cube} from="cubes" /></Scene>`, every three.js class lowercased as a tag (`<mesh position={[x, 0, 0]}><boxGeometry args={[1, 1, 1]} /><meshStandardMaterial color="orange" /></mesh>`), raycasts become DOM events with `event.point` (`DOM.click('.cube')`), per-frame motion `animate={{ rotation: (t) => [0, t, 0] }}` (never state), tests in jsdom `sceneOf(el).click(meshEl)`. Loaded assets are tags: `<Model src="/tree.glb" position={[0, 0, 0]} />` (GLTF by default; `loader={OBJLoader}` or a configured loader instance for others; one clone per element) and `<Texture src="/wood.jpg" />` inside a material (attaches as `map`; `attach="normalMap"`), with `<Suspense fallback={…}>` around them (inside the Scene: a 3D fallback; around it: the scene is created once loaded); cached per URL, freed with the last element using it, `Model.preload(src)`; a failed load renders the component's `onError`. Dragging: `capture="xz"` on a mesh captures the pointer from the press to the release (`gotpointercapture`, then every `pointermove` with `event.captured`, `event.point` on the drag plane and `event.delta` from the press, then `lostpointercapture`; a drag clicks nothing; camera controls sit it out); `draggable` sends the HTML drag events, so `processDrag({ draggable: DOM.select('.box'), dropZone: DOM.select('.bin') })` works; tests `sceneOf(el).drag(meshEl, [x, y])`; guide `renderers/three.md`. 2D editors, whiteboards, diagrams (experimental): `import { Canvas, pointer } from 'sygnal/canvas'`; shapes are data in state, one box-based vocabulary (`{ id, type: 'rect' | 'ellipse' | 'text' | 'frame' | 'image' | 'line' | 'path', x, y, width, height, rotation, fill, stroke, radius, parent }`, an ellipse is its box, not SVG's cx/cy/rx/ry): `<Canvas className="board" camera={state.camera}><shapes className="doc" items={state.shapes} active={draggedIds} />{handles(selectionBox(state.shapes, state.selection), state.camera)}</Canvas>`; one element paints, culls and hit-tests all shapes, a hit is a DOM event with `e.hit` = the id: `DOWN: DOM.select('.board').events('pointerdown').map(pointer)` (plain `{ x, y, hit, part, shift, mod }`, world coordinates); every press is captured (`e.captured`, `e.delta` from the press); pan/zoom built in, the camera a controlled value (`CAMERA: DOM.select('.board').events('camerachange').detail()`); drags go through actions (`gesture.start/move/delta`, `snap`, `resize`, `rotation`, `turn`; `history('shapes')`: `commit(s, next, gesture.before)` = one undo step per gesture, `UNDO: h.undo`; with `sygnal/yjs` `shared()` the same entries become per-user undo). Patch only changed shapes (`shapes.map(s => s.id === id ? { ...s, x } : s)`; rebuilding all is SYG262: every frame repaints; per move, work on the changed shapes only: `positionsOf(shapes, prev)` is an id → index map shared across a drag's arrays, a derived list returns its previous array when its rows didn't change); `follow={{ ids, from }}` only for huge selections; `exportSVG(shapes, ids)`; tests `canvasOf(el).pointer('down', x, y)`; guide `renderers/canvas.md`. Text wraps to its `width` (words, `\n`; `wrap: 'char' | 'none'`, `maxLines` ends in '…', `align`, `lineHeight`; no width: one line, box measured; `layoutText(text, { width, fontSize })` → `{ lines, width, height }`). Images: `{ type: 'image', src: '/a.png', x, y, width, height, fit: 'contain', alt }` (crop `sx sy sw sh`, `flipX`, `smoothing: false` for pixel art), loaded once per URL, painted when loaded (`imageload` / `imageerror` events on the canvas); `<Image src x y />` inside `<Canvas>` makes `<Suspense>` wait (a failed load: `onError`); sprite sheets `...frameOf({ src, frameWidth, frameHeight, columns }, frameAt([1, 2], s.tick, 8))`.
412
+ - 2D games on `sygnal/canvas` (`examples/platformer`): the world is state, plain functions over plain data; a fixed-step frame timer steps it with the sampled keys: `Game.timers = (s) => ({ loop: s.mode == 'playing' && { frame: 'STEP', step: 1000 / 60, keys: { left: ['ArrowLeft', 'KeyA'], right: 'ArrowRight', jump: 'Space' } } })`, `STEP: (s, { held, pressed }) => step(s, held, pressed)` (`pressed`: since the last frame, so a tap shorter than a frame counts; keys default-prevented, released on window blur, ignored in text fields); menu keys (Enter, P) through `keymap` (they work while the loop is off). `<Canvas navigate={false} a11y={0}>` (Space is the jump; no projection), `<shapes items={hills} parallax={0.5} />` (scrolls at half the camera, own coordinates), cached layers for tiles / scenery (keep node identity), `<shapes items={actors} live />` for what moves every frame (no ids); layers paint in their order. The camera is state: `camera: follow(s.camera, player, { width, height, deadzone: { width: 120, height }, offset: { x: -60 }, lerp: 0.2, bounds, round: true })` in the step (pure; the same object while still); a scrolling camera moves the cached layers' canvases (CSS transform), painting only what comes into view. The canvas paints in the frame the step ran. Never a variable `dt` for physics. Tests: fake timers, real `KeyboardEvent`s on `document`, `await t.frames(60)`; `settle()` ignores the loop; a `startRecording()` replays exactly (each STEP carries its keys). Guide: `renderers/canvas.md` (Games), `guide/timers.md`.
413
+
414
+ # Sygnal: Typed API calls (`sygnal/api`, dev preview)
415
+
416
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
417
+
418
+ - **Typed API calls** (dev preview, `sygnal/api`): requests built from the server's contract, no URLs or reply types written: `const api = orpcClient(contract, { prefix: '/api' })` (an oRPC contract, served by oRPC's OpenAPIHandler; or `openApiClient<paths>()`, `honoClient<ExtractSchema<typeof app>>()`), then `api.quotes.list({ tag })` is a request (a resource), `api.quotes.add(input, { ok: 'ADDED', error: 'FAILED', invalidates: [api.quotes.list] })` a sink value, a stream endpoint a `connections` entry; actions typed `Output<typeof api.quotes.add>` / `ApiFailure<typeof api.quotes.add>`; tests `t.respond('HTTP', fixture(api.quotes.list, rows), api.quotes.list)`. Function-first (`sygnal({ api: { functions: true, handler: 'server/api.ts' } })`): `src/quotes.server.ts` exports `query(z.object({ tag: z.string() }), async ({ tag }) => …)` / `mutation` / `stream` (input always validated), which components import and call like endpoints (the client build gets stubs only); the server mounts `serverFunctions(import.meta.glob('/src/**/*.server.ts', { eager: true }), { os })` with oRPC. Guide: `node_modules/sygnal/dist/guide/typed-apis.md`
419
+
420
+ # Sygnal: Collaborative state (`sygnal/yjs`, experimental)
421
+
422
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
423
+
424
+ - **Collaborative state** (experimental, `sygnal/yjs`; `npm install yjs y-protocols`, optional peers): several users edit one key of the state at once, merged by a Yjs document. `Board.uses = { board: shared({ presence: 'peers', history: 'history', shape: { title: 'text', items: collection({ text: 'text' }) } }) }` (import `shared`, `collection`, `makeYjsDriver` from `'sygnal/yjs'`); keep `board` in `Board.initialState` (`shared()` adds no slice of its own: `ownsState: false`, so no SYG127). Reducers stay ordinary: each new `state.board` is diffed into the document (`board.LOCAL`, once per flush) and other users' changes arrive as `board.REMOTE` (applied only while there's no unsynced local edit; both hidden in DevTools as built-in). main.js: `run(Board, { SHARED: makeYjsDriver({ doc, provider }) })` with the app's own `Y.Doc` and provider (y-websocket, Hocuspocus, y-webrtc, y-indexeddb); the first value seeds an empty document after the provider's first sync (`seed: 'whenSynced'`, default; `'ifEmpty'` for a local-only doc), else the document wins. Arrays of objects with `id` are id-keyed collections (concurrent add/edit/move/remove merge); declare `'text'` fields for character-level merging and declare empty arrays (`'list'` / `collection()`; else SYG261). Undo per user: `UNDO: { SHARED: { undo: 'board' } }`, `REDO: { SHARED: { redo: 'board' } }`, never `undo({ key: 'board' })` (SYG260: it reverts others' changes); presence `FOCUS: { SHARED: (state, id) => ({ presence: { editing: id } }) }` → `state.peers`; offline `{ SHARED: { connect: false } }`. Tests: `const net = createNetwork(), peer = net.join()` (from `'sygnal/yjs/testing'`), `renderComponent(Board, { drivers: { SHARED: makeYjsDriver({ doc: peer.doc, provider: peer }) } })`, `peer.offline()` / `peer.online()`. Guide: `node_modules/sygnal/dist/guide/collaborative-state.md`
425
+
426
+ # Sygnal: Other renderer targets: terminal, LLM agent, React Native, primitives, Web Worker
427
+
428
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
429
+
430
+ - Other renderer targets, the same components (intents must select controls to be portable; every target makes the DOM's events): a terminal `runTerminal(App, { styles })` / tests `createTerminal()` + `t.press('Tab')` + `t.frame()` (`sygnal/terminal`), an LLM agent `const { ui } = runAgentUI(App); serveMcp(ui, { tools: agentTools(app) })` (accessibility snapshot + `ui_click` / `ui_type` / … tools, `sygnal/agent-ui`), React Native `<SygnalView app={App} />` (`sygnal/react-native`), one file for web + native + terminal with the primitives `View` / `Text` / `Pressable` / `TextInput` / `Switch` / `Image` / `ScrollView` / `List` (`sygnal/primitives`, RN style objects, `controls({ Add: Pressable })`), your own on `sygnal/host` https://sygnal.js.org/renderers/overview/
431
+ - Terminal apps (`sygnal/terminal`): `runTerminal(App, { styles, drivers, mouse: true })`; the views stay HTML and the terminal stylesheet is `[selector, style]` rules. A full-screen layout is boxes in that sheet: `['main', { display: 'flex', flexDirection: 'column', height: '100%' }]`, `['.body', { flex: 1, display: 'flex' }]` (a flex row whose items have `width: '40%'` / `flex: 1` / `border` lays them out side by side), `['.list', { width: '40%', border: 'round', overflow: 'auto' }]` (scrolls with a scrollbar, keeps the focus in view; the title is its `aria-label`), plus `padding`, `gap`, `color`, `background`, `bold`/`dim`/`inverse`, and `:focus` / `:focus-within` / `:checked` selectors. Native `<select>`, `<dialog>` (`ELEMENT: { showModal: Confirm }`: the focus moves in and stays in, Escape closes it, `DOM.close(Confirm)` hears it), `[popover]`, `<details>`, `<textarea>` and radio groups behave as in a browser; the footer shows what the keys do on the focused element. A list is one Tab stop (roving `tabIndex`, ↑ / ↓ inside it, prevent their default so the focus doesn't move on), so Tab reaches the next pane. Quit from the model with `QUIT: { TERMINAL: () => 'exit' }` (also `{ title }`, `'bell'`). A Collection item's element is the item's: a row click is the item's intent + `PARENT`, focus it from the parent with `focusWithin(...)`. Every `sygnal/ui` native part works in a terminal (dialog, popover, tooltip, tabs, accordion, disclosure, `<Toaster />` with `drivers: { TIMER: makeTimerDriver() }`); a terminal box's title is its `aria-label`, so a `dialogAttrs` dialog keeps `aria-label="Confirm"`. Tests: `const t = createTerminal({ styles, width: 80, height: 24 }); const app = t.run(App, { HTTP })` (adds DOM and TERMINAL), `await t.settle()` (quiet: flushed, element commands, short delays; drives fake timers), then `t.press('Enter')`, `t.type()`, `t.paste()`, `t.click(line, col)`, `t.wheel(line, col, rows)`, `t.keyHint()`, `t.commands`, and compare `t.frame()` (plain text) https://sygnal.js.org/renderers/terminal/
432
+ - A whole app in a Web Worker (experimental, the app unchanged: worker `const target = createWorkerTarget(self); run(App, { DOM: target.driver, STORE: target.remote('STORE', ['get']) })` from `sygnal/worker`, page `startBridge(new Worker(url, { type: 'module' }), root, { drivers: { STORE } })` from `sygnal/worker/page`; default actions are decided on the page from declarations, so use `events('keydown', { preventDefault: { key: 'Tab' } })` (true or a pattern, not a function); not yet: `sygnal/ui` dialogs/popovers, widgets, `fromReact`/`fromZag`, `ELEMENT` commands, layout reads, drag and drop, devtools, HMR) https://sygnal.js.org/renderers/off-main-thread/
433
+
434
+ # Sygnal: Sandboxed components (`sygnal/sandbox`, dev preview)
435
+
436
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
437
+
438
+ - Untrusted or model-written components (dev preview): `sygnal/sandbox` (`npm install quickjs-emscripten-core @jitl/quickjs-wasmfile-release-sync`) runs one in QuickJS-in-WASM, rendered into the real DOM through an allowlist: `import { Sandboxed } from 'sygnal/sandbox'` + `import kernel from 'sygnal/sandbox/kernel?raw'` (sygnal/vite builds it from the installed packages; else `buildSandboxKernel()` from `sygnal/sandbox/build`), `<Sandboxed className="card" kernel={kernel} source={cjs} emits={{ ANSWER: AnswerSchema }} input={{ bill: state.bill }} />` (`source`: CommonJS, JSX compiled to `__h`/`__frag`; `emits` required: only declared types with schema-valid data arrive, SYG692 otherwise) + `ANSWER: DOM.select('.card').events('emit').detail().filter(e => e.type === 'ANSWER').map(e => e.data)`, `'sandboxerror'` (`{ reason, message }`); `isolation: 'worker'` (default: hostile code, a watchdog) or `'thread'` (model-written code, sync events); the guest has `DOM`, `STATE`, `EVENTS`, `PROPS`, and `HTTP` only via `capabilities.fetch: { allow: [urlPrefix] }`; guide `advanced/sandboxed-components`. Model-written parts in a composed page (experimental, outside semver): `const gen = compose.generated(generatedRuntime({ kernel, compile: sucraseCompiler(() => import('sucrase')) }), { data: { orders: { description, shape, from: (s) => s.orders } }, emits: { OPEN_CUSTOMER: { description, schema: z.object({ id: z.number() }) } } })` (`generatedRuntime`, `sucraseCompiler` from `sygnal/sandbox`; sucrase is the app's dependency), then `parts: { custom: gen.part }` (opt in per catalog; `compose.llm()` only), `compose.llm({ instructions: gen.instructions })`, `uses = { fix: gen.repair() }`, `OPEN_CUSTOMER: gen.events(CHILD, 'OPEN_CUSTOMER')` (`{ node, ...data }`, schema-validated); defaults worker, `maxUses: 3`, `maxCode: 4000`, `maxAttempts: 2`, check before mount on, no capabilities; `gen.card('TYPE')` is a `chat({ ask: { catalog, direct: true } })` card answered by that event; guide `ai-compose.md` "Generated parts".
439
+
440
+ # Sygnal: Record and replay (`sygnal/replay`, dev preview)
441
+
442
+ > A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.
443
+
444
+ - Record and replay (dev preview, `sygnal/replay`): `const rec = startRecording()` before `run(App)` records the session's input actions (redaction of typed text and server data on by default; `{ redact: { keep: ['SET_FILTER'] } }` / `false`); `rec.stop()` gives JSON. In a test, `const r = await replay(App, log)` (also from `'sygnal'`) replays it in renderComponent: `r.divergence` (first action whose state differs, with `diff`), `r.view` (view-only change), `r.effects`, `r.unhandled`, `r.warnings`, `r.final`, `r.t.dispose()`. `replayTest(log)` writes the test file, `bugReport(log, r)` Markdown; DevTools' Copy as test has `{ mode: 'replay' }`. Guide: https://sygnal.js.org/guide/record-replay/