plexi-sdk 0.3.5__tar.gz → 0.5.1__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 (40) hide show
  1. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/.gitignore +1 -0
  2. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/PKG-INFO +4 -3
  3. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/README.md +3 -2
  4. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/__init__.py +3 -3
  5. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_adapter.py +142 -41
  6. plexi_sdk-0.5.1/plexi_sdk/_keys.py +87 -0
  7. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_protocol.py +2 -2
  8. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_theme.py +2 -2
  9. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_v3_delta.py +69 -6
  10. plexi_sdk-0.5.1/plexi_sdk/_v3_errors.py +158 -0
  11. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_v3_process.py +1 -1
  12. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_v3_runtime.py +336 -43
  13. plexi_sdk-0.5.1/plexi_sdk/_v3_state.py +210 -0
  14. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_version.py +32 -3
  15. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/effects.py +103 -6
  16. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/events.py +85 -57
  17. plexi_sdk-0.5.1/plexi_sdk/templates/manifest.toml +20 -0
  18. plexi_sdk-0.5.1/plexi_sdk/templates/plugin-contract.md +51 -0
  19. plexi_sdk-0.5.1/plexi_sdk/templates/plugin_init.py +62 -0
  20. plexi_sdk-0.5.1/plexi_sdk/templates/test_plugin_init.py +61 -0
  21. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/testing.py +24 -16
  22. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/tools.py +32 -4
  23. plexi_sdk-0.5.1/plexi_sdk/ui.py +1852 -0
  24. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/pyproject.toml +1 -1
  25. plexi_sdk-0.3.5/plexi_sdk/_keys.py +0 -34
  26. plexi_sdk-0.3.5/plexi_sdk/_v3_state.py +0 -93
  27. plexi_sdk-0.3.5/plexi_sdk/midi.py +0 -222
  28. plexi_sdk-0.3.5/plexi_sdk/templates/AGENTS.md +0 -47
  29. plexi_sdk-0.3.5/plexi_sdk/templates/agent_init.py +0 -77
  30. plexi_sdk-0.3.5/plexi_sdk/templates/app_init.py +0 -46
  31. plexi_sdk-0.3.5/plexi_sdk/templates/app_init_tools.py +0 -35
  32. plexi_sdk-0.3.5/plexi_sdk/templates/app_init_ui.py +0 -25
  33. plexi_sdk-0.3.5/plexi_sdk/templates/manifest.toml +0 -15
  34. plexi_sdk-0.3.5/plexi_sdk/templates/test_app_init.py +0 -87
  35. plexi_sdk-0.3.5/plexi_sdk/ui.py +0 -2819
  36. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/_types.py +0 -0
  37. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/py.typed +0 -0
  38. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/state_format.py +0 -0
  39. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/templates/__init__.py +0 -0
  40. {plexi_sdk-0.3.5 → plexi_sdk-0.5.1}/plexi_sdk/templates/gitignore +0 -0
@@ -61,6 +61,7 @@ tools/e2e_authoring/*.egg-info/
61
61
  .plexi-beta/
62
62
  .plexi-pr-*/
63
63
  .superpowers/
64
+ .pi/
64
65
 
65
66
  # Claude agent memory (local, not shared)
66
67
  .claude/agent-memory/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: plexi-sdk
3
- Version: 0.3.5
3
+ Version: 0.5.1
4
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
@@ -48,7 +48,7 @@ def init(size, args):
48
48
 
49
49
 
50
50
  def update(event):
51
- if isinstance(event, KeyEvent) and event.key == "plus" and event.pressed:
51
+ if isinstance(event, KeyEvent) and event.key == "+" and event.pressed:
52
52
  return [SetState({"count": state.get("count", 0) + 1})]
53
53
  return []
54
54
 
@@ -71,11 +71,12 @@ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonica
71
71
 
72
72
  | Physical key | `event.key` |
73
73
  |---|---|
74
- | Enter / Return | `"return"` |
74
+ | Enter / Return | `"enter"` |
75
75
  | Escape | `"escape"` |
76
76
  | Backspace | `"backspace"` |
