@native-sdk/cli 0.5.4 → 0.6.1

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 (149) hide show
  1. package/build/app.zig +50 -1
  2. package/build.zig +588 -32
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +3 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +280 -8
  9. package/packages/core/sdk/core.ts +481 -2
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +599 -3
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +39 -2
  17. package/skill-data/ts-core/SKILL.md +4 -2
  18. package/src/app_runner/root.zig +32 -10
  19. package/src/automation/layout_fingerprint.zig +160 -0
  20. package/src/automation/protocol.zig +82 -33
  21. package/src/automation/root.zig +1 -0
  22. package/src/automation/server.zig +1 -1
  23. package/src/automation/snapshot.zig +68 -9
  24. package/src/automation/watcher.zig +1 -1
  25. package/src/embed/host.zig +5 -0
  26. package/src/embed/ui_host.zig +13 -0
  27. package/src/platform/linux/gtk_host.c +527 -13
  28. package/src/platform/linux/gtk_host.h +25 -0
  29. package/src/platform/linux/root.zig +280 -7
  30. package/src/platform/macos/appkit_host.h +104 -6
  31. package/src/platform/macos/appkit_host.m +1368 -74
  32. package/src/platform/macos/cef_host.mm +110 -1
  33. package/src/platform/macos/root.zig +287 -7
  34. package/src/platform/null_platform.zig +398 -4
  35. package/src/platform/null_platform_tests.zig +35 -0
  36. package/src/platform/root.zig +9 -0
  37. package/src/platform/types.zig +386 -14
  38. package/src/platform/windows/root.zig +298 -9
  39. package/src/platform/windows/webview2_host.cpp +330 -5
  40. package/src/primitives/app_manifest/validation.zig +18 -0
  41. package/src/primitives/canvas/a11y_audit.zig +33 -11
  42. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  43. package/src/primitives/canvas/drawing.zig +25 -0
  44. package/src/primitives/canvas/equality.zig +8 -0
  45. package/src/primitives/canvas/events.zig +103 -16
  46. package/src/primitives/canvas/frame.zig +125 -1
  47. package/src/primitives/canvas/layout_audit.zig +22 -5
  48. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  49. package/src/primitives/canvas/render_tests.zig +13 -10
  50. package/src/primitives/canvas/root.zig +48 -0
  51. package/src/primitives/canvas/terminal_box.zig +471 -0
  52. package/src/primitives/canvas/terminal_grid.zig +978 -0
  53. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  54. package/src/primitives/canvas/test_support.zig +1 -0
  55. package/src/primitives/canvas/tests.zig +1 -0
  56. package/src/primitives/canvas/text_tests.zig +39 -4
  57. package/src/primitives/canvas/tokens.zig +115 -12
  58. package/src/primitives/canvas/ui.zig +524 -5
  59. package/src/primitives/canvas/ui_markup.zig +195 -2
  60. package/src/primitives/canvas/ui_markup_compiled.zig +172 -1
  61. package/src/primitives/canvas/ui_markup_compiled_tests.zig +133 -8
  62. package/src/primitives/canvas/ui_markup_contract.zig +88 -5
  63. package/src/primitives/canvas/ui_markup_contract_tests.zig +39 -1
  64. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  65. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  66. package/src/primitives/canvas/ui_markup_tests.zig +149 -0
  67. package/src/primitives/canvas/ui_markup_view.zig +191 -0
  68. package/src/primitives/canvas/ui_markup_view_tests.zig +403 -19
  69. package/src/primitives/canvas/ui_schema.zig +97 -17
  70. package/src/primitives/canvas/ui_schema_tests.zig +18 -11
  71. package/src/primitives/canvas/ui_tests.zig +141 -9
  72. package/src/primitives/canvas/widget_access.zig +28 -2
  73. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  74. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  75. package/src/primitives/canvas/widget_layout.zig +59 -11
  76. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  77. package/src/primitives/canvas/widget_render.zig +272 -18
  78. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  79. package/src/primitives/canvas/widget_routing.zig +59 -7
  80. package/src/primitives/canvas/widget_runtime.zig +23 -0
  81. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  82. package/src/primitives/canvas/widget_semantics.zig +119 -11
  83. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  84. package/src/primitives/canvas/widget_tree.zig +17 -0
  85. package/src/primitives/canvas/widgets.zig +132 -0
  86. package/src/root.zig +16 -0
  87. package/src/runtime/api.zig +76 -6
  88. package/src/runtime/automation_commands.zig +20 -1
  89. package/src/runtime/automation_snapshot.zig +25 -1
  90. package/src/runtime/automation_widget_dispatch.zig +73 -8
  91. package/src/runtime/bridge_payload.zig +1 -0
  92. package/src/runtime/canvas_frame.zig +62 -7
  93. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  94. package/src/runtime/canvas_frame_helpers.zig +190 -1
  95. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  96. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  97. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  98. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  99. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  100. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  101. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  102. package/src/runtime/canvas_widget_display.zig +1 -1
  103. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  104. package/src/runtime/canvas_widget_events.zig +268 -26
  105. package/src/runtime/canvas_widget_runtime.zig +213 -29
  106. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  107. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  108. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  109. package/src/runtime/canvas_widget_state.zig +6 -0
  110. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  111. package/src/runtime/core.zig +73 -2
  112. package/src/runtime/effects.zig +6389 -54
  113. package/src/runtime/effects_channel_tests.zig +3519 -0
  114. package/src/runtime/effects_pty_tests.zig +1362 -0
  115. package/src/runtime/effects_tests.zig +14 -9
  116. package/src/runtime/effects_video_tests.zig +3609 -0
  117. package/src/runtime/flow.zig +25 -4
  118. package/src/runtime/gpu_surface_events.zig +475 -15
  119. package/src/runtime/media_surface.zig +116 -11
  120. package/src/runtime/media_surface_tests.zig +61 -0
  121. package/src/runtime/pty.zig +1252 -0
  122. package/src/runtime/pty_windows.zig +1780 -0
  123. package/src/runtime/root.zig +25 -0
  124. package/src/runtime/runtime_event_tests.zig +20 -1
  125. package/src/runtime/session_journal.zig +367 -61
  126. package/src/runtime/session_record.zig +16 -0
  127. package/src/runtime/session_replay.zig +395 -11
  128. package/src/runtime/session_tests.zig +114 -19
  129. package/src/runtime/terminal_session.zig +1569 -0
  130. package/src/runtime/terminal_session_tests.zig +450 -0
  131. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  132. package/src/runtime/terminal_vt_stub.zig +13 -0
  133. package/src/runtime/tests.zig +6 -0
  134. package/src/runtime/ts_core_host.zig +980 -140
  135. package/src/runtime/ts_core_host_tests.zig +1059 -1
  136. package/src/runtime/ts_ui_app.zig +16 -5
  137. package/src/runtime/ui_app.zig +2338 -67
  138. package/src/runtime/ui_app_tests.zig +3171 -744
  139. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  140. package/src/runtime/ui_app_window_tests.zig +268 -0
  141. package/src/runtime/view.zig +190 -2
  142. package/src/runtime/view_widget_scroll.zig +218 -68
  143. package/src/runtime/view_widget_text.zig +11 -2
  144. package/src/runtime/view_widget_tree.zig +111 -3
  145. package/src/runtime/window_storage.zig +45 -2
  146. package/src/runtime/window_view_runtime.zig +34 -2
  147. package/src/runtime/window_views.zig +1 -0
  148. package/src/terminal_session_tests_root.zig +15 -0
  149. package/src/tooling/templates.zig +25 -7
@@ -38,6 +38,7 @@ const canvas_frame = @import("canvas_frame.zig");
38
38
  const canvas_limits = @import("canvas_limits.zig");
39
39
  const launch_timing = @import("launch_timing.zig");
40
40
  const runtime_effects = @import("effects.zig");
41
+ const terminal_session = @import("terminal_session.zig");
41
42
  const ui_app_provenance = @import("ui_app_provenance.zig");
42
43
 
43
44
  const Runtime = core.Runtime;
@@ -49,6 +50,14 @@ const ui_app_log = std.log.scoped(.zero_ui_app);
49
50
  /// Maximum number of webview panes a `UiApp` can drive (`Options.web_panes`).
50
51
  pub const max_web_panes: usize = 4;
51
52
 
53
+ /// One queued `on-terminal` dispatch: the terminal widget's id and the
54
+ /// post-change view state the reconcile produced (see
55
+ /// `applyTerminalLayout`). `id == 0` marks an empty slot.
56
+ const PendingTerminalState = struct {
57
+ id: canvas.ObjectId = 0,
58
+ state: canvas.TerminalState = .{},
59
+ };
60
+
52
61
  /// Approach-end hysteresis for `on_reach_end`, in viewports from the
53
62
  /// content end: fire when the offset comes within one viewport, re-arm
54
63
  /// only past one and a half — so the fire and re-arm boundaries never
@@ -176,14 +185,25 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
176
185
 
177
186
  pub const ChromeOptions = struct {
178
187
  /// Number of chrome commands preserved in front of the
179
- /// widget-generated commands.
188
+ /// widget-generated commands. With `variable_prefix`, the
189
+ /// BUDGET instead: `build` may emit any count up to it.
180
190
  prefix_commands: usize,
181
191
  /// Number of chrome commands preserved after the
182
- /// widget-generated commands.
192
+ /// widget-generated commands. Always exact.
183
193
  suffix_commands: usize = 0,
194
+ /// The prefix length is whatever `build` emitted this
195
+ /// rebuild (minus the fixed suffix) rather than an exact
196
+ /// pin — for chrome whose command count is model-derived
197
+ /// (a terminal grid, a data plot). The runtime re-learns
198
+ /// the split at every install, so its internal widget-span
199
+ /// regenerations keep preserving the right commands; the
200
+ /// exact-count default stays the teaching check for
201
+ /// fixed-shape chrome, where a drifted count is a bug.
202
+ variable_prefix: bool = false,
184
203
  /// Builds the chrome display-list commands: exactly
185
204
  /// `prefix_commands` commands followed by `suffix_commands`
186
- /// commands.
205
+ /// commands (up to `prefix_commands` under
206
+ /// `variable_prefix`).
187
207
  build: *const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void,
188
208
  };
189
209
 
@@ -478,6 +498,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
478
498
  /// Optional mapping from shell command events (menus, shortcuts,
479
499
  /// native controls) into messages.
480
500
  on_command: ?*const fn (name: []const u8) ?MsgT = null,
501
+ /// Optional mapping from app lifecycle events into messages.
502
+ /// A single-window app can use activate/deactivate as its
503
+ /// keyboard-focus signal for custom canvas chrome whose
504
+ /// pixels live outside the widget focus register.
505
+ on_lifecycle: ?*const fn (event: core.LifecycleEvent) ?MsgT = null,
481
506
  /// Model-driven selection for declared platform chrome
482
507
  /// (`scene.chrome.tabs`): returns the id of the tab the
483
508
  /// model currently selects (one of the declared tab ids, or
@@ -537,6 +562,26 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
537
562
  /// can never steal typing — a fallback that yields to every
538
563
  /// consuming widget can carry them safely.
539
564
  on_key: ?*const fn (keyboard: canvas.WidgetKeyboardEvent) ?MsgT = null,
565
+ /// Deliver `.key_up` phases through `on_key` too. OFF by
566
+ /// default: most key consumers act on presses alone, and a
567
+ /// release arriving unexpectedly would double-fire a
568
+ /// name-gated action. A terminal-class consumer opts in to
569
+ /// forward key releases to the child (the kitty keyboard
570
+ /// protocol's event reporting); consumers that opt in MUST
571
+ /// branch on `keyboard.phase`.
572
+ key_release_events: bool = false,
573
+ /// Optional mapping from unclaimed COMMITTED TEXT into
574
+ /// messages — `on_key`'s typing sibling for apps that
575
+ /// consume text themselves without a text-entry widget
576
+ /// focused (a terminal grid). Delivered for `.text_input`
577
+ /// phases only, after the same widget-precedence routing
578
+ /// `on_key` yields to: a focused editable widget keeps its
579
+ /// typing, and only unclaimed text falls through. The
580
+ /// event's `text` carries the committed UTF-8 (IME
581
+ /// composition results included), so consumers stay
582
+ /// layout- and input-method-correct — key names never
583
+ /// reconstruct text.
584
+ on_text: ?*const fn (keyboard: canvas.WidgetKeyboardEvent) ?MsgT = null,
540
585
  /// Optional mapping from trackpad pinch gestures into
541
586
  /// messages — the app-level gesture channel (the `on_key`
542
587
  /// shape). Pinch deliberately bypasses the widget pipeline:
@@ -557,6 +602,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
557
602
  /// a pinch source emit these (macOS today); everywhere else
558
603
  /// the channel simply never fires.
559
604
  on_pinch: ?*const fn (pinch: platform.PinchEvent) ?MsgT = null,
605
+ /// Optional mapping from wheel/trackpad scrolls over a gpu
606
+ /// surface into messages — the pinch channel's sibling, for
607
+ /// apps whose content scrolls without a scroll-region
608
+ /// widget (a terminal's scrollback). Delivered for every
609
+ /// raw `.scroll` input on a focused gpu surface; apps that
610
+ /// also declare canvas scroll regions should leave this
611
+ /// null (regions consume wheel input themselves).
612
+ on_wheel: ?*const fn (wheel: platform.WheelEvent) ?MsgT = null,
560
613
  /// Optional mapping from runtime timer events (started via
561
614
  /// `runtime.startTimer`) into messages. Framework-reserved timer
562
615
  /// ids (>= `platform.reserved_timer_id_base`) are handled
@@ -690,6 +743,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
690
743
  window_id: platform.WindowId = 0,
691
744
  on_close: ?MsgT = null,
692
745
  installed: bool = false,
746
+ /// This slot's handler-tree currency (the per-slot half of
747
+ /// `main_tree_current`): false only between handing the
748
+ /// runtime this window's new layout and adopting the
749
+ /// matching tree — so one window's failed publication never
750
+ /// poisons its siblings, and this window's own next
751
+ /// successful rebuild (a frame-driven retry included)
752
+ /// restores it.
753
+ tree_current: bool = true,
754
+ /// The `<video src>` declaration the in-flight build pass
755
+ /// recorded (arena-borrowed; consumed by
756
+ /// `rebuildWindowSlot` immediately after the pass succeeds
757
+ /// and the tree installs — a failed layout's declaration
758
+ /// never reaches the reconciler).
759
+ pending_video_declaration: ?Ui.VideoDeclaration = null,
693
760
  canvas_size: geometry.SizeF = .{ .width = 1, .height = 1 },
694
761
  /// The device scale of THIS window's surface, adopted from
695
762
  /// its own frame and resize events. Secondary windows can sit
@@ -864,6 +931,75 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
864
931
  hold_view_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
865
932
  hold_view_label_len: usize = 0,
866
933
  hold_window_id: platform.WindowId = 1,
934
+ /// Hover-Msg delivery mirror: the containment chain — and which
935
+ /// view it belongs to — as the app last HEARD it. The runtime
936
+ /// owns the STANDING chain per view (derived from journaled
937
+ /// input at the same seams the hover wash resolves through);
938
+ /// this mirror is the dispatch bookkeeping, and the diff
939
+ /// between the two is exactly the enter/leave Msgs owed. One
940
+ /// pointer, one standing mirror (the hold-arming shape). Leave
941
+ /// Msgs are captured when their enter dispatches (the
942
+ /// context-menu snapshot's capture-at-presentation rule), so a
943
+ /// widget unmounted mid-hover still delivers the paired leave
944
+ /// the live tree can no longer resolve — no enter without its
945
+ /// eventual leave. Captures are DEEP copies: payload slices are
946
+ /// duplicated into the slot's own bytes below, because a
947
+ /// standing hover outlives the build-arena pair's two-build
948
+ /// lifetime and a by-value capture of a `ui.fmt` payload would
949
+ /// dangle into a reset arena.
950
+ hover_msg_window_id: platform.WindowId = 1,
951
+ hover_msg_view_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
952
+ hover_msg_view_label_len: usize = 0,
953
+ hover_msg_chain: [canvas.max_widget_depth]canvas.ObjectId = undefined,
954
+ hover_msg_chain_len: usize = 0,
955
+ /// Capture SLOT per mirror chain position (`hover_msg_slot_none`
956
+ /// = no capture): containment is per LISTENER, so when an outer
957
+ /// listener unbinds while an inner one stands, the retained
958
+ /// entry keeps its slot — and its captured leave — while only
959
+ /// the departed id's edges dispatch. Slots decouple capture
960
+ /// ownership from chain position so retained entries never need
961
+ /// their captures moved or re-taken.
962
+ hover_msg_slots: [canvas.max_widget_depth]u8 = undefined,
963
+ hover_msg_slot_used: [hover_msg_slot_count]bool = [_]bool{false} ** hover_msg_slot_count,
964
+ /// Captured leave Msgs BY SLOT (see `hover_msg_slots`).
965
+ hover_msg_leave_msgs: [hover_msg_slot_count]?MsgT = undefined,
966
+ /// Per-SLOT arenas owning the captured leave Msgs' payload
967
+ /// bytes (see `captureHoverLeave`): reset when the slot
968
+ /// releases or re-captures, freed at deinit. Arena-backed so a
969
+ /// payload of any size can be owned — a fixed budget would turn
970
+ /// a large `ui.fmt` payload into a silently unpaired leave.
971
+ hover_msg_leave_arenas: [hover_msg_slot_count]std.heap.ArenaAllocator = undefined,
972
+ /// Re-entrancy guard for `drainHoverMsgs`: the drain's own
973
+ /// dispatches must not drain recursively through `dispatch`'s
974
+ /// tail.
975
+ hover_msg_draining: bool = false,
976
+ /// Handler-tree currency for hover-Msg delivery — the shared
977
+ /// invariant over every rebuild/error seam, PER TREE FAMILY: a
978
+ /// flag holds while its last rebuild attempt fully succeeded,
979
+ /// so a failed build — or a failed publication that left a
980
+ /// tree pointing at a build the runtime never adopted — defers
981
+ /// entering edges into that tree instead of resolving them
982
+ /// through a stale handler table or consuming them as absent.
983
+ /// Two flags because the families recover independently: a
984
+ /// main-only rebuild (a resize, a frame path) must never
985
+ /// restore currency for a secondary-window tree whose
986
+ /// publication failed — only a clean pass over the slots does.
987
+ /// `build_generation` ticks on every successful rebuild, so
988
+ /// standing captures refresh exactly when handler bindings can
989
+ /// have moved and never otherwise. Captured leaves dispatch
990
+ /// regardless: their Msgs are owned bytes, not tree lookups.
991
+ main_tree_current: bool = true,
992
+ build_generation: u64 = 0,
993
+ /// The `build_generation` the mirror's captures were last
994
+ /// refreshed against.
995
+ hover_msg_captured_generation: u64 = 0,
996
+ /// Nonzero while `eventFn` is on the stack: `dispatch` and
997
+ /// `drainEffects` tails drain hover edges only for DIRECT
998
+ /// callers (embedders, command handlers, tests) — inside a
999
+ /// runtime event, draining belongs to the event's own tail so
1000
+ /// hover dispatches can never rebuild a view out from under the
1001
+ /// input cycle's pending scroll/resize/change observations.
1002
+ hover_msg_event_depth: u32 = 0,
867
1003
  /// Context-menu presentation fallback state: the widget whose
868
1004
  /// declared menu is mounted as an anchored canvas surface because
869
1005
  /// the platform could not present it natively. Set by
@@ -875,6 +1011,41 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
875
1011
  context_menu_fallback_window_id: platform.WindowId = 1,
876
1012
  context_menu_fallback_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
877
1013
  context_menu_fallback_label_len: usize = 0,
