plexi-sdk 0.1.14__tar.gz → 0.2.0__tar.gz

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 (38) hide show
  1. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/.gitignore +9 -0
  2. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/PKG-INFO +5 -11
  3. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/README.md +2 -7
  4. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/__init__.py +9 -17
  5. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_adapter.py +100 -54
  6. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_keys.py +4 -1
  7. plexi_sdk-0.2.0/plexi_sdk/_v3_delta.py +121 -0
  8. plexi_sdk-0.2.0/plexi_sdk/_v3_runtime.py +615 -0
  9. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_v3_state.py +1 -1
  10. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_version.py +4 -1
  11. plexi_sdk-0.2.0/plexi_sdk/effects.py +222 -0
  12. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/events.py +65 -22
  13. plexi_sdk-0.2.0/plexi_sdk/templates/AGENTS.md +40 -0
  14. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/templates/app_init.py +12 -7
  15. plexi_sdk-0.2.0/plexi_sdk/templates/gitignore +28 -0
  16. plexi_sdk-0.2.0/plexi_sdk/templates/manifest.toml +15 -0
  17. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/templates/test_app_init.py +8 -1
  18. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/testing.py +56 -2
  19. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/ui.py +792 -317
  20. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/__init__.py +6 -0
  21. plexi_sdk-0.2.0/plexi_sdk/widgets/text_input.py +11 -0
  22. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/pyproject.toml +6 -4
  23. plexi_sdk-0.1.14/plexi_sdk/_v3_runtime.py +0 -436
  24. plexi_sdk-0.1.14/plexi_sdk/effects.py +0 -136
  25. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_constants.py +0 -0
  26. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_protocol.py +0 -0
  27. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_theme.py +0 -0
  28. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_types.py +0 -0
  29. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/_v3_process.py +0 -0
  30. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/midi.py +0 -0
  31. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/py.typed +0 -0
  32. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/templates/__init__.py +0 -0
  33. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/templates/agent_init.py +0 -0
  34. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/keymap.py +0 -0
  35. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/list_view.py +0 -0
  36. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/scroll.py +0 -0
  37. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/text_area.py +0 -0
  38. {plexi_sdk-0.1.14 → plexi_sdk-0.2.0}/plexi_sdk/widgets/text_buffer.py +0 -0
@@ -51,6 +51,9 @@ __pycache__/
51
51
  *.pyo
52
52
  sdk/python/**/__pycache__/
53
53
  sdk/python/*.egg-info/
54
+ .venv/
55
+ .pytest_cache/
56
+ tools/e2e_authoring/*.egg-info/
54
57
 
55
58
  # Local config
56
59
  .plexi/
@@ -71,3 +74,9 @@ entities.json
71
74
 
72
75
  # Stint task graph (local only)
73
76
  .stint/
77
+
78
+
79
+ # Agent skill logs (runtime artifacts)
80
+ .agents/**/LOG.md
81
+ .agents/**/RUN_STATE.md
82
+ .agents/**/HUMAN_CHECKS.md
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plexi-sdk
3
- Version: 0.1.14
4
- Summary: Python SDK v3 for Plexi apps running through native ProcessApp
3
+ Version: 0.2.0
4
+ Summary: Python SDK v3 for Plexi apps running through the CPython-in-WASM runtime
5
5
  Project-URL: Homepage, https://github.com/ianjamesburke/PLEXI
6
6
  Project-URL: Repository, https://github.com/ianjamesburke/PLEXI
7
7
  Project-URL: Documentation, https://github.com/ianjamesburke/PLEXI/tree/main/sdk/python
@@ -12,16 +12,15 @@ Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
14
14
  Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.11
16
15
  Classifier: Programming Language :: Python :: 3.12
17
16
  Classifier: Programming Language :: Python :: 3.13
18
17
  Classifier: Topic :: Software Development :: Libraries
19
- Requires-Python: >=3.11
18
+ Requires-Python: >=3.12
20
19
  Description-Content-Type: text/markdown
21
20
 
22
21
  # plexi-sdk
23
22
 
24
- Python SDK v3 for building Plexi apps running through native `ProcessApp`.
23
+ Python SDK v3 for building Plexi apps running inside the CPython-in-WASM runtime.
25
24
 
26
25
  Full design spec: [`SDK_V3.md`](SDK_V3.md)
27
26
 
