polyui 0.1.0__tar.gz → 0.1.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 (89) hide show
  1. {polyui-0.1.0 → polyui-0.1.1}/Cargo.lock +11 -11
  2. {polyui-0.1.0 → polyui-0.1.1}/Cargo.toml +5 -5
  3. {polyui-0.1.0 → polyui-0.1.1}/PKG-INFO +2 -1
  4. {polyui-0.1.0/bindings/python → polyui-0.1.1}/README.md +1 -0
  5. {polyui-0.1.0 → polyui-0.1.1/bindings/python}/README.md +1 -0
  6. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/polyui.pyi +37 -0
  7. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/host.rs +348 -1
  8. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/lib.rs +2 -0
  9. polyui-0.1.1/bindings/python/src/stream.rs +76 -0
  10. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/validator.rs +88 -2
  11. polyui-0.1.1/bindings/python/tests/test_stream.py +130 -0
  12. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/.gitignore +0 -0
  13. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/Cargo.toml +0 -0
  14. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/examples/fastapi_app.py +0 -0
  15. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/catalogs.rs +0 -0
  16. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/client.rs +0 -0
  17. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/convert.rs +0 -0
  18. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/errors.rs +0 -0
  19. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/functions.rs +0 -0
  20. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/src/surface.rs +0 -0
  21. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/conftest.py +0 -0
  22. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_charts.py +0 -0
  23. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_client.py +0 -0
  24. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_embed.py +0 -0
  25. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_example.py +0 -0
  26. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_pipeline.py +0 -0
  27. {polyui-0.1.0 → polyui-0.1.1}/bindings/python/tests/test_validate.py +0 -0
  28. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/Cargo.toml +0 -0
  29. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/README.md +0 -0
  30. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/dataset.rs +0 -0
  31. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/describe.rs +0 -0
  32. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/format.rs +0 -0
  33. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/layout.rs +0 -0
  34. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/lib.rs +0 -0
  35. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/scene.rs +0 -0
  36. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/spec.rs +0 -0
  37. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/svg.rs +0 -0
  38. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/text.rs +0 -0
  39. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/src/ticks.rs +0 -0
  40. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/compile.rs +0 -0
  41. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/area_uz_cyrl.svg +0 -0
  42. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/bar_dark_en.svg +0 -0
  43. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/bar_uz_latn.json +0 -0
  44. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/bar_uz_latn.svg +0 -0
  45. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/dense_labels_en.svg +0 -0
  46. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/empty_ru.svg +0 -0
  47. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/grouped_bar_en.svg +0 -0
  48. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/hostile_en.svg +0 -0
  49. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/line_ru.svg +0 -0
  50. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/pie_en.svg +0 -0
  51. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden/scatter_en.svg +0 -0
  52. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-chart/tests/golden.rs +0 -0
  53. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/Cargo.toml +0 -0
  54. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/README.md +0 -0
  55. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/catalogs/chart.json +0 -0
  56. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/catalogs/core.json +0 -0
  57. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/catalogs/embed.json +0 -0
  58. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/catalog.rs +0 -0
  59. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/client.rs +0 -0
  60. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/codec.rs +0 -0
  61. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/decode.rs +0 -0
  62. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/embed.rs +0 -0
  63. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/fits.rs +0 -0
  64. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/json.rs +0 -0
  65. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/lib.rs +0 -0
  66. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/limits.rs +0 -0
  67. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/pointer.rs +0 -0
  68. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/protocol.rs +0 -0
  69. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/sanitize.rs +0 -0
  70. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/stream.rs +0 -0
  71. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/summary.rs +0 -0
  72. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/text.rs +0 -0
  73. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/tools/compact.rs +0 -0
  74. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/tools.rs +0 -0
  75. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/validate.rs +0 -0
  76. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/value.rs +0 -0
  77. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/view.rs +0 -0
  78. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/src/voice.rs +0 -0
  79. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/conformance.rs +0 -0
  80. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/embed.rs +0 -0
  81. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/pipeline.rs +0 -0
  82. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/regressions.rs +0 -0
  83. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/robustness.rs +0 -0
  84. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/scene.rs +0 -0
  85. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/security.rs +0 -0
  86. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/security_pack.rs +0 -0
  87. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/stream.rs +0 -0
  88. {polyui-0.1.0 → polyui-0.1.1}/crates/polyui-core/tests/tools.rs +0 -0
  89. {polyui-0.1.0 → polyui-0.1.1}/pyproject.toml +0 -0
@@ -2746,7 +2746,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
2746
2746
 
2747
2747
  [[package]]
2748
2748
  name = "polyui"