77
77
  | Space | `"space"` |
78
78
  | Arrow keys | `"up"` / `"down"` / `"left"` / `"right"` |
79
+ | Operators / Punctuation | `"+"` / `"-"` / `"*"` / `"/"` / `"="` |
79
80
 
80
81
  ## New App
81
82
 
@@ -28,7 +28,7 @@ def init(size, args):
28
28
 
29
29
 
30
30
  def update(event):
31
- if isinstance(event, KeyEvent) and event.key == "plus" and event.pressed:
31
+ if isinstance(event, KeyEvent) and event.key == "+" and event.pressed:
32
32
  return [SetState({"count": state.get("count", 0) + 1})]
33
33
  return []
34
34
 
@@ -51,11 +51,12 @@ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonica
51
51
 
52
52
  | Physical key | `event.key` |
53
53
  |---|---|
54
- | Enter / Return | `"return"` |
54
+ | Enter / Return | `"enter"` |
55
55
  | Escape | `"escape"` |
56
56
  | Backspace | `"backspace"` |
57
57
  | Space | `"space"` |
58
58
  | Arrow keys | `"up"` / `"down"` / `"left"` / `"right"` |
59
+ | Operators / Punctuation | `"+"` / `"-"` / `"*"` / `"/"` / `"="` |
59
60
 
60
61
  ## New App
61
62
 