1014
+ /// The secondary click's pointer location from the request event
1015
+ /// (view-local canvas points): threaded to `Ui.finalize` so the
1016
+ /// synthesized surface anchors at the click, not the target's
1017
+ /// edge.
1018
+ context_menu_fallback_point: geometry.PointF = .{},
1019
+ /// The presented native menu's selection snapshot: the per-item
1020
+ /// dispatch Msgs captured (by value) at present time, keyed by
1021
+ /// the request's token. Native presentation is asynchronous (a
1022
+ /// GTK popover outlives its presenting dispatch), so a rebuild
1023
+ /// while the menu is open — a timer reordering conditional
1024
+ /// items, an effect re-mapping captured messages — must never
1025
+ /// redirect the visible selection: `handleContextMenu` resolves
1026
+ /// a token-matching selection HERE, never through the live
1027
+ /// tree. 0 = no snapshot armed (then the live tree is the shown
1028
+ /// menu: the fallback surface and the automation verb both
1029
+ /// validate against it directly).
1030
+ context_menu_shown_token: u64 = 0,
1031
+ context_menu_shown_count: usize = 0,
1032
+ context_menu_shown_msgs: [platform.max_context_menu_items]?MsgT = undefined,
1033
+ /// The build-arena generation PINNED under the presented menu.
1034
+ /// A snapshot Msg may carry build-arena slices (the documented
1035
+ /// payload shape — `ui.fmt` strings and allocator-form
1036
+ /// bindings), and the open menu outlives the arena pair's
1037
+ /// two-build lifetime, so while the snapshot is armed the arena
1038
+ /// that built the presented tree is exempt from the rebuild
1039
+ /// reset: rebuilds landing on its turn allocate on top instead
1040
+ /// (growth is bounded by the menu's open span; the next reset
1041
+ /// after release reclaims it). The dispatched Msg is therefore
1042
+ /// the ORIGINAL value — same bytes, same pointers as the
1043
+ /// fallback surface and the automation verb dispatch. Released
1044
+ /// on selection, dismissal (the runtime's dismissed notice),
1045
+ /// supersession by the next presentation, and teardown. Markup
1046
+ /// payloads need nothing more: they are path-only — model
1047
+ /// storage or this same build arena, never document literals.
1048
+ context_menu_pin: ?ContextMenuPin = null,
878
1049
  /// The windowed virtual lists the LAST build declared
879
1050
  /// (`Ui.virtualList` records): scroll events on these regions
880
1051
  /// re-derive the view even without an app `on_scroll` binding,
@@ -883,10 +1054,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
883
1054
  virtual_windows: [canvas.max_virtual_windows]canvas.VirtualWindowRecord = [_]canvas.VirtualWindowRecord{.{}} ** canvas.max_virtual_windows,
884
1055
  virtual_window_count: usize = 0,
885
1056
  /// Scroll regions whose `on_reach_end` fired and has not re-armed
886
- /// (the approach-end hysteresis state, keyed by widget id).
887
- reach_end_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
1057
+ /// (the approach-end hysteresis state, keyed by widget id AND the
1058
+ /// axis the reach was measured on: a region whose primary axis
1059
+ /// changes — content growing sideways after a vertical fire —
1060
+ /// must not have the stale axis's latch suppress the fresh one).
1061
+ reach_end_fired: [max_reach_latches]ReachLatch = [_]ReachLatch{.{}} ** max_reach_latches,
888
1062
  /// The approach-START mirror (`on_reach_start` hysteresis).
889
- reach_start_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
1063
+ reach_start_fired: [max_reach_latches]ReachLatch = [_]ReachLatch{.{}} ** max_reach_latches,
890
1064
  /// Retained offset tables for VARIABLE-extent virtual lists,
891
1065
  /// claimed per list identity during builds (`Ui.virtualWindow`
892
1066
  /// through the extent source) and patched by the post-layout
@@ -895,6 +1069,95 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
895
1069
  /// slots drops the excess to estimate-only math with a debug
896
1070
  /// warning.
897
1071
  virtual_extent_tables: [canvas.max_virtual_windows]canvas.VirtualExtentTable = [_]canvas.VirtualExtentTable{.{}} ** canvas.max_virtual_windows,
1072
+ /// The `<video src>` declaration the LAST main-canvas build
1073
+ /// recorded (`Ui.video_declaration`), captured by the build pass
1074
+ /// for the post-rebuild reconcile; the src slice lives in that
1075
+ /// build's arena, valid until the next rebuild.
1076
+ video_build_declaration: ?VideoBuildDeclaration = null,
1077
+ /// The in-flight rebuild's capture, committed into
1078
+ /// `video_build_declaration` only once the rebuild INSTALLS
1079
+ /// (the `self.tree` assignment): a build that fails after the
1080
+ /// capture never mounted, and the retained tree on the glass
1081
+ /// still shows the old declaration — a later reconcile (a
1082
+ /// secondary window's close) acting on the unmounted build's
1083
+ /// capture would stop or replace a playback the presented tree
1084
+ /// still declares. Seeded from the committed value at each
1085
+ /// rebuild's start, so a failed rebuild changes nothing.
1086
+ video_build_staged: ?VideoBuildDeclaration = null,
1087
+ video_build_staged_src_buffer: [1024]u8 = undefined,
1088
+ /// The load identity of the playback the declarative
1089
+ /// reconciler started (`Effects.videoOwnerToken` right after
1090
+ /// its own loadVideo; 0 = owns nothing): the ownership proof
1091
+ /// for the stop and flag-delta paths. The derived key alone
1092
+ /// is not one — it is a pure function of the source string,
1093
+ /// and a manual load could carry the same key.
1094
+ video_declared_token: u64 = 0,
1095
+ /// Recursion bound for the post-reconcile chrome repass in
1096
+ /// `rebuild` (see the call site): the repass reconciles an
1097
+ /// unchanged declaration, so the mirrors are already a fixed
1098
+ /// point — this guard just makes one level a hard guarantee.
1099
+ video_chrome_repass: bool = false,
1100
+ /// Backing bytes for `video_build_declaration.src`, copied out
1101
+ /// of the build arena at capture (the slot captures' rule): the
1102
+ /// declaration outlives the pass that recorded it — a later
1103
+ /// FAILED rebuild resets the arena it would otherwise borrow
1104
+ /// from, and the reconcile can run from a window close before
1105
+ /// the next successful build.
1106
+ video_build_src_buffer: [1024]u8 = undefined,
1107
+ /// The video mirrors as the LAST main-canvas build rendered
1108
+ /// them (stamped at build time, before the post-build reconcile
1109
+ /// can move them): `drainEffects` compares against the live
1110
+ /// snapshot so a Msg-less mirror move — a handler-less
1111
+ /// declarative playback's synchronous failure delivering its
1112
+ /// staged terminal — still re-renders the house chrome instead
1113
+ /// of leaving controls painted for a playback that is gone.
1114
+ video_rendered_snapshot: Effects.VideoSnapshot = .{},
1115
+ /// Applied declarative-video state: whether a declared src owns
1116
+ /// the playback right now, the src it loaded (so an unchanged
1117
+ /// declaration never reloads — loadVideo replaces the playback
1118
+ /// whole), and the applied loop/muted flags for delta updates.
1119
+ video_declared: bool = false,
1120
+ video_declared_src_buffer: [1024]u8 = undefined,
1121
+ video_declared_src_len: usize = 0,
1122
+ video_declared_loop: bool = false,
1123
+ video_declared_muted: bool = false,
1124
+ /// The last declared src the video loader REFUSED (see
1125
+ /// `applyVideoDeclaration`): remembered so an unchanged bad
1126
+ /// declaration is taught once, not re-attempted every rebuild —
1127
+ /// and kept OUT of the applied-src tracking above, so the
1128
+ /// playback the reconciler actually owns stays stoppable.
1129
+ video_refused_src_buffer: [1024]u8 = undefined,
1130
+ video_refused_src_len: usize = 0,
1131
+ /// The `<video src>` declarations SECONDARY windows' builds
1132
+ /// recorded, one retained entry per declaring window, copied
1133
+ /// out of the slot arenas (slot builds and the main build
1134
+ /// interleave, so a borrowed slice could die under the
1135
+ /// reconciler). `Ui.video` promises that declaring the element
1136
+ /// IS the playback in every window's tree; the main canvas
1137
+ /// build wins when it declares (one player, one owner), and
1138
+ /// among slots the current owner keeps the player until it
1139
+ /// stops declaring or closes — at which point the next
1140
+ /// RETAINED declaration promotes immediately, no rebuild
1141
+ /// required (`slotVideoDeclaration`).
1142
+ video_slot_declarations: [max_ui_windows]SlotVideoDeclaration = @splat(.{}),
1143
+ /// The slot window currently owning the declarative playback
1144
+ /// (0 while none does).
1145
+ video_slot_owner: platform.WindowId = 0,
1146
+ /// The framework-owned terminal sessions behind `<terminal
1147
+ /// pty={key}>` (see `terminal_session.zig`): the emulator store
1148
+ /// the builder's grid lookup resolves through, fed by the
1149
+ /// effects channel's pty tap. Compiles to inert no-ops when the
1150
+ /// `terminal_vt` seam carries the stub.
1151
+ terminal_sessions: terminal_session.TerminalSessions,
1152
+ /// `on-terminal` states the last rebuild's view-state reconcile
1153
+ /// produced (a resize the layout derived, an applied scrollback
1154
+ /// echo): dispatched at the rebuild's tail, one bounded pass —
1155
+ /// the nested rebuild each dispatch runs reconciles to the same
1156
+ /// state and produces nothing new (`terminal_state_draining`
1157
+ /// makes that one level a hard guarantee).
1158
+ terminal_state_pending: [terminal_session.max_sessions]PendingTerminalState = @splat(.{}),
1159
+ terminal_state_pending_count: usize = 0,
1160
+ terminal_state_draining: bool = false,
898
1161
  /// Live model-declared secondary windows (`Options.windows_fn`),
899
1162
  /// keyed by window label.
900
1163
  window_slots: [max_ui_windows]WindowSlot,
@@ -926,10 +1189,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
926
1189
  },
927
1190
  .window_slots = windowSlotsInit(backing),
928
1191
  .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
1192
+ .hover_msg_leave_arenas = hoverMsgLeaveArenasInit(backing),
929
1193
  .effects = Effects.init(backing),
1194
+ .terminal_sessions = terminal_session.TerminalSessions.init(backing),
930
1195
  };
931
1196
  }
932
1197
 
1198
+ /// One arena per hover-capture slot, over the backing allocator.
1199
+ fn hoverMsgLeaveArenasInit(backing: std.mem.Allocator) [hover_msg_slot_count]std.heap.ArenaAllocator {
1200
+ var arenas: [hover_msg_slot_count]std.heap.ArenaAllocator = undefined;
1201
+ for (&arenas) |*arena| arena.* = std.heap.ArenaAllocator.init(backing);
1202
+ return arenas;
1203
+ }
1204
+
933
1205
  /// Heap-allocate the app and construct every field — the
934
1206
  /// Model included — in place, so nothing app-sized ever rides
935
1207
  /// the stack. The Model starts as its default value; set fields
@@ -982,7 +1254,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
982
1254
  },
983
1255
  .window_slots = windowSlotsInit(backing),
984
1256
  .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
1257
+ .hover_msg_leave_arenas = hoverMsgLeaveArenasInit(backing),
985
1258
  .effects = Effects.init(backing),
1259
+ .terminal_sessions = terminal_session.TerminalSessions.init(backing),
986
1260
  };
987
1261
  }
988
1262
 
@@ -1003,6 +1277,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1003
1277
  // services binding there, so this second call frees app-side
1004
1278
  // memory only and never touches the dead platform.
1005
1279
  self.effects.deinit();
1280
+ self.terminal_sessions.deinit();
1006
1281
  self.arenas[0].deinit();
1007
1282
  self.arenas[1].deinit();
1008
1283
  self.markup_arenas[0].deinit();
@@ -1017,6 +1292,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1017
1292
  slot.arenas[0].deinit();
1018
1293
  slot.arenas[1].deinit();
1019
1294
  }
1295
+ for (&self.hover_msg_leave_arenas) |*arena| arena.deinit();
1020
1296
  if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
1021
1297
  if (self.pixel_scratch.len > 0) self.backing.free(self.pixel_scratch);
1022
1298
  self.pixel_buffer = &.{};
@@ -1059,6 +1335,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1059
1335
  self.effects.bindServices(&runtime.options.platform.services);
1060
1336
  self.effects.bindEnviron(runtime.options.environ);
1061
1337
  self.effects.bindImages(runtime.canvasImageRegistryBinding());
1338
+ self.effects.bindMediaSurfaces(runtime.mediaSurfaceBinding());
1062
1339
  self.effects.bindWindowActions(.{
1063
1340
  .context = runtime,
1064
1341
  .close_fn = effectsCloseWindowByLabel,
@@ -1069,6 +1346,34 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1069
1346
  if (runtime.options.session_recorder) |recorder| {
1070
1347
  self.effects.bindJournal(recorder.effectJournal());
1071
1348
  }
1349
+ // The terminal-session seams (no-ops on stub builds): the
1350
+ // pty tap feeds every delivered event into the store, and
1351
+ // the gateway routes the store's outbound bytes (keystrokes,
1352
+ // emulator query answers) and grid sizes back through the
1353
+ // JOURNALED pty verbs. Idempotent, like every bind here.
1354
+ if (comptime terminal_session.enabled) {
1355
+ self.effects.pty_tap = .{ .context = @ptrCast(self), .notify = terminalPtyTap };
1356
+ self.terminal_sessions.setGateway(.{
1357
+ .context = @ptrCast(self),
1358
+ .write = terminalGatewayWrite,
1359
+ .resize = terminalGatewayResize,
1360
+ });
1361
+ }
1362
+ }
1363
+
1364
+ fn terminalPtyTap(context: *anyopaque, event: *const runtime_effects.EffectPtyEvent) void {
1365
+ const self: *Self = @ptrCast(@alignCast(context));
1366
+ self.terminal_sessions.notePtyEvent(event);
1367
+ }
1368
+
1369
+ fn terminalGatewayWrite(context: *anyopaque, key: u64, bytes: []const u8) bool {
1370
+ const self: *Self = @ptrCast(@alignCast(context));
1371
+ return self.effects.ptyWrite(key, bytes);
1372
+ }
1373
+
1374
+ fn terminalGatewayResize(context: *anyopaque, key: u64, cols: u16, rows: u16) void {
1375
+ const self: *Self = @ptrCast(@alignCast(context));
1376
+ self.effects.ptyResize(key, cols, rows);
1072
1377
  }
1073
1378
 
1074
1379
  /// Session-replay control (`App.replay_fn`): arm the effects
@@ -1119,6 +1424,50 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1119
1424
  record.status,
1120
1425
  record.payload,
1121
1426
  ),
1427
+ // `.channel` records deliver the RECORDED event
1428
+ // verbatim through the channel the replayed
1429
+ // dispatch opened — the source thread never re-runs
1430
+ // at replay, so the journaled events are the whole
1431
+ // stream. Admission `.rejected` records never reach
1432
+ // here (marked by `exit_reason == .rejected`, they
1433
+ // regenerate and are skipped); an executor-truth
1434
+ // rejection feeds and retires the parked slot.
1435
+ .channel => try self.effects.feedChannelEvent(
1436
+ record.key,
1437
+ record.channel_kind,
1438
+ record.payload,
1439
+ record.dropped,
1440
+ record.channel_dropped_total,
1441
+ ),
1442
+ // `.pty` records deliver the RECORDED session:
1443
+ // output batches (resolved from the blob store
1444
+ // into `payload` by the replayer) feed the parked
1445
+ // spawn byte-identically — no shell ever runs —
1446
+ // and the exit retires it. Admission `.rejected`
1447
+ // records never reach here (they regenerate and
1448
+ // are skipped); executor-truth start failures feed
1449
+ // and retire the park at the spawn's dispatch
1450
+ // position.
1451
+ .pty => switch (record.pty_kind) {
1452
+ .output => try self.effects.feedPtyOutput(record.key, record.payload),
1453
+ .exit => try self.effects.feedPtyExit(
1454
+ record.key,
1455
+ record.code,
1456
+ record.pty_signal,
1457
+ record.exit_reason,
1458
+ record.pty_dropped_writes,
1459
+ ),
1460
+ // Write-admission verdicts are executor truth
1461
+ // (whether the FIFO had room depends on how fast
1462
+ // the child was reading): queue each — WITH the
1463
+ // pty key it was recorded against — for the
1464
+ // replayed dispatch's own `ptyWrite` calls, which
1465
+ // consume them in call order against the same
1466
+ // key (the clock feed's shape, keyed: the same
1467
+ // count and results against a different session
1468
+ // is still divergent input).
1469
+ .write => try self.effects.pushReplayPtyWriteVerdict(record.key, record.code == 1),
1470
+ },
1122
1471
  // Spectrum records feed through the band-carrying
1123
1472
  // helper so replay repaints identical bars; every
1124
1473
  // other audio kind rides the plain shape.
@@ -1126,8 +1475,38 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1126
1475
  try self.effects.feedAudioSpectrum(record.audio_bands, record.audio_position_ms, record.audio_duration_ms)
1127
1476
  else
1128
1477
  try self.effects.feedAudioEventBuffering(record.audio_kind, record.audio_position_ms, record.audio_duration_ms, record.audio_playing, record.audio_buffering),
1478
+ // `.video` records feed the whole journaled shape —
1479
+ // dimensions included — routed by the journaled
1480
+ // load identity (`video_token`), so replay delivers
1481
+ // the identical Msg stream with NO producer and NO
1482
+ // platform player behind it, even when the record's
1483
+ // load was replaced or stopped by the very dispatch
1484
+ // that produced it (see `feedVideoRecord`).
1485
+ .video => try self.effects.feedVideoRecord(
1486
+ record.key,
1487
+ record.video_token,
1488
+ record.video_handled,
1489
+ record.video_kind,
1490
+ record.video_position_ms,
1491
+ record.video_duration_ms,
1492
+ record.video_playing,
1493
+ record.video_buffering,
1494
+ record.video_width,
1495
+ record.video_height,
1496
+ ),
1497
+ // `.video_load` records carry the recording host's
1498
+ // cascade resolution — which source the load
1499
+ // actually played — because the replayed fake load
1500
+ // cannot probe the filesystem. Queued, not applied:
1501
+ // the record precedes the event whose dispatch
1502
+ // issues the load (see `pushReplayVideoSource`).
1503
+ .video_load => self.effects.pushReplayVideoSource(record.key, record.video_token, record.video_source, record.video_kind == .failed),
1129
1504
  .timer => {},
1130
1505
  },
1506
+ .finish => {
1507
+ try self.effects.finishReplay();
1508
+ try self.effects.settleReplayFeeds();
1509
+ },
1131
1510
  }
1132
1511
  }
1133
1512
 
@@ -1147,8 +1526,28 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1147
1526
  // events land before the first frame on every launch, so it
1148
1527
  // used to cost a full view build on the launch path.
1149
1528
  if (!self.installed) return;
1150
- try self.rebuild(runtime, self.canvas_window_id);
1151
- try self.rebuildWindowSlots(runtime);
1529
+ // Hover edges the rebuilds produce (an unmounted hovered
1530
+ // element's leave, an adoption re-hit-test's handoff)
1531
+ // settle at this tail for DIRECT callers — command
1532
+ // handlers, embedders, tests — without waiting for the
1533
+ // next platform event, and on the REBUILD-ERROR path too:
1534
+ // a failed secondary-window rebuild must not strand the
1535
+ // leave the main rebuild already produced. Inside a runtime
1536
+ // event the event's own tail drains instead, and the
1537
+ // drain's own dispatches re-enter here guarded.
1538
+ var rebuild_error: ?anyerror = null;
1539
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1540
+ rebuild_error = err;
1541
+ };
1542
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1543
+ rebuild_error = err;
1544
+ };
1545
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1546
+ self.drainHoverMsgs(runtime) catch |err| {
1547
+ if (rebuild_error == null) rebuild_error = err;
1548
+ };
1549
+ }
1550
+ if (rebuild_error) |err| return err;
1152
1551
  // A Msg dispatched FROM a secondary window still rebuilt the
1153
1552
  // main canvas above (one model, every window's view derives
1154
1553
  // from it); `window_id` names the dispatch origin for apps
@@ -1192,10 +1591,39 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1192
1591
  dispatched = true;
1193
1592
  }
1194
1593
  self.publishAudioState(runtime);
1594
+ var rebuild_error: ?anyerror = null;
1195
1595
  if (dispatched) {
1196
- try self.rebuild(runtime, self.canvas_window_id);
1197
- try self.rebuildWindowSlots(runtime);
1596
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1597
+ rebuild_error = err;
1598
+ };
1599
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1600
+ rebuild_error = err;
1601
+ };
1602
+ } else if (self.installed and
1603
+ !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1604
+ {
1605
+ // A drained Msg-less video terminal (a handler-less
1606
+ // declarative playback's synchronous failure) moved
1607
+ // the mirrors after the last build rendered them:
1608
+ // re-render the chrome so its controls never keep
1609
+ // advertising a playback that is gone.
1610
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1611
+ rebuild_error = err;
1612
+ };
1613
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1614
+ rebuild_error = err;
1615
+ };
1198
1616
  }
1617
+ // Same tail as `dispatch`, same error-path duty: effect-
1618
+ // driven rebuilds settle the hover edges they produced
1619
+ // (this path is also public — host-pumped embeds call it
1620
+ // directly).
1621
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1622
+ self.drainHoverMsgs(runtime) catch |err| {
1623
+ if (rebuild_error == null) rebuild_error = err;
1624
+ };
1625
+ }
1626
+ if (rebuild_error) |err| return err;
1199
1627
  }
