@native-sdk/cli 0.5.2 → 0.5.3

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 (82) hide show
  1. package/build.zig +41 -0
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/events.ts +39 -2
  6. package/packages/core/src/checker.ts +1 -1
  7. package/packages/core/src/emitter.ts +39 -3
  8. package/packages/core/src/infer.ts +53 -7
  9. package/skill-data/automation/SKILL.md +7 -4
  10. package/skill-data/core/references/app-model-runtime.md +3 -0
  11. package/skill-data/native-ui/SKILL.md +1 -0
  12. package/src/app_runner/root.zig +25 -0
  13. package/src/automation/protocol.zig +20 -1
  14. package/src/embed/host.zig +27 -0
  15. package/src/embed/tests.zig +69 -0
  16. package/src/embed/ui_host.zig +4 -0
  17. package/src/platform/macos/appkit_host.h +11 -0
  18. package/src/platform/macos/appkit_host.m +130 -0
  19. package/src/platform/macos/root.zig +34 -0
  20. package/src/platform/null_platform_tests.zig +39 -0
  21. package/src/platform/root.zig +3 -0
  22. package/src/platform/types.zig +109 -4
  23. package/src/primitives/canvas/chart.zig +7 -7
  24. package/src/primitives/canvas/chart_tests.zig +66 -0
  25. package/src/primitives/canvas/commands.zig +48 -0
  26. package/src/primitives/canvas/events.zig +161 -0
  27. package/src/primitives/canvas/font_ttf.zig +155 -8
  28. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  29. package/src/primitives/canvas/reference.zig +67 -8
  30. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  31. package/src/primitives/canvas/root.zig +25 -0
  32. package/src/primitives/canvas/ui.zig +35 -2
  33. package/src/primitives/canvas/ui_markup.zig +24 -0
  34. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  35. package/src/primitives/canvas/ui_markup_compiled.zig +40 -3
  36. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  37. package/src/primitives/canvas/ui_markup_contract.zig +9 -0
  38. package/src/primitives/canvas/ui_markup_contract_tests.zig +24 -0
  39. package/src/primitives/canvas/ui_markup_tests.zig +26 -0
  40. package/src/primitives/canvas/ui_markup_view.zig +53 -4
  41. package/src/primitives/canvas/ui_markup_view_tests.zig +73 -2
  42. package/src/primitives/canvas/ui_schema.zig +16 -0
  43. package/src/primitives/canvas/ui_schema_tests.zig +10 -11
  44. package/src/primitives/canvas/ui_tests.zig +31 -0
  45. package/src/primitives/canvas/vector.zig +258 -141
  46. package/src/primitives/canvas/widget_access.zig +1 -1
  47. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  48. package/src/primitives/canvas/widget_layout.zig +9 -4
  49. package/src/primitives/canvas/widget_render.zig +78 -40
  50. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  51. package/src/primitives/canvas/widget_semantics.zig +6 -1
  52. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  53. package/src/primitives/canvas/widget_text_input.zig +118 -10
  54. package/src/primitives/canvas/widgets.zig +16 -0
  55. package/src/root.zig +5 -0
  56. package/src/runtime/api.zig +13 -0
  57. package/src/runtime/automation_commands.zig +33 -0
  58. package/src/runtime/automation_widget_dispatch.zig +64 -0
  59. package/src/runtime/canvas_font_tests.zig +272 -3
  60. package/src/runtime/canvas_fonts.zig +60 -20
  61. package/src/runtime/canvas_frame_helpers.zig +15 -0
  62. package/src/runtime/canvas_image_tests.zig +26 -0
  63. package/src/runtime/canvas_images.zig +33 -7
  64. package/src/runtime/canvas_limits.zig +44 -8
  65. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  66. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  67. package/src/runtime/canvas_widget_events.zig +24 -4
  68. package/src/runtime/canvas_widget_runtime.zig +24 -7
  69. package/src/runtime/canvas_widget_state.zig +6 -1
  70. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  71. package/src/runtime/core.zig +98 -6
  72. package/src/runtime/flow.zig +27 -0
  73. package/src/runtime/gpu_surface_events.zig +7 -0
  74. package/src/runtime/media_surface.zig +726 -0
  75. package/src/runtime/media_surface_tests.zig +1476 -0
  76. package/src/runtime/root.zig +9 -0
  77. package/src/runtime/session_journal.zig +30 -3
  78. package/src/runtime/session_tests.zig +126 -4
  79. package/src/runtime/tests.zig +1 -0
  80. package/src/runtime/ts_ui_app.zig +56 -0
  81. package/src/runtime/ui_app.zig +58 -0
  82. package/src/runtime/ui_app_tests.zig +334 -0