@@ -1,7 +1,7 @@
1
1
  """Plexi Python SDK.
2
2
 
3
3
  Apps expose module-level ``init(size, args)``, ``update(event)``, and ``view()``
4
- functions. The V3AppRuntime drives the event loop: host sends JSON events on
4
+ functions. The PluginRuntime drives the event loop: host sends JSON events on
5
5
  stdin, app responds with effects and component trees on stdout.
6
6
 
7
7
  Python apps are sandboxed. They run through the CPython-in-WASM adapter
@@ -18,7 +18,7 @@ from ._version import __version__
18
18
 
19
19
  SDK_ID = f"plexi-sdk-py/{__version__}"
20
20
 
21
- from ._v3_state import StateSnapshot, log, state
21
+ from ._v3_state import ComponentState, StateSnapshot, component, log, state, use_state
22
22
  from . import effects as effects
23
23
  from . import events as events
24
24
  from . import tools as tools
@@ -35,7 +35,7 @@ from .ui import (
35
35
  ProgressBar as ProgressBar,
36
36
  TextEdit as TextEdit,
37
37
  )
38
- from ._theme import theme, Theme, AppPalette, rgba, dim
38
+ from ._theme import theme, Theme, PluginPalette, rgba, dim
39
39
  from .state_format import (
40
40
  ChecklistItem as ChecklistItem,
41
41
  parse_checklist as parse_checklist,
@@ -16,14 +16,14 @@ from . import events as event_types
16
16
  _module = None
17
17
 
18
18
 
19
- def load_app(module_name: str) -> None:
19
+ def load_plugin(module_name: str) -> None:
20
20
  global _module
21
21
  _module = importlib.import_module(module_name)
22
22
 
23
23
 
24
24
  def call_lifecycle(fn_name: str, json_arg: str) -> str:
25
25
  if _module is None:
26
- raise RuntimeError("no Plexi app module loaded")
26
+ raise RuntimeError("no Plexi plugin module loaded")
27
27
  fn = getattr(_module, fn_name)
28
28
  arg = json.loads(json_arg) if json_arg else {}
29
29
 
@@ -74,6 +74,14 @@ def _encode_effect(effect: Any) -> dict[str, Any]:
74
74
  if getattr(effect_types, type(effect).__name__, None) is not type(effect):
75
75
  raise TypeError(f"Unknown effect type: {type(effect).__name__}")
76
76
  payload = _jsonable(asdict(cast(Any, effect)))
77
+ if isinstance(effect, effect_types.HttpFetch):
78
+ payload["url"] = effect.resolved_url()
79
+ if payload.get("params") is None:
80
+ payload.pop("params", None)
81
+ if payload.get("tag") is None:
82
+ payload.pop("tag", None)
83
+ if payload.get("request_id") is None:
84
+ payload.pop("request_id", None)
77
85
  payload["type"] = type(effect).__name__
78
86
  return payload
79
87
 
@@ -104,10 +112,20 @@ def _decode_event(payload: dict[str, Any]) -> Any:
104
112
  }
105
113
  if cls is event_types.KeyEvent and isinstance(kwargs.get("modifiers"), dict):
106
114
  kwargs["modifiers"] = event_types.Modifiers(**kwargs["modifiers"])
107
- if cls is event_types.SystemStatsResult and isinstance(kwargs.get("stats"), dict):
108
- kwargs["stats"] = event_types.SystemStats(**kwargs["stats"])
109
- if cls is event_types.HttpResponse and isinstance(kwargs.get("body"), list):
110
- kwargs["body"] = bytes(kwargs["body"])
115
+ if cls is event_types.HttpResponse:
116
+ if isinstance(kwargs.get("body"), list):
117
+ kwargs["body"] = bytes(kwargs["body"])
118
+ elif isinstance(kwargs.get("body"), str):
119
+ kwargs["body"] = kwargs["body"].encode("utf-8")
120
+ raw_headers = kwargs.get("headers")
121
+ if isinstance(raw_headers, dict):
122
+ kwargs["headers"] = [(str(k), str(v)) for k, v in raw_headers.items()]
123
+ elif isinstance(raw_headers, list):
124
+ kwargs["headers"] = [
125
+ (str(item[0]), str(item[1]))
126
+ for item in raw_headers
127
+ if isinstance(item, (list, tuple)) and len(item) == 2
128
+ ]
111
129
  if cls is event_types.PipeMessage and isinstance(kwargs.get("payload"), dict):
112
130
  kwargs["payload"] = event_types.PipePayload(**kwargs["payload"])
113
131
  return cast(Any, cls)(**kwargs)
@@ -131,6 +149,12 @@ def _require_view_component(root: Any) -> None:
131
149
  f"view() returned the effect {type(root).__name__}. Effects are returned "
132
150
  "from update() or init(); view() returns exactly one component."
133
151
  )
152
+ if not (isinstance(root, dict) or hasattr(root, "to_node") or is_dataclass(root)):
153
+ raise TypeError(
154
+ f"view() returned {type(root).__name__}, which is not a component. "
155
+ "Return exactly one plexi_sdk.ui component, for example "
156
+ "Column(children=[Text(...)])."
157
+ )
134
158
 
135
159
 
136
160
  def _encode_uitree(root: Any) -> dict[str, Any]:
@@ -140,9 +164,19 @@ def _encode_uitree(root: Any) -> dict[str, Any]:
140
164
  def flatten(node: Any, key: str) -> int:
141
165
  node_id = len(arena)
142
166
  arena.append({"id": node_id, "key": key, "data": {"type": "Pending"}})
143
- explicit_key = getattr(node, "key", "") or key
167
+ # An explicit Keyed key is a path segment, not a replacement for the
168
+ # path accumulated above it. That makes the key unique in the tree
169
+ # and keeps every descendant on that keyed identity when siblings move.
170
+ own_key = getattr(node, "key", "") or (
171
+ node.get("_plexi_key", "") if isinstance(node, dict) else ""
172
+ )
173
+ # `flatten` receives a positional child address. Replace that final
174
+ # address segment for Keyed rather than appending to it: the keyed node
175
+ # is the direct child of its container, regardless of its list index.
176
+ key_parent = key.rsplit("/", 1)[0] if "/" in key else ""
177
+ explicit_key = f"{key_parent}/@{own_key}" if own_key else key
144
178
  if isinstance(node, dict):
145
- data = node
179
+ data = {k: v for k, v in node.items() if k != "_plexi_key"}
146
180
  elif hasattr(node, "to_node"):
147
181
  data = node.to_node()
148
182
  elif is_dataclass(node):
@@ -175,9 +209,9 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
175
209
  "entries": data.get("entries", []),
176
210
  "divider": data.get("divider", True),
177
211
  }
178
- if node_type == "app_bar":
212
+ if node_type == "surface_header":
179
213
  return {
180
- "type": "AppBar",
214
+ "type": "SurfaceHeader",
181
215
  "title": data.get("title", ""),
182
216
  "subtitle": data.get("subtitle", ""),
183
217
  }
@@ -195,6 +229,7 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
195
229
  "type": "Column",
196
230
  "children": child_ids,
197
231
  "align": data.get("align", "start"),
232
+ "justify": data.get("justify", "start"),
198
233
  "grow": data.get("grow", False),
199
234
  }
200
235
  # Carry gap only when the app set one: absence lets the host apply its
@@ -202,6 +237,50 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
202
237
  if data.get("gap") is not None:
203
238
  out["gap"] = data["gap"]
204
239
  return out
240
+ if node_type in ("card", "Card"):
241
+ if "child" in data and isinstance(data["child"], int):
242
+ child_id = data["child"]
243
+ elif "child" in data and data["child"] is not None:
244
+ child_id = flatten(data["child"], f"{key}/child")
245
+ else:
246
+ inner_col: dict[str, Any] = {
247
+ "type": "column",
248
+ "children": data.get("children", []),
249
+ }
250
+ if data.get("gap") is not None:
251
+ inner_col["gap"] = data["gap"]
252
+ child_id = flatten(inner_col, f"{key}/body")
253
+ pad = float(data.get("padding", data.get("top", 12.0)))
254
+ return {
255
+ "type": "Card",
256
+ "card": True,
257
+ "child": child_id,
258
+ "top": pad,
259
+ "right": pad,
260
+ "bottom": pad,
261
+ "left": pad,
262
+ }
263
+ if node_type in ("DataTable", "data_table", "table", "Table"):
264
+ children = data.get("children", [])
265
+ child_ids = [
266
+ flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
267
+ ]
268
+ selected = data.get("selected", data.get("selected_idx"))
269
+ if selected is not None:
270
+ selected = int(selected)
271
+ out = {
272
+ "type": "DataTable",
273
+ "columns": [str(c) for c in data.get("columns", [])],
274
+ "rows": [[str(cell) for cell in r] for r in data.get("rows", [])],
275
+ "selected": selected,
276
+ "on_select": data.get("on_select"),
277
+ "children": child_ids,
278
+ "align": data.get("align", "start"),
279
+ "grow": data.get("grow", False),
280
+ }
281
+ if data.get("gap") is not None:
282
+ out["gap"] = data["gap"]
283
+ return out
205
284
  if node_type in ("row", "Row"):
206
285
  children = data.get("children", [])
207
286
  child_ids = [
@@ -210,7 +289,8 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
210
289
  out = {
211
290
  "type": "Row",
212
291
  "children": child_ids,
213
- "align": data.get("align", "start"),
292
+ "align": data.get("align", "center"),
293
+ "justify": data.get("justify", "start"),
214
294
  "grow": data.get("grow", False),
215
295
  }
216
296
  if data.get("gap") is not None:
@@ -238,37 +318,58 @@ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, A
238
318
  items = data.get("items", [])
239
319
  child_ids = []
240
320
  for idx, item in enumerate(items):
241
- text = str(item.get("name", "")) if isinstance(item, dict) else str(item)
242
- description = ""
243
- leading = ""
244
- trailing = ""
245
- if isinstance(item, dict):
246
- description = str(item.get("description", "") or "")
247
- leading = str(item.get("leading", "") or "")
248
- trailing = str(item.get("trailing", "") or "")
249
- if description:
250
- main = {
251
- "type": "column",
252
- "children": [
253
- {"type": "text", "text": text, "bold": True},
254
- {"type": "text", "text": description, "size": 11.0},
255
- ],
256
- "gap": 2.0,
257
- }
258
- else:
259
- main = {"type": "text", "text": text}
260
- if leading or trailing:
261
- row_children: list[dict[str, Any]] = []
262
- if leading:
263
- row_children.append({"type": "text", "text": leading})
264
- row_children.append(main)
265
- if trailing:
266
- row_children.append({"type": "text", "text": trailing})
267
- child = {"type": "row", "children": row_children, "gap": 8.0}
321
+ if hasattr(item, "to_node"):
322
+ item_node: Any = item
323
+ elif isinstance(item, dict) and ("type" in item or "kind" in item):
324
+ item_node = item
268
325
  else:
269
- child = main
270
- child_ids.append(flatten(child, f"{key}/{idx}"))
271
- selected = data.get("selected_idx")
326
+ text = (
327
+ str(item.get("name", item.get("label", "")))
328
+ if isinstance(item, dict)
329
+ else str(item)
330
+ )
331
+ description = ""
332
+ leading = ""
333
+ trailing = ""
334
+ if isinstance(item, dict):
335
+ description = str(item.get("description", "") or "")
336
+ leading = str(item.get("leading", "") or "")
337
+ trailing = str(item.get("trailing", "") or "")
338
+ if description:
339
+ main: Any = {
340
+ "type": "column",
341
+ "children": [
342
+ {"type": "text", "text": text, "bold": True},
343
+ {
344
+ "type": "text",
345
+ "text": description,
346
+ "size": 12.0,
347
+ "color": "muted",
348
+ },
349
+ ],
350
+ "gap": 2.0,
351
+ }
352
+ else:
353
+ main = {"type": "text", "text": text}
354
+ if leading or trailing:
355
+ row_children: list[dict[str, Any]] = []
356
+ if leading:
357
+ row_children.append({"type": "text", "text": leading})
358
+ row_children.append(main)
359
+ if trailing:
360
+ row_children.append(
361
+ {
362
+ "type": "text",
363
+ "text": trailing,
364
+ "size": 12.0,
365
+ "color": "muted",
366
+ }
367
+ )
368
+ item_node = {"type": "row", "children": row_children, "gap": 8.0}
369
+ else:
370
+ item_node = main
371
+ child_ids.append(flatten(item_node, f"{key}/{idx}"))
372
+ selected = data.get("selected_idx", data.get("selected"))
272
373
  if selected is not None:
273
374
  selected = int(selected)
274
375
  return {
@@ -0,0 +1,87 @@
1
+ """Key normalization: egui Debug / word names to SDK canonical key strings."""
2
+ from __future__ import annotations
3
+
4
+ _KEY_ALIASES: dict[str, str] = {
5
+ "arrowleft": "left",
6
+ "left": "left",
7
+ "arrowright": "right",
8
+ "right": "right",
9
+ "arrowup": "up",
10
+ "up": "up",
11
+ "arrowdown": "down",
12
+ "down": "down",
13
+ "enter": "enter",
14
+ "return": "enter",
15
+ "escape": "escape",
16
+ "esc": "escape",
17
+ "backspace": "backspace",
18
+ "delete": "delete",
19
+ "insert": "insert",
20
+ "home": "home",
21
+ "end": "end",
22
+ "pageup": "pageup",
23
+ "page_up": "pageup",
24
+ "pagedown": "pagedown",
25
+ "page_down": "pagedown",
26
+ "tab": "tab",
27
+ "space": "space",
28
+ " ": "space",
29
+ "plus": "+",
30
+ "+": "+",
31
+ "minus": "-",
32
+ "-": "-",
33
+ "equals": "=",
34
+ "equal": "=",
35
+ "=": "=",
36
+ "slash": "/",
37
+ "/": "/",
38
+ "asterisk": "*",
39
+ "multiply": "*",
40
+ "*": "*",
41
+ "backslash": "\\",
42
+ "\\": "\\",
43
+ "semicolon": ";",
44
+ ";": ";",
45
+ "colon": ":",
46
+ ":": ":",
47
+ "quote": "'",
48
+ "'": "'",
49
+ "backtick": "`",
50
+ "`": "`",
51
+ "comma": ",",
52
+ ",": ",",
53
+ "period": ".",
54
+ ".": ".",
55
+ "openbracket": "[",
56
+ "open_bracket": "[",
57
+ "[": "[",
58
+ "closebracket": "]",
59
+ "close_bracket": "]",
60
+ "]": "]",
61
+ "opencurlybracket": "{",
62
+ "open_curly_bracket": "{",
63
+ "{": "{",
64
+ "closecurlybracket": "}",
65
+ "close_curly_bracket": "}",
66
+ "}": "}",
67
+ "pipe": "|",
68
+ "|": "|",
69
+ "questionmark": "?",
70
+ "?": "?",
71
+ "exclamationmark": "!",
72
+ "!": "!",
73
+ }
74
+
75
+
76
+ def normalize_key(key: str) -> str:
77
+ if not key:
78
+ return ""
79
+ if key == " ":
80
+ return "space"
81
+ lowered = key.lower()
82
+ if lowered in _KEY_ALIASES:
83
+ return _KEY_ALIASES[lowered]
84
+ if lowered.startswith("num") and len(lowered) == 4 and lowered[3].isdigit():
85
+ return lowered[3]
86
+ return lowered
87
+
@@ -1,12 +1,12 @@
1
1
  # AUTO-GENERATED — do not edit by hand.
2
2
  # Regenerate with: just gen-schema
3
- # Protocol: pgap/3
3
+ # Protocol: pgap/4
4
4
 
5
5
  from __future__ import annotations
6
6
  from dataclasses import dataclass
7
7
  from typing import Optional
8
8
 
9
- PROTOCOL_VERSION = "pgap/3"
9
+ PROTOCOL_VERSION = "pgap/4"
10
10
 
11
11
 
12
12
  @dataclass
@@ -98,7 +98,7 @@ class Theme:
98
98
  self.is_dark = _luminance(self.bg) < 0.5
99
99
 
100
100
 
101
- class AppPalette:
101
+ class PluginPalette:
102
102
  """Light/dark palette for app-defined color tokens.