1200
1628
 
1201
1629
  /// Mirror the effects channel's audio playback state into the
@@ -1214,6 +1642,27 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1214
1642
  runtime.audio_duration_ms = audio.duration_ms;
1215
1643
  runtime.audio_spectrum_bands = audio.spectrum_bands;
1216
1644
  runtime.audio_spectrum_events = audio.spectrum_events;
1645
+ self.publishVideoState(runtime);
1646
+ }
1647
+
1648
+ /// The video channel's mirror publication, riding every
1649
+ /// `publishAudioState` call site — the same "wherever a
1650
+ /// dispatch or drain may have moved playback" contract, one
1651
+ /// seam instead of two at each site.
1652
+ fn publishVideoState(self: *Self, runtime: *Runtime) void {
1653
+ const video = self.effects.videoSnapshot();
1654
+ runtime.video_active = video.active;
1655
+ runtime.video_key = video.key;
1656
+ runtime.video_surface_id = video.surface;
1657
+ runtime.video_playing = video.playing;
1658
+ runtime.video_buffering = video.buffering;
1659
+ runtime.video_looping = video.looping;
1660
+ runtime.video_muted = video.muted;
1661
+ runtime.video_source = video.source;
1662
+ runtime.video_position_ms = video.position_ms;
1663
+ runtime.video_duration_ms = video.duration_ms;
1664
+ runtime.video_width = video.width;
1665
+ runtime.video_height = video.height;
1217
1666
  }
1218
1667
 
1219
1668
  /// The design tokens for the next rebuild: the model-derived
@@ -1344,12 +1793,35 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1344
1793
  }
1345
1794
  }
1346
1795
  var tokens = runtime.tokensWithTextMeasure(self.effectiveTokens());
1347
- const next_index = self.arena_index ^ 1;
1796
+ // Stamp the mirrors this build renders BEFORE building:
1797
+ // the post-build reconcile (`applyVideoDeclaration`) can
1798
+ // move them, and `drainEffects` uses the stamp to know the
1799
+ // published chrome no longer matches (see
1800
+ // `video_rendered_snapshot`).
1801
+ self.video_rendered_snapshot = self.effects.videoSnapshot();
1802
+ const next_index = self.contextMenuRebuildIndex(null, self.arena_index);
1348
1803
  // Widget layout is inset by the runtime's viewport chrome
1349
1804
  // (safe areas + keyboard on mobile, zero on desktop); the
1350
1805
  // canvas itself stays surface-sized so chrome and the clear
1351
1806
  // color still paint edge to edge under notches and bars.
1352
1807
  const bounds = geometry.RectF.fromSize(self.canvas_size).deflate(self.layoutViewportInsets(runtime, window_id));
1808
+ // Under an open menu's pin, consecutive rebuilds route into
1809
+ // the LIVE tree's arena (`contextMenuRebuildIndex` freezes
1810
+ // the pinned side): the pass below resets that arena, so a
1811
+ // failure anywhere before the assignments would leave
1812
+ // `self.tree` dangling into reset, partially rewritten
1813
+ // storage. Drop the reference instead — handlers go quiet
1814
+ // until the next successful rebuild, and a stale-arena Msg
1815
+ // can never dispatch. The pinned snapshot is untouched: the
1816
+ // presented menu still resolves.
1817
+ var live_tree_reset = next_index == self.arena_index;
1818
+ errdefer if (live_tree_reset) {
1819
+ self.tree = null;
1820
+ };
1821
+ // Seed the staged video capture from the committed one, so
1822
+ // a pass that fails before capturing (or an over-long
1823
+ // declaration) leaves the committed state untouched.
1824
+ self.stageVideoDeclarationFromCommitted();
1353
1825
  var built = try self.buildLayoutPass(runtime, window_id, bounds, tokens, next_index);
1354
1826
  // Window-control clearance is a one-retry pass like the
1355
1827
  // virtual-window coverage retry inside the build: only when
@@ -1370,10 +1842,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1370
1842
  const layout = built.layout;
1371
1843
  launch_timing.lapOnce("first_view_built");
1372
1844
 