@@ -38,9 +37,6 @@ Changes to `sdk/python/plexi_sdk/` take effect immediately.
38
37
  An app is three module-level functions:
39
38
 
40
39
  ```python
41
- #!/usr/bin/env python3
42
- from __future__ import annotations
43
-
44
40
  from plexi_sdk import state
45
41
  from plexi_sdk.effects import SetTitle, SetState
46
42
  from plexi_sdk.events import KeyEvent
@@ -85,8 +81,6 @@ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonica
85
81
 
86
82
  ```sh
87
83
  plexi app init myapp
88
- plexi app check myapp --png-dir /tmp/myapp-shots
89
- plexi app open myapp
90
84
  ```
91
85
 
92
- Generates `myapp/main.py`, `myapp/manifest.toml`, `myapp/tests/test_app.py`, and a per-app `.venv/` for Python isolation. `plexi app check` validates the SDK v3 shape, renders the size matrix, and can write PNG snapshots for visual review.
86
+ Generates `myapp/main.py` + `myapp/manifest.toml` with `python_compat = true`.
@@ -1,6 +1,6 @@
1
1
  # plexi-sdk
2
2
 
3
- Python SDK v3 for building Plexi apps running through native `ProcessApp`.
3
+ Python SDK v3 for building Plexi apps running inside the CPython-in-WASM runtime.
4
4
 
5
5
  Full design spec: [`SDK_V3.md`](SDK_V3.md)
6
6
 
@@ -17,9 +17,6 @@ Changes to `sdk/python/plexi_sdk/` take effect immediately.
17
17
  An app is three module-level functions:
18
18
 
19
19
  ```python
20
- #!/usr/bin/env python3
21
- from __future__ import annotations
22
-
23
20
  from plexi_sdk import state
24
21
  from plexi_sdk.effects import SetTitle, SetState
25
22
  from plexi_sdk.events import KeyEvent
@@ -64,8 +61,6 @@ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonica
64
61
 
65
62
  ```sh
66
63
  plexi app init myapp
67
- plexi app check myapp --png-dir /tmp/myapp-shots
68
- plexi app open myapp
69
64
  ```
70
65
 
71
- Generates `myapp/main.py`, `myapp/manifest.toml`, `myapp/tests/test_app.py`, and a per-app `.venv/` for Python isolation. `plexi app check` validates the SDK v3 shape, renders the size matrix, and can write PNG snapshots for visual review.
66
+ Generates `myapp/main.py` + `myapp/manifest.toml` with `python_compat = true`.
@@ -4,15 +4,17 @@ Apps expose module-level ``init(size, args)``, ``update(event)``, and ``view()``
4
4
  functions. The V3AppRuntime drives the event loop: host sends JSON events on
5
5
  stdin, app responds with effects and component trees on stdout.
6
6
 