103
103
 
104
104
  Both dicts must have the same keys. ``resolve(theme)`` returns the
@@ -108,7 +108,7 @@ class AppPalette:
108
108
  def __init__(self, dark: "dict[str, str]", light: "dict[str, str]") -> None:
109
109
  if set(dark.keys()) != set(light.keys()):
110
110
  raise ValueError(
111
- f"AppPalette: dark and light dicts must have the same keys. "
111
+ f"PluginPalette: dark and light dicts must have the same keys. "
112
112
  f"dark-only: {set(dark) - set(light)!r}, "
113
113
  f"light-only: {set(light) - set(dark)!r}"
114
114
  )
@@ -14,6 +14,22 @@ key. This module owns both halves of that contract:
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
+ # Wire type aliases map to their child field and whether it contains a list.
18
+ # Keep this aligned with decode_node_data and validate_python_ui_tree in the host.
19
+ CONTAINER_FIELDS = {
20
+ **dict.fromkeys(("column", "row", "datatable", "data_table", "table"), ("children", True)),
21
+ **dict.fromkeys(("listview", "list_view", "list-view"), ("items", True)),
22
+ **dict.fromkeys(("scroll", "padding", "card", "pinned"), ("child", False)),
23
+ }
24
+
25
+
26
+ def child_refs(data: dict) -> list:
27
+ spec = CONTAINER_FIELDS.get(data.get("type", "").lower())
28
+ if spec is None:
29
+ return []
30
+ field, many = spec
31
+ return data.get(field, []) if many else [data.get(field)]
32
+
17
33
 