1845
+ // The INSTALL WINDOW: from the moment the runtime ADOPTS
1846
+ // the new layout until the matching handler tree is adopted
1847
+ // below, the pair disagrees — the one place the main tree
1848
+ // goes stale (see `main_tree_current`; the stamp sits right
1849
+ // AFTER each `setCanvasWidgetLayout`, whose rejection is
1850
+ // validated-then-atomic — `validateWidgetLayoutPoolBudgets`
1851
+ // keeps the previous tree applied — so every failure before
1852
+ // adoption leaves the old, still-matching pair current). A
1853
+ // failure AFTER the window — animation scheduling, web
1854
+ // panes, the status item — leaves a genuinely current pair,
1855
+ // so hover enters keep flowing even when an idle app
1856
+ // performs no further rebuild.
1373
1857
  if (self.options.chrome) |chrome| {
1374
1858
  try self.installChromeDisplayList(runtime, window_id, chrome, layout, tokens);
1375
1859
  } else {
1376
- _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
1860
+ try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
1377
1861
  if (self.installed and self.rebuildEmitsTokens(runtime, window_id, self.options.canvas_label, tokens)) {
1378
1862
  _ = try runtime.emitCanvasWidgetDisplayList(window_id, self.options.canvas_label, tokens);
1379
1863
  }
@@ -1381,6 +1865,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1381
1865
 
1382
1866
  self.tree = tree;
1383
1867
  self.arena_index = next_index;
1868
+ live_tree_reset = false;
1869
+ self.main_tree_current = true;
1870
+ self.build_generation +%= 1;
1871
+ // Captures track EVERY tree transition (see
1872
+ // refreshHoverLeaveCaptures) — a transient failure is
1873
+ // retried at the next commit or drain and lands in the
1874
+ // dispatch-error ring (the rebuild itself already
1875
+ // committed; erroring it here would lie about the tree).
1876
+ if (self.refreshHoverLeaveCaptures()) |refresh_err| {
1877
+ runtime.recordDispatchError("hover_leave_capture", refresh_err);
1878
+ }
1879
+ // The build INSTALLED: its video declaration now speaks
1880
+ // for what the glass shows.
1881
+ self.commitStagedVideoDeclaration();
1384
1882
  // The fallback menu's target vanished from this build (the
1385
1883
  // model dropped the row, or its menu emptied): the open state
1386
1884
  // has nothing to present, so it closes.
@@ -1390,10 +1888,127 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1390
1888
  try self.scheduleAnimations(runtime, window_id);
1391
1889
  try self.scheduleLayoutTweens(runtime, window_id);
1392
1890
  self.applyWebPanes(runtime, window_id, layout);
1891
+ try self.applyTerminalLayout(runtime, window_id, layout, tokens);
1393
1892
  self.applyStatusItem(runtime);
1893
+ self.applyVideoDeclaration(runtime);
1894
+ // The reconcile can move the playback this very build
1895
+ // rendered (a src change loading an autoplaying
1896
+ // replacement): the just-installed chrome would advertise
1897
+ // the OLD transport state until a platform event arrived,
1898
+ // and its control would act on the new one — Play on the
1899
+ // label, pause in effect. One repass renders the chrome
1900
+ // from the moved mirrors; it reconciles the SAME
1901
+ // declaration (unchanged src reloads nothing), so the
1902
+ // mirrors are a fixed point and the repass ends the
1903
+ // recursion — the guard makes that a hard bound.
1904
+ if (!self.video_chrome_repass and
1905
+ !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1906
+ {
1907
+ self.video_chrome_repass = true;
1908
+ defer self.video_chrome_repass = false;
1909
+ try self.rebuild(runtime, window_id);
1910
+ return;
1911
+ }
1394
1912
  self.applyWindows(runtime);
1395
1913
  self.applyChromeSelection();
1396
1914
  self.applyChromeNavigation();
1915
+ // Deliver the `on-terminal` states this rebuild's view-state
1916
+ // reconcile produced. Each dispatch rebuilds, and the nested
1917
+ // reconcile finds an already-applied state (nothing new
1918
+ // queues), so one guarded pass is the whole drain.
1919
+ try self.drainTerminalStates(runtime, window_id);
1920
+ }
1921
+
1922
+ /// The `<terminal>` view-state reconcile against the freshly
1923
+ /// laid-out tree: derive each bound terminal's cols/rows from
1924
+ /// its frame (the painter's own sizing seam, so painted cells
1925
+ /// and the pty grid can never disagree), apply a CHANGED
1926
+ /// declared scrollback (source wins), resize the emulator and
1927
+ /// push `ptyResize`, and queue the post-change state for the
1928
+ /// widget's `on-terminal`. A no-op on stub builds and for trees
1929
+ /// without a bound terminal.
1930
+ fn applyTerminalLayout(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) anyerror!void {
1931
+ if (comptime !terminal_session.enabled) return;
1932
+ var applied = false;
1933
+ for (layout.nodes) |node| {
1934
+ if (node.widget.kind != .terminal) continue;
1935
+ const pty = node.widget.terminal.pty;
1936
+ if (pty == 0) continue;
1937
+ const frame = node.frame.normalized();
1938
+ if (frame.width <= 0 or frame.height <= 0) continue;
1939
+ // The grid text region sits inside the widget's own
1940
+ // padding (the house inset when none is declared) — the
1941
+ // exact rule the widget painter applies, so the derived
1942
+ // grid is the one the cells paint into.
1943
+ const padding = node.widget.layout.padding;
1944
+ const declared = padding.left + padding.top + padding.right + padding.bottom > 0;
1945
+ const inset: geometry.InsetsF = if (declared) padding else geometry.InsetsF.all(8);
1946
+ const content_width = @max(0, frame.width - inset.left - inset.right);
1947
+ const content_height = @max(0, frame.height - inset.top - inset.bottom);
1948
+ const metrics = canvas.terminalCellMetrics(tokens);
1949
+ if (metrics.width <= 0 or metrics.height <= 0) continue;
1950
+ const proposed = canvas.clampTerminalGrid(
1951
+ @intFromFloat(@max(2, @floor(content_width / metrics.width))),
1952
+ @intFromFloat(@max(2, @floor(content_height / metrics.height))),
1953
+ );
1954
+ const state = self.terminal_sessions.reconcile(
1955
+ pty,
1956
+ node.widget.terminal.scrollback,
1957
+ proposed.x,
1958
+ proposed.y,
1959
+ ) orelse continue;
1960
+ applied = true;
1961
+ if (self.terminal_state_pending_count < self.terminal_state_pending.len) {
1962
+ self.terminal_state_pending[self.terminal_state_pending_count] = .{
1963
+ .id = node.widget.id,
1964
+ .state = state,
1965
+ };
1966
+ self.terminal_state_pending_count += 1;
1967
+ }
1968
+ }
1969
+ // An applied change moved the published snapshot AFTER this
1970
+ // rebuild handed its layout over: refresh the retained
1971
+ // display list so the glass shows the post-reconcile grid
1972
+ // this frame (the widget diff always reports bound terminal
1973
+ // grids paint-dirty, and the refresh is batch-aware).
1974
+ if (applied and self.installed) {
1975
+ if (runtime.findViewIndex(window_id, self.options.canvas_label)) |view_index| {
1976
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(view_index);
1977
+ }
1978
+ }
1979
+ }
1980
+
1981
+ /// Repaint after INPUT moved a terminal's published snapshot (a
1982
+ /// scrollback snap on typing, a wheel scroll): dirty snapshots
1983
+ /// rebuild in place first, so the retained tree's borrowed grid
1984
+ /// pointers paint current state. A no-op when nothing is dirty.
1985
+ fn repaintTerminals(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1986
+ if (comptime !terminal_session.enabled) return;
1987
+ if (!self.terminal_sessions.refreshDirty()) return;
1988
+ if (!self.installed) return;
1989
+ if (runtime.findViewIndex(window_id, self.options.canvas_label)) |view_index| {
1990
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(view_index);
1991
+ }
1992
+ }
1993
+
1994
+ /// Dispatch the queued `on-terminal` states (see the rebuild
1995
+ /// tail). Guarded to one level: the nested rebuild each dispatch
1996
+ /// runs reconciles to the same applied state and queues nothing.
1997
+ fn drainTerminalStates(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1998
+ if (comptime !terminal_session.enabled) return;
1999
+ if (self.terminal_state_draining) return;
2000
+ if (self.terminal_state_pending_count == 0) return;
2001
+ self.terminal_state_draining = true;
2002
+ defer self.terminal_state_draining = false;
2003
+ while (self.terminal_state_pending_count > 0) {
2004
+ self.terminal_state_pending_count -= 1;
2005
+ const pending = self.terminal_state_pending[self.terminal_state_pending_count];
2006
+ self.terminal_state_pending[self.terminal_state_pending_count] = .{};
2007
+ const tree = self.tree orelse continue;
2008
+ if (tree.msgForTerminal(pending.id, pending.state)) |msg| {
2009
+ try self.dispatch(runtime, window_id, msg);
2010
+ }
2011
+ }
1397
2012
  }
1398
2013
 
1399
2014
  const BuiltLayout = struct {
@@ -1401,6 +2016,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1401
2016
  layout: canvas.WidgetLayoutTree,
1402
2017
  };
1403
2018
 
2019
+ /// One build's `<video src>` declaration as the reconcile
2020
+ /// consumes it (`Ui.VideoDeclaration` minus the chrome flag,
2021
+ /// which is a view concern). The src slice borrows the build
2022
+ /// arena — valid until the next rebuild, longer than the
2023
+ /// reconcile needs.
2024
+ const VideoBuildDeclaration = struct {
2025
+ src: []const u8,
2026
+ autoplay: bool,
2027
+ loop: bool,
2028
+ muted: bool,
2029
+ };
2030
+
1404
2031
  /// One view-build + flex-layout pass of `rebuild`, including the
1405
2032
  /// windowed-virtual-list coverage retry: builds the tree into the
1406
2033
  /// next arena and lays it out against `bounds` with `tokens`.
@@ -1424,13 +2051,27 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1424
2051
  var layout: canvas.WidgetLayoutTree = undefined;
1425
2052
  var pass: usize = 0;
1426
2053
  while (true) {
2054
+ // `contextMenuRebuildIndex` never routes a rebuild into
2055
+ // the pinned generation, so the reset is unconditional.
2056
+ std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != null or pin.arena_index != next_index else true);
1427
2057
  _ = self.arenas[next_index].reset(.retain_capacity);
1428
2058
  var ui = Ui.init(self.arenas[next_index].allocator());
2059
+ // The house video chrome renders the channel's honest
2060
+ // snapshot, stamped before the view fn runs — the model
2061
+ // carries none of it.
2062
+ ui.video_state = self.uiVideoState();
2063
+ // The terminal grid lookup (null on stub builds): each
2064
+ // `<terminal pty={key}>` resolves its session's published
2065
+ // snapshot during finalize, with THIS build's tokens
2066
+ // driving the palette's theme mapping.
2067
+ self.terminal_sessions.beginBuild(tokens);
2068
+ ui.terminal_lookup = self.terminal_sessions.lookup();
1429
2069
  ui.virtual_window_context = @ptrCast(&window_source);
1430
2070
  ui.virtual_window_source = VirtualWindowResolver.resolve;
1431
2071
  ui.virtual_extent_context = @ptrCast(self);
1432
2072
  ui.virtual_extent_source = virtualExtentResolve;
1433
2073
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(self.options.canvas_label);
2074
+ if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
1434
2075
  self.armUiFragmentHost(&ui);
1435
2076
  if (comptime features.runtime_markup) {
1436
2077
  if (self.markup_view != null and runtime.options.automation != null) {
@@ -1462,6 +2103,30 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1462
2103
  };
1463
2104
  runtime.frame_profile.end(.layout, layout_begin);
1464
2105
 
2106
+ // Capture the build's `<video src>` declaration for the
2107
+ // post-rebuild reconcile (last pass wins — each pass
2108
+ // resets the arena and re-records), COPIED out of the
2109
+ // build arena (`video_build_staged_src_buffer`):
2110
+ // borrowing the arena would dangle after a later failed
2111
+ // rebuild reset it. STAGED, not committed: the rebuild
2112
+ // commits at install (`commitStagedVideoDeclaration`),
2113
+ // so a build that fails downstream never speaks for the
2114
+ // tree still on the glass. Over-long sources are not
2115
+ // tracked and keep the previous capture — the slot
2116
+ // captures' rule (`captureSlotVideoDeclaration`).
2117
+ if (ui.video_declaration) |declaration| {
2118
+ if (declaration.src.len > 0 and declaration.src.len <= self.video_build_staged_src_buffer.len) {
2119
+ @memcpy(self.video_build_staged_src_buffer[0..declaration.src.len], declaration.src);
2120
+ self.video_build_staged = .{
2121
+ .src = self.video_build_staged_src_buffer[0..declaration.src.len],
2122
+ .autoplay = declaration.autoplay,
2123
+ .loop = declaration.loop,
2124
+ .muted = declaration.muted,
2125
+ };
2126
+ }
2127
+ } else {
2128
+ self.video_build_staged = null;
2129
+ }
1465
2130
  self.rememberVirtualWindows(&ui);
1466
2131
  // Measure the mounted rows of every variable-extent
1467
2132
  // list against the fresh layout and patch the retained
@@ -1730,6 +2395,36 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1730
2395
  return false;
1731
2396
  }
1732
2397
 
2398
+ /// One (id, axis) hysteresis latch: the axis rides along so a
2399
+ /// region whose primary axis changes re-arms honestly. Two
2400
+ /// slots per declarable window — the (id, axis) key space is
2401
+ /// twice the id space.
2402
+ const max_reach_latches = canvas.max_virtual_windows * 2;
2403
+
2404
+ const ReachLatch = struct {
2405
+ id: canvas.ObjectId = 0,
2406
+ axis: canvas.ScrollAxis = .vertical,
2407
+ };
2408
+
2409
+ const ReachAxis = struct {
2410
+ state: canvas.ScrollAxisState,
2411
+ axis: canvas.ScrollAxis,
2412
+ };
2413
+
2414
+ /// The axis reach-end/reach-start measure: the vertical axis
2415
+ /// wherever it has scrollable range (every pre-axis region, so
2416
+ /// existing apps see identical behavior), otherwise the
2417
+ /// horizontal one — a horizontal timeline's `on-reach-end` is
2418
+ /// its right edge. One rule for both signals so "the end" and
2419
+ /// "the start" always name the same axis.
2420
+ fn reachAxisState(scroll_state: canvas.ScrollState) ReachAxis {
2421
+ const vertical = scroll_state.axis(.vertical);
2422
+ if (vertical.maxOffset() > 0) return .{ .state = vertical, .axis = .vertical };
2423
+ const horizontal = scroll_state.axis(.horizontal);
2424
+ if (horizontal.maxOffset() > 0) return .{ .state = horizontal, .axis = .horizontal };
2425
+ return .{ .state = vertical, .axis = .vertical };
2426
+ }
2427
+
1733
2428
  /// Approach-end hysteresis (`on_reach_end`): fire when a scroll
1734
2429
  /// lands within `reach_end_fire_ratio` viewports of the content
1735
2430
  /// end and the region is armed; re-arm once the offset sits more
@@ -1738,37 +2433,43 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1738
2433
  /// under the unchanged offset. One Msg per approach, never a
1739
2434
  /// fetch storm from a user riding the end of the list.
1740
2435
  fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1741
- if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1742
- const remaining = scroll_state.content_extent - scroll_state.viewport_extent - scroll_state.offset;
1743
- if (remaining > scroll_state.viewport_extent * reach_end_rearm_ratio) {
1744
- self.clearReachEndFired(id);
2436
+ const reach = reachAxisState(scroll_state);
2437
+ const axis_state = reach.state;
2438
+ if (id == 0 or axis_state.viewport_extent <= 0) return false;
2439
+ const remaining = axis_state.content_extent - axis_state.viewport_extent - axis_state.offset;
2440
+ if (remaining > axis_state.viewport_extent * reach_end_rearm_ratio) {
2441
+ self.clearReachEndFired(id, reach.axis);
1745
2442
  return false;
1746
2443
  }
1747
- if (remaining > scroll_state.viewport_extent * reach_end_fire_ratio) return false;
1748
- if (self.reachEndFired(id)) return false;
1749
- self.markReachEndFired(id);
1750
- return true;
2444
+ if (remaining > axis_state.viewport_extent * reach_end_fire_ratio) return false;
2445
+ if (self.reachEndFired(id, reach.axis)) return false;
2446
+ // Fire only when the latch STORES: an unstorable latch
2447
+ // (table full — a degenerate tree) would otherwise fire on
2448
+ // every observation, the exact storm the hysteresis exists
2449
+ // to prevent. Silence is the safer failure.
2450
+ return self.markReachEndFired(id, reach.axis);
1751
2451
  }
1752
2452
 
1753
- fn reachEndFired(self: *const Self, id: canvas.ObjectId) bool {
1754
- for (self.reach_end_fired_ids) |fired| {
1755
- if (fired == id) return true;
2453
+ fn reachEndFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2454
+ for (self.reach_end_fired) |fired| {
2455
+ if (fired.id == id and fired.axis == axis) return true;
1756
2456
  }
1757
2457
  return false;
1758
2458
  }
1759
2459
 
1760
- fn markReachEndFired(self: *Self, id: canvas.ObjectId) void {
1761
- for (&self.reach_end_fired_ids) |*slot| {
1762
- if (slot.* == 0 or slot.* == id) {
1763
- slot.* = id;
1764
- return;
2460
+ fn markReachEndFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2461
+ for (&self.reach_end_fired) |*slot| {
2462
+ if (slot.id == 0 or (slot.id == id and slot.axis == axis)) {
2463
+ slot.* = .{ .id = id, .axis = axis };
2464
+ return true;
1765
2465
  }
1766
2466
  }
2467
+ return false;
1767
2468
  }
1768
2469
 
1769
- fn clearReachEndFired(self: *Self, id: canvas.ObjectId) void {
1770
- for (&self.reach_end_fired_ids) |*slot| {
1771
- if (slot.* == id) slot.* = 0;
2470
+ fn clearReachEndFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) void {
2471
+ for (&self.reach_end_fired) |*slot| {
2472
+ if (slot.id == id and slot.axis == axis) slot.* = .{};
1772
2473
  }
1773
2474
  }
1774
2475
 
@@ -1783,37 +2484,40 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1783
2484
  /// only moves on scroll OBSERVATIONS, so a programmatic jump out
1784
2485
  /// of the band re-arms on the next user scroll, not instantly.
1785
2486
  fn reachStartShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1786
- if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1787
- const remaining = scroll_state.offset;
1788
- if (remaining > scroll_state.viewport_extent * reach_start_rearm_ratio) {
1789
- self.clearReachStartFired(id);
2487
+ const reach = reachAxisState(scroll_state);
2488
+ const axis_state = reach.state;
2489
+ if (id == 0 or axis_state.viewport_extent <= 0) return false;
2490
+ const remaining = axis_state.offset;
2491
+ if (remaining > axis_state.viewport_extent * reach_start_rearm_ratio) {
2492
+ self.clearReachStartFired(id, reach.axis);
1790
2493
  return false;
1791
2494
  }
1792
- if (remaining > scroll_state.viewport_extent * reach_start_fire_ratio) return false;
1793
- if (self.reachStartFired(id)) return false;
1794
- self.markReachStartFired(id);
1795
- return true;
2495
+ if (remaining > axis_state.viewport_extent * reach_start_fire_ratio) return false;
2496
+ if (self.reachStartFired(id, reach.axis)) return false;
2497
+ // Fire only when the latch stores (the reach-end rule).
2498
+ return self.markReachStartFired(id, reach.axis);
1796
2499
  }
1797
2500
 
1798
- fn reachStartFired(self: *const Self, id: canvas.ObjectId) bool {
1799
- for (self.reach_start_fired_ids) |fired| {
1800
- if (fired == id) return true;
2501
+ fn reachStartFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2502
+ for (self.reach_start_fired) |fired| {
2503
+ if (fired.id == id and fired.axis == axis) return true;
1801
2504
  }
1802
2505
  return false;
1803
2506
  }
1804
2507
 
1805
- fn markReachStartFired(self: *Self, id: canvas.ObjectId) void {
1806
- for (&self.reach_start_fired_ids) |*slot| {
1807
- if (slot.* == 0 or slot.* == id) {
1808
- slot.* = id;
1809
- return;
2508
+ fn markReachStartFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2509
+ for (&self.reach_start_fired) |*slot| {
2510
+ if (slot.id == 0 or (slot.id == id and slot.axis == axis)) {
2511
+ slot.* = .{ .id = id, .axis = axis };
2512
+ return true;
1810
2513
  }
1811
2514
  }
2515
+ return false;
1812
2516
  }
1813
2517
 
1814
- fn clearReachStartFired(self: *Self, id: canvas.ObjectId) void {
1815
- for (&self.reach_start_fired_ids) |*slot| {
1816
- if (slot.* == id) slot.* = 0;
2518
+ fn clearReachStartFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) void {
2519
+ for (&self.reach_start_fired) |*slot| {
2520
+ if (slot.id == id and slot.axis == axis) slot.* = .{};
1817
2521
  }
1818
2522
  }
1819
2523
 
@@ -1975,6 +2679,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1975
2679
  /// the model already knows).
1976
2680
  fn closeWindowSlot(self: *Self, runtime: *Runtime, index: usize) void {
1977
2681
  const window_id = self.window_slots[index].window_id;
2682
+ self.releaseContextMenuSnapshotForWindow(window_id);
2683
+ // The reconcile-closed window's video declaration dies with
2684
+ // it, exactly as in `handleWindowClosed`.
2685
+ self.captureSlotVideoDeclaration(window_id, null);
2686
+ self.applyVideoDeclaration(runtime);
1978
2687
  const last = self.window_slot_count - 1;
1979
2688
  var removed = self.window_slots[index];
1980
2689
  self.window_slots[index] = self.window_slots[last];
@@ -1990,6 +2699,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1990
2699
  /// Drop a slot whose runtime window is ALREADY gone (the user
1991
2700
  /// closed it): bookkeeping only, no platform call.
1992
2701
  fn forgetWindowSlot(self: *Self, index: usize) ?MsgT {
2702
+ self.releaseContextMenuSnapshotForWindow(self.window_slots[index].window_id);
1993
2703
  const on_close = self.window_slots[index].on_close;
1994
2704
  const last = self.window_slot_count - 1;
1995
2705
  var removed = self.window_slots[index];
@@ -2015,8 +2725,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2015
2725
  fn rebuildWindowSlot(self: *Self, runtime: *Runtime, slot: *WindowSlot) anyerror!void {
2016
2726
  if (self.options.window_view == null) return;
2017
2727
  var tokens = runtime.tokensWithTextMeasure(self.slotEffectiveTokens(slot));
2018
- const next_index = slot.arena_index ^ 1;
2728
+ const next_index = self.contextMenuRebuildIndex(slot.window_id, slot.arena_index);
2019
2729
  const bounds = geometry.RectF.fromSize(slot.canvas_size).deflate(runtime.viewportInsetsForWindow(slot.window_id));
2730
+ // Same live-arena guard as the main canvas rebuild: under
2731
+ // this window's pin the build routes into the slot's LIVE
2732
+ // arena, so a failing pass must drop `slot.tree` rather
2733
+ // than leave it dangling into the reset storage.
2734
+ var live_tree_reset = next_index == slot.arena_index;
2735
+ errdefer if (live_tree_reset) {
2736
+ slot.tree = null;
2737
+ };
2020
2738
  var built = try self.buildWindowSlotPass(slot, bounds, tokens, next_index);
2021
2739
  // The same one-retry window-control clearance the main
2022
2740
  // rebuild runs (see `rebuild`): a secondary hidden-inset
@@ -2030,16 +2748,103 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2030
2748
  }
2031
2749
  const tree = built.tree;
2032
2750
  const layout = built.layout;
2033
- _ = try runtime.setCanvasWidgetLayout(slot.window_id, slot.canvasLabel(), layout);
2751
+ // The slot's install window — the per-slot mirror of the
2752
+ // main rebuild's stamp: stale only from the runtime's
2753
+ // ADOPTION of the new layout (whose rejection is atomic, so
2754
+ // earlier failures keep the old pair current) until the
2755
+ // matching handler tree lands below, wherever the rebuild
2756
+ // was driven from (the full pass or a direct resize/install
2757
+ // site).
2758
+ try self.publishWidgetLayoutTracked(runtime, slot.window_id, slot.canvasLabel(), layout, &slot.tree_current);
2034
2759
  if (slot.installed and self.rebuildEmitsTokens(runtime, slot.window_id, slot.canvasLabel(), tokens)) {
2035
2760
  _ = try runtime.emitCanvasWidgetDisplayList(slot.window_id, slot.canvasLabel(), tokens);
2036
2761
  }
2037
2762
  slot.tree = tree;
2038
2763
  slot.arena_index = next_index;
2764
+ live_tree_reset = false;
2765
+ slot.tree_current = true;
2766
+ self.build_generation +%= 1;
2767
+ // Same per-transition capture refresh as the main rebuild,
2768
+ // same dispatch-error-ring surfacing.
2769
+ if (self.refreshHoverLeaveCaptures()) |refresh_err| {
2770
+ runtime.recordDispatchError("hover_leave_capture", refresh_err);
2771
+ }
2039
2772
  // Same close-on-vanish rule as the main canvas rebuild.
2040
2773
  if (self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0 and tree.context_menu_fallback == null) {
2041
2774
  self.clearContextMenuFallback();
2042
2775
  }
2776
+ // Reconcile the video declaration THIS build recorded or
2777
+ // withdrew (a no-op when nothing changed — the reconciler
2778
+ // diffs the applied src), captured only now that the tree
2779
+ // really installed. The main rebuild already ran it, but
2780
+ // slot builds run after, so a slot-declared video must not
2781
+ // wait a cycle to load.
2782
+ self.captureSlotVideoDeclaration(slot.window_id, slot.pending_video_declaration);
2783
+ const rendered = self.effects.videoSnapshot();
2784
+ self.applyVideoDeclaration(runtime);
2785
+ // The reconcile can activate (or move) the playback this
2786
+ // slot's build rendered — a first mount of an autoplaying
2787
+ // declaration builds its chrome from the still-inactive
2788
+ // snapshot — so one guarded repass renders it from the
2789
+ // moved mirrors, the main rebuild's rule: the repass
2790
+ // reconciles an unchanged declaration, so the mirrors are
2791
+ // a fixed point and the guard makes one level a hard
2792
+ // bound.
2793
+ if (!self.video_chrome_repass and !std.meta.eql(rendered, self.effects.videoSnapshot())) {
2794
+ self.video_chrome_repass = true;
2795
+ defer self.video_chrome_repass = false;
2796
+ try self.rebuildWindowSlot(runtime, slot);
2797
+ }
2798
+ }
2799
+
2800
+ /// One retained secondary-window `<video src>` declaration
2801
+ /// (see `video_slot_declarations`): the window's latest build
2802
+ /// output, kept even while another window owns the player so
2803
+ /// the owner's close or withdrawal promotes it without waiting
2804
+ /// for the declaring window's next rebuild.
2805
+ const SlotVideoDeclaration = struct {
2806
+ used: bool = false,
2807
+ window_id: platform.WindowId = 0,
2808
+ src_buffer: [1024]u8 = undefined,
2809
+ src_len: usize = 0,
2810
+ autoplay: bool = false,
2811
+ loop: bool = false,
2812
+ muted: bool = false,
2813
+ };
2814
+
2815
+ /// Record (or withdraw) a secondary window's `<video src>`
2816
+ /// declaration, copied out of the slot build's arena — one
2817
+ /// retained entry per window (the table matches the window
2818
+ /// budget, so an upsert always finds room). Over-long and
2819
+ /// empty sources are not tracked (`loadVideo` would reject
2820
+ /// them, and tracking one would reload every rebuild).
2821
+ fn captureSlotVideoDeclaration(self: *Self, window_id: platform.WindowId, declaration: ?Ui.VideoDeclaration) void {
2822
+ if (declaration) |decl| {
2823
+ if (decl.src.len == 0 or decl.src.len > 1024) return;
2824
+ const entry = blk: {
2825
+ for (&self.video_slot_declarations) |*candidate| {
2826
+ if (candidate.used and candidate.window_id == window_id) break :blk candidate;
2827
+ }
2828
+ for (&self.video_slot_declarations) |*candidate| {
2829
+ if (!candidate.used) break :blk candidate;
2830
+ }
2831
+ return;
2832
+ };
2833
+ @memcpy(entry.src_buffer[0..decl.src.len], decl.src);
2834
+ entry.src_len = decl.src.len;
2835
+ entry.window_id = window_id;
2836
+ entry.autoplay = decl.autoplay;
2837
+ entry.loop = decl.loop;
2838
+ entry.muted = decl.muted;
2839
+ entry.used = true;
2840
+ return;
2841
+ }
2842
+ for (&self.video_slot_declarations) |*candidate| {
2843
+ if (candidate.used and candidate.window_id == window_id) {
2844
+ candidate.* = .{};
2845
+ }
2846
+ }
2847
+ if (self.video_slot_owner == window_id) self.video_slot_owner = 0;
2043
2848
  }
2044
2849
 
2045
2850
  /// One view-build + flex-layout pass of `rebuildWindowSlot`,
@@ -2055,12 +2860,33 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2055
2860
  next_index: usize,
2056
2861
  ) anyerror!BuiltLayout {
2057
2862
  const window_view = self.options.window_view.?;
2863
+ // `contextMenuRebuildIndex` never routes a rebuild into the
2864
+ // pinned generation, so the reset is unconditional.
2865
+ std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != slot.window_id or pin.arena_index != next_index else true);
2058
2866
  _ = slot.arenas[next_index].reset(.retain_capacity);
2059
2867
  var ui = Ui.init(slot.arenas[next_index].allocator());
2868
+ // Window views render the same honest video chrome state,
2869
+ // and their `<video src>` declarations reconcile the channel
2870
+ // too — `Ui.video` promises that declaring the element IS
2871
+ // the playback in every window's tree. The main canvas
2872
+ // build's declaration wins when both declare (one player,
2873
+ // one owner); the capture below records this slot's claim.
2874
+ ui.video_state = self.uiVideoState();
2875
+ // Window views resolve terminal bindings through the same
2876
+ // session store as the main canvas — one emulator per pty
2877
+ // key, whichever tree binds it.
2878
+ self.terminal_sessions.beginBuild(tokens);
2879
+ ui.terminal_lookup = self.terminal_sessions.lookup();
2060
2880
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(slot.canvasLabel());
2881
+ if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
2061
2882
  self.armUiFragmentHost(&ui);
2062
2883
  const node = window_view(&ui, &self.model, slot.label());
2063
2884
  const tree = try ui.finalizeWithTokens(node, tokens);
2885
+ // The declaration is captured by `rebuildWindowSlot` AFTER
2886
+ // the pass (and its clearance retry) succeeds and the tree
2887
+ // installs: a build whose layout errors never displays, so
2888
+ // its declaration must not steer the playback either.
2889
+ slot.pending_video_declaration = ui.video_declaration;
2064
2890
  const layout = canvas.layoutWidgetTreeWithTokens(tree.root, bounds, tokens, &self.layout_nodes) catch |err| {
2065
2891
  if (err == error.WidgetLayoutListFull) {
2066
2892
  ui_app_log.warn(
@@ -2182,20 +3008,31 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2182
3008
  var chrome_builder = canvas.Builder.init(&chrome_commands);
2183
3009
  try chrome.build(&self.model, &chrome_builder, self.canvas_size, tokens);
2184
3010
  const chrome_list = chrome_builder.displayList();
2185
- if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
3011
+ if (chrome.variable_prefix) {
3012
+ if (chrome_list.commands.len < chrome.suffix_commands or
3013
+ chrome_list.commands.len - chrome.suffix_commands > chrome.prefix_commands)
3014
+ {
3015
+ return error.InvalidChromeCommandCount;
3016
+ }
3017
+ } else if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
2186
3018
  return error.InvalidChromeCommandCount;
2187
3019
  }
3020
+ const prefix_len = chrome_list.commands.len - chrome.suffix_commands;
2188
3021
 
2189
3022
  var commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
2190
3023
  var builder = canvas.Builder.init(&commands);
2191
- for (chrome_list.commands[0..chrome.prefix_commands]) |command| try builder.append(command);
3024
+ for (chrome_list.commands[0..prefix_len]) |command| try builder.append(command);
2192
3025
  try layout.emitDisplayList(&builder, tokens);
2193
- for (chrome_list.commands[chrome.prefix_commands..]) |command| try builder.append(command);
3026
+ for (chrome_list.commands[prefix_len..]) |command| try builder.append(command);
2194
3027
 
2195
3028
  _ = try runtime.setCanvasDisplayList(window_id, self.options.canvas_label, builder.displayList());
2196
- _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
3029
+ // The main install window opens at the layout's true
3030
+ // adoption inside the tracked publication (see `rebuild`)
3031
+ // and closes when the caller adopts the matching handler
3032
+ // tree.
3033
+ try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
2197
3034
  _ = try runtime.emitCanvasWidgetDisplayListWithChrome(window_id, self.options.canvas_label, tokens, .{
2198
- .prefix_command_count = chrome.prefix_commands,
3035
+ .prefix_command_count = prefix_len,
2199
3036
  .suffix_command_count = chrome.suffix_commands,
2200
3037
  });
2201
3038
  }
@@ -2773,6 +3610,223 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2773
3610
  }
2774
3611
  }
2775
3612
 
3613
+ /// The video channel snapshot in the builder's chrome shape
3614
+ /// (`Ui.VideoPlaybackState`), stamped onto every Ui before its
3615
+ /// view fn runs.
3616
+ fn uiVideoState(self: *const Self) Ui.VideoPlaybackState {
3617
+ const snap = self.effects.videoSnapshot();
3618
+ return .{
3619
+ .active = snap.active,
3620
+ .playing = snap.playing,
3621
+ .buffering = snap.buffering,
3622
+ .completed = snap.completed,
3623
+ .position_ms = snap.position_ms,
3624
+ .duration_ms = snap.duration_ms,
3625
+ // The surface + reported stream dimensions drive the
3626
+ // video surface's CONTAIN fit: the builder stamps the
3627
+ // fitted-draw geometry on whichever media surface this
3628
+ // playback feeds (Ui.stampVideoSurfaceFit).
3629
+ .surface = snap.surface,
3630
+ .width = snap.width,
3631
+ .height = snap.height,
3632
+ };
3633
+ }
3634
+
3635
+ /// Whether a `<video src>` names an http(s) stream — the
3636
+ /// `loadVideo` cascade's scheme split; everything else is a
3637
+ /// local app-assets path.
3638
+ fn videoSrcIsUrl(src: []const u8) bool {
3639
+ return std.ascii.startsWithIgnoreCase(src, "http://") or
3640
+ std.ascii.startsWithIgnoreCase(src, "https://");
3641
+ }
3642
+
3643
+ /// Reconcile the build's `<video src>` declaration into the
3644
+ /// video playback channel — the windows/tray pattern: presence
3645
+ /// IS playback. A new or changed src loads (loadVideo's replace
3646
+ /// semantics — one player is the whole surface, keyed by the
3647
+ /// src hash so identical declarations share identity); an
3648
+ /// unchanged src applies only loop/muted deltas; a build with
3649
+ /// no declaration while one was applied stops the playback (the
3650
+ /// element left the view; declarative ownership ends it).
3651
+ /// Deterministic under replay: only fx verbs, which regenerate
3652
+ /// from the replayed rebuilds — never a journal write of its
3653
+ /// own.
3654
+ /// The secondary-window declaration as the reconciler consumes
3655
+ /// it — the current owner window's retained entry while it
3656
+ /// still declares, otherwise the first retained declaration
3657
+ /// PROMOTES on the spot (the previous owner closed or stopped
3658
+ /// declaring; a mounted video in another window must not wait
3659
+ /// for an unrelated rebuild to start). Null when no slot
3660
+ /// declares. The src borrows the app struct's own copy, stable
3661
+ /// across builds.
3662
+ fn slotVideoDeclaration(self: *Self) ?VideoBuildDeclaration {
3663
+ const entry = blk: {
3664
+ if (self.video_slot_owner != 0) {
3665
+ for (&self.video_slot_declarations) |*candidate| {
3666
+ if (candidate.used and candidate.window_id == self.video_slot_owner) break :blk candidate;
3667
+ }
3668
+ }
3669
+ for (&self.video_slot_declarations) |*candidate| {
3670
+ if (candidate.used) break :blk candidate;
3671
+ }
3672
+ self.video_slot_owner = 0;
3673
+ return null;
3674
+ };
3675
+ self.video_slot_owner = entry.window_id;
3676
+ return .{
3677
+ .src = entry.src_buffer[0..entry.src_len],
3678
+ .autoplay = entry.autoplay,
3679
+ .loop = entry.loop,
3680
+ .muted = entry.muted,
3681
+ };
3682
+ }
3683
+
3684
+ /// Seed the in-flight rebuild's staged capture from the
3685
+ /// committed declaration (see `video_build_staged`).
3686
+ fn stageVideoDeclarationFromCommitted(self: *Self) void {
3687
+ if (self.video_build_declaration) |committed| {
3688
+ @memcpy(self.video_build_staged_src_buffer[0..committed.src.len], committed.src);
3689
+ self.video_build_staged = .{
3690
+ .src = self.video_build_staged_src_buffer[0..committed.src.len],
3691
+ .autoplay = committed.autoplay,
3692
+ .loop = committed.loop,
3693
+ .muted = committed.muted,
3694
+ };
3695
+ } else {
3696
+ self.video_build_staged = null;
3697
+ }
3698
+ }
3699
+
3700
+ /// Commit the installed build's staged capture (see
3701
+ /// `video_build_staged`).
3702
+ fn commitStagedVideoDeclaration(self: *Self) void {
3703
+ if (self.video_build_staged) |staged| {
3704
+ @memcpy(self.video_build_src_buffer[0..staged.src.len], staged.src);
3705
+ self.video_build_declaration = .{
3706
+ .src = self.video_build_src_buffer[0..staged.src.len],
3707
+ .autoplay = staged.autoplay,
3708
+ .loop = staged.loop,
3709
+ .muted = staged.muted,
3710
+ };
3711
+ } else {
3712
+ self.video_build_declaration = null;
3713
+ }
3714
+ }
3715
+
3716
+ fn applyVideoDeclaration(self: *Self, runtime: *Runtime) void {
3717
+ const declaration = self.video_build_declaration orelse self.slotVideoDeclaration() orelse {
3718
+ if (self.video_declared) {
3719
+ self.video_declared = false;
3720
+ const declared_key = std.hash.Wyhash.hash(0x76696465, self.video_declared_src_buffer[0..self.video_declared_src_len]) | 1;
3721
+ self.video_declared_src_len = 0;
3722
+ // Stop ONLY the playback this reconciler started:
3723
+ // an update handler may have replaced it with its
3724
+ // own load (a different key) between rebuilds, and
3725
+ // declarative ownership must never kill a playback
3726
+ // it does not own.
3727
+ const snapshot = self.effects.videoSnapshot();
3728
+ if (snapshot.active and snapshot.key == declared_key and
3729
+ self.effects.videoOwnerToken() == self.video_declared_token)
3730
+ {
3731
+ self.effects.stopVideo();
3732
+ }
3733
+ self.video_declared_token = 0;
3734
+ self.publishAudioState(runtime);
3735
+ }
3736
+ return;
3737
+ };
3738
+ // The installing rebuild can reach here before any dispatch
3739
+ // bound the channel (first-bind-sticks, so this is free
3740
+ // afterwards); the load below needs the platform services.
3741
+ self.bindEffectsChannel(runtime);
3742
+ const src = declaration.src;
3743
+ if (src.len > self.video_declared_src_buffer.len) {
3744
+ // Longer than the platform source bound: loadVideo
3745
+ // would reject it; refusing to track it here keeps an
3746
+ // over-long declaration from reloading every rebuild.
3747
+ return;
3748
+ }
3749
+ const applied = self.video_declared_src_buffer[0..self.video_declared_src_len];
3750
+ if (!self.video_declared or !std.mem.eql(u8, applied, src)) {
3751
+ const options: Effects.LoadVideoOptions = .{
3752
+ // Key from the src (nonzero by construction): the
3753
+ // declaration IS the playback's identity.
3754
+ .key = std.hash.Wyhash.hash(0x76696465, src) | 1,
3755
+ .surface = canvas.video_playback_surface_id,
3756
+ .path = if (videoSrcIsUrl(src)) "" else src,
3757
+ .url = if (videoSrcIsUrl(src)) src else "",
3758
+ .autoplay = declaration.autoplay,
3759
+ .loop = declaration.loop,
3760
+ .muted = declaration.muted,
3761
+ };
3762
+ // Validate BEFORE committing: a source the engine's own
3763
+ // deterministic gates refuse (a malformed URL, say)
3764
+ // must not take over the tracked ownership — the
3765
+ // engine keeps the CURRENT playback on a rejected
3766
+ // load, and tracking the refused src would make a
3767
+ // later element removal hash the refused source
3768
+ // instead of the playback still running, stranding it
3769
+ // forever. The refused src is remembered separately so
3770
+ // an unchanged bad declaration is not re-attempted
3771
+ // (and re-taught) every rebuild.
3772
+ if (Effects.videoLoadRejected(options)) {
3773
+ const refused = self.video_refused_src_buffer[0..self.video_refused_src_len];
3774
+ if (src.len <= self.video_refused_src_buffer.len and !std.mem.eql(u8, refused, src)) {
3775
+ @memcpy(self.video_refused_src_buffer[0..src.len], src);
3776
+ self.video_refused_src_len = src.len;
3777
+ ui_app_log.warn(
3778
+ "declared <video src> was refused by the video loader (empty or over-long source, or a non-http(s) URL): the declaration is ignored and the current playback, if any, keeps running",
3779
+ .{},
3780
+ );
3781
+ }
3782
+ return;
3783
+ }
3784
+ self.video_refused_src_len = 0;
3785
+ @memcpy(self.video_declared_src_buffer[0..src.len], src);
3786
+ self.video_declared_src_len = src.len;
3787
+ self.video_declared = true;
3788
+ self.video_declared_loop = declaration.loop;
3789
+ self.video_declared_muted = declaration.muted;
3790
+ self.effects.loadVideo(options);
3791
+ self.video_declared_token = self.effects.videoOwnerToken();
3792
+ self.publishAudioState(runtime);
3793
+ return;
3794
+ }
3795
+ // Same src: apply flag deltas in place — a reload would
3796
+ // restart the playback the declaration did not change. Only
3797
+ // while the declared playback still OWNS the channel: an
3798
+ // update handler that replaced it (its own key) took the
3799
+ // single player over, and the reconciler yields until the
3800
+ // declaration itself changes.
3801
+ // Ownership is the TOKEN of the load this reconciler
3802
+ // issued, not the derived key: the key is a pure function
3803
+ // of the source string, and an update's manual load could
3804
+ // carry the same one — the reconciler must never stop or
3805
+ // mutate a playback it did not start.
3806
+ const declared_key = std.hash.Wyhash.hash(0x76696465, src) | 1;
3807
+ const snapshot = self.effects.videoSnapshot();
3808
+ if (!snapshot.active or snapshot.key != declared_key or
3809
+ self.effects.videoOwnerToken() != self.video_declared_token) return;
3810
+ var moved = false;
3811
+ if (declaration.loop != self.video_declared_loop) {
3812
+ self.video_declared_loop = declaration.loop;
3813
+ self.effects.setVideoLoop(declaration.loop);
3814
+ moved = true;
3815
+ }
3816
+ if (declaration.muted != self.video_declared_muted) {
3817
+ self.video_declared_muted = declaration.muted;
3818
+ self.effects.setVideoMuted(declaration.muted);
3819
+ moved = true;
3820
+ }
3821
+ // A flag delta moves the channel mirrors without any
3822
+ // dispatch or drain behind it, so the runtime mirror
3823
+ // republishes here exactly like the load and removal paths
3824
+ // — an automation snapshot taken after a <video muted> or
3825
+ // <video loop> flip must report the new value, not the one
3826
+ // published before the reconcile.
3827
+ if (moved) self.publishAudioState(runtime);
3828
+ }
3829
+
2776
3830
  fn sceneFn(context: *anyopaque) anyerror!app_manifest.ShellConfig {
2777
3831
  const self: *Self = @ptrCast(@alignCast(context));
2778
3832
  return self.options.scene;
@@ -2780,7 +3834,73 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2780
3834
 
2781
3835
  fn eventFn(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
2782
3836
  const self: *Self = @ptrCast(@alignCast(context));
3837
+ self.hover_msg_event_depth += 1;
3838
+ defer self.hover_msg_event_depth -= 1;
3839
+ // Hover enter/leave delivery rides the tail of runtime
3840
+ // events: the standing chain moves during pointer routing,
3841
+ // scroll reconciles (wheel, kinetic, drivers, keyboard),
3842
+ // dismissals, and any rebuild the dispatches above
3843
+ // performed — the drain seam catches them all, and replay
3844
+ // re-runs the same events through the same seam. The drain
3845
+ // runs on the handler's ERROR path too (the degraded-error
3846
+ // doctrine): a failing handler must not strand edges the
3847
+ // event already produced — a closed window's leave, a
3848
+ // failed rebuild's prune — until some later event happens
3849
+ // by. Mid-cycle DERIVED widget events skip the drain (see
3850
+ // `hoverDrainsAfterEvent`): their input cycle's terminal
3851
+ // `gpu_surface_input` dispatch drains after the cycle's
3852
+ // pending scroll/resize/change observations were delivered,
3853
+ // so a hover Msg's rebuild can never unmount a view whose
3854
+ // promised observation is still queued.
3855
+ handleRuntimeEvent(self, runtime, event_value) catch |err| {
3856
+ if (hoverDrainsAfterEvent(event_value)) self.drainHoverMsgs(runtime) catch {};
3857
+ return err;
3858
+ };
3859
+ if (hoverDrainsAfterEvent(event_value)) try self.drainHoverMsgs(runtime);
3860
+ }
3861
+
3862
+ /// Whether the hover drain runs at this event's tail. Derived
3863
+ /// widget events that only occur INSIDE a gpu-surface input
3864
+ /// cycle defer to the cycle's terminal `gpu_surface_input`
3865
+ /// dispatch — which always follows them, after the pending
3866
+ /// scroll/resize/change drains. Scroll/resize/change events also
3867
+ /// arrive standalone from the native-driver and kinetic paths;
3868
+ /// those defer at most one frame (both paths run under an
3869
+ /// actively pumping frame channel), which is the price of never
3870
+ /// rebuilding mid-cycle. Dismiss events DO drain: the
3871
+ /// automation/accessibility dismiss verb dispatches one
3872
+ /// standalone, and a dismissal's own Msg rebuild already runs
3873
+ /// before the cycle's pending drains, so draining here adds no
3874
+ /// new hazard class. Everything else — commands, timers, wakes,
3875
+ /// frames, the terminal input dispatch, native menu selections —
3876
+ /// drains immediately.
3877
+ fn hoverDrainsAfterEvent(event_value: Event) bool {
3878
+ return switch (event_value) {
3879
+ // Keyboard events usually ride an input cycle (their
3880
+ // terminal dispatch drains); the standalone ones —
3881
+ // accessibility selection edits, context-menu
3882
+ // cut/paste/select-all — have no cycle and drain here.
3883
+ .canvas_widget_keyboard => |keyboard_event| keyboard_event.standalone,
3884
+ .canvas_widget_pointer,
3885
+ .canvas_widget_drag,
3886
+ .canvas_widget_file_drop,
3887
+ .canvas_widget_context_press,
3888
+ .canvas_widget_context_menu_request,
3889
+ .canvas_widget_context_menu_shown,
3890
+ .canvas_widget_scroll,
3891
+ .canvas_widget_resize,
3892
+ .canvas_widget_change,
3893
+ => false,
3894
+ else => true,
3895
+ };
3896
+ }
3897
+
3898
+ fn handleRuntimeEvent(self: *Self, runtime: *Runtime, event_value: Event) anyerror!void {
2783
3899
  switch (event_value) {
3900
+ .lifecycle => |lifecycle| {
3901
+ const map = self.options.on_lifecycle orelse return;
3902
+ if (map(lifecycle)) |msg| try self.dispatch(runtime, self.canvas_window_id, msg);
3903
+ },
2784
3904
  .command => |command| {
2785
3905
  const map = self.options.on_command orelse return;
2786
3906
  if (map(command.name)) |msg| {
@@ -2820,6 +3940,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2820
3940
  .audio => |audio_event| if (self.effects.takeAudioMsg(audio_event)) |msg| {
2821
3941
  try self.dispatch(runtime, self.canvas_window_id, msg);
2822
3942
  },
3943
+ // Platform video reports route the same way: through
3944
+ // the effects channel into the app's `on_event` Msg,
3945
+ // journaled at the delivery boundary. Without an app
3946
+ // Msg the report still moved the channel mirrors, and
3947
+ // the house `<video controls>` chrome renders those —
3948
+ // so publish and rebuild anyway (window slots included:
3949
+ // a secondary window's tree consumes the same
3950
+ // snapshot), keeping the transport live with no model
3951
+ // plumbing (position ticks arrive at the platform's
3952
+ // coarse ~2 Hz cadence, so the extra rebuilds stay
3953
+ // cheap).
3954
+ .video => |video_event| if (self.effects.takeVideoMsg(video_event)) |msg| {
3955
+ try self.dispatch(runtime, self.canvas_window_id, msg);
3956
+ } else if (self.installed) {
3957
+ try self.rebuildVideoChrome(runtime);
3958
+ },
2823
3959
  .effects_wake => try self.drainEffects(runtime),
2824
3960
  .gpu_surface_frame => |frame_event| try self.handleFrame(runtime, frame_event),
2825
3961
  .gpu_surface_resized => |resize_event| try self.handleResize(runtime, resize_event),
@@ -2827,6 +3963,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2827
3963
  .canvas_widget_keyboard => |keyboard_event| try self.handleKeyboard(runtime, keyboard_event),
2828
3964
  .canvas_widget_scroll => |scroll_event| try self.handleScroll(runtime, scroll_event),
2829
3965
  .canvas_widget_context_menu => |menu_event| try self.handleContextMenu(runtime, menu_event),
3966
+ .canvas_widget_context_menu_shown => |shown_event| try self.handleContextMenuShown(runtime, shown_event),
3967
+ .canvas_widget_context_menu_dismissed => |dismissed_event| try self.handleContextMenuDismissed(runtime, dismissed_event),
2830
3968
  .canvas_widget_context_menu_request => |request_event| try self.handleContextMenuRequest(runtime, request_event),
2831
3969
  .canvas_widget_dismiss => |dismiss_event| try self.handleDismiss(runtime, dismiss_event),
2832
3970
  .canvas_widget_context_press => |press_event| try self.handleContextPress(runtime, press_event),
@@ -2837,7 +3975,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2837
3975
  // Raw gpu-surface input stays runtime-internal EXCEPT the
2838
3976
  // pinch kinds, which surface through the app-level pinch
2839
3977
  // channel (widget routing never claims a pinch).
2840
- .gpu_surface_input => |input_event| try self.handlePinch(runtime, input_event),
3978
+ .gpu_surface_input => |input_event| {
3979
+ try self.handlePinch(runtime, input_event);
3980
+ // A wheel over a bound terminal is the widget's
3981
+ // scrollback gesture and consumes the event before
3982
+ // the app-level wheel seam (widget precedence).
3983
+ if (!(try self.handleTerminalWheel(runtime, input_event))) {
3984
+ try self.handleWheel(runtime, input_event);
3985
+ }
3986
+ },
2841
3987
  else => {},
2842
3988
  }
2843
3989
  }
@@ -2850,6 +3996,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2850
3996
  /// next rebuild (source wins), exactly like a dismissed surface.
2851
3997
  fn handleWindowClosed(self: *Self, runtime: *Runtime, closed: core.WindowClosedEvent) anyerror!void {
2852
3998
  const index = self.windowSlotIndexByWindowId(closed.window_id) orelse return;
3999
+ // A closed window's video declaration dies with it: withdraw
4000
+ // its retained entry and reconcile — an owning window's
4001
+ // playback stops (or the next retained declaration promotes
4002
+ // in its place), a non-owner just drops out of the table.
4003
+ self.captureSlotVideoDeclaration(closed.window_id, null);
4004
+ self.applyVideoDeclaration(runtime);
2853
4005
  const on_close = self.forgetWindowSlot(index);
2854
4006
  if (on_close) |msg| {
2855
4007
  try self.dispatch(runtime, self.canvas_window_id, msg);
@@ -3047,6 +4199,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3047
4199
  self.applyWebPanes(runtime, frame_event.window_id, layout);
3048
4200
  } else |_| {}
3049
4201
  }
4202
+ // Terminal outbound pacing: a child that read without
4203
+ // echoing freed stdin-FIFO room no output event announces,
4204
+ // so pending session bytes (a retained query reply, a paste
4205
+ // tail) flush on the presented-frame clock — journaled
4206
+ // write verdicts on a journaled event, so replay drains
4207
+ // identically. A no-op when nothing is pending.
4208
+ if (comptime terminal_session.enabled) {
4209
+ _ = self.terminal_sessions.flushPending();
4210
+ }
3050
4211
  try self.presentFrame(runtime, frame_event, self.options.canvas_label, installing);
3051
4212
  if (installing) return;
3052
4213
  const on_frame = self.options.on_frame orelse return;
@@ -3296,6 +4457,55 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3296
4457
  return map(chrome);
3297
4458
  }
3298
4459
 
4460
+ /// Route primary pointer selection into a bound terminal before
4461
+ /// ordinary press dispatch. The layout query supplies the
4462
+ /// terminal's resolved frame; coordinates are translated into
4463
+ /// the same padded content box the painter and size reconcile
4464
+ /// use, then Ghostty owns cell snapping and tracked selection
4465
+ /// pins. Returns whether an active selection should suppress a
4466
+ /// release-time `on_press`.
4467
+ fn handleTerminalPointer(self: *Self, runtime: *Runtime, pointer_event: core.CanvasWidgetPointerEvent) anyerror!bool {
4468
+ if (comptime !terminal_session.enabled) return false;
4469
+ switch (pointer_event.pointer.phase) {
4470
+ .down, .move, .up, .cancel => {},
4471
+ .hover, .wheel => return false,
4472
+ }
4473
+ if (pointer_event.pointer.phase == .down and pointer_event.pointer.button != 0) return false;
4474
+ const target = pointer_event.target orelse return false;
4475
+ const layout = runtime.canvasWidgetLayout(pointer_event.window_id, pointer_event.view_label) catch return false;
4476
+ var terminal_node: ?canvas.WidgetLayoutNode = null;
4477
+ for (layout.nodes) |node| {
4478
+ if (node.widget.id != target.id) continue;
4479
+ if (node.widget.kind != .terminal or node.widget.terminal.pty == 0) return false;
4480
+ terminal_node = node;
4481
+ break;
4482
+ }
4483
+ const node = terminal_node orelse return false;
4484
+ if (!self.terminal_sessions.hasSession(node.widget.terminal.pty)) return false;
4485
+
4486
+ const frame = node.frame.normalized();
4487
+ const padding = node.widget.layout.padding;
4488
+ const declared = padding.left + padding.top + padding.right + padding.bottom > 0;
4489
+ const inset: geometry.InsetsF = if (declared) padding else geometry.InsetsF.all(8);
4490
+ const content = geometry.RectF.init(
4491
+ frame.x + inset.left,
4492
+ frame.y + inset.top,
4493
+ @max(0, frame.width - inset.left - inset.right),
4494
+ @max(0, frame.height - inset.top - inset.bottom),
4495
+ );
4496
+ if (content.isEmpty()) return false;
4497
+ const result = self.terminal_sessions.pointerSelection(node.widget.terminal.pty, .{
4498
+ .phase = pointer_event.pointer.phase,
4499
+ .x = pointer_event.pointer.point.x - content.x,
4500
+ .y = pointer_event.pointer.point.y - content.y,
4501
+ .width = content.width,
4502
+ .height = content.height,
4503
+ .click_count = pointer_event.pointer.click_count,
4504
+ });
4505
+ if (result.changed) try self.repaintTerminals(runtime, pointer_event.window_id);
4506
+ return pointer_event.pointer.phase == .up and result.selection_active;
4507
+ }
4508
+
3299
4509
  /// Typed press dispatch resolves through the press target — the
3300
4510
  /// deepest widget on the hit path that claims presses — so a press
3301
4511
  /// on a pressable row's plain text children lands on the row's
@@ -3306,6 +4516,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3306
4516
  /// Msg), and any release/cancel disarms it.
3307
4517
  fn handlePointer(self: *Self, runtime: *Runtime, pointer_event: core.CanvasWidgetPointerEvent) anyerror!void {
3308
4518
  const tree = self.treeForViewLabel(pointer_event.view_label) orelse return;
4519
+ const terminal_selected = try self.handleTerminalPointer(runtime, pointer_event);
3309
4520
  switch (pointer_event.pointer.phase) {
3310
4521
  .down => {
3311
4522
  self.disarmHold(runtime);
@@ -3332,10 +4543,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3332
4543
  },
3333
4544
  else => {},
3334
4545
  }
3335
- // A pointer gesture that performed a text edit (the search
3336
- // field's built-in clear) maps to the field's `on_input`
3337
- // Msg — the runtime already applied the edit; the model
3338
- // hears it here so a source-owned buffer clears too.
4546
+ // A pointer gesture that performed a text edit (editable
4547
+ // caret/selection placement or the search field's built-in
4548
+ // clear) maps to the field's `on_input` Msg — the runtime
4549
+ // already applied the edit; the model hears it here so a
4550
+ // source-owned buffer stays in lockstep too.
3339
4551
  if (pointer_event.edit) |edit| {
3340
4552
  if (pointer_event.target) |edit_target| {
3341
4553
  if (tree.msgForTextEdit(edit_target.id, edit)) |msg| {
@@ -3343,6 +4555,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3343
4555
  }
3344
4556
  }
3345
4557
  }
4558
+ // A selection gesture owns the release the way a static
4559
+ // text drag does: keep its highlight and dispatch no press.
4560
+ if (terminal_selected) return;
3346
4561
  const target = pointer_event.press_target orelse return;
3347
4562
  // A released press on a synthesized fallback menu item is a
3348
4563
  // context-menu selection, not an ordinary press: it resolves
@@ -3350,6 +4565,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3350
4565
  // closes the surface.
3351
4566
  if (pointer_event.pointer.phase == .up) {
3352
4567
  if (try self.dispatchContextMenuFallbackItem(runtime, tree, pointer_event.window_id, target.id)) return;
4568
+ // House video chrome is runtime-consumed: a release on
4569
+ // the transport's play/pause control drives the video
4570
+ // channel directly (no app Msg exists to resolve), and
4571
+ // the rebuild re-renders the chrome from the moved
4572
+ // mirrors.
4573
+ if (tree.findWidget(target.id)) |widget| {
4574
+ if (widget.video_control == .toggle) {
4575
+ try self.toggleVideoControl(runtime);
4576
+ return;
4577
+ }
4578
+ }
3353
4579
  }
3354
4580
  // The click count rides the release into typed dispatch: a
3355
4581
  // double-click's second release resolves the target's
@@ -3361,6 +4587,688 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3361
4587
  }
3362
4588
  }
3363
4589
 
4590
+ /// Cap on hover-Msg drain passes per runtime event: each pass
4591
+ /// delivers one coalesced containment transition, and the Msgs
4592
+ /// it dispatches can rebuild the tree and move the standing
4593
+ /// chain again (an enter handler that unmounts the hovered
4594
+ /// element owes an immediate leave — the second pass delivers
4595
+ /// it). The cap exists ONLY as a flap guard (an app whose enter
4596
+ /// mounts and whose leave unmounts, forever), sized far past
4597
+ /// any honest cascade — even one where every enter replaces the
4598
+ /// listener under a stationary pointer — so a finite sequence
4599
+ /// always settles within one drain; residue past the cap
4600
+ /// delivers on the next event's drain.
4601
+ const hover_msg_drain_passes: usize = 64;
4602
+
4603
+ /// Refresh every standing capture from the mirror view's live
4604
+ /// tree when the trees moved underneath: called at EVERY
4605
+ /// rebuild commit — two dispatches in one cycle (payload A to
4606
+ /// B, then unmount) must deliver B, so the refresh cannot wait
4607
+ /// for drain time and see only the final tree — and again
4608
+ /// defensively at drain time. UPSERT only (an unbound leave
4609
+ /// keeps the last capture). Returns the first TRANSIENT failure
4610
+ /// (allocation) after attempting every entry, leaving the
4611
+ /// generation behind so the next commit or drain retries.
4612
+ fn refreshHoverLeaveCaptures(self: *Self) ?anyerror {
4613
+ if (self.hover_msg_chain_len == 0) return null;
4614
+ if (self.hover_msg_captured_generation == self.build_generation) return null;
4615
+ if (!self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) return null;
4616
+ const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel()) orelse return null;
4617
+ var first_error: ?anyerror = null;
4618
+ var refreshed = true;
4619
+ for (0..self.hover_msg_chain_len) |position| {
4620
+ // A refused entry's pair is disabled (its enter never
4621
+ // dispatched); a rebind only takes effect on re-entry.
4622
+ if (self.hover_msg_slots[position] == hover_msg_slot_refused) continue;
4623
+ const leave_msg = mirror_tree.msgFor(self.hover_msg_chain[position], .hover_leave) orelse continue;
4624
+ // Copy-then-swap: the replacement lands in a FRESH slot
4625
+ // (the pool sizing guarantees one is free) and the old
4626
+ // capture releases only after it succeeded — a failed
4627
+ // allocation must never destroy the still-valid capture
4628
+ // it was refreshing.
4629
+ const fresh = self.claimHoverSlot() orelse {
4630
+ refreshed = false;
4631
+ ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
4632
+ if (first_error == null) first_error = error.OutOfMemory;
4633
+ continue;
4634
+ };
4635
+ self.captureHoverLeave(fresh, leave_msg) catch |err| {
4636
+ self.releaseHoverSlot(fresh);
4637
+ switch (err) {
4638
+ error.OutOfMemory => {
4639
+ // Transient: keep the old capture, retry at
4640
+ // the next commit or drain — the generation
4641
+ // stays behind — and surface the failure
4642
+ // LOUD: if the element unmounts before a
4643
+ // retry lands, its refreshed leave is lost,
4644
+ // and that must never be silent.
4645
+ refreshed = false;
4646
+ ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
4647
+ if (first_error == null) first_error = err;
4648
+ },
4649
+ error.HoverCapturePayloadUnsupported => {
4650
+ // A rebind to an unownable payload. An
4651
+ // entry with a standing capture keeps it
4652
+ // quietly (the promise the enter earned);
4653
+ // an entry that never had one — entered
4654
+ // with no leave bound, then given one no
4655
+ // copy can own — is marked so the
4656
+ // degradation is WARNED once, not silent,
4657
+ // and not re-warned every generation.
4658
+ if (self.hover_msg_slots[position] == hover_msg_slot_none) {
4659
+ self.hover_msg_slots[position] = hover_msg_slot_unowned;
4660
+ ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
4661
+ }
4662
+ },
4663
+ }
4664
+ continue;
4665
+ };
4666
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
4667
+ self.hover_msg_slots[position] = fresh;
4668
+ }
4669
+ if (refreshed) self.hover_msg_captured_generation = self.build_generation;
4670
+ return first_error;
4671
+ }
4672
+
4673
+ /// The mirror-view adoption count for the tracked publication
4674
+ /// below (0 when the view is not found — then no adoption can
4675
+ /// have happened either).
4676
+ fn canvasWidgetLayoutAdoptions(runtime: *Runtime, window_id: platform.WindowId, label: []const u8) u64 {
4677
+ for (runtime.views[0..runtime.view_count]) |*view| {
4678
+ if (view.window_id == window_id and std.mem.eql(u8, view.label, label)) return view.canvas_widget_layout_adoptions;
4679
+ }
4680
+ return 0;
4681
+ }
4682
+
4683
+ /// Publish a widget layout with the hover-currency stamp at the
4684
+ /// TRUE adoption boundary: `setCanvasWidgetLayout` adopts the
4685
+ /// layout partway through its pipeline (validated-then-atomic)
4686
+ /// and runs more fallible work after — source-text copies, host
4687
+ /// scroll/drag syncs, display refresh — so a failure THERE must
4688
+ /// still mark the pair stale, while a pre-adoption rejection
4689
+ /// must not. The view's adoption counter is the witness.
4690
+ fn publishWidgetLayoutTracked(self: *Self, runtime: *Runtime, window_id: platform.WindowId, label: []const u8, layout: canvas.WidgetLayoutTree, current_flag: *bool) anyerror!void {
4691
+ _ = self;
4692
+ const adoptions_before = canvasWidgetLayoutAdoptions(runtime, window_id, label);
4693
+ _ = runtime.setCanvasWidgetLayout(window_id, label, layout) catch |err| {
4694
+ if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) current_flag.* = false;
4695
+ return err;
4696
+ };
4697
+ current_flag.* = false;
4698
+ }
4699
+
4700
+ /// The handler tree behind a hover mirror's VIEW IDENTITY —
4701
+ /// window id AND canvas label, never label alone: a replacement
4702
+ /// window can reuse a closed window's canvas label (and even
4703
+ /// rebuild the same structural ids), and resolving the old
4704
+ /// window's captures through the new window's tree would
4705
+ /// dispatch the wrong message under the old window id.
4706
+ fn hoverTreeFor(self: *Self, window_id: platform.WindowId, view_label: []const u8) ?*const Ui.Tree {
4707
+ if (std.mem.eql(u8, view_label, self.options.canvas_label)) {
4708
+ if (window_id != self.canvas_window_id) return null;
4709
+ return if (self.tree) |*tree| tree else null;
4710
+ }
4711
+ if (self.windowSlotByCanvasLabel(view_label)) |slot| {
4712
+ if (slot.window_id != window_id) return null;
4713
+ return if (slot.tree) |*tree| tree else null;
4714
+ }
4715
+ return null;
4716
+ }
4717
+
4718
+ /// The currency flag governing hover-Msg resolution through the
4719
+ /// handler tree behind the view identity (see
4720
+ /// `main_tree_current`): the main canvas keys on the main flag,
4721
+ /// every secondary window on ITS OWN slot's — one window's
4722
+ /// failed publication never defers hover into its siblings, and
4723
+ /// a same-label replacement window never answers for its
4724
+ /// predecessor. An unknown identity has no tree at all; the
4725
+ /// null-tree checks own that case.
4726
+ fn hoverTreeCurrentFor(self: *Self, window_id: platform.WindowId, view_label: []const u8) bool {
4727
+ if (std.mem.eql(u8, view_label, self.options.canvas_label)) return self.main_tree_current;
4728
+ if (self.windowSlotByCanvasLabel(view_label)) |slot| {
4729
+ if (slot.window_id != window_id) return true;
4730
+ return slot.tree_current;
4731
+ }
4732
+ return true;
4733
+ }
4734
+
4735
+ /// The capture-slot pool covers BOTH populations a transition
4736
+ /// can hold at once — the departing chain's captures (released
4737
+ /// only after each leave Msg is consumed) and the standing
4738
+ /// mirror's (a mid-batch rebuild's refresh can fill every
4739
+ /// entry before the first leave releases) — plus one in-flight
4740
+ /// swap slot, so a legitimate deep handoff between disjoint
4741
+ /// branches can never exhaust it. `claimHoverSlot` still
4742
+ /// degrades like an allocation failure rather than trapping if
4743
+ /// the accounting is ever wrong.
4744
+ const hover_msg_slot_count: usize = canvas.max_widget_depth * 2 + 1;
4745
+
4746
+ /// The "no capture slot" sentinel in `hover_msg_slots` (the slot
4747
+ /// space is `hover_msg_slot_count`, far below it).
4748
+ const hover_msg_slot_none: u8 = 0xFF;
4749
+
4750
+ /// The "pair disabled" marker: this standing entry's leave
4751
+ /// payload cannot be owned (a single-item pointer only a Zig
4752
+ /// view could construct), so its ENTER was refused too — no
4753
+ /// enter without a deliverable leave. Permanent while the entry
4754
+ /// stands (re-hovering after a rebind retries); refused
4755
+ /// entries dispatch nothing on exit and are skipped by the
4756
+ /// capture refresh.
4757
+ const hover_msg_slot_refused: u8 = 0xFE;
4758
+
4759
+ /// The "entered, but the leave rebind is unownable" marker: the
4760
+ /// enter already dispatched (with no leave bound, or an ownable
4761
+ /// one), then a rebuild bound a payload no copy can own. The
4762
+ /// leave degrades to live-tree resolution — silence on unmount
4763
+ /// — warned ONCE at the rebind; the refresh keeps re-attempting
4764
+ /// it, so a later ownable rebind upgrades to a real capture.
4765
+ const hover_msg_slot_unowned: u8 = 0xFD;
4766
+
4767
+ /// Capture a leave Msg for later delivery into `slot`: a DEEP
4768
+ /// copy whose payload slices live in the slot's own arena (any
4769
+ /// size — a budget here would turn a large payload into an
4770
+ /// unpaired leave). Allocation failure PROPAGATES so the caller
4771
+ /// can defer the enter instead of dispatching one whose paired
4772
+ /// leave is already lost; the one non-transient refusal — a
4773
+ /// payload shape that cannot be owned (a single-item pointer
4774
+ /// only a Zig view could construct) — degrades to an empty
4775
+ /// capture with a debug note, and delivery falls back to the
4776
+ /// live tree while the element stands.
4777
+ fn captureHoverLeave(self: *Self, slot: u8, msg: MsgT) error{ OutOfMemory, HoverCapturePayloadUnsupported }!void {
4778
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4779
+ self.hover_msg_leave_msgs[slot] = deepCopyMsgValue(MsgT, msg, self.hover_msg_leave_arenas[slot].allocator(), 0) catch |err| {
4780
+ // A refused capture holds no bytes either: the partial
4781
+ // copy is released with the arena before the verdict.
4782
+ // OutOfMemory is transient (callers defer and retry);
4783
+ // HoverCapturePayloadUnsupported is permanent (callers
4784
+ // disable the pair — no enter without a deliverable
4785
+ // leave).
4786
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4787
+ self.hover_msg_leave_msgs[slot] = null;
4788
+ return err;
4789
+ };
4790
+ }
4791
+
4792
+ /// Claim a free capture slot, or null when none is free — the
4793
+ /// pool is sized so that never happens for legitimate
4794
+ /// transitions (see `hover_msg_slot_count`), and callers treat
4795
+ /// null exactly like a transient allocation failure: defer and
4796
+ /// retry, never trap.
4797
+ fn claimHoverSlot(self: *Self) ?u8 {
4798
+ for (&self.hover_msg_slot_used, 0..) |*used, slot| {
4799
+ if (used.*) continue;
4800
+ used.* = true;
4801
+ return @intCast(slot);
4802
+ }
4803
+ return null;
4804
+ }
4805
+
4806
+ /// Release a slot: reset its arena (the captured Msg was already
4807
+ /// consumed — dispatch is synchronous) and free it, so a retired
4808
+ /// slot never retains a large payload copy until some later
4809
+ /// hover happens to reuse it.
4810
+ fn releaseHoverSlot(self: *Self, slot: u8) void {
4811
+ if (slot >= hover_msg_slot_count) return;
4812
+ self.hover_msg_leave_msgs[slot] = null;
4813
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4814
+ self.hover_msg_slot_used[slot] = false;
4815
+ }
4816
+
4817
+ /// Recursively copy a Msg value so it owns every byte it
4818
+ /// references: scalars ride through, slices are duplicated into
4819
+ /// `allocator` (element-wise, so nested slices copy too), and
4820
+ /// payload shapes that cannot be owned (single-item pointers,
4821
+ /// untagged unions) refuse rather than alias.
4822
+ /// Pointer-indirection bound for one captured Msg: a run of
4823
+ /// nested slices deeper than this is either a cyclic value
4824
+ /// graph (which no copy terminates) or data no Msg payload has
4825
+ /// business carrying — both refuse as unsupported instead of
4826
+ /// recursing toward exhaustion. Structs and arrays add no
4827
+ /// depth; only slice hops count.
4828
+ const hover_msg_capture_max_indirections: usize = 64;
4829
+
4830
+ fn deepCopyMsgValue(comptime T: type, value: T, allocator: std.mem.Allocator, indirections: usize) error{ OutOfMemory, HoverCapturePayloadUnsupported }!T {
4831
+ return switch (@typeInfo(T)) {
4832
+ .void, .int, .float, .bool, .@"enum", .vector, .error_set => value,
4833
+ .optional => |info| if (value) |inner| try deepCopyMsgValue(info.child, inner, allocator, indirections) else null,
4834
+ .error_union => |info| if (value) |payload| @as(T, try deepCopyMsgValue(info.payload, payload, allocator, indirections)) else |err| @as(T, err),
4835
+ .array => |info| blk: {
4836
+ var out: T = undefined;
4837
+ for (0..info.len) |index| out[index] = try deepCopyMsgValue(info.child, value[index], allocator, indirections);
4838
+ // A sentinel-terminated array carries one element
4839
+ // past its length: stamp it, never leave it
4840
+ // undefined.
4841
+ if (comptime std.meta.sentinel(T)) |sentinel| out[info.len] = sentinel;
4842
+ break :blk out;
4843
+ },
4844
+ .@"struct" => |info| blk: {
4845
+ var out = value;
4846
+ inline for (info.fields) |field| {
4847
+ @field(out, field.name) = try deepCopyMsgValue(field.type, @field(value, field.name), allocator, indirections);
4848
+ }
4849
+ break :blk out;
4850
+ },
4851
+ .@"union" => |info| if (comptime info.tag_type == null) error.HoverCapturePayloadUnsupported else switch (value) {
4852
+ inline else => |payload, tag| @unionInit(T, @tagName(tag), try deepCopyMsgValue(@TypeOf(payload), payload, allocator, indirections)),
4853
+ },
4854
+ .pointer => |info| blk: {
4855
+ if (info.size != .slice) return error.HoverCapturePayloadUnsupported;
4856
+ if (indirections >= hover_msg_capture_max_indirections) return error.HoverCapturePayloadUnsupported;
4857
+ // The copy preserves the slice type's OWN alignment
4858
+ // and sentinel, so over-aligned payloads
4859
+ // (`[]align(64) const u8`) and sentinel slices
4860
+ // type-check and round-trip.
4861
+ const alignment: ?std.mem.Alignment = comptime align_blk: {
4862
+ const declared = info.alignment orelse break :align_blk null;
4863
+ if (declared == @alignOf(info.child)) break :align_blk null;
4864
+ break :align_blk std.mem.Alignment.fromByteUnits(declared);
4865
+ };
4866
+ const out = try allocator.allocWithOptions(info.child, value.len, alignment, comptime std.meta.sentinel(T));
4867
+ for (value, 0..) |element, index| out[index] = try deepCopyMsgValue(info.child, element, allocator, indirections + 1);
4868
+ break :blk out;
4869
+ },
4870
+ else => error.HoverCapturePayloadUnsupported,
4871
+ };
4872
+ }
4873
+
4874
+ fn hoverMsgViewLabel(self: *const Self) []const u8 {
4875
+ return self.hover_msg_view_label_storage[0..self.hover_msg_view_label_len];
4876
+ }
4877
+
4878
+ /// Deliver hover enter/leave Msgs owed since the last drain:
4879
+ /// diff the runtime's standing containment chain against the
4880
+ /// delivered mirror and dispatch the edges — leaves innermost
4881
+ /// first, then enters outermost first (the DOM's
4882
+ /// mouseleave/mouseenter order). Intermediate flickers within
4883
+ /// one event coalesce away: only the settled containment
4884
+ /// dispatches, which is what "discrete edges, never per-move"
4885
+ /// means under a fast pointer.
4886
+ fn drainHoverMsgs(self: *Self, runtime: *Runtime) anyerror!void {
4887
+ if (!self.installed) return;
4888
+ if (self.hover_msg_draining) return;
4889
+ self.hover_msg_draining = true;
4890
+ defer self.hover_msg_draining = false;
4891
+ // A pass's error degrades WITHOUT aborting the drain: its
4892
+ // mirror commit already happened, and the containment its
4893
+ // dispatches moved (an enter handler that unmounted itself)
4894
+ // still owes edges only a further pass can deliver. The
4895
+ // first error propagates after the loop, into the same
4896
+ // degraded handling every event handler gets.
4897
+ var first_error: ?anyerror = null;
4898
+ var passes: usize = 0;
4899
+ while (passes < hover_msg_drain_passes) : (passes += 1) {
4900
+ const progressed = self.stepHoverMsgs(runtime) catch |err| blk: {
4901
+ if (first_error == null) first_error = err;
4902
+ break :blk true;
4903
+ };
4904
+ if (!progressed) break;
4905
+ }
4906
+ if (first_error) |err| return err;
4907
+ }
4908
+
4909
+ /// One drain pass: resolve the view whose standing chain is
4910
+ /// live, compare it to the mirror, and — when they differ —
4911
+ /// dispatch the owed edges and commit the mirror. Returns
4912
+ /// whether it dispatched anything (the drain loop re-checks:
4913
+ /// a dispatched Msg's rebuild may have moved the chain again).
4914
+ ///
4915
+ /// One pointer means at most one view should hold a standing
4916
+ /// chain; if a host ever leaves two populated (a missing
4917
+ /// pointer-cancel on window switch), the mirror's own view
4918
+ /// wins while it stands — deterministic, never flapping.
4919
+ fn stepHoverMsgs(self: *Self, runtime: *Runtime) anyerror!bool {
4920
+ var standing_index: ?usize = null;
4921
+ for (runtime.views[0..runtime.view_count], 0..) |*view, index| {
4922
+ if (view.kind != .gpu_surface) continue;
4923
+ if (view.canvas_widget_hover_msg_chain_len == 0) continue;
4924
+ const is_mirror = view.window_id == self.hover_msg_window_id and
4925
+ std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
4926
+ if (is_mirror) {
4927
+ standing_index = index;
4928
+ break;
4929
+ }
4930
+ if (standing_index == null) standing_index = index;
4931
+ }
4932
+
4933
+ // The standing chain and the view identity it belongs to
4934
+ // (the mirror's own view when nothing stands anywhere:
4935
+ // its entries owe leaves against that view's tree). The
4936
+ // label is COPIED out of runtime view storage: the
4937
+ // dispatches below can close windows and compact the view
4938
+ // array, and a lookup through a reused label slice could
4939
+ // resolve another view's tree.
4940
+ var standing_window: platform.WindowId = self.hover_msg_window_id;
4941
+ var standing_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined;
4942
+ var standing_label_len: usize = @min(self.hover_msg_view_label_len, standing_label_storage.len);
4943
+ @memcpy(standing_label_storage[0..standing_label_len], self.hover_msg_view_label_storage[0..standing_label_len]);
4944
+ var standing_chain: [canvas.max_widget_depth]canvas.ObjectId = undefined;
4945
+ var standing_len: usize = 0;
4946
+ if (standing_index) |index| {
4947
+ const view = &runtime.views[index];
4948
+ standing_window = view.window_id;
4949
+ standing_label_len = @min(view.label.len, standing_label_storage.len);
4950
+ @memcpy(standing_label_storage[0..standing_label_len], view.label[0..standing_label_len]);
4951
+ standing_len = view.canvas_widget_hover_msg_chain_len;
4952
+ @memcpy(standing_chain[0..standing_len], view.canvas_widget_hover_msg_chain[0..standing_len]);
4953
+ }
4954
+ const standing_label: []const u8 = standing_label_storage[0..standing_label_len];
4955
+
4956
+ const same_view = standing_window == self.hover_msg_window_id and
4957
+ std.mem.eql(u8, standing_label, self.hoverMsgViewLabel());
4958
+ const mirror_len = self.hover_msg_chain_len;
4959
+
4960
+ // Handler bindings move with rebuilds: when the trees
4961
+ // changed since the standing captures were taken, refresh
4962
+ // every mirror entry's capture from its live tree — a leave
4963
+ // handler ADDED while the listener already stood must be
4964
+ // captured before an unmount needs it, and a changed
4965
+ // payload delivers its latest value. UPSERT only: an
4966
+ // element whose leave binding VANISHED keeps the previously
4967
+ // captured Msg (the standing enter was promised its pair;
4968
+ // unbinding never un-promises it). Runs before the settled
4969
+ // fast path below, which compares ids and would never see a
4970
+ // binding-only change.
4971
+ var first_error: ?anyerror = self.refreshHoverLeaveCaptures();
4972
+
4973
+ // The diff is a SET diff over listener ids, not a positional
4974
+ // one: containment is per listener, so an outer listener
4975
+ // unbinding (or binding) while an inner one stands must
4976
+ // dispatch edges for the changed id ONLY — the retained
4977
+ // entry keeps standing, its capture untouched in its slot.
4978
+ // A view change retains nothing (one pointer, one view).
4979
+ var retained_slots: [canvas.max_widget_depth]u8 = undefined;
4980
+ var entering_at: [canvas.max_widget_depth]bool = undefined;
4981
+ var entering_any = false;
4982
+ var identical = same_view and standing_len == mirror_len;
4983
+ for (standing_chain[0..standing_len], 0..) |id, position| {
4984
+ var slot: u8 = hover_msg_slot_none;
4985
+ var retained = false;
4986
+ if (same_view) {
4987
+ for (self.hover_msg_chain[0..mirror_len], 0..) |mirror_id, mirror_position| {
4988
+ if (mirror_id != id) continue;
4989
+ slot = self.hover_msg_slots[mirror_position];
4990
+ retained = true;
4991
+ if (mirror_position != position) identical = false;
4992
+ break;
4993
+ }
4994
+ }
4995
+ retained_slots[position] = slot;
4996
+ entering_at[position] = !retained;
4997
+ if (!retained) {
4998
+ entering_any = true;
4999
+ identical = false;
5000
+ }
5001
+ }
5002
+ if (identical) {
5003
+ if (first_error) |err| return err;
5004
+ return false;
5005
+ }
5006
+
5007
+ // Entering edges resolve through the DESTINATION view's
5008
+ // handler tree, and only a CURRENT one (`hoverTreeCurrentFor`): a
5009
+ // failed rebuild may have cleared it, or — worse — left a
5010
+ // tree standing whose build the runtime never adopted, and
5011
+ // resolving through that dispatches stale handlers or
5012
+ // consumes enters as absent. When it is not ready, the
5013
+ // enters DEFER (the standing chain keeps carrying them, so
5014
+ // the drain after the next successful rebuild retries)
5015
+ // while the leaves this transition owes still dispatch
5016
+ // below — their Msgs are owned captures, not tree lookups,
5017
+ // and a broken destination must never withhold them.
5018
+ const destination_ready = !entering_any or
5019
+ (self.hoverTreeCurrentFor(standing_window, standing_label) and self.hoverTreeFor(standing_window, standing_label) != null);
5020
+ if (!destination_ready) {
5021
+ var any_leaving = false;
5022
+ for (self.hover_msg_chain[0..mirror_len]) |id| {
5023
+ const still_standing = same_view and blk: {
5024
+ for (standing_chain[0..standing_len]) |candidate| {
5025
+ if (candidate == id) break :blk true;
5026
+ }
5027
+ break :blk false;
5028
+ };
5029
+ if (!still_standing) {
5030
+ any_leaving = true;
5031
+ break;
5032
+ }
5033
+ }
5034
+ // Nothing deliverable now: enters wait for a current
5035
+ // tree, retained entries stay put.
5036
+ if (!any_leaving) return false;
5037
+ }
5038
+
5039
+ // The leaves this pass owes — mirror ids absent from the
5040
+ // standing chain — innermost-first. Their captured Msgs own
5041
+ // their payload bytes (see `captureHoverLeave`), so the
5042
+ // rebuilds the dispatches below perform cannot invalidate
5043
+ // them. Ids and the OLD view identity ride along so a
5044
+ // capture that could not be owned can still resolve from
5045
+ // the live tree while its element stands.
5046
+ const leave_window = self.hover_msg_window_id;
5047
+ var leave_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined;
5048
+ const leave_label_len = self.hover_msg_view_label_len;
5049
+ @memcpy(leave_label_storage[0..leave_label_len], self.hover_msg_view_label_storage[0..leave_label_len]);
5050
+ var leave_ids: [canvas.max_widget_depth]canvas.ObjectId = undefined;
5051
+ var leave_slots: [canvas.max_widget_depth]u8 = undefined;
5052
+ var leave_count: usize = 0;
5053
+ var index = mirror_len;
5054
+ while (index > 0) {
5055
+ index -= 1;
5056
+ const id = self.hover_msg_chain[index];
5057
+ const still_standing = same_view and blk: {
5058
+ for (standing_chain[0..standing_len]) |candidate| {
5059
+ if (candidate == id) break :blk true;
5060
+ }
5061
+ break :blk false;
5062
+ };
5063
+ if (still_standing) continue;
5064
+ leave_ids[leave_count] = id;
5065
+ leave_slots[leave_count] = self.hover_msg_slots[index];
5066
+ leave_count += 1;
5067
+ }
5068
+
5069
+ // Commit the mirror before dispatching so a mid-dispatch
5070
+ // error can never re-deliver the same edges: standing ids in
5071
+ // standing order, retained entries keeping their slots,
5072
+ // entering entries slotless until their enter actually
5073
+ // dispatches below. The identity rewrite only runs on a view
5074
+ // CHANGE — when the view stood, `standing_label` was copied
5075
+ // from the mirror's own storage.
5076
+ if (!same_view) {
5077
+ self.hover_msg_window_id = standing_window;
5078
+ const label_len = @min(standing_label.len, self.hover_msg_view_label_storage.len);
5079
+ @memcpy(self.hover_msg_view_label_storage[0..label_len], standing_label[0..label_len]);
5080
+ self.hover_msg_view_label_len = label_len;
5081
+ }
5082
+ @memcpy(self.hover_msg_chain[0..standing_len], standing_chain[0..standing_len]);
5083
+ @memcpy(self.hover_msg_slots[0..standing_len], retained_slots[0..standing_len]);
5084
+ self.hover_msg_chain_len = standing_len;
5085
+ // A deferred entering side stays OUT of the mirror: the
5086
+ // standing chain still carries those ids, so the drain
5087
+ // after the next successful rebuild sees them entering and
5088
+ // delivers then.
5089
+ if (!destination_ready) self.unwindHoverEnters(&entering_at, 0);
5090
+
5091
+ // Deliver: leaves innermost-first, then enters
5092
+ // outermost-first; retained ids dispatch nothing. Each
5093
+ // dispatch degrades PER EDGE — an error is remembered and
5094
+ // the remaining edges still deliver (the mirror is already
5095
+ // committed, so an aborted batch could never be retried;
5096
+ // one failed rebuild must not swallow its siblings' edges)
5097
+ // — and the first error propagates after the batch, into
5098
+ // the same degraded handling every event handler gets.
5099
+ for (leave_ids[0..leave_count], leave_slots[0..leave_count]) |id, slot| {
5100
+ // A refused entry never entered: it owes nothing on
5101
+ // exit.
5102
+ if (slot == hover_msg_slot_refused) continue;
5103
+ // The capture wins (leave answers what enter announced);
5104
+ // an unowned capture falls back to the live tree while
5105
+ // its element still stands there.
5106
+ const captured: ?MsgT = if (slot >= hover_msg_slot_count) null else self.hover_msg_leave_msgs[slot];
5107
+ const msg = captured orelse blk: {
5108
+ if (!self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) break :blk null;
5109
+ const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]) orelse break :blk null;
5110
+ break :blk live.msgFor(id, .hover_leave);
5111
+ } orelse {
5112
+ self.releaseHoverSlot(slot);
5113
+ continue;
5114
+ };
5115
+ self.dispatch(runtime, leave_window, msg) catch |err| {
5116
+ if (first_error == null) first_error = err;
5117
+ };
5118
+ // The leave Msg was consumed synchronously: its slot
5119
+ // releases now instead of holding a payload copy until
5120
+ // some later hover reuses it.
5121
+ self.releaseHoverSlot(slot);
5122
+ }
5123
+ for (standing_chain[0..standing_len], 0..) |id, position| {
5124
+ if (!destination_ready) break;
5125
+ if (!entering_at[position]) continue;
5126
+ if (!self.hoverTreeCurrentFor(standing_window, standing_label)) {
5127
+ // An earlier edge's failed rebuild left this tree
5128
+ // stale mid-batch: the same deferral as above — drop
5129
+ // the unentered tail from the mirror and retry after
5130
+ // a rebuild lands.
5131
+ self.unwindHoverEnters(&entering_at, position);
5132
+ break;
5133
+ }
5134
+ // Resolve from the LIVE tree per edge: an earlier edge
5135
+ // in this batch may have rebuilt the view (payload
5136
+ // bytes are only promised for their own dispatch), and
5137
+ // its update may even have unmounted this element — a
5138
+ // vanished handler then dispatches no enter and owes no
5139
+ // leave. The paired leave is captured BEFORE the enter
5140
+ // dispatches, from the same tree that resolved it, so
5141
+ // an enter whose own handler unmounts the element still
5142
+ // has its leave to deliver.
5143
+ const live = self.hoverTreeFor(standing_window, standing_label) orelse {
5144
+ // A failed rebuild cleared the tree mid-batch: drop
5145
+ // the not-yet-entered ids from the mirror so the
5146
+ // next drain retries them once the tree returns (the
5147
+ // entering-with-no-tree deferral above then holds
5148
+ // the line instead of consuming enters as silence).
5149
+ self.unwindHoverEnters(&entering_at, position);
5150
+ break;
5151
+ };
5152
+ const enter_msg = live.msgFor(id, .hover_enter);
5153
+ if (live.msgFor(id, .hover_leave)) |leave_msg| {
5154
+ const slot = self.claimHoverSlot() orelse {
5155
+ // Pool pressure degrades like allocation
5156
+ // pressure: defer this id and the entering tail
5157
+ // to the next drain.
5158
+ self.unwindHoverEnters(&entering_at, position);
5159
+ if (first_error == null) first_error = error.OutOfMemory;
5160
+ break;
5161
+ };
5162
+ self.captureHoverLeave(slot, leave_msg) catch |err| switch (err) {
5163
+ error.OutOfMemory => {
5164
+ // Transient: an enter whose paired leave
5165
+ // cannot be owned must not dispatch — defer
5166
+ // this id and the rest of the entering tail
5167
+ // to the next drain instead of breaking the
5168
+ // pairing guarantee.
5169
+ self.releaseHoverSlot(slot);
5170
+ self.unwindHoverEnters(&entering_at, position);
5171
+ if (first_error == null) first_error = error.OutOfMemory;
5172
+ break;
5173
+ },
5174
+ error.HoverCapturePayloadUnsupported => {
5175
+ // Permanent: no copy can own this payload
5176
+ // (a single-item pointer), so the PAIR is
5177
+ // disabled — the enter is refused too,
5178
+ // once, loudly, and the entry settles as
5179
+ // refused instead of retrying every drain.
5180
+ self.releaseHoverSlot(slot);
5181
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5182
+ self.hover_msg_slots[position] = hover_msg_slot_refused;
5183
+ ui_app_log.warn("on_hover_leave payload cannot be owned (a single-item pointer): the hover pair is disabled for this element - bind a slice or scalar payload instead", .{});
5184
+ continue;
5185
+ },
5186
+ };
5187
+ // A mid-batch rebuild's capture refresh can have
5188
+ // filled this position's slot already (an earlier
5189
+ // edge's dispatch rebuilt): release it before the
5190
+ // fresh assignment so no slot ever leaks.
5191
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5192
+ self.hover_msg_slots[position] = slot;
5193
+ } else {
5194
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5195
+ self.hover_msg_slots[position] = hover_msg_slot_none;
5196
+ }
5197
+ if (enter_msg) |msg| {
5198
+ self.dispatch(runtime, standing_window, msg) catch |err| {
5199
+ if (first_error == null) first_error = err;
5200
+ };
5201
+ }
5202
+ }
5203
+ if (first_error) |err| return err;
5204
+ return true;
5205
+ }
5206
+
5207
+ /// Drop the not-yet-entered entering ids (positions >= `from`
5208
+ /// with `entering_at` set) from the committed mirror, compacting
5209
+ /// ids and slots in lockstep: the standing chain still carries
5210
+ /// them, so a later drain — once the tree (or memory) is back —
5211
+ /// sees them as entering again and retries. Their positions hold
5212
+ /// no capture slots yet, so nothing needs releasing.
5213
+ fn unwindHoverEnters(self: *Self, entering_at: *const [canvas.max_widget_depth]bool, from: usize) void {
5214
+ var kept: usize = 0;
5215
+ for (0..self.hover_msg_chain_len) |position| {
5216
+ if (position >= from and entering_at[position]) {
5217
+ // A mid-batch capture refresh can have filled this
5218
+ // never-entered position's slot: release it so an
5219
+ // unwound enter never leaks its claim.
5220
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5221
+ continue;
5222
+ }
5223
+ self.hover_msg_chain[kept] = self.hover_msg_chain[position];
5224
+ self.hover_msg_slots[kept] = self.hover_msg_slots[position];
5225
+ kept += 1;
5226
+ }
5227
+ self.hover_msg_chain_len = kept;
5228
+ }
5229
+
5230
+ /// Re-render the house video chrome from the moved channel
5231
+ /// mirrors, everywhere it shows: the main canvas rebuilds
5232
+ /// against ITS window (never a control event's origin window —
5233
+ /// the main canvas label resolves only there), and the window
5234
+ /// slots rebuild after it, so a `<video controls>` declared in
5235
+ /// a secondary window's tree repaints too — `dispatch`'s exact
5236
+ /// rebuild discipline, minus the Msg.
5237
+ fn rebuildVideoChrome(self: *Self, runtime: *Runtime) anyerror!void {
5238
+ self.publishAudioState(runtime);
5239
+ try self.rebuild(runtime, self.canvas_window_id);
5240
+ try self.rebuildWindowSlots(runtime);
5241
+ }
5242
+
5243
+ /// Activate the house transport's play/pause control — the
5244
+ /// runtime-consumed action both the pointer release and the
5245
+ /// keyboard control intent (Enter/Space on the focused button)
5246
+ /// resolve to: no app Msg exists, the video channel is driven
5247
+ /// directly and the chrome re-renders from the moved mirrors.
5248
+ fn toggleVideoControl(self: *Self, runtime: *Runtime) anyerror!void {
5249
+ const snapshot = self.effects.videoSnapshot();
5250
+ if (snapshot.playing) {
5251
+ self.effects.pauseVideo();
5252
+ } else if (snapshot.completed) {
5253
+ // The natural end retired the player, so play would
5254
+ // refuse with one `.failed` — a broken answer to a
5255
+ // valid control. Play on a finished playback means
5256
+ // from-the-start: a fresh load of the same source. The
5257
+ // restart mints a fresh load identity, so declarative
5258
+ // ownership re-captures it (`video_declared_token`) —
5259
+ // the reconciler must keep recognizing the playback it
5260
+ // started, or removal and flag deltas would go dead
5261
+ // after a replay-from-end.
5262
+ const declared = self.video_declared_token != 0 and
5263
+ self.effects.videoOwnerToken() == self.video_declared_token;
5264
+ self.effects.restartVideo();
5265
+ if (declared) self.video_declared_token = self.effects.videoOwnerToken();
5266
+ } else {
5267
+ self.effects.playVideo();
5268
+ }
5269
+ try self.rebuildVideoChrome(runtime);
5270
+ }
5271
+
3364
5272
  fn disarmHold(self: *Self, runtime: *Runtime) void {
3365
5273
  if (self.hold_armed_id != 0 and !self.hold_fired) runtime.cancelTimer(press_hold_timer_id) catch {};
3366
5274
  self.hold_armed_id = 0;
@@ -3452,13 +5360,138 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3452
5360
  }
3453
5361
  if (tree.findWidget(target.id)) |widget| {
3454
5362
  if (!widget.state.disabled) {
5363
+ // A focused BOUND terminal owns its keys the way
5364
+ // an editable text widget owns typing: specials
5365
+ // and chords encode through the session's
5366
+ // emulator toward the pty; consumed either way so
5367
+ // the app-level key fallback can never fire while
5368
+ // the user is driving the terminal. An ended
5369
+ // session declines, and the key falls through
5370
+ // (an app may bind a restart chord).
5371
+ if (widget.kind == .terminal and widget.terminal.pty != 0) {
5372
+ // Focus traversal/spatial navigation routes
5373
+ // the arriving key to the NEW target. That
5374
+ // key moved focus; it is not terminal input
5375
+ // (Tabbing into a terminal must not also
5376
+ // complete at the shell prompt). Once the
5377
+ // terminal already owns focus, the focus pass
5378
+ // leaves Tab in place and this flag is false,
5379
+ // so Tab/Shift+Tab encode normally below.
5380
+ if (keyboard_event.keyboard.focus_moved) return;
5381
+ // The runtime clipboard pass already copied
5382
+ // this emulator selection. Do not forward the
5383
+ // same Cmd/Ctrl+C chord to the child (where
5384
+ // Ctrl+C would be an interrupt).
5385
+ const copy_chord = (keyboard_event.keyboard.phase == .key_down or keyboard_event.keyboard.phase == .key_up) and
5386
+ keyboard_event.keyboard.modifiers.hasCommandModifier() and
5387
+ !keyboard_event.keyboard.modifiers.alt and
5388
+ !keyboard_event.keyboard.modifiers.shift and
5389
+ std.ascii.eqlIgnoreCase(keyboard_event.keyboard.key, "c");
5390
+ if (copy_chord) {
5391
+ if (widget.terminal.grid) |grid| {
5392
+ if (grid.selection_active) return;
5393
+ }
5394
+ }
5395
+ if (self.terminal_sessions.keyEvent(widget.terminal.pty, keyboard_event.keyboard)) {
5396
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5397
+ return;
5398
+ }
5399
+ }
3455
5400
  if (canvas.isWidgetTextEntry(widget)) return;
3456
- if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard) != null) return;
5401
+ if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard)) |intent| {
5402
+ // Keyboard activation of the house video
5403
+ // transport's play/pause control drives the
5404
+ // channel exactly like the pointer release
5405
+ // — the control advertises Play/Pause to
5406
+ // focus and accessibility, so Enter/Space
5407
+ // must act, not be consumed silently.
5408
+ if (widget.video_control == .toggle and intent.kind == .press) {
5409
+ try self.toggleVideoControl(runtime);
5410
+ }
5411
+ // The seek slider's keyboard and assistive
5412
+ // steps land here as set_value intents —
5413
+ // no widget change event exists on these
5414
+ // paths — so the step maps its fraction
5415
+ // onto the duration and drives the channel,
5416
+ // the pointer scrub's exact rule; consuming
5417
+ // it silently would move the thumb
5418
+ // optimistically and let the next tick
5419
+ // snap it back.
5420
+ if (widget.video_control == .scrub and intent.kind == .set_value) {
5421
+ if (intent.value) |fraction| {
5422
+ const snap = self.effects.videoSnapshot();
5423
+ if (snap.duration_ms > 0) {
5424
+ self.effects.seekVideo(@intFromFloat(std.math.clamp(@as(f64, fraction), 0, 1) * @as(f64, @floatFromInt(snap.duration_ms))));
5425
+ }
5426
+ try self.rebuildVideoChrome(runtime);
5427
+ }
5428
+ }
5429
+ return;
5430
+ }
5431
+ }
5432
+ }
5433
+ }
5434
+ if (keyboard_event.keyboard.phase == .text_input) {
5435
+ // A focused BOUND terminal consumes committed text ahead
5436
+ // of the app-level `on_text` seam — the typing channel
5437
+ // the terminal element promises (IME results included;
5438
+ // the runtime already gates this dispatch to committed
5439
+ // insertions). Text arrives TARGET-LESS here because the
5440
+ // terminal deliberately stays out of the TextBuffer
5441
+ // pipeline; the stamped focused id names it.
5442
+ if (comptime terminal_session.enabled) {
5443
+ if (keyboard_event.keyboard.focused_id) |focused_id| {
5444
+ if (tree.findWidget(focused_id)) |widget| {
5445
+ if (widget.kind == .terminal and widget.terminal.pty != 0) {
5446
+ const edit = keyboard_event.keyboard.textEditEvent() orelse return;
5447
+ if (edit != .insert_text) return;
5448
+ if (keyboard_event.terminal_paste) {
5449
+ // Clipboard paste is provenance-
5450
+ // sensitive terminal input: the
5451
+ // session must apply bracketed-paste
5452
+ // framing and paste sanitization.
5453
+ // Consume it even when the session
5454
+ // ended between presentation and
5455
+ // dispatch; clipboard bytes addressed
5456
+ // to a terminal must never leak to the
5457
+ // app-level `on_text` fallback.
5458
+ if (self.terminal_sessions.pasteInput(widget.terminal.pty, edit.insert_text)) {
5459
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5460
+ }
5461
+ return;
5462
+ }
5463
+ if (self.terminal_sessions.textInput(widget.terminal.pty, edit.insert_text)) {
5464
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5465
+ return;
5466
+ }
5467
+ }
5468
+ }
3457
5469
  }
3458
5470
  }
5471
+ // A provenance-tagged terminal paste is terminal-addressed
5472
+ // even when no enabled emulator is wired in this build.
5473
+ // Never leak its clipboard bytes to app-level `on_text`.
5474
+ if (keyboard_event.terminal_paste) return;
5475
+ const text_map = self.options.on_text orelse return;
5476
+ // COMMITTED text only. An IME preedit (`set_composition`)
5477
+ // or a cancel is provisional and must never reach a
5478
+ // consumer with no editor state (a terminal) — otherwise
5479
+ // a composition-in-progress routed through a focused
5480
+ // non-text widget would type bytes the user has not
5481
+ // committed and cannot retract. `insert_text` is the
5482
+ // committed insertion (a plain text_input, or the
5483
+ // resolved commit the host delivers as text); every
5484
+ // other edit kind is skipped here.
5485
+ const edit = keyboard_event.keyboard.textEditEvent() orelse return;
5486
+ if (edit != .insert_text) return;
5487
+ if (text_map(keyboard_event.keyboard)) |msg| {
5488
+ try self.dispatch(runtime, keyboard_event.window_id, msg);
5489
+ }
5490
+ return;
3459
5491
  }