@@ -140,6 +140,12 @@ pub fn canvasWidgetPointerEventFromGpuInput(input_event: GpuSurfaceInputEvent) ?
140
140
  .ime_set_composition,
141
141
  .ime_commit_composition,
142
142
  .ime_cancel_composition,
143
+ // Pinch is not a widget pointer gesture: it reaches the app as
144
+ // the raw `gpu_surface_input` event (timeline/canvas zoom is an
145
+ // app-level concern, not a widget press/scroll).
146
+ .pinch_begin,
147
+ .pinch_change,
148
+ .pinch_end,
143
149
  => return null,
144
150
  };
145
151
  return .{
@@ -163,6 +169,9 @@ pub fn canvasWidgetInputBatchesDisplayListRefresh(kind: platform.GpuSurfaceInput
163
169
  .ime_set_composition,
164
170
  .ime_commit_composition,
165
171
  .ime_cancel_composition,
172
+ .pinch_begin,
173
+ .pinch_change,
174
+ .pinch_end,
166
175
  => true,
167
176
  };
168
177
  }
@@ -181,6 +190,9 @@ pub fn canvasWidgetKeyboardEventFromGpuInput(input_event: GpuSurfaceInputEvent,
181
190
  .ime_set_composition,
182
191
  .ime_commit_composition,
183
192
  .ime_cancel_composition,
193
+ .pinch_begin,
194
+ .pinch_change,
195
+ .pinch_end,
184
196
  => return null,
185
197
  };
186
198
  return .{
@@ -221,6 +233,9 @@ fn canvasWidgetTextEditEventFromGpuInput(input_event: GpuSurfaceInputEvent) ?can
221
233
  .pointer_move,
222
234
  .pointer_drag,
223
235
  .scroll,
236
+ .pinch_begin,
237
+ .pinch_change,
238
+ .pinch_end,
224
239
  => null,
225
240
  };
226
241
  }
@@ -207,6 +207,32 @@ test "registerCanvasImageBytes decodes through the platform seam" {
207
207
  try std.testing.expectError(error.InvalidImageId, harness.runtime.registerCanvasImageBytes(0, encoded));
208
208
  }
209
209
 
210
+ test "registerCanvasImageBytes refuses reserved media-surface ids before decoding" {
211
+ const harness = try startedGpuHarness(std.testing.allocator);
212
+ defer harness.destroy(std.testing.allocator);
213
+ var app_state: RegistryApp = .{};
214
+ try harness.start(app_state.app());
215
+ harness.null_platform.image_decode = true;
216
+
217
+ const fixture = [_]u8{ 255, 0, 0, 255 };
218
+ var encoded_buffer: [1024]u8 = undefined;
219
+ var writer = std.Io.Writer.fixed(&encoded_buffer);
220
+ try canvas.png.writeRgba8(&writer, 1, 1, &fixture);
221
+ const encoded = writer.buffered();
222
+
223
+ // An id inside the reserved media-surface texture namespace is
224
+ // refused as an invalid id — not surfaced as a codec error — and
225
+ // the refusal happens before the platform decoder ever runs.
226
+ const reserved_id: canvas.ImageId = canvas.media_surface_image_id_bit | 9;
227
+ try std.testing.expectError(error.InvalidImageId, harness.runtime.registerCanvasImageBytes(reserved_id, encoded));
228
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.image_decode_count);
229
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.registeredCanvasImageCount());
230
+
231
+ // The same bytes under an ordinary id decode and register fine.
232
+ _ = try harness.runtime.registerCanvasImageBytes(9, encoded);
233
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.image_decode_count);
234
+ }
235
+
210
236
  // ---------------------------------------------------------------- avatar app
211
237
 
212
238
  const avatar_canvas_label = "avatar-canvas";
@@ -28,6 +28,7 @@ const canvas = @import("canvas");
28
28
  const canvas_frame_module = @import("canvas_frame.zig");
29
29
  const canvas_limits = @import("canvas_limits.zig");
30
30
  const effects_mod = @import("effects.zig");
31
+ const runtime_media_surface = @import("media_surface.zig");
31
32
 
32
33
  pub const max_registered_canvas_images = canvas_limits.max_registered_canvas_images;
33
34
  pub const max_registered_canvas_image_pixel_bytes = canvas_limits.max_registered_canvas_image_pixel_bytes;
@@ -78,6 +79,12 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
78
79
  /// `max_registered_canvas_images` slots hold other ids).