7
- SDK v3 Python apps run through native ProcessApp. Capabilities gate PGAP host
8
- APIs; they are not a process sandbox.
9
-
10
- A future CPython-in-WASM compatibility runtime may provide a sandboxed Python
11
- app route. That work is deferred and is not the current SDK v3 execution path.
7
+ Python apps are sandboxed. They run through the CPython-in-WASM adapter
8
+ (`src/host/wasm_python.rs`) inside their own `wasmtime::Store` with isolated
9
+ linear memory — the same component boundary a Rust WASM app gets, not a native
10
+ subprocess. An app reaches only the host interfaces Plexi links for its world,
11
+ and protected effects (file, network, AI, clipboard, pane, audio, GPU) each
12
+ require an explicit capability grant the user approves on first request. There
13
+ is no ambient process access to escape to. See `docs/wasm-runtime.md`
14
+ § Security Model for the full boundary.
12
15
  """
13
16
 
14
- from ._version import __version__ as __version__
15
-
17
+ __version__ = "3.0.0"
16
18
  SDK_ID = f"plexi-sdk-py/{__version__}"
17
19
 
18
20
  from ._v3_state import StateSnapshot, log, state
@@ -35,17 +37,7 @@ from .ui import (
35
37
  Tabs as Tabs,
36
38
  Grid as Grid,
37
39
  Toggle as Toggle,
38
- Clickable as Clickable,
39
40
  ProgressBar as ProgressBar,
40
41
  TextEdit as TextEdit,
41
42
  )
42
43
  from ._theme import theme, Theme, AppPalette
43
-
44
- _workspace_root: str = ""
45
- pane_width: float = 0.0
46
- pane_height: float = 0.0
47
- canvas_width: float = 0.0
48
- canvas_height: float = 0.0
49
- keys_held: set[str] = set()
50
- _state: StateSnapshot | None = None
51
- _in_view: bool = False
@@ -29,7 +29,6 @@ def call_lifecycle(fn_name: str, json_arg: str) -> str:
29
29
 
30
30
  if fn_name == "init":
31
31
  _set_sdk_state(arg.get("state", {}), in_view=False)
32
- _set_sdk_size(arg.get("size", [0.0, 0.0]))
33
32
  result = fn(tuple(arg.get("size", [0.0, 0.0])), arg.get("args", []))
34
33
  return json.dumps([_encode_effect(e) for e in result])
35
34
  if fn_name == "update":
@@ -43,24 +42,15 @@ def call_lifecycle(fn_name: str, json_arg: str) -> str:
43
42
  tree = fn()
44
43
  return json.dumps(_encode_uitree(tree))
45
44
  finally:
46
- sdk._in_view = False
45
+ setattr(sdk, "_in_view", False)
47
46
  _v3_state._in_view = False
48
47
  raise ValueError(f"unknown lifecycle function: {fn_name}")
49
48
 
50
49
 
51
- def _set_sdk_size(size: Any) -> None:
52
- if not isinstance(size, (list, tuple)) or len(size) < 2:
53
- return
54
- sdk.pane_width = float(size[0] or 0.0)
55
- sdk.pane_height = float(size[1] or 0.0)
56
- sdk.canvas_width = sdk.pane_width
57
- sdk.canvas_height = sdk.pane_height
58
-
59
-
60
50
  def _set_sdk_state(encoded: dict[str, str], in_view: bool) -> None:
61
51
  snapshot = _decode_state(encoded)
62
- sdk._state = snapshot
63
- sdk._in_view = in_view
52
+ setattr(sdk, "_state", snapshot)
53
+ setattr(sdk, "_in_view", in_view)
64
54
  _v3_state._state = snapshot
65
55
  _v3_state._in_view = in_view
66
56
 
@@ -104,37 +94,47 @@ def _decode_event(payload: dict[str, Any]) -> Any:
104
94
  event_type = payload.get("type")
105
95
  if not isinstance(event_type, str):
106
96
  raise TypeError("event payload missing string 'type'")
107
- cls: Any = getattr(event_types, event_type, None)
97
+ cls = getattr(event_types, event_type, None)
108
98
  if cls is None or not is_dataclass(cls):
109
99
  raise TypeError(f"Unknown event type: {event_type}")
110
- kwargs = {f.name: payload[f.name] for f in fields(cast(Any, cls)) if f.name in payload}
100
+ kwargs = {
101
+ f.name: payload[f.name]
102
+ for f in fields(cast(Any, cls))
103
+ if f.name in payload
104
+ }
111
105
  if cls is event_types.KeyEvent and isinstance(kwargs.get("modifiers"), dict):
112
106
  kwargs["modifiers"] = event_types.Modifiers(**kwargs["modifiers"])
113
- if cls is event_types.Resize:
114
- _set_sdk_size([kwargs.get("width", 0.0), kwargs.get("height", 0.0)])
115
- if cls is event_types.MouseEvent:
116
- button = kwargs.get("button")
117
- if button == "primary":
118
- kwargs["button"] = "left"
119
- elif button == "secondary":
120
- kwargs["button"] = "right"
121
107
  if cls is event_types.SystemStatsResult and isinstance(kwargs.get("stats"), dict):
122
108
  kwargs["stats"] = event_types.SystemStats(**kwargs["stats"])
123
- if cls is event_types.FileReadResult and isinstance(kwargs.get("content"), list):
124
- kwargs["content"] = bytes(kwargs["content"])
125
- if cls is event_types.FileListResult and isinstance(kwargs.get("entries"), list):
126
- kwargs["entries"] = [
127
- event_types.FileListEntry(**entry) if isinstance(entry, dict) else entry
128
- for entry in kwargs["entries"]
129
- ]
130
109
  if cls is event_types.HttpResponse and isinstance(kwargs.get("body"), list):
131
110
  kwargs["body"] = bytes(kwargs["body"])
132
111
  if cls is event_types.PipeMessage and isinstance(kwargs.get("payload"), dict):
133
112
  kwargs["payload"] = event_types.PipePayload(**kwargs["payload"])
134
- return cls(**kwargs)
113
+ return cast(Any, cls)(**kwargs)
114
+
115
+
116
+ def _require_view_component(root: Any) -> None:
117
+ """Teachable failure when view() breaks the effect contract.
118
+
119
+ The most common generated-app mistake is `return tree, SetTimer(...)` from
120
+ view(); without this check it dies later as an opaque
121
+ "Unknown UINode type: tuple".
122
+ """
123
+ if isinstance(root, (tuple, list)):
124
+ raise TypeError(
125
+ f"view() must return a single component tree, got {type(root).__name__}. "
126
+ "Effects (SetTimer, SetState, ...) are returned from update() or init(), "
127
+ "never from view()."
128
+ )
129
+ if is_dataclass(root) and getattr(effect_types, type(root).__name__, None) is type(root):
130
+ raise TypeError(
131
+ f"view() returned the effect {type(root).__name__}. Effects are returned "
132
+ "from update() or init(); view() returns exactly one component."
133
+ )
135
134
 
136
135
 
137
136
  def _encode_uitree(root: Any) -> dict[str, Any]:
137
+ _require_view_component(root)
138
138
  arena: list[dict[str, Any]] = []
139
139
 
140
140
  def flatten(node: Any, key: str) -> int:
@@ -160,55 +160,78 @@ def _encode_uitree(root: Any) -> dict[str, Any]:
160
160
 
161
161
  def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, Any]:
162
162
  node_type = data.get("type") or data.get("kind")
163
- if node_type == "label":
163
+ if node_type == "pinned":
164
+ child = data.get("child")
165
+ if not isinstance(child, dict):
166
+ raise TypeError("pinned node requires a child object")
164
167
  return {
165
- "type": "Text",
166
- "text": data.get("text", ""),
167
- "size": data.get("size"),
168
- "bold": data.get("bold", False),
169
- "truncate": data.get("truncate", False),
170
- "align": data.get("align", "start"),
168
+ "type": "Pinned",
169
+ "edge": data.get("edge", "bottom"),
170
+ "child": flatten(child, f"{key}/child"),
171
+ }
172
+ if node_type == "footer_keys":
173
+ return {
174
+ "type": "FooterKeys",
175
+ "entries": data.get("entries", []),
176
+ "divider": data.get("divider", True),
177
+ }
178
+ if node_type == "app_bar":
179
+ return {
180
+ "type": "AppBar",
181
+ "title": data.get("title", ""),
182
+ "subtitle": data.get("subtitle", ""),
183
+ }
184
+ if node_type == "spinner":
185
+ return {
186
+ "type": "Spinner",
187
+ "label": data.get("label", ""),
171
188
  }
172
189
  if node_type == "column":
173
190
  children = data.get("children", [])
174
191
  child_ids = [
175
192
  flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
176
193
  ]
177
- return {
194
+ out: dict[str, Any] = {
178
195
  "type": "Column",
179
196
  "children": child_ids,
180
- "gap": data.get("gap", 0.0),
181
197
  "align": data.get("align", "start"),
182
198
  "grow": data.get("grow", False),
183
199
  }
200
+ # Carry gap only when the app set one: absence lets the host apply its
201
+ # default inter-child spacing, an explicit value (including 0) wins.
202
+ if data.get("gap") is not None:
203
+ out["gap"] = data["gap"]
204
+ return out
184
205
  if node_type in ("row", "Row"):
185
206
  children = data.get("children", [])
186
207
  child_ids = [
187
208
  flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
188
209
  ]
189
- return {
210
+ out = {
190
211
  "type": "Row",
191
212
  "children": child_ids,
192
- "gap": data.get("gap", 0.0),
193
213
  "align": data.get("align", "start"),
194
214
  "grow": data.get("grow", False),
195
215
  }
216
+ if data.get("gap") is not None:
217
+ out["gap"] = data["gap"]
218
+ return out
196
219
  if node_type == "button":
197
220
  return {
198
- "type": "button",
199
- "node_id": data.get("node_id", data.get("on_click", "")),
221
+ "type": "Button",
200
222
  "label": data.get("label", ""),
223
+ "on_click": data.get("on_click", ""),
201
224
  "style": data.get("style", "secondary"),
202
225
  "disabled": data.get("disabled", False),
203
226
  }
204
- if node_type == "text_edit":
227
+ if node_type in ("TextInput", "text_input", "text-input"):
205
228
  return {
206
- "type": "text_edit",
207
- "node_id": data.get("node_id", ""),
208
- "placeholder": data.get("placeholder", ""),
229
+ "type": "TextInput",
209
230
  "value": data.get("value", ""),
210
- "multiline": data.get("multiline", False),
211
- "max_length": data.get("max_length", 0),
231
+ "placeholder": data.get("placeholder", ""),
232
+ "on_change": data.get("on_change", data.get("on-change", "")),
233
+ "on_submit": data.get("on_submit", data.get("on-submit", "")),
234
+ "password": data.get("password", False),
212
235
  }
213
236
  if node_type == "select_list":
214
237
  items = data.get("items", [])
@@ -216,19 +239,33 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
216
239
  for idx, item in enumerate(items):
217
240
  text = str(item.get("name", "")) if isinstance(item, dict) else str(item)
218
241
  description = ""
242
+ leading = ""
243
+ trailing = ""
219
244
  if isinstance(item, dict):
220
245
  description = str(item.get("description", "") or "")
246
+ leading = str(item.get("leading", "") or "")
247
+ trailing = str(item.get("trailing", "") or "")
221
248
  if description:
222
- child = {
249
+ main = {
223
250
  "type": "column",
224
251
  "children": [
225
- {"type": "label", "text": text, "bold": True},
226
- {"type": "label", "text": description, "size": 11.0},
252
+ {"type": "text", "text": text, "bold": True},
253
+ {"type": "text", "text": description, "size": 11.0},
227
254
  ],
228
255
  "gap": 2.0,
229
256
  }
230
257
  else:
231
- child = {"type": "label", "text": text}
258
+ main = {"type": "text", "text": text}
259
+ if leading or trailing:
260
+ row_children: list[dict[str, Any]] = []
261
+ if leading:
262
+ row_children.append({"type": "text", "text": leading})
263
+ row_children.append(main)
264
+ if trailing:
265
+ row_children.append({"type": "text", "text": trailing})
266
+ child = {"type": "row", "children": row_children, "gap": 8.0}
267
+ else:
268
+ child = main
232
269
  child_ids.append(flatten(child, f"{key}/{idx}"))
233
270
  selected = data.get("selected_idx")
234
271
  if selected is not None:
@@ -239,4 +276,13 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
239
276
  "selected": selected,
240
277
  "on_select": data.get("on_select"),
241
278
  }
279
+ if node_type in ("scroll", "Scroll"):
280
+ child = data.get("child")
281
+ if child is None:
282
+ raise TypeError("scroll node requires a child")
283
+ return {
284
+ "type": "Scroll",
285
+ "child": flatten(child, f"{key}/0"),
286
+ "horizontal": data.get("horizontal", False),
287
+ }
242
288
  return data
@@ -23,7 +23,10 @@ _KEY_ALIASES: dict[str, str] = {
23
23
  "`": "backtick",
24
24
  ",": "comma",
25
25
  ".": "period",
26
- "/": "slash",
26
+ # "/" is deliberately absent (stint 0462): the host already sends "/" as
27
+ # the literal character (python_key_name() in wasm_python.rs), matching
28
+ # what apps like logs.py check for (`key == "/"`). Aliasing it to "slash"
29
+ # here would re-break the exact bug that stint fixed.
27
30
  }
28
31
 
29
32
 
@@ -0,0 +1,121 @@
1
+ """Diffed component-tree protocol (stint 0438).
2
+
3
+ The guest emits a full ``component_tree`` only when the tree's shape changes;
4
+ otherwise it emits a ``tree_delta`` carrying just the arena slots that changed.
5
+ Node identity is the arena index produced by ``_encode_uitree`` — stable
6
+ frame-to-frame while the tree keeps the same root, node count, and per-slot
7
+ key. This module owns both halves of that contract:
8
+
9
+ - ``node_patch`` (emit side): shrink one changed slot to the smallest patch.
10
+ - ``apply_delta`` / ``TreeReconstructor`` (consume side): rebuild the full
11
+ arena the host will decode, so headless harnesses and tests can assert on a
12
+ reconstructed tree exactly as the live host does.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+
18
+ class DeltaApplyError(Exception):
19
+ """A ``tree_delta`` could not be applied to the previous tree.
20
+
21
+ Raised when a patch references a slot or canvas command index that does not
22
+ exist in the base tree, or when there is no base tree at all. The host
23
+ treats this as a desync and requests a full-tree resync; consumers that
24
+ cannot resync (test harnesses) surface it as a failure rather than paint a
25
+ corrupt tree.
26
+ """
27
+
28
+
29
+ def node_patch(node: dict, old: dict) -> dict:
30
+ """Patch entry for one changed arena slot.
31
+
32
+ A canvas node whose only change is same-length command mutations shrinks to
33
+ a ``commands_changed`` entry (games mutate a handful of commands per frame);
34
+ anything else replaces the whole node.
35
+ """
36
+ data = node["data"]
37
+ old_data = old["data"]
38
+ if (
39
+ data.get("type") in ("canvas", "Canvas")
40
+ and data.get("type") == old_data.get("type")
41
+ and len(data.get("commands", ())) == len(old_data.get("commands", ()))
42
+ and {k: v for k, v in data.items() if k != "commands"}
43
+ == {k: v for k, v in old_data.items() if k != "commands"}
44
+ ):
45
+ changed_commands = [
46
+ [index, command]
47
+ for index, (command, old_command) in enumerate(
48
+ zip(data["commands"], old_data["commands"])
49
+ )
50
+ if command != old_command
51
+ ]
52
+ return {
53
+ "id": node["id"],
54
+ "key": node["key"],
55
+ "commands_changed": changed_commands,
56
+ }
57
+ return node
58
+
59
+
60
+ def apply_delta(prev: dict, changed: list) -> dict:
61
+ """Rebuild the full encoded arena from ``prev`` plus a ``changed`` list.
62
+
63
+ ``prev`` is the previously emitted encoded tree (``{"root", "nodes"}``).
64
+ Deltas never change the root (a root change forces a full frame), so the
65
+ result carries ``prev``'s root. Raises :class:`DeltaApplyError` on any patch
66
+ that does not fit the base tree — the same fail-loud contract the host's
67
+ Rust decoder enforces.
68
+ """
69
+ nodes = list(prev["nodes"])
70
+ for patch in changed:
71
+ index = patch["id"]
72
+ if not 0 <= index < len(nodes):
73
+ raise DeltaApplyError(
74
+ f"delta patch id {index} out of range (arena has {len(nodes)} nodes)"
75
+ )
76
+ if "commands_changed" in patch:
77
+ base_node = nodes[index]
78
+ data = dict(base_node["data"])
79
+ commands = list(data.get("commands", []))
80
+ for command_index, command in patch["commands_changed"]:
81
+ if not 0 <= command_index < len(commands):
82
+ raise DeltaApplyError(
83
+ f"commands_changed index {command_index} out of range "
84
+ f"(node {index} has {len(commands)} commands)"
85
+ )
86
+ commands[command_index] = command
87
+ data["commands"] = commands
88
+ nodes[index] = {**base_node, "data": data}
89
+ else:
90
+ nodes[index] = patch
91
+ return {"root": prev["root"], "nodes": nodes}
92
+
93
+
94
+ class TreeReconstructor:
95
+ """Stateful consumer that turns a delta stream back into full trees.
96
+
97
+ Feed every protocol event through :meth:`ingest`. ``component_tree`` events
98
+ pass through and become the new base; ``tree_delta`` events are rebuilt into
99
+ an equivalent ``component_tree`` so downstream code only ever sees full
100
+ trees. Every other event passes through untouched.
101
+ """
102
+
103
+ def __init__(self) -> None:
104
+ self._last_tree: dict | None = None
105
+
106
+ def ingest(self, event: dict) -> dict:
107
+ event_type = event.get("type")
108
+ if event_type == "component_tree":
109
+ self._last_tree = event.get("tree")
110
+ return event
111
+ if event_type == "tree_delta":
112
+ if self._last_tree is None:
113
+ raise DeltaApplyError("tree_delta received before any full tree")
114
+ rebuilt = apply_delta(self._last_tree, event.get("changed", []))
115
+ self._last_tree = rebuilt
116
+ return {
117
+ "type": "component_tree",
118
+ "frame_id": event.get("frame_id"),
119
+ "tree": rebuilt,
120
+ }
121
+ return event