3460
5492
  const map = self.options.on_key orelse return;
3461
- if (keyboard_event.keyboard.phase != .key_down) return;
5493
+ const release = keyboard_event.keyboard.phase == .key_up and self.options.key_release_events;
5494
+ if (keyboard_event.keyboard.phase != .key_down and !release) return;
3462
5495
  if (map(keyboard_event.keyboard)) |msg| {
3463
5496
  try self.dispatch(runtime, keyboard_event.window_id, msg);
3464
5497
  }
@@ -3491,6 +5524,70 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3491
5524
  }
3492
5525
  }
3493
5526
 
5527
+ /// Wheel scrollback over a bound `<terminal>`: natural
5528
+ /// direction, like every terminal — the gesture belongs to the
5529
+ /// widget under the pointer, so it consumes the event ahead of
5530
+ /// the app-level `on_wheel` seam (widget precedence). The
5531
+ /// applied position reports through `on-terminal` like every
5532
+ /// runtime-applied view-state change, and the Msg rides the
5533
+ /// same journaled input event, so a recorded scroll replays to
5534
+ /// the identical viewport. Returns whether a terminal consumed
5535
+ /// the wheel.
5536
+ fn handleTerminalWheel(self: *Self, runtime: *Runtime, input_event: platform.GpuSurfaceInputEvent) anyerror!bool {
5537
+ if (comptime !terminal_session.enabled) return false;
5538
+ if (input_event.kind != .scroll) return false;
5539
+ if (input_event.delta_y == 0) return false;
5540
+ const layout = runtime.canvasWidgetLayout(input_event.window_id, input_event.label) catch return false;
5541
+ const point = geometry.PointF.init(input_event.x, input_event.y);
5542
+ // The TOPMOST bound terminal under the pointer (later nodes
5543
+ // paint over earlier ones).
5544
+ var target: ?canvas.WidgetLayoutNode = null;
5545
+ for (layout.nodes) |node| {
5546
+ if (node.widget.kind != .terminal) continue;
5547
+ if (node.widget.terminal.pty == 0) continue;
5548
+ if (!node.frame.normalized().containsPoint(point)) continue;
5549
+ target = node;
5550
+ }
5551
+ const node = target orelse return false;
5552
+ if (!self.terminal_sessions.hasSession(node.widget.terminal.pty)) return false;
5553
+ if (self.terminal_sessions.wheel(node.widget.terminal.pty, input_event.delta_y)) {
5554
+ try self.repaintTerminals(runtime, input_event.window_id);
5555
+ if (self.terminal_sessions.currentState(node.widget.terminal.pty)) |state| {
5556
+ if (self.treeForViewLabel(input_event.label)) |tree| {
5557
+ if (tree.msgForTerminal(node.widget.id, state)) |msg| {
5558
+ try self.dispatch(runtime, input_event.window_id, msg);
5559
+ }
5560
+ }
5561
+ }
5562
+ }
5563
+ // Over a bound terminal the gesture is the terminal's even
5564
+ // when the viewport is already pinned — the app wheel seam
5565
+ // must not double-consume it.
5566
+ return true;
5567
+ }
5568
+
5569
+ /// Wheel/trackpad scrolls reach the app as the pinch channel's
5570
+ /// sibling (`Options.on_wheel`): the raw `.scroll` kind of the
5571
+ /// gpu-surface input surface, for apps whose content scrolls
5572
+ /// without a scroll-region widget (a terminal's scrollback).
5573
+ /// The Msg dispatch rides the same journaled input event, so a
5574
+ /// recorded scroll replays to the identical model.
5575
+ fn handleWheel(self: *Self, runtime: *Runtime, input_event: platform.GpuSurfaceInputEvent) anyerror!void {
5576
+ const map = self.options.on_wheel orelse return;
5577
+ if (input_event.kind != .scroll) return;
5578
+ if (map(.{
5579
+ .window_id = input_event.window_id,
5580
+ .label = input_event.label,
5581
+ .delta_x = input_event.delta_x,
5582
+ .delta_y = input_event.delta_y,
5583
+ .x = input_event.x,
5584
+ .y = input_event.y,
5585
+ .modifiers = input_event.modifiers,
5586
+ })) |msg| {
5587
+ try self.dispatch(runtime, input_event.window_id, msg);
5588
+ }
5589
+ }
5590
+
3494
5591
  /// Split-fraction changes route through the split's `on_resize`