18
34
  class DeltaApplyError(Exception):
19
35
  """A ``tree_delta`` could not be applied to the previous tree.
@@ -57,7 +73,32 @@ def node_patch(node: dict, old: dict) -> dict:
57
73
  return node
58
74
 
59
75
 
60
- def apply_delta(prev: dict, changed: list) -> dict:
76
+ def _node_index(nodes: list[dict], node_id: int) -> int:
77
+ for index, node in enumerate(nodes):
78
+ if node.get("id") == node_id:
79
+ return index
80
+ raise DeltaApplyError(f"delta patch id {node_id} is not present in the arena")
81
+
82
+
83
+ def validate_tree(tree: dict) -> None:
84
+ """Reject a tree whose ids or child references cannot be rendered."""
85
+ nodes = tree.get("nodes")
86
+ if not isinstance(nodes, list):
87
+ raise DeltaApplyError("tree is missing its nodes array")
88
+ ids = [node.get("id") for node in nodes]
89
+ if len(ids) != len(set(ids)):
90
+ raise DeltaApplyError("tree contains duplicate node ids")
91
+ known_ids = set(ids)
92
+ if tree.get("root") not in known_ids:
93
+ raise DeltaApplyError("tree root is not present in its arena")
94
+ for node in nodes:
95
+ data = node.get("data", {})
96
+ if any(ref not in known_ids for ref in child_refs(data)):
97
+ raise DeltaApplyError(f"tree node {node.get('id')} references a missing child")
98
+
99
+
100
+ def apply_delta(prev: dict, changed: list, *, added: list | None = None,
101
+ removed: list | None = None) -> dict:
61
102
  """Rebuild the full encoded arena from ``prev`` plus a ``changed`` list.