79
80
  pub fn registerCanvasImage(self: *Runtime, id: canvas.ImageId, width: usize, height: usize, rgba8: []const u8) anyerror!void {
80
81
  if (id == 0) return error.InvalidImageId;
82
+ // The high bit is the media-surface texture namespace
83
+ // (`canvas.media_surface_image_id_bit`): producer-pushed
84
+ // textures and registered images share one flat id space,
85
+ // so a registration inside the reserved namespace is
86
+ // refused loudly rather than shadowed silently.
87
+ if ((id & canvas.media_surface_image_id_bit) != 0) return error.InvalidImageId;
81
88
  if (width == 0 or height == 0) return error.InvalidImageDimensions;
82
89
  const row_len = std.math.mul(usize, width, 4) catch return error.InvalidImageDimensions;
83
90
  const byte_len = std.math.mul(usize, row_len, height) catch return error.InvalidImageDimensions;
@@ -116,8 +123,17 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
116
123
  /// `error.UnsupportedService` (platform has no codec),
117
124
  /// `error.ImageDecodeFailed` (undecodable bytes),
118
125
  /// `error.ImageTooLarge` (decoded pixels over the slot bound).
126
+ /// `error.InvalidImageId` covers the same ids
127
+ /// `registerCanvasImage` refuses (0 and the reserved
128
+ /// media-surface namespace) and fires before any decode work.
119
129
  pub fn registerCanvasImageBytes(self: *Runtime, id: canvas.ImageId, bytes: []const u8) anyerror!RegisteredCanvasImage {
120
130
  if (id == 0) return error.InvalidImageId;
131
+ // Same reserved-namespace refusal as `registerCanvasImage`
132
+ // (see the comment there), checked before the decode so an
133
+ // unusable id never reaches the platform codec — the caller
134
+ // gets `error.InvalidImageId`, not a codec error, and pays
135
+ // no decode cost for it.
136
+ if ((id & canvas.media_surface_image_id_bit) != 0) return error.InvalidImageId;
121
137
  const decoded = try self.options.platform.services.decodeImage(bytes, &canvas_image_decode_scratch.get().bytes);
122
138
  if (decoded.rgba8.len > max_registered_canvas_image_pixel_bytes) return error.ImageTooLarge;
123
139
  try registerCanvasImage(self, id, decoded.width, decoded.height, decoded.rgba8);
@@ -153,7 +169,11 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
153
169
  /// The registered set as the `ReferenceImage` slice both
154
170
  /// renderers consume, rebuilt into runtime scratch (pixels are
155
171
  /// borrowed from the slot pool, valid until the next
156
- /// register/unregister).
172
+ /// register/unregister), with the adopted media-surface
173
+ /// textures appended as `presentation_only` entries — GPU and
174
+ /// packet hosts upload and composite those, the deterministic
175
+ /// reference renderer skips them by policy (the media surface's
176
+ /// id-derived placeholder is what it draws instead).
157
177
  pub fn registeredCanvasImages(self: *Runtime) []const canvas.ReferenceImage {
158
178
  for (self.canvas_image_entries[0..self.canvas_image_count], 0..) |entry, index| {
159
179
  self.canvas_image_resources_scratch[index] = .{
@@ -163,7 +183,11 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
163
183
  .pixels = self.canvas_image_pixels[index][0..entry.byte_len],
164
184
  };
165
185
  }
166
- return self.canvas_image_resources_scratch[0..self.canvas_image_count];
186
+ const media = runtime_media_surface.RuntimeMediaSurfaces(Runtime).adoptedMediaSurfaceTextures(
187
+ self,
188
+ self.canvas_image_resources_scratch[self.canvas_image_count..],
189
+ );
190
+ return self.canvas_image_resources_scratch[0 .. self.canvas_image_count + media.len];
167
191
  }
168
192
 
169
193
  /// Dimensions of a registered image, or null when `id` is not
@@ -213,11 +237,13 @@ pub fn RuntimeCanvasImages(comptime Runtime: type) type {
213
237
  return null;
214
238
  }
215
239
 
216
- /// Registered pixels changed: force every gpu_surface view to
217
- /// re-render its next frame (an image swap with an unchanged
218
- /// display list would otherwise take the skip path) and request
219
- /// frames so the repaint is not gated on other input.
220
- fn noteCanvasImagesChanged(self: *Runtime) void {
240
+ /// Registered pixels (or adopted media-surface textures, which
241
+ /// ride the same resource set) changed: force every gpu_surface
242
+ /// view to re-render its next frame (an image swap with an
243
+ /// unchanged display list would otherwise take the skip path)
244
+ /// and request frames so the repaint is not gated on other
245
+ /// input. Pub for media_surface.zig's adoption path.
246
+ pub fn noteCanvasImagesChanged(self: *Runtime) void {
221
247
  const frame_methods = canvas_frame_module.RuntimeCanvasFrames(Runtime);
222
248
  for (self.views[0..self.view_count], 0..) |*view, index| {
223
249
  if (!view.open or view.kind != .gpu_surface) continue;
@@ -105,6 +105,31 @@ pub const max_canvas_text_layout_lines_per_view: usize = 8192;
105
105
  pub const max_registered_canvas_images: usize = 16;
106
106
  pub const max_registered_canvas_image_pixel_bytes: usize = 1024 * 1024;
107
107
 
108
+ // Media-surface texture channels (media_surface.zig): producer-pushed
109
+ // dynamic textures composited by media_surface widgets. Sized at video
110
+ // scale, not avatar scale — one 1080p RGBA8 frame is ~7.9 MiB, so the
111
+ // per-channel bound fits it exactly (8 MiB) and refuses 4K until the
112
+ // format axis grows real zero-copy paths; 4 concurrent channels covers
113
+ // a player plus a camera preview plus headroom, and a fifth acquire
114
+ // fails loudly (`error.MediaSurfaceChannelsExhausted`). Both bounds are
115
+ // VALIDATION bounds plus per-USE allocation sizes, never Runtime-struct
116
+ // reservations: an ADOPTED texture's buffer is one lazy frame-budget
117
+ // allocation from the runtime's `owned_allocator` (frozen from
118
+ // `Options.allocator` at init) at the entry's first adoption (freed by
119
+ // `Runtime.deinit`), so a runtime with no
120
+ // media producers carries zero media-texture bytes — an embedded pool
121
+ // at this bound put 4 x 8 MiB = 32 MiB in EVERY Runtime, measured on
122
+ // the docs wasm preview host (one Runtime per component tile, wasm
123
+ // linear memory never overcommits) as 137.5 -> 169.5 MB per instance
124
+ // before any producer existed, the registered-font-pool regression's
125
+ // twin. The producer-side STAGING buffers are allocated at first claim
126
+ // into process-lived module state and kept for the process's life —
127
+ // the mailbox a producer thread may touch after its runtime died,
128
+ // which is why they can never be freed (the effects executor's
129
+ // process-lifetime doctrine).
130
+ pub const max_media_surface_channels: usize = 4;
131
+ pub const max_media_surface_pixel_bytes: usize = 8 * 1024 * 1024;
132
+
108
133
  // Runtime-registered font faces: TrueType bytes apps register under a
109
134
  // caller-chosen FontId (>= canvas.min_registered_font_id) so their own
110
135
  // typefaces resolve everywhere a font id rides — token overrides, text
@@ -116,15 +141,26 @@ pub const max_registered_canvas_image_pixel_bytes: usize = 1024 * 1024;
116
141
  // so re-registering an id with different bytes would serve stale glyphs —
117
142
  // re-use of a registered id fails loudly instead (`error.FontIdInUse`).
118
143
  // The slot count covers a real brand set (a text family in 2-3 weights
119
- // plus a display and a mono face); the per-font bound fits full
120
- // static-instance UI faces (the bundled faces are 71/116 KB; a large
121
- // Latin+Cyrillic+Greek UI face is a few hundred KB) while refusing
122
- // multi-megabyte CJK/variable fonts the glyph pipeline is not sized for.
123
- // Memory is fixed-capacity address space in the Runtime: 8 x 2 MiB =
124
- // 16 MiB, pages touched only as fonts register; oversized files and a
125
- // ninth font fail loudly (`error.FontTooLarge` / `error.FontRegistryFull`).
144
+ // plus a display and a mono face); the per-font bound fits full CJK
145
+ // faces — the glyph pipeline is sized for them (canvas.font_ttf budgets)
146
+ // and the canonical Google Fonts TrueType builds measure 9.6 MB (Noto
147
+ // Sans JP), 10.4 (KR), 11.9 (TC), 13.6 (Noto Serif JP), and 17.8 (Noto
148
+ // Sans SC), so 24 MiB covers the largest measured with ~1.4x headroom.
149
+ // Latin UI faces stay a few hundred KB (the bundled faces are 71/116 KB).
150
+ // Both bounds are VALIDATION bounds, not storage reservations: the
151
+ // registry heap-allocates each font's exact file size from the
152
+ // allocator the runtime froze at init (`Options.allocator`, captured
153
+ // into `Runtime.owned_allocator`) at registration (canvas_fonts.zig), so
154
+ // a runtime with no registered fonts carries zero font bytes. An
155
+ // embedded slot pool at this bound would put 8 x 24 MiB = 192 MiB in
156
+ // EVERY Runtime — measured on the docs wasm preview host (one Runtime
157
+ // per component tile, wasm linear memory never overcommits) as 137.5 ->
158
+ // 313.5 MB per instance before any font registered. Oversized files and
159
+ // a ninth font fail loudly (`error.FontTooLarge` /
160
+ // `error.FontRegistryFull`). The gpu-surface registration side-channel
161
+ // bound (`platform.max_gpu_surface_font_bytes`) pins the same value.
126
162
  pub const max_registered_canvas_fonts: usize = 8;
127
- pub const max_registered_canvas_font_bytes: usize = 2 * 1024 * 1024;
163
+ pub const max_registered_canvas_font_bytes: usize = 24 * 1024 * 1024;
128
164
 
129
165
  // The retained widget-tree budgets (raised 256 -> 1024; see the header
130
166
  // comment). `automation.snapshot.max_widgets_per_view`
@@ -168,6 +168,129 @@ test "keyboard-only selection (shift+arrows) feeds copy" {
168
168
  try std.testing.expectEqualStrings("ry", try harness.runtime.readClipboard(&clipboard_buffer));
169
169
  }
170
170
 
171
+ test "a multi-line paste into a single-line field strips line breaks; a textarea keeps them" {
172
+ var app_state: ClipboardTestApp = .{};
173
+ const app = app_state.app();
174
+ const harness = try createClipboardHarness(app);
175
+ defer harness.destroy(std.testing.allocator);
176
+
177
+ const children = [_]canvas.Widget{
178
+ .{
179
+ .id = 2,
180
+ .kind = .text_field,
181
+ .frame = geometry.RectF.init(12, 16, 200, 36),
182
+ .text = "",
183
+ },
184
+ .{
185
+ .id = 3,
186
+ .kind = .textarea,
187
+ .frame = geometry.RectF.init(12, 64, 280, 100),
188
+ .text = "",
189
+ },
190
+ };
191
+ var nodes: [3]canvas.WidgetLayoutNode = undefined;
192
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &children }, geometry.RectF.init(0, 0, 320, 200), &nodes);
193
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
194
+
195
+ // Interior LF, CRLF, and a trailing CR: the single-line field strips
196
+ // every break (the HTML value-sanitization rule — lines join with
197
+ // nothing between them), and the app-facing keyboard event carries
198
+ // the SAME stripped insert so a model mirror stays byte-identical.
199
+ try harness.runtime.writeClipboard("alpha\nbeta\r\ngamma\r");
200
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
201
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
202
+ var retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
203
+ try std.testing.expectEqualStrings("alphabetagamma", retained.nodes[1].widget.text);
204
+ try std.testing.expectEqualDeep(canvas.TextSelection.collapsed(14), retained.nodes[1].widget.text_selection.?);
205
+ try std.testing.expectEqualStrings("alphabetagamma", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
206
+ try std.testing.expect(!app_state.saw_truncated);
207
+
208
+ // The SAME clipboard pasted into the textarea keeps its breaks: only
209
+ // single-line kinds sanitize.
210
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 100));
211
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
212
+ retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
213
+ try std.testing.expectEqualStrings("alpha\nbeta\r\ngamma\r", retained.nodes[2].widget.text);
214
+ try std.testing.expectEqualStrings("alpha\nbeta\r\ngamma\r", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
215
+ }
216
+
217
+ test "a paste of only line breaks into a single-line field inserts nothing and keeps the selection" {
218
+ var app_state: ClipboardTestApp = .{};
219
+ const app = app_state.app();
220
+ const harness = try createClipboardHarness(app);
221
+ defer harness.destroy(std.testing.allocator);
222
+
223
+ const text_field = canvas.Widget{
224
+ .id = 2,
225
+ .kind = .text_field,
226
+ .frame = geometry.RectF.init(12, 16, 200, 36),
227
+ .text = "Keep",
228
+ };
229
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
230
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
231
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
232
+
233
+ // Select all, then paste bare newlines: the sanitized insert is
234
+ // EMPTY, so the edit suppresses — nothing inserts, the live
235
+ // selection survives, and the app hears no insert at all (an empty
236
+ // insert is cut's delete-selection edit, which this must never be).
237
+ try harness.runtime.writeClipboard("\r\n\n");
238
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
239
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("a", cmd));
240
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
241
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
242
+ try std.testing.expectEqualStrings("Keep", retained.nodes[1].widget.text);
243
+ try std.testing.expectEqualDeep(canvas.TextSelection{ .anchor = 0, .focus = 4 }, retained.nodes[1].widget.text_selection.?);
244
+ try std.testing.expect(!app_state.saw_empty_insert);
245
+ try std.testing.expectEqual(@as(usize, 0), app_state.last_edit_insert_len);
246
+ }
247
+
248
+ test "a near-capacity multi-line paste sanitizes before it clamps" {
249
+ var app_state: ClipboardTestApp = .{};
250
+ const app = app_state.app();
251
+ const harness = try createClipboardHarness(app);
252
+ defer harness.destroy(std.testing.allocator);
253
+
254
+ // Fill the view's shared widget-text storage to EXACTLY three free
255
+ // bytes, the boundary where the sanitize/clamp ordering shows:
256
+ // pasting "a\nbc" must land "abc" (sanitized 3 bytes, fits whole).
257
+ // Clamping the raw clipboard first would spend the third byte on
258
+ // the '\n' the seam strips anyway — "a\nb" then "ab" — silently
259
+ // discarding the valid 'c' and flagging a truncation that never
260
+ // happened to the bytes that count.
261
+ const fill_len = canvas_limits.max_canvas_widget_text_bytes_per_view - 3;
262
+ const fill = try std.testing.allocator.alloc(u8, fill_len);
263
+ defer std.testing.allocator.free(fill);
264
+ @memset(fill, 'x');
265
+ const text_field = canvas.Widget{
266
+ .id = 2,
267
+ .kind = .text_field,
268
+ .frame = geometry.RectF.init(12, 16, 200, 36),
269
+ .text = fill,
270
+ };
271
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
272
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
273
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
274
+ // Pin the boundary premise: exactly 3 bytes of capacity remain.
275
+ try std.testing.expectEqual(fill_len, harness.runtime.views[0].widget_text_len);
276
+
277
+ try harness.runtime.writeClipboard("a\nbc");
278
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_down, 100, 30));
279
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("end", .{}));
280
+ try harness.runtime.dispatchPlatformEvent(app, keyInput("v", cmd));
281
+
282
+ // The retained editor holds the whole sanitized suffix ...
283
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
284
+ const text = retained.nodes[1].widget.text;
285
+ try std.testing.expectEqual(fill_len + 3, text.len);
286
+ try std.testing.expectEqualStrings("abc", text[text.len - 3 ..]);
287
+ try std.testing.expectEqualDeep(canvas.TextSelection.collapsed(text.len), retained.nodes[1].widget.text_selection.?);
288
+ // ... the app's stamped edit is byte-identical to what the editor
289
+ // applied, and nothing was (falsely) reported truncated.
290
+ try std.testing.expectEqualStrings("abc", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
291
+ try std.testing.expect(!app_state.saw_truncated);
292
+ }
293
+
171
294
  test "paste clamps to view text capacity and flags truncation loudly" {
172
295
  var app_state: ClipboardTestApp = .{};
173
296
  const app = app_state.app();
@@ -25,6 +25,9 @@ const MenuTestApp = struct {
25
25
  last_menu_item_index: usize = 0,
26
26
  request_count: u32 = 0,
27
27
  last_request_target: canvas.ObjectId = 0,
28
+ last_edit_insert: [64]u8 = undefined,
29
+ last_edit_insert_len: usize = 0,
30
+ saw_truncated: bool = false,
28
31
 
29
32
  fn app(self: *@This()) App {
30
33
  return .{ .context = self, .name = "context-menus", .source = platform.WebViewSource.html("<h1>Hello</h1>"), .event_fn = event };
@@ -45,6 +48,17 @@ const MenuTestApp = struct {
45
48
  self.request_count += 1;
46
49
  self.last_request_target = request_event.target_id;
47
50
  },
51
+ .canvas_widget_keyboard => |keyboard_event| {
52
+ if (keyboard_event.keyboard.edit_truncated) self.saw_truncated = true;
53
+ if (keyboard_event.keyboard.edit) |edit| switch (edit) {
54
+ .insert_text => |text| {
55
+ const len = @min(text.len, self.last_edit_insert.len);
56
+ @memcpy(self.last_edit_insert[0..len], text[0..len]);
57
+ self.last_edit_insert_len = len;
58
+ },
59
+ else => {},
60
+ };
61
+ },
48
62
  else => {},
49
63
  }
50
64
  }
@@ -210,6 +224,47 @@ test "right click on editable text presents the default edit menu wired to clipb
210
224
  try std.testing.expectEqualDeep(canvas.TextSelection{ .anchor = 0, .focus = 5 }, retained.nodes[1].widget.text_selection.?);
211
225
  }