3495
5592
  /// constructor. The payload is the fraction the runtime already
3496
5593
  /// applied, so a model that stores it and echoes it back into
@@ -3511,6 +5608,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3511
5608
  /// on it, the same contract keyboard slider steps follow.
3512
5609
  fn handleWidgetChange(self: *Self, runtime: *Runtime, change_event: core.CanvasWidgetChangeEvent) anyerror!void {
3513
5610
  const tree = self.treeForViewLabel(change_event.view_label) orelse return;
5611
+ // House video chrome is runtime-consumed: a change on the
5612
+ // transport's seek slider maps its 0..1 fraction onto the
5613
+ // playback's duration and seeks the channel directly (no
5614
+ // app Msg exists to resolve). A duration-less playback (not
5615
+ // loaded yet) seeks nowhere honestly.
5616
+ if (tree.findWidget(change_event.id)) |widget| {
5617
+ if (widget.video_control == .scrub) {
5618
+ const snap = self.effects.videoSnapshot();
5619
+ if (snap.duration_ms > 0) {
5620
+ const fraction: f64 = std.math.clamp(change_event.value, 0, 1);
5621
+ self.effects.seekVideo(@intFromFloat(fraction * @as(f64, @floatFromInt(snap.duration_ms))));
5622
+ }
5623
+ try self.rebuildVideoChrome(runtime);
5624
+ return;
5625
+ }
5626
+ }
3514
5627
  if (tree.msgForChange(change_event.id, change_event.value)) |msg| {
3515
5628
  try self.dispatch(runtime, change_event.window_id, msg);
3516
5629
  }
@@ -3555,16 +5668,156 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3555
5668
  }