2749
- version = "0.1.0"
2749
+ version = "0.1.1"
2750
2750
  dependencies = [
2751
2751
  "clap",
2752
2752
  "polyui-core",
@@ -2757,7 +2757,7 @@ dependencies = [
2757
2757
 
2758
2758
  [[package]]
2759
2759
  name = "polyui-bench"
2760
- version = "0.1.0"
2760
+ version = "0.1.1"
2761
2761
  dependencies = [
2762
2762
  "clap",
2763
2763
  "futures-util",
@@ -2771,7 +2771,7 @@ dependencies = [
2771
2771
 
2772
2772
  [[package]]
2773
2773
  name = "polyui-chart"
2774
- version = "0.1.0"
2774
+ version = "0.1.1"
2775
2775
  dependencies = [
2776
2776
  "serde",
2777
2777
  "serde_json",
@@ -2779,7 +2779,7 @@ dependencies = [
2779
2779
 
2780
2780
  [[package]]
2781
2781
  name = "polyui-core"
2782
- version = "0.1.0"
2782
+ version = "0.1.1"
2783
2783
  dependencies = [
2784
2784
  "base64 0.22.1",
2785
2785
  "serde",
@@ -2789,7 +2789,7 @@ dependencies = [
2789
2789
 
2790
2790
  [[package]]
2791
2791
  name = "polyui-decode"
2792
- version = "0.1.0"
2792
+ version = "0.1.1"
2793
2793
  dependencies = [
2794
2794
  "clap",
2795
2795
  "llguidance",
@@ -2799,7 +2799,7 @@ dependencies = [
2799
2799
 
2800
2800
  [[package]]
2801
2801
  name = "polyui-ffi"
2802
- version = "0.1.0"
2802
+ version = "0.1.1"
2803
2803
  dependencies = [
2804
2804
  "polyui-core",
2805
2805
  "serde_json",
@@ -2807,7 +2807,7 @@ dependencies = [
2807
2807
 
2808
2808
  [[package]]
2809
2809
  name = "polyui-node"
2810
- version = "0.1.0"
2810
+ version = "0.1.1"
2811
2811
  dependencies = [
2812
2812
  "getrandom 0.4.3",
2813
2813
  "napi",
@@ -2821,7 +2821,7 @@ dependencies = [
2821
2821
 
2822
2822
  [[package]]
2823
2823
  name = "polyui-python"
2824
- version = "0.1.0"
2824
+ version = "0.1.1"
2825
2825
  dependencies = [
2826
2826
  "getrandom 0.4.3",
2827
2827
  "polyui-chart",
@@ -2834,7 +2834,7 @@ dependencies = [
2834
2834
 
2835
2835
  [[package]]
2836
2836
  name = "polyui-query"
2837
- version = "0.1.0"
2837
+ version = "0.1.1"
2838
2838
  dependencies = [
2839
2839
  "datafusion",
2840
2840
  "serde",
@@ -2844,7 +2844,7 @@ dependencies = [
2844
2844
 
2845
2845
  [[package]]
2846
2846
  name = "polyui-server"
2847
- version = "0.1.0"
2847
+ version = "0.1.1"
2848
2848
  dependencies = [
2849
2849
  "axum",
2850
2850
  "futures-util",
@@ -2863,7 +2863,7 @@ dependencies = [
2863
2863
 
2864
2864
  [[package]]
2865
2865
  name = "polyui-wasm"
2866
- version = "0.1.0"
2866
+ version = "0.1.1"
2867
2867
  dependencies = [
2868
2868
  "polyui-core",
2869
2869
  "serde_json",
@@ -3,7 +3,7 @@ resolver = "3"
3
3
  members = ["crates/polyui-core", "crates/polyui-chart", "bindings/python"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.1.0"
6
+ version = "0.1.1"
7
7
  edition = "2024"
8
8
  rust-version = "1.88"
9
9
  license = "Apache-2.0"
@@ -15,10 +15,10 @@ keywords = ["llm", "agents", "generative-ui", "mcp", "tool-use"]
15
15
  categories = ["gui", "web-programming"]
16
16
 
17
17
  [workspace.dependencies]
18
- polyui-core = { path = "crates/polyui-core", version = "0.1.0" }
19
- polyui-chart = { path = "crates/polyui-chart", version = "0.1.0" }
20
- polyui-server = { path = "crates/polyui-server", version = "0.1.0" }
21
- polyui-query = { path = "crates/polyui-query", version = "0.1.0" }
18
+ polyui-core = { path = "crates/polyui-core", version = "0.1.1" }
19
+ polyui-chart = { path = "crates/polyui-chart", version = "0.1.1" }
20
+ polyui-server = { path = "crates/polyui-server", version = "0.1.1" }
21
+ polyui-query = { path = "crates/polyui-query", version = "0.1.1" }
22
22
  serde = { version = "1", features = ["derive"] }
23
23
  serde_json = { version = "1", features = ["preserve_order"] }
24
24
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: polyui
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: Programming Language :: Python :: Implementation :: CPython
@@ -81,6 +81,7 @@ What you get:
81
81
  | `Validator.resolve_refs`, `compile_charts`, `attach_apps`, `seal_actions`, `downgrade`, `summary`, `fallback` | The same steps one at a time, if you want to run them yourself. |
82
82
  | `Surface`, `Update` | Validated results. `to_dict()` and `Surface.from_dict()` let you keep them in a session store. |
83
83
  | `tool_definitions(catalogs, actions, strict=False, profile="compact")` | The Anthropic tool JSON for `show_ui`, `update_ui` and `close_ui`. `profile="full"` puts every prop in the schema and is needed for `strict`. |
84
+ | `ShowStream`, `Validator.feed_show(stream, chunk, ...)`, `Validator.finish_show(stream, payload=None, ...)` | Stream a `show_ui` call: `ui.open` and `ui.patch` for each component as it arrives, then the full check. See [Streaming](https://github.com/murtazox04/polyui/blob/main/docs/bindings.md#streaming-a-show_ui-call). |
84
85
  | `Validator.ref_keys(payload)` | The declared `source:key` refs a tool call uses, to fetch before `prepare_show(..., refs=...)`. |
85
86
  | `open_message`, `patch_message`, `close_message`, `closed_summary` | Protocol messages and the close summary. |
86
87
  | `compile_chart`, `chart_svg`, `describe_chart` | Chart scene, standalone SVG and the spoken summary. |
@@ -60,6 +60,7 @@ What you get:
60
60
  | `Validator.resolve_refs`, `compile_charts`, `attach_apps`, `seal_actions`, `downgrade`, `summary`, `fallback` | The same steps one at a time, if you want to run them yourself. |
61
61
  | `Surface`, `Update` | Validated results. `to_dict()` and `Surface.from_dict()` let you keep them in a session store. |
62
62
  | `tool_definitions(catalogs, actions, strict=False, profile="compact")` | The Anthropic tool JSON for `show_ui`, `update_ui` and `close_ui`. `profile="full"` puts every prop in the schema and is needed for `strict`. |
63
+ | `ShowStream`, `Validator.feed_show(stream, chunk, ...)`, `Validator.finish_show(stream, payload=None, ...)` | Stream a `show_ui` call: `ui.open` and `ui.patch` for each component as it arrives, then the full check. See [Streaming](https://github.com/murtazox04/polyui/blob/main/docs/bindings.md#streaming-a-show_ui-call). |
63
64
  | `Validator.ref_keys(payload)` | The declared `source:key` refs a tool call uses, to fetch before `prepare_show(..., refs=...)`. |
64
65
  | `open_message`, `patch_message`, `close_message`, `closed_summary` | Protocol messages and the close summary. |
65
66
  | `compile_chart`, `chart_svg`, `describe_chart` | Chart scene, standalone SVG and the spoken summary. |
@@ -60,6 +60,7 @@ What you get:
60
60
  | `Validator.resolve_refs`, `compile_charts`, `attach_apps`, `seal_actions`, `downgrade`, `summary`, `fallback` | The same steps one at a time, if you want to run them yourself. |
61
61
  | `Surface`, `Update` | Validated results. `to_dict()` and `Surface.from_dict()` let you keep them in a session store. |
62
62
  | `tool_definitions(catalogs, actions, strict=False, profile="compact")` | The Anthropic tool JSON for `show_ui`, `update_ui` and `close_ui`. `profile="full"` puts every prop in the schema and is needed for `strict`. |
63
+ | `ShowStream`, `Validator.feed_show(stream, chunk, ...)`, `Validator.finish_show(stream, payload=None, ...)` | Stream a `show_ui` call: `ui.open` and `ui.patch` for each component as it arrives, then the full check. See [Streaming](https://github.com/murtazox04/polyui/blob/main/docs/bindings.md#streaming-a-show_ui-call). |
63
64
  | `Validator.ref_keys(payload)` | The declared `source:key` refs a tool call uses, to fetch before `prepare_show(..., refs=...)`. |
64
65
  | `open_message`, `patch_message`, `close_message`, `closed_summary` | Protocol messages and the close summary. |
65
66
  | `compile_chart`, `chart_svg`, `describe_chart` | Chart scene, standalone SVG and the spoken summary. |
@@ -203,6 +203,28 @@ class Validator:
203
203
  next_id: IdFactory | None = None,
204
204
  refs: Mapping[str, Any] | None = None,
205
205
  ) -> Prepared: ...
206
+ def feed_show(
207
+ self,
208
+ stream: ShowStream,
209
+ chunk: str,
210
+ user: Any = None,
211
+ surface_id: str | None = None,
212
+ declared: Sequence[str] | None = None,
213
+ locale: str = "en",
214
+ next_id: IdFactory | None = None,
215
+ refs: Mapping[str, Any] | None = None,
216
+ ) -> list[Json]: ...
217
+ def finish_show(
218
+ self,
219
+ stream: ShowStream,
220
+ payload: Payload | None = None,
221
+ user: Any = None,
222
+ surface_id: str | None = None,
223
+ declared: Sequence[str] | None = None,
224
+ locale: str = "en",
225
+ next_id: IdFactory | None = None,
226
+ refs: Mapping[str, Any] | None = None,
227
+ ) -> Prepared: ...
206
228
  def ref_keys(self, payload: Payload) -> list[str]: ...
207
229
  def tool_definitions(
208
230
  self,
@@ -211,6 +233,21 @@ class Validator:
211
233
  profile: ToolProfile | None = None,
212
234
  ) -> list[Json]: ...
213
235
 
236
+ @final
237
+ class ShowStream:
238
+ def __new__(cls) -> ShowStream: ...
239
+ @property
240
+ def opened(self) -> str | None: ...
241
+ @property
242
+ def seq(self) -> int: ...
243
+ @property
244
+ def stopped(self) -> bool: ...
245
+ @property
246
+ def finished(self) -> bool: ...
247
+ @property
248
+ def text(self) -> str: ...
249
+ def close_message(self) -> Json | None: ...
250
+
214
251
  @final
215
252
  class Client:
216
253
  def __new__(
@@ -2,7 +2,8 @@ use polyui_chart::{ChartOptions, ChartSpec};
2
2
  use polyui_core::catalog::EMBED_ID;
3
3
  use polyui_core::embed::{self, UiResource};
4
4
  use polyui_core::pointer;
5
- use polyui_core::protocol::{Close, Component, DataUpdate, Message, Open, Patch};
5
+ use polyui_core::protocol::{Close, Component, DataOp, DataUpdate, Message, Open, Patch};
6
+ use polyui_core::stream::{ShowUiStream, StreamEvent};
6
7
  use polyui_core::tools::{ToolOptions, ToolProfile};
7
8
  use polyui_core::validate::{
8
9
  self, Location, Operation, Problem, Problems, SealedAction, Surface, Update, Validator,
@@ -416,6 +417,352 @@ pub fn prepare_show(
416
417
  })
417
418
  }
418
419
 
420
+ pub struct ShowStream {
421
+ stream: ShowUiStream,
422
+ dead: bool,
423
+ named: Option<String>,
424
+ root: Option<String>,
425
+ model: Vec<Component>,
426
+ prepared: Vec<Component>,
427
+ actions: Vec<SealedAction>,
428
+ opened: Option<Opened>,
429
+ }
430
+
431
+ #[derive(Clone)]
432
+ struct Opened {
433
+ client: Surface,
434
+ seq: u64,
435
+ }
436
+
437
+ impl Default for ShowStream {
438
+ fn default() -> Self {
439
+ Self {
440
+ stream: ShowUiStream::new(Limits::default()),
441
+ dead: false,
442
+ named: None,
443
+ root: None,
444
+ model: Vec::new(),
445
+ prepared: Vec::new(),
446
+ actions: Vec::new(),
447
+ opened: None,
448
+ }
449
+ }
450
+ }
451
+
452
+ fn reachable(root: &str, components: &[Component]) -> Vec<String> {
453
+ let mut seen: Vec<String> = Vec::new();
454
+ let mut pending = vec![root.to_string()];
455
+ while let Some(id) = pending.pop() {
456
+ if seen.contains(&id) {
457
+ continue;
458
+ }
459
+ if let Some(component) = components.iter().find(|component| component.id == id) {
460
+ pending.extend(component.children.iter().cloned());
461
+ }
462
+ seen.push(id);
463
+ }
464
+ seen
465
+ }
466
+
467
+ fn data_changes(before: &Map<String, Value>, after: &Map<String, Value>) -> Vec<DataOp> {
468
+ let removed = before
469
+ .keys()
470
+ .filter(|key| !after.contains_key(*key))
471
+ .map(|key| DataOp::Remove {
472
+ path: format!("/{}", pointer::escape_token(key)),
473
+ });
474
+ let changed = after
475
+ .iter()
476
+ .filter(|(key, value)| before.get(*key) != Some(*value))
477
+ .map(|(key, value)| DataOp::Set {
478
+ path: format!("/{}", pointer::escape_token(key)),
479
+ value: value.clone(),
480
+ });
481
+ removed.chain(changed).collect()
482
+ }
483
+
484
+ pub struct StreamContext<'a, 'b> {
485
+ pub settings: &'a Settings,
486
+ pub refs: &'a dyn RefResolver,
487
+ pub surface_id: Option<&'a str>,
488
+ pub view: &'a View<'a>,
489
+ pub next_id: &'b mut dyn FnMut() -> String,
490
+ pub read: &'b mut ReadApp<'b>,
491
+ }
492
+
493
+ impl ShowStream {
494
+ pub fn opened(&self) -> Option<&str> {
495
+ self.opened
496
+ .as_ref()
497
+ .and_then(|opened| opened.client.id.as_deref())
498
+ }
499
+
500
+ pub fn seq(&self) -> u64 {
501
+ self.opened.as_ref().map_or(0, |opened| opened.seq)
502
+ }
503
+
504
+ pub fn stopped(&self) -> bool {
505
+ self.dead
506
+ }
507
+
508
+ pub fn text(&self) -> &str {
509
+ self.stream.text()
510
+ }
511
+
512
+ pub fn close_message(&self) -> Option<Value> {
513
+ let opened = self.opened.as_ref()?;
514
+ let id = opened.client.id.as_deref()?;
515
+ Some(close_message(id, opened.seq + 1))
516
+ }
517
+
518
+ pub fn feed(&mut self, context: &mut StreamContext<'_, '_>, chunk: &str) -> Vec<Value> {
519
+ if self.dead {
520
+ return Vec::new();
521
+ }
522
+ let validator = context.settings.validator(context.refs);
523
+ let mut fresh = Vec::new();
524
+ for event in self.stream.feed(&validator, chunk) {
525
+ match event {
526
+ StreamEvent::Surface(id) => self.named = Some(id),
527
+ StreamEvent::Root(id) => self.root = Some(id),
528
+ StreamEvent::Component { component, .. } => fresh.push(component),
529
+ StreamEvent::Rejected { .. } | StreamEvent::Invalid(_) => {
530
+ self.dead = true;
531
+ return Vec::new();
532
+ }
533
+ StreamEvent::Data(_) => {}
534
+ }
535
+ }
536
+ if !fresh.is_empty() && !self.accept(context, fresh) {
537
+ self.dead = true;
538
+ return Vec::new();
539
+ }
540
+ self.publish(context)
541
+ }
542
+
543
+ fn accept(&mut self, context: &mut StreamContext<'_, '_>, fresh: Vec<Component>) -> bool {
544
+ let Ok(mut prepared) = context
545
+ .settings
546
+ .resolve(&fresh, context.refs, Operation::Show)
547
+ else {
548
+ return false;
549
+ };
550
+ let empty = Value::Object(Map::new());
551
+ let mut problems = attach_scenes(&mut prepared, &empty, "components", &context.view.chart);
552
+ if context.view.draws_embeds() {
553
+ problems.extend(attach_apps(&mut prepared, "components", context.read));
554
+ }
555
+ if !problems.is_empty() {
556
+ return false;
557
+ }
558
+ let sealed = context.settings.seal(&mut prepared, context.next_id);
559
+ self.model.extend(fresh);
560
+ self.prepared.extend(prepared);
561
+ self.actions.extend(sealed);
562
+ true
563
+ }
564
+
565
+ fn publish(&mut self, context: &StreamContext<'_, '_>) -> Vec<Value> {
566
+ let locale = context.view.locale();
567
+ let Some(opened) = self.opened.as_mut() else {
568
+ let Some(root) = self.root.clone() else {
569
+ return Vec::new();
570
+ };
571
+ if !self.model.iter().any(|component| component.id == root) {
572
+ return Vec::new();
573
+ }
574
+ let id = self
575
+ .named
576
+ .clone()
577
+ .or_else(|| context.surface_id.map(str::to_string))
578
+ .unwrap_or_else(|| DEFAULT_SURFACE.to_string());
579
+ let shown = reachable(&root, &self.prepared);
580
+ let client = Surface {
581
+ id: Some(id.clone()),
582
+ root,
583
+ components: self
584
+ .prepared
585
+ .iter()
586
+ .filter(|component| shown.contains(&component.id))
587
+ .cloned()
588
+ .collect(),
589
+ data: Map::new(),
590
+ };
591
+ let view = context
592
+ .settings
593
+ .client_view(&client, context.view.declared, locale);
594
+ let fallback = client.fallback(&context.settings.catalogs, locale);
595
+ let message = open_message(&id, &view, 1, Some(fallback));
596
+ self.opened = Some(Opened { client, seq: 1 });
597
+ return vec![message];
598
+ };
599
+ let fresh: Vec<Component> = self
600
+ .prepared
601
+ .iter()
602
+ .filter(|component| opened.client.get(&component.id).is_none())
603
+ .cloned()
604
+ .collect();
605
+ if fresh.is_empty() {
606
+ return Vec::new();
607
+ }
608
+ opened.client.components.extend(fresh.iter().cloned());
609
+ let view = context
610
+ .settings
611
+ .client_view(&opened.client, context.view.declared, locale);
612
+ let upsert: Vec<Component> = view
613
+ .components
614
+ .iter()
615
+ .filter(|component| fresh.iter().any(|added| added.id == component.id))
616
+ .cloned()
617
+ .collect();
618
+ opened.seq += 1;
619
+ let id = opened.client.id.clone().unwrap_or_default();
620
+ vec![patch_message(&id, opened.seq, upsert, Vec::new(), None)]
621
+ }
622
+
623
+ pub fn finish(
624
+ &self,
625
+ context: &mut StreamContext<'_, '_>,
626
+ input: Option<&Input>,
627
+ ) -> Result<Prepared, Problems> {
628
+ let streamed_text;
629
+ let input = match input {
630
+ Some(input) => input,
631
+ None => {
632
+ streamed_text = Input::Text(self.stream.text().to_string());
633
+ &streamed_text
634
+ }
635
+ };
636
+ let Some(opened) = self.opened.clone() else {
637
+ return prepare_show(
638
+ context.settings,
639
+ input,
640
+ context.refs,
641
+ context.surface_id,
642
+ context.view,
643
+ context.next_id,
644
+ context.read,
645
+ );
646
+ };
647
+ let mut model = context.settings.show_ui(input)?;
648
+ let id = opened.client.id.clone().unwrap_or_default();
649
+ if model.id.as_deref().is_some_and(|named| named != id) {
650
+ return Err(Problems {
651
+ operation: Operation::Show,
652
+ items: vec![Problem::new(
653
+ Location::Field("surface".into()),
654
+ format!("The surface id changed from \"{id}\" while streaming."),
655
+ )],
656
+ });
657
+ }
658
+ let data = model.data_value();
659
+ let mut client = model.clone();
660
+ let mut actions = Vec::new();
661
+ let mut positions = Vec::new();
662
+ let mut fresh = Vec::new();
663
+ for (index, component) in model.components.iter().enumerate() {
664
+ let earlier = self
665
+ .model
666
+ .iter()
667
+ .position(|seen| seen == component)
668
+ .filter(|_| component.type_name != CHART_TYPE || model.data.is_empty());
669
+ match earlier {
670
+ Some(at) => {
671
+ client.components[index] = self.prepared[at].clone();
672
+ actions.extend(
673
+ self.actions
674
+ .iter()
675
+ .filter(|action| action.component == component.id)
676
+ .cloned(),
677
+ );
678
+ }
679
+ None => {
680
+ positions.push(index);
681
+ fresh.push(component.clone());
682
+ }
683
+ }
684
+ }
685
+ if !fresh.is_empty() {
686
+ let mut prepared = context
687
+ .settings
688
+ .resolve(&fresh, context.refs, Operation::Show)
689
+ .map_err(|problems| reindex(problems, &positions))?;
690
+ let mut problems =
691
+ attach_scenes(&mut prepared, &data, "components", &context.view.chart);
692
+ if context.view.draws_embeds() {
693
+ problems.extend(attach_apps(&mut prepared, "components", context.read));
694
+ }
695
+ fail(Operation::Show, problems).map_err(|problems| reindex(problems, &positions))?;
696
+ actions.extend(context.settings.seal(&mut prepared, context.next_id));
697
+ for (index, component) in positions.into_iter().zip(prepared) {
698
+ client.components[index] = component;
699
+ }
700
+ }
701
+ model.id = Some(id.clone());
702
+ client.id = Some(id.clone());
703
+ let locale = context.view.locale();
704
+ let before = context
705
+ .settings
706
+ .client_view(&opened.client, context.view.declared, locale);
707
+ let after = context
708
+ .settings
709
+ .client_view(&client, context.view.declared, locale);
710
+ let mut seq = opened.seq;
711
+ let mut messages = Vec::new();
712
+ let ops = data_changes(&before.data, &after.data);
713
+ if !ops.is_empty() {
714
+ seq += 1;
715
+ messages.push(
716
+ Message::Data(DataUpdate {
717
+ surface: id.clone(),
718
+ seq,
719
+ ops,
720
+ })
721
+ .to_value(),
722
+ );
723
+ }
724
+ let upsert: Vec<Component> = after
725
+ .components
726
+ .iter()
727
+ .filter(|component| before.get(&component.id) != Some(*component))
728
+ .cloned()
729
+ .collect();
730
+ let remove: Vec<String> = before
731
+ .components
732
+ .iter()
733
+ .filter(|component| after.get(&component.id).is_none())
734
+ .map(|component| component.id.clone())
735
+ .collect();
736
+ let root = (after.root != before.root).then(|| after.root.clone());
737
+ if !upsert.is_empty() || !remove.is_empty() || root.is_some() {
738
+ seq += 1;
739
+ messages.push(patch_message(&id, seq, upsert, remove, root));
740
+ }
741
+ let summary = model.summary(&id, &context.settings.catalogs, locale);
742
+ Ok(Prepared {
743
+ surface_id: id,
744
+ model,
745
+ client,
746
+ messages,
747
+ summary,
748
+ actions,
749
+ seq,
750
+ touched: Vec::new(),
751
+ })
752
+ }
753
+ }
754
+
755
+ fn reindex(mut problems: Problems, positions: &[usize]) -> Problems {
756
+ for problem in &mut problems.items {
757
+ if let Location::Item { index, .. } = &mut problem.location
758
+ && let Some(position) = positions.get(*index)
759
+ {
760
+ *index = *position;
761
+ }
762
+ }
763
+ problems
764
+ }
765
+
419
766
  pub struct Current<'a> {
420
767
  pub model: &'a Surface,
421
768
  pub client: &'a Surface,
@@ -4,6 +4,7 @@ mod convert;
4
4
  mod errors;
5
5
  mod functions;
6
6
  mod host;
7
+ mod stream;
7
8
  mod surface;
8
9
  mod validator;
9
10
 
@@ -19,6 +20,7 @@ fn polyui(module: &Bound<'_, PyModule>) -> PyResult<()> {
19
20
  module.add_class::<surface::PyUpdate>()?;
20
21
  module.add_class::<surface::PyPrepared>()?;
21
22
  module.add_class::<client::PyClient>()?;
23
+ module.add_class::<stream::PyShowStream>()?;
22
24
  module.add_function(wrap_pyfunction!(functions::tool_definitions, module)?)?;
23
25
  module.add_function(wrap_pyfunction!(functions::open_message, module)?)?;
24
26
  module.add_function(wrap_pyfunction!(functions::patch_message, module)?)?;
@@ -0,0 +1,76 @@
1
+ use crate::convert::to_py;
2
+ use crate::host::ShowStream;
3
+ use pyo3::exceptions::PyRuntimeError;
4
+ use pyo3::prelude::*;
5
+
6
+ #[pyclass(name = "ShowStream", module = "polyui")]
7
+ pub struct PyShowStream {
8
+ pub inner: ShowStream,
9
+ pub finished: bool,
10
+ }
11
+
12
+ impl PyShowStream {
13
+ pub fn live(&mut self) -> PyResult<&mut ShowStream> {
14
+ if self.finished {
15
+ return Err(PyRuntimeError::new_err("this stream is already finished"));
16
+ }
17
+ Ok(&mut self.inner)
18
+ }
19
+ }
20
+
21
+ #[pymethods]
22
+ impl PyShowStream {
23
+ #[new]
24
+ fn new() -> Self {
25
+ Self {
26
+ inner: ShowStream::default(),
27
+ finished: false,
28
+ }
29
+ }
30
+
31
+ #[getter]
32
+ fn opened(&self) -> Option<String> {
33
+ self.inner.opened().map(str::to_string)
34
+ }
35
+
36
+ #[getter]
37
+ fn seq(&self) -> u64 {
38
+ self.inner.seq()
39
+ }
40
+
41
+ #[getter]
42
+ fn stopped(&self) -> bool {
43
+ self.inner.stopped()
44
+ }
45
+
46
+ #[getter]
47
+ fn finished(&self) -> bool {
48
+ self.finished
49
+ }
50
+
51
+ #[getter]
52
+ fn text(&self) -> String {
53
+ self.inner.text().to_string()
54
+ }
55
+
56
+ fn close_message<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
57
+ self.inner
58
+ .close_message()
59
+ .map(|message| to_py(py, &message))
60
+ .transpose()
61
+ }
62
+
63
+ fn __repr__(&self) -> String {
64
+ let opened = self
65
+ .inner
66
+ .opened()
67
+ .map_or_else(|| "None".to_string(), |id| format!("{id:?}"));
68
+ let flag = |value: bool| if value { "True" } else { "False" };
69
+ format!(
70
+ "ShowStream(opened={opened}, seq={}, stopped={}, finished={})",
71
+ self.inner.seq(),
72
+ flag(self.inner.stopped()),
73
+ flag(self.finished)
74
+ )
75
+ }
76
+ }
@@ -2,9 +2,10 @@ use crate::catalogs::PyCatalogs;
2
2
  use crate::convert::{input, to_json, to_py};
3
3
  use crate::errors::{RefRefusedError, catalog_error, validation_error};
4
4
  use crate::host::{
5
- self, Current, Input, Settings, SourceRefs, View, action_id, attach_apps, attach_scenes,
6
- chart_options,
5
+ self, Current, Input, Settings, SourceRefs, StreamContext, View, action_id, attach_apps,
6
+ attach_scenes, chart_options,
7
7
  };
8
+ use crate::stream::PyShowStream;
8
9
  use crate::surface::{PyPrepared, PySurface, PyUpdate, sealed_list};
9
10
  use polyui_core::embed::UiResource;
10
11
  use polyui_core::tools;
@@ -512,6 +513,91 @@ impl PyValidator {
512
513
  Ok(PyPrepared { inner: prepared })
513
514
  }
514
515
 
516
+ #[pyo3(signature = (stream, chunk, user=None, surface_id=None, declared=None, locale="en", next_id=None, refs=None))]
517
+ #[allow(clippy::too_many_arguments)]
518
+ fn feed_show<'py>(
519
+ &self,
520
+ py: Python<'py>,
521
+ stream: &Bound<'py, PyShowStream>,
522
+ chunk: &str,
523
+ user: Option<&Bound<'py, PyAny>>,
524
+ surface_id: Option<&str>,
525
+ declared: Option<Vec<String>>,
526
+ locale: &str,
527
+ next_id: Option<&Bound<'py, PyAny>>,
528
+ refs: Option<&Bound<'py, PyAny>>,
529
+ ) -> PyResult<Bound<'py, PyAny>> {
530
+ let given = Self::given(refs)?;
531
+ let view = View::new(declared.as_deref(), locale);
532
+ let none = py.None().into_bound(py);
533
+ let user = user.unwrap_or(&none);
534
+ let mut ids = Ids::new(next_id);
535
+ let callback = self.ui_resource.as_ref().map(|callback| callback.bind(py));
536
+ let mut apps = Apps::new(callback, user);
537
+ let mut state = stream.borrow_mut();
538
+ let live = state.live()?;
539
+ let messages = self.with_refs(py, user, given.as_ref(), |refs| {
540
+ let mut next = || ids.next();
541
+ let mut read = |uri: &str| apps.read(uri);
542
+ let mut context = StreamContext {
543
+ settings: &self.settings,
544
+ refs,
545
+ surface_id,
546
+ view: &view,
547
+ next_id: &mut next,
548
+ read: &mut read,
549
+ };
550
+ Ok(live.feed(&mut context, chunk))
551
+ })?;
552
+ apps.finish()?;
553
+ ids.finish()?;
554
+ to_py(py, &serde_json::Value::Array(messages))
555
+ }
556
+
557
+ #[pyo3(signature = (stream, payload=None, user=None, surface_id=None, declared=None, locale="en", next_id=None, refs=None))]
558
+ #[allow(clippy::too_many_arguments)]
559
+ fn finish_show<'py>(
560
+ &self,
561
+ py: Python<'py>,
562
+ stream: &Bound<'py, PyShowStream>,
563
+ payload: Option<&Bound<'py, PyAny>>,
564
+ user: Option<&Bound<'py, PyAny>>,
565
+ surface_id: Option<&str>,
566
+ declared: Option<Vec<String>>,
567
+ locale: &str,
568
+ next_id: Option<&Bound<'py, PyAny>>,
569
+ refs: Option<&Bound<'py, PyAny>>,
570
+ ) -> PyResult<PyPrepared> {
571
+ let payload = payload.map(input).transpose()?;
572
+ let given = Self::given(refs)?;
573
+ let view = View::new(declared.as_deref(), locale);
574
+ let none = py.None().into_bound(py);
575
+ let user = user.unwrap_or(&none);
576
+ let mut ids = Ids::new(next_id);
577
+ let callback = self.ui_resource.as_ref().map(|callback| callback.bind(py));
578
+ let mut apps = Apps::new(callback, user);
579
+ let mut state = stream.borrow_mut();
580
+ let finished = state.live()?;
581
+ let prepared = self.with_refs(py, user, given.as_ref(), |refs| {
582
+ let mut next = || ids.next();
583
+ let mut read = |uri: &str| apps.read(uri);
584
+ let mut context = StreamContext {
585
+ settings: &self.settings,
586
+ refs,
587
+ surface_id,
588
+ view: &view,
589
+ next_id: &mut next,
590
+ read: &mut read,
591
+ };
592
+ finished.finish(&mut context, payload.as_ref())
593
+ });
594
+ state.finished = true;
595
+ apps.finish()?;
596
+ let prepared = prepared?;
597
+ ids.finish()?;
598
+ Ok(PyPrepared { inner: prepared })
599
+ }
600
+
515
601
  fn ref_keys(&self, payload: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
516
602
  Ok(self.settings.ref_keys(&input(payload)?))
517
603
  }
@@ -0,0 +1,130 @@
1
+ import json
2
+ from itertools import count
3
+
4
+ import pytest
5
+ from conftest import ACTIONS, lookup
6
+
7
+ import polyui
8
+
9
+ USER = {"id": "u1"}
10
+
11
+
12
+ def ids():
13
+ made = count(1)
14
+ return lambda: f"h{next(made)}"
15
+
16
+
17
+ def chunks(text, size=15):
18
+ return [text[at : at + size] for at in range(0, len(text), size)]
19
+
20
+
21
+ @pytest.fixture
22
+ def hosted(catalogs):
23
+ return polyui.Validator(
24
+ catalogs,
25
+ actions=ACTIONS,
26
+ ref_sources={"account": {"kind": "string", "max": 40}},
27
+ resolver=lookup,
28
+ )
29
+
30
+
31
+ def stream_all(validator, payload, **options):
32
+ stream = polyui.ShowStream()
33
+ sent = []
34
+ text = json.dumps(payload)
35
+ for at, chunk in enumerate(chunks(text)):
36
+ for message in validator.feed_show(stream, chunk, **options):
37
+ sent.append((at, message))
38
+ return stream, sent, len(chunks(text))
39
+
40
+
41
+ def test_components_reach_the_client_while_the_call_streams(hosted, bills_card):
42
+ next_id = ids()
43
+ stream, sent, total = stream_all(hosted, bills_card, user=USER, next_id=next_id)
44
+ kinds = [message["t"] for _, message in sent]
45
+ assert kinds[0] == "ui.open"
46
+ assert set(kinds[1:]) == {"ui.patch"}
47
+ assert sent[0][0] < total // 2
48
+ assert [message["seq"] for _, message in sent] == list(range(1, len(sent) + 1))
49
+ streamed = json.dumps([message for _, message in sent])
50
+ assert "**** 4471" in streamed
51
+ assert "$ref" not in streamed
52
+ assert stream.opened == "s1"
53
+ assert not stream.stopped
54
+
55
+ prepared = hosted.finish_show(stream, user=USER, next_id=next_id)
56
+ assert prepared.messages == []
57
+ assert prepared.seq == stream.seq
58
+ handles = [action["action_id"] for action in prepared.actions]
59
+ assert handles == ["h1", "h2"]
60
+ assert all(handle in streamed for handle in handles)
61
+ assert prepared.model.get("power")["props"]["label"] == {"$ref": "account:power"}
62
+ assert prepared.summary == hosted.prepare_show(bills_card, user=USER).summary
63
+ assert stream.finished
64
+ with pytest.raises(RuntimeError, match="finished"):
65
+ hosted.feed_show(stream, "{}")
66
+
67
+
68
+ def test_finish_without_an_early_open_is_prepare_show(hosted, bills_card):
69
+ stream = polyui.ShowStream()
70
+ assert hosted.feed_show(stream, json.dumps(bills_card)[:20], user=USER) == []
71
+ prepared = hosted.finish_show(stream, bills_card, user=USER, surface_id="s7")
72
+ assert [message["t"] for message in prepared.messages] == ["ui.open"]
73
+ assert prepared.surface_id == "s7"
74
+
75
+
76
+ def test_a_bad_component_stops_the_stream_and_the_final_check_decides(hosted, bills_card):
77
+ broken = json.loads(json.dumps(bills_card))
78
+ broken["components"][3]["type"] = "Marquee"
79
+ stream, sent, _ = stream_all(hosted, broken, user=USER)
80
+ assert sent
81
+ assert stream.stopped
82
+ with pytest.raises(polyui.ValidationError) as caught:
83
+ hosted.finish_show(stream, user=USER)
84
+ assert "Marquee" in str(caught.value)
85
+ assert stream.close_message() == {
86
+ "v": 1,
87
+ "t": "ui.close",
88
+ "surface": "s1",
89
+ "seq": stream.seq + 1,
90
+ }
91
+
92
+
93
+ def test_a_refused_ref_stops_the_preview_but_not_the_final_call(hosted, bills_card):
94
+ stream, sent, _ = stream_all(hosted, bills_card, user=USER, refs={})
95
+ assert stream.stopped
96
+ assert "**** 4471" not in json.dumps([message for _, message in sent])
97
+ prepared = hosted.finish_show(stream, user=USER, refs={"account:power": "**** 4471"})
98
+ assert prepared.client.get("power")["props"]["label"] == "**** 4471"
99
+ upserted = [
100
+ component["id"]
101
+ for message in prepared.messages
102
+ if message["t"] == "ui.patch"
103
+ for component in message["upsert"]
104
+ ]
105
+ assert "power" in upserted
106
+
107
+
108
+ def test_changed_components_and_data_are_patched_at_the_end(hosted):
109
+ first = {
110
+ "root": "card",
111
+ "components": [
112
+ {"id": "card", "type": "Card", "props": {"title": "Draft"}, "children": ["t"]},
113
+ {"id": "t", "type": "Text", "props": {"text": "Hello"}},
114
+ ],
115
+ }
116
+ stream, sent, _ = stream_all(hosted, first)
117
+ assert sent
118
+ final = {
119
+ "root": "card",
120
+ "components": [
121
+ {"id": "card", "type": "Card", "props": {"title": "Final"}},
122
+ ],
123
+ "data": [{"path": "/name", "value": "Ali"}],
124
+ }
125
+ prepared = hosted.finish_show(stream, final)
126
+ kinds = [message["t"] for message in prepared.messages]
127
+ assert kinds == ["ui.data", "ui.patch"]
128
+ patch = prepared.messages[1]
129
+ assert patch["remove"] == ["t"]
130
+ assert patch["upsert"][0]["props"]["title"] == "Final"
File without changes