212
226
 
227
+ test "a near-capacity multi-line context-menu paste sanitizes before it clamps" {
228
+ var app_state: MenuTestApp = .{};
229
+ const app = app_state.app();
230
+ const harness = try createMenuHarness(app);
231
+ defer harness.destroy(std.testing.allocator);
232
+
233
+ // Same boundary as the cmd+V shortcut test: exactly three free bytes
234
+ // in the view's shared widget-text storage, clipboard "a\nbc". The
235
+ // context menu's Paste flows through the same sanitize-then-clamp
236
+ // helper, so the sanitized "abc" lands whole instead of the raw
237
+ // clamp's "a\nb" -> "ab".
238
+ const fill_len = canvas_limits.max_canvas_widget_text_bytes_per_view - 3;
239
+ const fill = try std.testing.allocator.alloc(u8, fill_len);
240
+ defer std.testing.allocator.free(fill);
241
+ @memset(fill, 'x');
242
+ const text_field = canvas.Widget{
243
+ .id = 2,
244
+ .kind = .text_field,
245
+ .frame = geometry.RectF.init(12, 16, 200, 36),
246
+ .text = fill,
247
+ };
248
+ var nodes: [2]canvas.WidgetLayoutNode = undefined;
249
+ const layout = try canvas.layoutWidgetTree(.{ .kind = .stack, .children = &.{text_field} }, geometry.RectF.init(0, 0, 320, 200), &nodes);
250
+ _ = try harness.runtime.setCanvasWidgetLayout(1, "canvas", layout);
251
+ try std.testing.expectEqual(fill_len, harness.runtime.views[0].widget_text_len);
252
+
253
+ try harness.runtime.writeClipboard("a\nbc");
254
+ try harness.runtime.dispatchPlatformEvent(app, rightClick(100, 30));
255
+ // Paste is the default edit menu's third item.
256
+ try harness.runtime.dispatchPlatformEvent(app, menuAction(2, 3));
257
+
258
+ // Retained editor and the app's stamped edit hear the same whole
259
+ // sanitized suffix, with no false truncation flag.
260
+ const retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
261
+ const text = retained.nodes[1].widget.text;
262
+ try std.testing.expectEqual(fill_len + 3, text.len);
263
+ try std.testing.expectEqualStrings("abc", text[text.len - 3 ..]);
264
+ try std.testing.expectEqualStrings("abc", app_state.last_edit_insert[0..app_state.last_edit_insert_len]);
265
+ try std.testing.expect(!app_state.saw_truncated);
266
+ }
267
+
213
268
  test "right click on selected static text presents a copy-only menu" {
214
269
  var app_state: MenuTestApp = .{};
215
270
  const app = app_state.app();
@@ -1796,9 +1796,12 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
1796
1796
  /// - cut: copy, then stamp a delete-selection edit onto the routed
1797
1797
  /// keyboard event so runtime widget and app model apply the same
1798
1798
  /// removal.
1799
- /// - paste: reads the clipboard into `paste_buffer`, clamps it to
1800
- /// the view's text capacity (setting `edit_truncated` loudly),
1801
- /// and stamps the insertion onto the routed keyboard event.
1799
+ /// - paste: reads the clipboard into `paste_buffer`, sanitizes it
1800
+ /// for the target kind and THEN clamps to the view's text
1801
+ /// capacity (setting `edit_truncated` loudly) — order matters:
1802
+ /// clamping first would spend capacity on line-break bytes the
1803
+ /// seam strips anyway — and stamps the insertion onto the
1804
+ /// routed keyboard event.
1802
1805
  ///
1803
1806
  /// Platforms without a clipboard capability report
1804
1807
  /// `UnsupportedService`; the shortcut degrades to a no-op instead
@@ -1877,7 +1880,24 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
1877
1880
  const index = runtimeFindViewIndex(self, keyboard_event.window_id, keyboard_event.view_label) orelse return;
1878
1881
  if (self.views[index].kind != .gpu_surface) return;
1879
1882
  const target = keyboard_event.target orelse return;
1880
- const edit = self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
1883
+ const derived = self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
1884
+ // Single-line sanitization happens HERE — after derivation,
1885
+ // BEFORE the stamp — so the retained editor and the app's
1886
+ // `on_input` mirror hear byte-identical sanitized inserts
1887
+ // (clipboard paste from both entry points, typed and
1888
+ // automation text_input, IME composition — every insertion
1889
+ // source flows through this one seam). Pre-stamped pastes
1890
+ // arrive already sanitized (`clampCanvasWidgetPasteText`
1891
+ // strips BEFORE clamping so capacity never counts stripped
1892
+ // bytes); re-sanitizing them is a no-op. A suppressed edit (an
1893
+ // insert that was ONLY line breaks) also clears any raw
1894
+ // pre-stamped paste so the app can never hear bytes the
1895
+ // editor refused; the app-side fallback derivation applies
1896
+ // the same sanitize rule, so both derivations still agree.
1897
+ const edit = canvas.sanitizedSingleLineTextInputEvent(target.kind, derived) orelse {
1898
+ keyboard_event.keyboard.edit = null;
1899
+ return;
1900
+ };
1881
1901
  keyboard_event.keyboard.edit = edit;
1882
1902
 
1883
1903
  const dirty = try self.views[index].applyCanvasWidgetTextEdit(target.id, edit) orelse return;
@@ -393,16 +393,33 @@ pub fn canvasWidgetEditableTextKind(kind: canvas.WidgetKind) bool {
393
393
  return kind == .input or kind == .text_field or kind == .search_field or kind == .combobox or kind == .textarea;
394
394
  }
395
395
 
396
- /// Clipboard paste text clamped to what the view's shared widget text
397
- /// storage can absorb (the bytes the edit replaces are freed first).
398
- /// Clamping lands on a UTF-8 boundary; `truncated` is the loud flag the
399
- /// runtime forwards to apps on the keyboard event.
396
+ /// Clipboard paste text sanitized for the target kind and then clamped
397
+ /// to what the view's shared widget text storage can absorb (the bytes
398
+ /// the edit replaces are freed first). Clamping lands on a UTF-8
399
+ /// boundary; `truncated` is the loud flag the runtime forwards to apps
400
+ /// on the keyboard event.
400
401
  pub const CanvasWidgetPasteClamp = struct {
401
402
  text: []const u8 = "",
402
403
  truncated: bool = false,
403
404
  };
404
405
 
405
406
  pub fn clampCanvasWidgetPasteText(widget: canvas.Widget, view_text_len: usize, text: []const u8) CanvasWidgetPasteClamp {
407
+ // Sanitize BEFORE clamping — the shared step for BOTH paste entry
408
+ // points (the cmd+V shortcut and the context-menu Paste). A
409
+ // single-line target strips \r/\n at the edit-derivation seam
410
+ // anyway, so capacity must be measured against the bytes that
411
+ // actually land: clamping the raw clipboard first discarded valid
412
+ // suffix text near the limit ("a\nbc" into 3 free bytes clamped to
413
+ // "a\nb" and then sanitized to "ab", when the sanitized "abc" fits
414
+ // whole). The stamped edit is the post-clamp bytes, so the retained
415
+ // editor and the app's `on_input` mirror still hear identically —
416
+ // the seam's re-sanitize is a no-op on already-stripped text. A
417
+ // paste that sanitizes to nothing clamps to nothing; that is the
418
+ // sanitize rule speaking, NOT capacity, so `truncated` stays false.
419
+ const sanitized = if (canvas.sanitizedSingleLineTextInputEvent(widget.kind, .{ .insert_text = text })) |event|
420
+ event.insert_text
421
+ else
422
+ return .{};
406
423
  const capacity = @import("canvas_limits.zig").max_canvas_widget_text_bytes_per_view;
407
424
  const replaced_len = blk: {
408
425
  if (widget.text_composition) |composition| break :blk composition.byteLen(widget.text.len);
@@ -411,9 +428,9 @@ pub fn clampCanvasWidgetPasteText(widget: canvas.Widget, view_text_len: usize, t
411
428
  };
412
429
  const used = view_text_len -| replaced_len;
413
430
  const available = capacity -| used;
414
- if (text.len <= available) return .{ .text = text };
415
- const clamped = canvas.snapTextOffset(text, available);
416
- return .{ .text = text[0..clamped], .truncated = true };
431
+ if (sanitized.len <= available) return .{ .text = sanitized };
432
+ const clamped = canvas.snapTextOffset(sanitized, available);
433
+ return .{ .text = sanitized[0..clamped], .truncated = true };
417
434
  }
418
435
 
419
436
  pub fn canvasWidgetSingleLineTextKind(kind: canvas.WidgetKind) bool {
@@ -819,7 +819,12 @@ pub fn RuntimeCanvasWidgetState(comptime Runtime: type) type {
819
819
  if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
820
820
  if (!self.views[index].canEditCanvasWidgetText(id)) return error.InvalidCommand;
821
821
 
822
- const dirty = try self.views[index].applyCanvasWidgetTextEdit(id, edit) orelse return self.views[index].info();
822
+ // Direct runtime edits sanitize like every other insertion
823
+ // source (the keyboard choke point's rule): a single-line
824
+ // field's editor never accepts a line break, whoever writes.
825
+ const node = self.views[index].widgetLayoutTree().findById(id) orelse return error.InvalidCommand;
826
+ const sanitized = canvas.sanitizedSingleLineTextInputEvent(node.widget.kind, edit) orelse return self.views[index].info();
827
+ const dirty = try self.views[index].applyCanvasWidgetTextEdit(id, sanitized) orelse return self.views[index].info();
823
828
  try CanvasWidgetEventMethods(Runtime).invalidateForCanvasWidgetDirty(self, index, dirty);
824
829
  _ = try CanvasWidgetDisplayMethods(Runtime).refreshCanvasWidgetDisplayListIfOwned(self, index);
825
830
  return self.views[index].info();