62
103
 
63
104
  ``prev`` is the previously emitted encoded tree (``{"root", "nodes"}``).
@@ -69,10 +110,12 @@ def apply_delta(prev: dict, changed: list) -> dict:
69
110
  nodes = list(prev["nodes"])
70
111
  for patch in changed:
71
112
  index = patch["id"]
72
- if not 0 <= index < len(nodes):
113
+ try:
114
+ index = _node_index(nodes, index)
115
+ except DeltaApplyError as error:
73
116
  raise DeltaApplyError(
74
- f"delta patch id {index} out of range (arena has {len(nodes)} nodes)"
75
- )
117
+ f"delta patch id {patch['id']} out of range (arena has {len(nodes)} nodes)"
118
+ ) from error
76
119
  if "commands_changed" in patch:
77
120
  base_node = nodes[index]
78
121
  data = dict(base_node["data"])
@@ -88,7 +131,21 @@ def apply_delta(prev: dict, changed: list) -> dict:
88
131
  nodes[index] = {**base_node, "data": data}
89
132
  else:
90
133
  nodes[index] = patch
91
- return {"root": prev["root"], "nodes": nodes}
134
+ removed_ids = removed or []
135
+ if len(set(removed_ids)) != len(removed_ids):
136
+ raise DeltaApplyError("keyed delta removes an id more than once")
137
+ known_ids = {node["id"] for node in nodes}
138
+ if any(node_id not in known_ids for node_id in removed_ids):
139
+ raise DeltaApplyError("keyed delta removes an unknown id")
140
+ nodes = [node for node in nodes if node["id"] not in set(removed_ids)]
141
+ for node in added or []:
142
+ node_id = node.get("id")
143
+ if not isinstance(node_id, int) or node_id in {n["id"] for n in nodes}:
144
+ raise DeltaApplyError("keyed delta adds a missing or duplicate id")
145
+ nodes.append(node)
146
+ rebuilt = {"root": prev["root"], "nodes": nodes}
147
+ validate_tree(rebuilt)
148
+ return rebuilt
92
149
 
93
150
 
94
151
  class TreeReconstructor:
@@ -106,12 +163,18 @@ class TreeReconstructor:
106
163
  def ingest(self, event: dict) -> dict:
107
164
  event_type = event.get("type")
108
165
  if event_type == "component_tree":
166
+ validate_tree(event.get("tree") or {})
109
167
  self._last_tree = event.get("tree")
110
168
  return event
111
169
  if event_type == "tree_delta":
112
170
  if self._last_tree is None:
113
171
  raise DeltaApplyError("tree_delta received before any full tree")
114
- rebuilt = apply_delta(self._last_tree, event.get("changed", []))
172
+ rebuilt = apply_delta(
173
+ self._last_tree,
174
+ event.get("changed", []),
175
+ added=event.get("added"),
176
+ removed=event.get("removed"),
177
+ )
115
178
  self._last_tree = rebuilt
116
179
  return {
117
180
  "type": "component_tree",