3556
5669
  }
3557
5670
 
3558
- /// A native context-menu selection: resolve the selected
3559
- /// item's declared `Msg` through the tree's handler table.
5671
+ /// The runtime handed a widget's declared menu to the native
5672
+ /// presenter: capture the shown items' dispatch Msgs (by value)
5673
+ /// keyed by the request's token, and PIN the build-arena
5674
+ /// generation the presented tree was built from — the payloads'
5675
+ /// slices stay valid, at their original addresses, however many
5676
+ /// rebuilds the open menu outlives (`context_menu_pin`).
5677
+ /// Selection resolves from this snapshot, so the user always
5678
+ /// gets the item they SAW even when the tree rebuilds under the
5679
+ /// open menu. A new presentation supersedes the previous pin.
5680
+ fn handleContextMenuShown(self: *Self, runtime: *Runtime, shown_event: core.CanvasWidgetContextMenuShownEvent) anyerror!void {
5681
+ // A pinned rebuild failure may have dropped the live tree
5682
+ // while the previous menu was open. This shown event
5683
+ // PROMISES a snapshot for the replacement menu, so restore
5684
+ // the tree first — silently arming nothing would leave the
5685
+ // presented menu's selection to fall through a null tree
5686
+ // and dispatch no message.
5687
+ if (self.treeForViewLabel(shown_event.view_label) == null) try self.restoreMissingTree(runtime);
5688
+ const tree = self.treeForViewLabel(shown_event.view_label) orelse return;
5689
+ const count = @min(shown_event.item_count, self.context_menu_shown_msgs.len);
5690
+ for (0..count) |item_index| {
5691
+ self.context_menu_shown_msgs[item_index] = tree.msgForContextMenu(shown_event.target_id, item_index);
5692
+ }
5693
+ self.context_menu_shown_token = shown_event.token;
5694
+ self.context_menu_shown_count = count;
5695
+ self.context_menu_pin = if (std.mem.eql(u8, shown_event.view_label, self.options.canvas_label))
5696
+ .{ .window_id = null, .arena_index = self.arena_index }
5697
+ else if (self.windowSlotByCanvasLabel(shown_event.view_label)) |slot|
5698
+ .{ .window_id = slot.window_id, .arena_index = slot.arena_index }
5699
+ else
5700
+ null;
5701
+ }
5702
+
5703
+ /// The arena index this canvas's next rebuild must use:
5704
+ /// normally the pair alternates, but while the presented menu's
5705
+ /// pin holds one generation of THIS canvas (matched by stable
5706
+ /// window identity, null = the main canvas), every rebuild
5707
+ /// routes through the partner arena instead — consecutive
5708
+ /// builds reset and reuse one side while the pinned side stays
5709
+ /// frozen, exactly the cadence the clearance-retry pass already
5710
+ /// runs within a single rebuild. Memory under an open menu is
5711
+ /// therefore bounded at two trees, however many rebuilds occur.
5712
+ fn contextMenuRebuildIndex(self: *const Self, window_id: ?platform.WindowId, current_index: usize) usize {
5713
+ const natural = current_index ^ 1;
5714
+ const pin = self.context_menu_pin orelse return natural;
5715
+ if (pin.arena_index != natural) return natural;
5716
+ const matches = if (pin.window_id) |pin_window|
5717
+ (window_id orelse return natural) == pin_window
5718
+ else
5719
+ window_id == null;
5720
+ return if (matches) natural ^ 1 else natural;
5721
+ }
5722
+
5723
+ /// Window teardown for the pin's owner: the slot's arenas are
5724
+ /// about to deinit (and another slot swap-moves into its index),
5725
+ /// so a snapshot presented from this window must disarm NOW —
5726
+ /// a stale pin would otherwise keep steering the reused slot's
5727
+ /// rebuild cadence around a generation that no longer exists.
5728
+ fn releaseContextMenuSnapshotForWindow(self: *Self, window_id: platform.WindowId) void {
5729
+ const pin = self.context_menu_pin orelse return;
5730
+ const pin_window = pin.window_id orelse return;
5731
+ if (pin_window == window_id) self.releaseContextMenuSnapshot();
5732
+ }
5733
+
5734
+ /// Disarm the presented-menu snapshot and release the pinned
5735
+ /// build generation. Every way a request ends comes through
5736
+ /// here: selection (after its dispatch), the runtime's
5737
+ /// dismissed notice, an out-of-range selection swallow, and the
5738
+ /// pin-owning window's teardown.
5739
+ fn releaseContextMenuSnapshot(self: *Self) void {
5740
+ self.context_menu_shown_token = 0;
5741
+ self.context_menu_shown_count = 0;
5742
+ self.context_menu_pin = null;
5743
+ }
5744
+
5745
+ /// The presented menu closed without a selection: a stale
5746
+ /// token's notice is ignored (a superseding presentation
5747
+ /// already replaced the snapshot and the pin).
5748
+ fn handleContextMenuDismissed(self: *Self, runtime: *Runtime, dismissed_event: core.CanvasWidgetContextMenuDismissedEvent) anyerror!void {
5749
+ if (dismissed_event.token == 0 or dismissed_event.token != self.context_menu_shown_token) return;
5750
+ self.releaseContextMenuSnapshot();
5751
+ try self.restoreMissingTree(runtime);
5752
+ }
5753
+
5754
+ /// A pinned rebuild failure dropped a live tree (`rebuild`'s
5755
+ /// live-arena guard) while its menu stayed on the glass, and
5756
+ /// the request just resolved WITHOUT a Msg dispatch (dismissal,
5757
+ /// an out-of-range swallow, an unmapped item): restore the tree
5758
+ /// now. No Msg-driven rebuild is coming, and with no handler
5759
+ /// table every pointer, keyboard, and scroll event silently
5760
+ /// no-ops until an unrelated resize, timer, or effect happens
5761
+ /// to rebuild.
5762
+ fn restoreMissingTree(self: *Self, runtime: *Runtime) anyerror!void {
5763
+ if (!self.installed) return;
5764
+ var missing = self.tree == null;
5765
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
5766
+ if (slot.installed and slot.tree == null) missing = true;
5767
+ }
5768
+ if (missing) try self.rebuildAllViews(runtime);
5769
+ }
5770
+
5771
+ /// A native context-menu selection: resolve the selected item's
5772
+ /// declared `Msg`. A selection carrying the presented snapshot's
5773
+ /// token resolves from the snapshot (what the user saw); only a
5774
+ /// snapshot-less dispatch — the automation verb, which validates
5775
+ /// against the live tree itself — resolves through the tree's
5776
+ /// handler table.
3560
5777
  fn handleContextMenu(self: *Self, runtime: *Runtime, menu_event: core.CanvasWidgetContextMenuEvent) anyerror!void {
3561
- const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
3562
5778
  // A selection on this menu closes it whatever the source: an
3563
5779
  // automation-invoked selection while the fallback surface is
3564
5780
  // open must not leave the surface mounted.
3565
5781
  if (self.context_menu_fallback_target == menu_event.target_id) {
3566
5782
  self.clearContextMenuFallback();
3567
5783
  }
5784
+ if (menu_event.token != 0 and menu_event.token == self.context_menu_shown_token) {
5785
+ const count = self.context_menu_shown_count;
5786
+ // The request is consumed on every path out of this
5787
+ // block — resolved, out-of-range, or a failed dispatch.
5788
+ defer self.releaseContextMenuSnapshot();
5789
+ if (menu_event.item_index < count) {
5790
+ if (self.context_menu_shown_msgs[menu_event.item_index]) |msg| {
5791
+ // The Msg is stored by value and its pinned-arena
5792
+ // payload slices are consumed by `update` itself;
5793
+ // the rebuild that follows reads only the model.
5794
+ // Release the pin BEFORE the dispatch: nothing
5795
+ // resets the pinned arena until the rebuild, and
5796
+ // the rebuild then routes into the partner arena
5797
+ // naturally — so a Msg whose update pushes the
5798
+ // model past a build budget fails the rebuild
5799
+ // WITHOUT resetting the live arena underneath it.
5800
+ // Input keeps working on the previous tree, and
5801
+ // the app's controls can recover the model —
5802
+ // production's degraded-error contract.
5803
+ self.releaseContextMenuSnapshot();
5804
+ try self.dispatch(runtime, menu_event.window_id, msg);
5805
+ return;
5806
+ }
5807
+ }
5808
+ // Swallowed without a Msg (out of range, or an item the
5809
+ // presented tree never mapped): no dispatch rebuilds, so
5810
+ // restore a live tree a failed pinned rebuild dropped.
5811
+ try self.restoreMissingTree(runtime);
5812
+ return;
5813
+ }
5814
+ // Snapshot-less resolution (the automation verb, or a menu
5815
+ // whose shown event could not arm — its restore attempt
5816
+ // failed while the model was unbuildable): the model may
5817
+ // have recovered since, so restore a dropped tree before
5818
+ // resolving rather than silently dispatching nothing.
5819
+ if (self.treeForViewLabel(menu_event.view_label) == null) try self.restoreMissingTree(runtime);
5820
+ const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
3568
5821
  if (tree.msgForContextMenu(menu_event.target_id, menu_event.item_index)) |msg| {
3569
5822
  try self.dispatch(runtime, menu_event.window_id, msg);
3570
5823
  }
@@ -3581,6 +5834,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3581
5834
  self.context_menu_fallback_label_len = label_len;
3582
5835
  self.context_menu_fallback_window_id = request_event.window_id;
3583
5836
  self.context_menu_fallback_target = request_event.target_id;
5837
+ self.context_menu_fallback_point = request_event.point;
3584
5838
  try self.rebuildAllViews(runtime);
3585
5839
  }
3586
5840
 
@@ -3675,3 +5929,20 @@ fn effectsQuitApp(context: *anyopaque) bool {
3675
5929
  runtime.quitApp() catch return false;
3676
5930
  return true;
3677
5931
  }
5932
+
5933
+ /// The build storage pinned under a presented native context menu:
5934
+ /// which canvas's arena pair and which generation (index) of that pair
5935
+ /// built the presented tree. The canvas is named by STABLE window
5936
+ /// identity (`window_id` null = the main canvas), never by slot index —
5937
+ /// removing a window swap-moves another slot into its place, and an
5938
+ /// index-keyed pin would start protecting the wrong arena. While set,
5939
+ /// rebuilds of that canvas route through the PARTNER arena
5940
+ /// (`contextMenuRebuildIndex`), so the pinned generation stays
5941
+ /// untouched — the snapshot's Msg payloads keep their original storage
5942
+ /// and pointer identity — and memory holds at two trees (the pinned
5943
+ /// one plus the partner, reset on its normal cadence) however long the
5944
+ /// menu stays open.
5945
+ const ContextMenuPin = struct {
5946
+ window_id: ?platform.WindowId,
5947
+ arena_index: usize,
5948
+ };