@native-sdk/cli 0.5.0 → 0.5.2

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 (60) hide show
  1. package/build/app.zig +198 -13
  2. package/build/ts_run.mjs +58 -19
  3. package/build.zig +42 -0
  4. package/package.json +13 -9
  5. package/packages/core/package-lock.json +4 -3
  6. package/packages/core/package.json +3 -2
  7. package/packages/core/src/typed_ast.ts +11 -1
  8. package/skill-data/native-ui/SKILL.md +2 -2
  9. package/src/platform/types.zig +9 -0
  10. package/src/platform/windows/webview2_host.cpp +24 -0
  11. package/src/primitives/canvas/layout_audit.zig +5 -5
  12. package/src/primitives/canvas/root.zig +6 -0
  13. package/src/primitives/canvas/tokens.zig +185 -7
  14. package/src/primitives/canvas/ui.zig +27 -5
  15. package/src/primitives/canvas/ui_markup.zig +27 -4
  16. package/src/primitives/canvas/ui_markup_compiled.zig +9 -1
  17. package/src/primitives/canvas/ui_markup_compiled_tests.zig +127 -0
  18. package/src/primitives/canvas/ui_markup_tests.zig +47 -0
  19. package/src/primitives/canvas/ui_markup_view.zig +10 -1
  20. package/src/primitives/canvas/ui_markup_view_tests.zig +78 -0
  21. package/src/primitives/canvas/ui_schema.zig +15 -1
  22. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  23. package/src/primitives/canvas/widget_builtin_tests.zig +439 -5
  24. package/src/primitives/canvas/widget_layout.zig +142 -3
  25. package/src/primitives/canvas/widget_layout_tests.zig +82 -0
  26. package/src/primitives/canvas/widget_metrics.zig +16 -8
  27. package/src/primitives/canvas/widget_tree.zig +14 -2
  28. package/src/primitives/canvas/widgets.zig +12 -0
  29. package/src/runtime/automation_widget_dispatch.zig +95 -28
  30. package/src/runtime/canvas_frame.zig +15 -0
  31. package/src/runtime/canvas_widget_anchored_tests.zig +253 -65
  32. package/src/runtime/canvas_widget_context_menu.zig +3 -2
  33. package/src/runtime/canvas_widget_events.zig +1271 -3
  34. package/src/runtime/canvas_widget_floating_tests.zig +2801 -0
  35. package/src/runtime/canvas_widget_scroll_drivers.zig +1 -1
  36. package/src/runtime/canvas_widget_state.zig +82 -5
  37. package/src/runtime/core.zig +30 -0
  38. package/src/runtime/effects.zig +1037 -133
  39. package/src/runtime/effects_fetch_tests.zig +42 -0
  40. package/src/runtime/effects_file_tests.zig +220 -0
  41. package/src/runtime/effects_tests.zig +287 -0
  42. package/src/runtime/flow.zig +24 -1
  43. package/src/runtime/gpu_surface_events.zig +44 -5
  44. package/src/runtime/session_journal.zig +25 -13
  45. package/src/runtime/session_record.zig +166 -0
  46. package/src/runtime/session_tests.zig +453 -0
  47. package/src/runtime/ui_app.zig +137 -39
  48. package/src/runtime/ui_app_tests.zig +681 -0
  49. package/src/runtime/ui_app_window_tests.zig +182 -0
  50. package/src/runtime/view.zig +86 -0
  51. package/src/runtime/view_widget_text.zig +18 -1
  52. package/src/runtime/view_widget_tree.zig +339 -20
  53. package/src/runtime/widget_bridge.zig +26 -0
  54. package/src/runtime/window_storage.zig +61 -15
  55. package/src/runtime/window_view_runtime.zig +13 -0
  56. package/src/runtime/window_views.zig +6 -0
  57. package/src/tooling/package.zig +311 -8
  58. package/src/tooling/templates.zig +97 -9
  59. package/src/tooling/ts_core.zig +626 -13
  60. package/src/tooling/verbs.zig +88 -2
@@ -9,6 +9,7 @@ const app_manifest = @import("app_manifest");
9
9
  const core = @import("core.zig");
10
10
  const ui_app_model = @import("ui_app.zig");
11
11
  const effects_mod = @import("effects.zig");
12
+ const clock_mod = @import("clock.zig");
12
13
 
13
14
  const canvas_label = "fetch-canvas";
14
15
 
@@ -980,6 +981,47 @@ test "real fetch reports connection refused as connect_failed" {
980
981
  try std.testing.expectEqual(@as(usize, 0), h.app_state.model.body_len);
981
982
  }
982
983
 
984
+ test "a fetch whose exchange cannot start cancellably is rejected, never run inline" {
985
+ var h = try Harness.create();
986
+ defer h.destroy();
987
+ const fx = &h.app_state.effects;
988
+ // Pin the no-capacity path through the injectable seam (the real
989
+ // trigger — the executor refusing `std.Io.concurrent` — needs
990
+ // resource exhaustion). If a regression ran the exchange inline
991
+ // instead, this loopback connect would fail fast as
992
+ // `.connect_failed` and the assert below would catch the lie.
993
+ fx.fetch_concurrent_start = false;
994
+
995
+ var url_buffer: [128]u8 = undefined;
996
+ test_url = std.fmt.bufPrint(&url_buffer, "http://127.0.0.1:9/", .{}) catch unreachable;
997
+ test_method = .GET;
998
+ test_headers = &.{};
999
+ test_payload = null;
1000
+ test_timeout_ms = effects_mod.default_effect_fetch_timeout_ms;
1001
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1002
+ try waitForResponse(&h);
1003
+
1004
+ // Exactly one honest `.rejected` terminal — the fetch never
1005
+ // started — counted through the rejection seam.
1006
+ try std.testing.expectEqual(effects_mod.EffectFetchOutcome.rejected, h.app_state.model.outcome.?);
1007
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.rejected_count);
1008
+ try std.testing.expectEqual(@as(u16, 0), h.app_state.model.status);
1009
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.model.body_len);
1010
+ try std.testing.expectEqual(@as(u32, 1), fx.fetch_start_rejections.load(.acquire));
1011
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.activeCount());
1012
+
1013
+ // Teardown returns promptly: no uncancelable inline exchange is
1014
+ // left for the unconditional fetch join to wait on.
1015
+ const start_ns = clock_mod.monotonicNanoseconds();
1016
+ fx.deinit();
1017
+ const elapsed_ms = (clock_mod.monotonicNanoseconds() - start_ns) / std.time.ns_per_ms;
1018
+ try std.testing.expect(elapsed_ms < 10_000);
1019
+ for (&fx.slots) |*slot| {
1020
+ try std.testing.expect(slot.worker_thread == null);
1021
+ try std.testing.expect(slot.state.load(.acquire) != .running);
1022
+ }
1023
+ }
1024
+
983
1025
  test "real fetch times out against a hanging route" {
984
1026
  var h = try Harness.create();
985
1027
  defer h.destroy();
@@ -11,6 +11,7 @@ const app_manifest = @import("app_manifest");
11
11
  const core = @import("core.zig");
12
12
  const ui_app_model = @import("ui_app.zig");
13
13
  const effects_mod = @import("effects.zig");
14
+ const clock_mod = @import("clock.zig");
14
15
 
15
16
  const canvas_label = "file-canvas";
16
17
 
@@ -346,6 +347,16 @@ test "real executor writes a file (creating parent dirs) and reads it back" {
346
347
  try h.app_state.dispatch(&h.harness.runtime, 1, .load);
347
348
  try waitForRealResult(&h, 4);
348
349
  try std.testing.expectEqualStrings("{\"n\":2}", h.app_state.model.bytesPrefix());
350
+
351
+ // Happy-path teardown pin: quick local ops join promptly and the
352
+ // abandon safety net never fires (no leak, no detached thread).
353
+ const fx = &h.app_state.effects;
354
+ fx.deinit();
355
+ try std.testing.expectEqual(@as(u32, 0), fx.abandoned_file_workers);
356
+ for (&fx.slots) |*slot| {
357
+ try std.testing.expect(slot.worker_thread == null);
358
+ try std.testing.expect(slot.state.load(.acquire) != .running);
359
+ }
349
360
  }
350
361
 
351
362
  test "real executor reports missing files as not_found" {
@@ -386,6 +397,215 @@ test "real executor cuts over-bound reads with outcome truncated" {
386
397
  );
387
398
  }
388
399
 
400
+ // --------------------------------------------------- bounded teardown
401
+
402
+ /// Create a FIFO at `path` (POSIX-only; callers gate on the platform).
403
+ /// A file write against it blocks forever inside `open(O_WRONLY)`
404
+ /// while no reader exists — the uninterruptible-blocking-I/O posture
405
+ /// the teardown deadline exists for.
406
+ fn makeFifo(path: []const u8) !void {
407
+ var command_buffer: [512]u8 = undefined;
408
+ const command = try std.fmt.bufPrint(&command_buffer, "mkfifo '{s}'", .{path});
409
+ const result = try std.process.run(std.testing.allocator, std.testing.io, .{
410
+ .argv = &.{ "/bin/sh", "-c", command },
411
+ });
412
+ defer std.testing.allocator.free(result.stdout);
413
+ defer std.testing.allocator.free(result.stderr);
414
+ try std.testing.expect(result.term == .exited and result.term.exited == 0);
415
+ }
416
+
417
+ test "teardown abandons a file worker stuck on a reader-less FIFO and leaks its world loudly" {
418
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
419
+ const io = std.testing.io;
420
+ var tmp = std.testing.tmpDir(.{});
421
+ defer tmp.cleanup();
422
+
423
+ var fifo_path_buffer: [256]u8 = undefined;
424
+ const fifo_path = try std.fmt.bufPrint(&fifo_path_buffer, ".zig-cache/tmp/{s}/stuck.fifo", .{tmp.sub_path[0..]});
425
+ try makeFifo(fifo_path);
426
+
427
+ var h = try Harness.create();
428
+ defer h.destroy();
429
+ const fx = &h.app_state.effects;
430
+ // Tiny injected budget, interruption disabled: this test pins the
431
+ // SAFETY NET (abandon-and-leak). The interruption path that
432
+ // normally converges first has its own test below.
433
+ fx.file_join_deadline_ms = 300;
434
+ fx.file_join_interrupt = false;
435
+
436
+ test_path = fifo_path;
437
+ test_bytes = "never delivered";
438
+ try h.app_state.dispatch(&h.harness.runtime, 1, .save);
439
+ // Let the worker reach the blocking open. Not required for the
440
+ // abandon to fire — with interruption off, any still-running
441
+ // posture past the deadline is abandoned — but it exercises the
442
+ // real blocked shape.
443
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(50), .awake);
444
+
445
+ const start_ns = clock_mod.monotonicNanoseconds();
446
+ fx.deinit();
447
+ const elapsed_ms = (clock_mod.monotonicNanoseconds() - start_ns) / std.time.ns_per_ms;
448
+
449
+ // Teardown returned on the budget's order of magnitude (generous
450
+ // bound for congested runners) instead of hanging behind the FIFO
451
+ // forever...
452
+ try std.testing.expect(elapsed_ms < 10_000);
453
+ // ...and abandoned exactly the stuck worker, loudly through the
454
+ // counter seam, leaving no joinable thread and no running slot —
455
+ // the owner may free the channel's memory right now.
456
+ try std.testing.expectEqual(@as(u32, 1), fx.abandoned_file_workers);
457
+ for (&fx.slots) |*slot| {
458
+ try std.testing.expect(slot.worker_thread == null);
459
+ try std.testing.expect(slot.state.load(.acquire) != .running);
460
+ }
461
+
462
+ // The process is healthy after the leak: a fresh channel runs a
463
+ // real file round trip and its own safety net stays quiet.
464
+ var h2 = try Harness.create();
465
+ defer h2.destroy();
466
+ var path_buffer: [256]u8 = undefined;
467
+ test_path = try std.fmt.bufPrint(&path_buffer, ".zig-cache/tmp/{s}/healthy.json", .{tmp.sub_path[0..]});
468
+ test_bytes = "{\"alive\":true}";
469
+ try h2.app_state.dispatch(&h2.harness.runtime, 1, .save);
470
+ try waitForRealResult(&h2, 1);
471
+ try std.testing.expectEqual(effects_mod.EffectFileOutcome.ok, h2.app_state.model.last_outcome.?);
472
+ try std.testing.expectEqual(@as(u32, 0), h2.app_state.effects.abandoned_file_workers);
473
+
474
+ // Wake the abandoned worker under the leak invariant: opening the
475
+ // FIFO's read end completes its blocked open; it performs its
476
+ // write against its (leaked, still-valid) context and buffer,
477
+ // closes the FIFO, finds itself abandoned, and exits without
478
+ // touching the torn-down channel — if the leak were not honored,
479
+ // this is where a use-after-free would crash the test. Draining to
480
+ // EOF keeps the read end open across the worker's write (a write
481
+ // into a reader-less pipe raises SIGPIPE, and the io's no-op
482
+ // handler is not installed between tests) and proves the worker
483
+ // really woke: EOF only arrives once it opened and closed the
484
+ // write end.
485
+ var reader = try std.Io.Dir.cwd().openFile(io, fifo_path, .{});
486
+ defer reader.close(io);
487
+ var drain_buffer: [128]u8 = undefined;
488
+ while (true) {
489
+ const read_slices: [1][]u8 = .{&drain_buffer};
490
+ const count = reader.readStreaming(io, &read_slices) catch break;
491
+ if (count == 0) break;
492
+ }
493
+ }
494
+
495
+ test "an abandoned file worker survives the owner's allocator dying: its leak is process-lived only" {
496
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
497
+ const io = std.testing.io;
498
+ var tmp = std.testing.tmpDir(.{});
499
+ defer tmp.cleanup();
500
+
501
+ var fifo_path_buffer: [256]u8 = undefined;
502
+ const fifo_path = try std.fmt.bufPrint(&fifo_path_buffer, ".zig-cache/tmp/{s}/arena.fifo", .{tmp.sub_path[0..]});
503
+ try makeFifo(fifo_path);
504
+
505
+ // The channel — and every caller-side allocation it makes — lives
506
+ // in an arena backed by the leak-checking testing allocator and is
507
+ // deinitialized right after teardown: the exact owner-lifetime
508
+ // posture the abandon leak must survive. The channel struct itself
509
+ // sits in the arena too, so even the worker's `self` pointer dies
510
+ // with the owner.
511
+ const Channel = effects_mod.Effects(FileMsg);
512
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
513
+ var arena_live = true;
514
+ defer if (arena_live) arena.deinit();
515
+ const fx = try arena.allocator().create(Channel);
516
+ fx.* = Channel.init(arena.allocator());
517
+ // Tiny injected budget, interruption disabled: pin the
518
+ // abandon-and-leak safety net, exactly like the loud-leak test.
519
+ fx.file_join_deadline_ms = 300;
520
+ fx.file_join_interrupt = false;
521
+
522
+ fx.writeFile(.{ .key = 1, .path = fifo_path, .bytes = "never delivered", .on_result = null });
523
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(50), .awake);
524
+
525
+ fx.deinit();
526
+ try std.testing.expectEqual(@as(u32, 1), fx.abandoned_file_workers);
527
+
528
+ // Kill the owner's allocator: everything the channel ever got from
529
+ // it — including the channel struct — is gone. The abandoned
530
+ // worker must not notice: all it can still reach (its context,
531
+ // that context's buffer, the executor io) is `process_allocator`
532
+ // storage.
533
+ arena.deinit();
534
+ arena_live = false;
535
+
536
+ // Wake the abandoned worker under that invariant: opening the
537
+ // FIFO's read end completes its blocked open; it writes through
538
+ // its process-lived context and buffer, finds itself abandoned,
539
+ // and exits without touching the dead arena — if any of its
540
+ // reachable memory were caller-allocated, this walk is where the
541
+ // use-after-free would crash the test. Draining to EOF keeps the
542
+ // read end open across the worker's write and proves the worker
543
+ // really woke.
544
+ var reader = try std.Io.Dir.cwd().openFile(io, fifo_path, .{});
545
+ defer reader.close(io);
546
+ var drain_buffer: [128]u8 = undefined;
547
+ while (true) {
548
+ const read_slices: [1][]u8 = .{&drain_buffer};
549
+ const count = reader.readStreaming(io, &read_slices) catch break;
550
+ if (count == 0) break;
551
+ }
552
+
553
+ // And the happy path still frees everything through the same
554
+ // seams: a fresh channel backed DIRECTLY by the testing allocator
555
+ // runs a real write to completion and tears down joined — the
556
+ // leak check at test end guards the caller-side allocations, and
557
+ // `joinWorker`/`deinit` return the context, worker buffer, and
558
+ // executor io to `process_allocator`.
559
+ var healthy = Channel.init(std.testing.allocator);
560
+ defer healthy.deinit();
561
+ var path_buffer: [256]u8 = undefined;
562
+ const healthy_path = try std.fmt.bufPrint(&path_buffer, ".zig-cache/tmp/{s}/healthy.json", .{tmp.sub_path[0..]});
563
+ healthy.writeFile(.{ .key = 2, .path = healthy_path, .bytes = "{\"alive\":true}", .on_result = null });
564
+ var waited_ms: usize = 0;
565
+ while (waited_ms < 20_000) : (waited_ms += 10) {
566
+ if (healthy.hasPending()) break;
567
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
568
+ }
569
+ try std.testing.expect(healthy.hasPending());
570
+ healthy.deinit();
571
+ try std.testing.expectEqual(@as(u32, 0), healthy.abandoned_file_workers);
572
+ }
573
+
574
+ test "teardown interrupts a file worker stuck on a reader-less FIFO and joins it with no leak" {
575
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
576
+ const io = std.testing.io;
577
+ var tmp = std.testing.tmpDir(.{});
578
+ defer tmp.cleanup();
579
+
580
+ var fifo_path_buffer: [256]u8 = undefined;
581
+ const fifo_path = try std.fmt.bufPrint(&fifo_path_buffer, ".zig-cache/tmp/{s}/interrupted.fifo", .{tmp.sub_path[0..]});
582
+ try makeFifo(fifo_path);
583
+
584
+ var h = try Harness.create();
585
+ defer h.destroy();
586
+ const fx = &h.app_state.effects;
587
+ // Interruption stays on (the default): the best-effort cancel at
588
+ // the halfway mark must interrupt the blocked open and JOIN the
589
+ // worker — the abandon safety net must never fire here.
590
+ fx.file_join_deadline_ms = 2_000;
591
+
592
+ test_path = fifo_path;
593
+ test_bytes = "never delivered";
594
+ try h.app_state.dispatch(&h.harness.runtime, 1, .save);
595
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(50), .awake);
596
+
597
+ fx.deinit();
598
+
599
+ // Joined, not leaked: the syscall interruption converged the
600
+ // worker inside the deadline (deinit is deadline-bounded either
601
+ // way, so reaching these asserts already proves it returned).
602
+ try std.testing.expectEqual(@as(u32, 0), fx.abandoned_file_workers);
603
+ for (&fx.slots) |*slot| {
604
+ try std.testing.expect(slot.worker_thread == null);
605
+ try std.testing.expect(slot.state.load(.acquire) != .running);
606
+ }
607
+ }
608
+
389
609
  test "a cancel racing a finished file effect still reports one cancelled terminal" {
390
610
  var tmp = std.testing.tmpDir(.{});
391
611
  defer tmp.cleanup();
@@ -5,6 +5,7 @@ const app_manifest = @import("app_manifest");
5
5
  const core = @import("core.zig");
6
6
  const ui_app_model = @import("ui_app.zig");
7
7
  const effects_mod = @import("effects.zig");
8
+ const clock_mod = @import("clock.zig");
8
9
  const platform_mod = @import("../platform/root.zig");
9
10
 
10
11
  const canvas_label = "stream-canvas";
@@ -864,6 +865,292 @@ test "real executor cancels a long-running stream cleanly" {
864
865
  try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.activeCount());
865
866
  }
866
867
 
868
+ test "teardown mid-stream kills the real child and joins its worker before returning" {
869
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
870
+ var h = try Harness.create();
871
+ defer h.destroy();
872
+
873
+ // A child that would outlive the whole suite: only the teardown's
874
+ // kill can end it. Waiting for the first line proves the worker is
875
+ // mid-stream (child spawned, stdout pipe open) when deinit runs —
876
+ // the exact posture of the e2e battery's timed-out cancel test.
877
+ test_argv = &.{ "/bin/sh", "-c", "echo streaming; sleep 30" };
878
+ test_stdin = null;
879
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
880
+ try waitForRealCompletion(&h, sawLine);
881
+
882
+ const fx = &h.app_state.effects;
883
+ const start_ns = clock_mod.monotonicNanoseconds();
884
+ fx.deinit();
885
+ const elapsed_ms = (clock_mod.monotonicNanoseconds() - start_ns) / std.time.ns_per_ms;
886
+
887
+ // The kill ended the child — nothing waited out its 30s sleep
888
+ // (generous bound: a loaded runner still reaps a SIGKILLed child
889
+ // orders of magnitude faster than the sleep)...
890
+ try std.testing.expect(elapsed_ms < 10_000);
891
+ // ...and every worker was JOINED, not abandoned: no slot keeps a
892
+ // thread handle and none is still running, so the owner may free
893
+ // the channel's memory immediately. This pins the ownership hole
894
+ // behind the e2e cascade: a timed-out harness used to free the
895
+ // channel while a detached worker still held its slot pointer,
896
+ // and the worker segfaulted the NEXT test inside
897
+ // `slot.child_mutex.lock()`. The abandonment itself was a
898
+ // thread-timing window; the joined-and-idle invariant asserted
899
+ // here is its deterministic contract.
900
+ for (&fx.slots) |*slot| {
901
+ try std.testing.expect(slot.worker_thread == null);
902
+ try std.testing.expect(slot.state.load(.acquire) != .running);
903
+ }
904
+ // Joined, not abandoned: the group-kill converged this worker well
905
+ // inside the spawn deadline, so the abandon safety net stayed quiet.
906
+ try std.testing.expectEqual(@as(u32, 0), fx.abandoned_spawn_workers);
907
+ }
908
+
909
+ // The escaped-descendant shape the spawn teardown deadline exists for:
910
+ // `set -m` enables job control in the child shell, which puts the
911
+ // background job in its OWN process group — outside the group
912
+ // `killPublishedChild` signals — while the job keeps the inherited
913
+ // stdout write end open. The shell exits at once; the escapee never
914
+ // sees the kill; EOF never arrives; the worker's blocking read would
915
+ // hold teardown forever. (This is `setsid` daemonization in portable
916
+ // clothes — macOS ships no setsid(1), but /bin/bash is everywhere the
917
+ // POSIX suites run.) Echoing `$!` hands the test the escapee's pid.
918
+ const escaped_holder_argv: []const []const u8 = &.{ "/bin/bash", "-c", "set -m; sleep 300 & echo $!" };
919
+
920
+ fn parseEscapedPid(h: *Harness) !std.posix.pid_t {
921
+ return std.fmt.parseInt(std.posix.pid_t, h.app_state.model.lineAt(0), 10);
922
+ }
923
+
924
+ test "teardown interrupts a spawn worker held hostage by an escaped descendant and joins it with no leak" {
925
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
926
+ var h = try Harness.create();
927
+ defer h.destroy();
928
+ const fx = &h.app_state.effects;
929
+ // Interruption stays on (the default): the group-kill provably
930
+ // misses the escapee, so the best-effort cancel at the halfway
931
+ // mark must interrupt the blocked pipe read and JOIN the worker —
932
+ // the abandon safety net must never fire here.
933
+ fx.spawn_join_deadline_ms = 2_000;
934
+
935
+ test_argv = escaped_holder_argv;
936
+ test_stdin = null;
937
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
938
+ // The echoed pid line proves the worker is mid-stream: child
939
+ // spawned and published, stdout pipe open, read blocked.
940
+ try waitForRealCompletion(&h, sawLine);
941
+ const escaped_pid = try parseEscapedPid(&h);
942
+ // The escapee outlives the interruption by design (nothing kills
943
+ // it); reap it so a 300s sleeper never leaks into the suite.
944
+ defer std.posix.kill(escaped_pid, .KILL) catch {};
945
+
946
+ fx.deinit();
947
+
948
+ // Joined, not leaked: the syscall interruption converged the worker
949
+ // inside the deadline (deinit is deadline-bounded either way, so
950
+ // reaching these asserts already proves it returned).
951
+ try std.testing.expectEqual(@as(u32, 0), fx.abandoned_spawn_workers);
952
+ for (&fx.slots) |*slot| {
953
+ try std.testing.expect(slot.worker_thread == null);
954
+ try std.testing.expect(slot.state.load(.acquire) != .running);
955
+ }
956
+ }
957
+
958
+ test "teardown abandons a spawn worker held hostage by an escaped descendant and leaks its context loudly" {
959
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
960
+ const io = std.testing.io;
961
+ var h = try Harness.create();
962
+ defer h.destroy();
963
+ const fx = &h.app_state.effects;
964
+ // Tiny injected budget, interruption disabled: this test pins the
965
+ // SAFETY NET (abandon-and-leak). The interruption path that
966
+ // normally converges this shape first has its own test above.
967
+ fx.spawn_join_deadline_ms = 300;
968
+ fx.spawn_join_interrupt = false;
969
+
970
+ test_argv = escaped_holder_argv;
971
+ test_stdin = null;
972
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
973
+ try waitForRealCompletion(&h, sawLine);
974
+ const escaped_pid = try parseEscapedPid(&h);
975
+
976
+ // Grab the worker context before teardown abandons the slot: after
977
+ // the abandon it is exactly the leaked, process-lived memory the
978
+ // test walks to reach the direct child's recorded pid.
979
+ var leaked: @TypeOf(fx.slots[0].spawn_ctx) = null;
980
+ for (&fx.slots) |*slot| {
981
+ if (slot.kind == .spawn and slot.state.load(.acquire) == .running) leaked = slot.spawn_ctx;
982
+ }
983
+ try std.testing.expect(leaked != null);
984
+
985
+ const start_ns = clock_mod.monotonicNanoseconds();
986
+ fx.deinit();
987
+ const elapsed_ms = (clock_mod.monotonicNanoseconds() - start_ns) / std.time.ns_per_ms;
988
+
989
+ // Teardown returned on the injected budget's order of magnitude
990
+ // (generous bound for congested runners) instead of waiting out the
991
+ // escapee's 300s sleep...
992
+ try std.testing.expect(elapsed_ms < 10_000);
993
+ // ...and abandoned exactly the stuck worker, loudly through the
994
+ // counter seam, leaving no joinable thread and no running slot —
995
+ // the owner may free the channel's memory right now.
996
+ try std.testing.expectEqual(@as(u32, 1), fx.abandoned_spawn_workers);
997
+ for (&fx.slots) |*slot| {
998
+ try std.testing.expect(slot.worker_thread == null);
999
+ try std.testing.expect(slot.state.load(.acquire) != .running);
1000
+ }
1001
+
1002
+ // The process stays healthy after the leak: a fresh channel runs a
1003
+ // spawn to completion and its own safety net stays quiet.
1004
+ var h2 = try Harness.create();
1005
+ defer h2.destroy();
1006
+ test_argv = &.{ "/bin/sh", "-c", "printf 'alive\\n'" };
1007
+ try h2.app_state.dispatch(&h2.harness.runtime, 1, .start);
1008
+ try waitForRealCompletion(&h2, sawExit);
1009
+ try std.testing.expectEqual(@as(u32, 0), h2.app_state.effects.abandoned_spawn_workers);
1010
+
1011
+ // Wake the abandoned worker under the leak invariant: killing the
1012
+ // escaped holder closes the last stdout write end, the blocked read
1013
+ // reaches EOF, and the worker walks its leaked context — the child
1014
+ // handshake it locks to mark reaping, the pid recorded there — to
1015
+ // reap the (zombie) direct child, then finds itself abandoned and
1016
+ // exits without touching the torn-down channel. If the leak were
1017
+ // not honored, this walk is where a use-after-free would crash the
1018
+ // test. The direct child's disappearance is the deterministic proof
1019
+ // the worker really woke and completed the walk: only its
1020
+ // `child.wait` reaps that zombie.
1021
+ const direct_pid = leaked.?.child_id.?;
1022
+ try std.posix.kill(escaped_pid, .KILL);
1023
+ var waited_ms: usize = 0;
1024
+ while (waited_ms < 20_000) : (waited_ms += 10) {
1025
+ if (std.posix.kill(direct_pid, @enumFromInt(0))) |_| {
1026
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
1027
+ } else |err| {
1028
+ try std.testing.expectEqual(error.ProcessNotFound, err);
1029
+ break;
1030
+ }
1031
+ }
1032
+ try std.testing.expectError(error.ProcessNotFound, std.posix.kill(direct_pid, @enumFromInt(0)));
1033
+ }
1034
+
1035
+ test "an abandoned spawn worker survives the owner's allocator dying: its leak is process-lived only" {
1036
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
1037
+ const io = std.testing.io;
1038
+
1039
+ // The channel — and every caller-side allocation it makes — lives
1040
+ // in an arena backed by the leak-checking testing allocator and is
1041
+ // deinitialized right after teardown: the exact owner-lifetime
1042
+ // posture the abandon leak must survive (mirroring the file
1043
+ // worker's arena test). The channel struct itself sits in the arena
1044
+ // too, so even the worker's `self` pointer dies with the owner.
1045
+ const Channel = effects_mod.Effects(StreamMsg);
1046
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
1047
+ var arena_live = true;
1048
+ defer if (arena_live) arena.deinit();
1049
+ const fx = try arena.allocator().create(Channel);
1050
+ fx.* = Channel.init(arena.allocator());
1051
+ fx.spawn_join_deadline_ms = 300;
1052
+ fx.spawn_join_interrupt = false;
1053
+
1054
+ // A short-lived escapee this time: it exits on its own (~2s), so
1055
+ // the abandoned worker's wake needs no outside kill — by then the
1056
+ // leaked context is the only handle on the effect left anywhere.
1057
+ fx.spawn(.{
1058
+ .key = 1,
1059
+ .argv = &.{ "/bin/bash", "-c", "set -m; sleep 2 & echo held" },
1060
+ .on_line = null,
1061
+ .on_exit = null,
1062
+ });
1063
+ // The queued "held" line proves the worker published its child and
1064
+ // reached the blocking read (publish happens-before the enqueue).
1065
+ var setup_ms: usize = 0;
1066
+ while (setup_ms < 20_000) : (setup_ms += 10) {
1067
+ if (fx.hasPending()) break;
1068
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
1069
+ }
1070
+ try std.testing.expect(fx.hasPending());
1071
+ var leaked: @TypeOf(fx.slots[0].spawn_ctx) = null;
1072
+ for (&fx.slots) |*slot| {
1073
+ if (slot.kind == .spawn and slot.state.load(.acquire) == .running) leaked = slot.spawn_ctx;
1074
+ }
1075
+ try std.testing.expect(leaked != null);
1076
+
1077
+ fx.deinit();
1078
+ try std.testing.expectEqual(@as(u32, 1), fx.abandoned_spawn_workers);
1079
+ const direct_pid = leaked.?.child_id.?;
1080
+
1081
+ // Kill the owner's allocator: everything the channel ever got from
1082
+ // it — including the channel struct — is gone. The abandoned worker
1083
+ // must not notice: all it can still reach (its context, that
1084
+ // context's buffers, the executor io) is `process_allocator`
1085
+ // storage.
1086
+ arena.deinit();
1087
+ arena_live = false;
1088
+
1089
+ // The escapee exits on its own; EOF wakes the abandoned worker,
1090
+ // which walks only its leaked context (marking reaping under the
1091
+ // context's child mutex, reaping the zombie direct child) and exits
1092
+ // without touching the dead arena — if any of its reachable memory
1093
+ // were caller-allocated, this walk is where the use-after-free
1094
+ // would crash the test. The zombie's disappearance proves the wake.
1095
+ var waited_ms: usize = 0;
1096
+ while (waited_ms < 20_000) : (waited_ms += 10) {
1097
+ if (std.posix.kill(direct_pid, @enumFromInt(0))) |_| {
1098
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
1099
+ } else |err| {
1100
+ try std.testing.expectEqual(error.ProcessNotFound, err);
1101
+ break;
1102
+ }
1103
+ }
1104
+ try std.testing.expectError(error.ProcessNotFound, std.posix.kill(direct_pid, @enumFromInt(0)));
1105
+
1106
+ // And the happy path still frees everything through the same seams:
1107
+ // a fresh channel backed DIRECTLY by the testing allocator runs a
1108
+ // real spawn to completion and tears down joined — the leak check
1109
+ // at test end guards the caller-side allocations, and
1110
+ // `joinWorker`/`deinit` return the context and executor io to
1111
+ // `process_allocator`.
1112
+ var healthy = Channel.init(std.testing.allocator);
1113
+ defer healthy.deinit();
1114
+ healthy.spawn(.{
1115
+ .key = 2,
1116
+ .argv = &.{ "/bin/sh", "-c", "printf 'alive\\n'" },
1117
+ .on_line = null,
1118
+ .on_exit = null,
1119
+ });
1120
+ var healthy_ms: usize = 0;
1121
+ while (healthy_ms < 20_000) : (healthy_ms += 10) {
1122
+ if (healthy.hasPending()) break;
1123
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
1124
+ }
1125
+ try std.testing.expect(healthy.hasPending());
1126
+ healthy.deinit();
1127
+ try std.testing.expectEqual(@as(u32, 0), healthy.abandoned_spawn_workers);
1128
+ }
1129
+
1130
+ test "a spawn teardown storm never leaks a worker into the next harness" {
1131
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
1132
+ // The e2e cascade's shape, run deterministically and repeatedly: a
1133
+ // harness dies while its real child still streams (or while a
1134
+ // cancel is racing the spawn), then the next round builds a fresh
1135
+ // executor over recycled heap. Before the join fix an abandoned
1136
+ // worker could resume inside freed memory and crash a later round;
1137
+ // with it, destroy cannot return while any worker lives. Bounded
1138
+ // iterations keep the storm CI-cheap.
1139
+ var round: usize = 0;
1140
+ while (round < 8) : (round += 1) {
1141
+ var h = try Harness.create();
1142
+ // Runs at each iteration's end — the storm's teardown — and on
1143
+ // an error return alike.
1144
+ defer h.destroy();
1145
+ test_argv = &.{ "/bin/sh", "-c", "echo tick; sleep 30" };
1146
+ test_stdin = null;
1147
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1148
+ // Odd rounds race a wire cancel against the spawn before the
1149
+ // teardown; even rounds tear down against the bare stream.
1150
+ if (round % 2 == 1) try h.app_state.dispatch(&h.harness.runtime, 1, .stop);
1151
+ }
1152
+ }
1153
+
867
1154
  test "real executor children inherit the parent environment" {
868
1155
  if (builtin.os.tag == .windows) return error.SkipZigTest;
869
1156
  var h = try Harness.create();
@@ -12,6 +12,7 @@ const launch_timing = @import("launch_timing.zig");
12
12
  const runtime_clock = @import("clock.zig");
13
13
  const shell_layout = @import("shell_layout.zig");
14
14
  const runtime_builtin_bridge = @import("builtin_bridge.zig");
15
+ const runtime_canvas_widget_events = @import("canvas_widget_events.zig");
15
16
  const runtime_canvas_widget_context_menu = @import("canvas_widget_context_menu.zig");
16
17
  const runtime_canvas_widget_scroll_drivers = @import("canvas_widget_scroll_drivers.zig");
17
18
  const runtime_gpu_surface_events = @import("gpu_surface_events.zig");
@@ -76,6 +77,10 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
76
77
  return runtime_canvas_widget_context_menu.RuntimeCanvasWidgetContextMenu(Runtime);
77
78
  }
78
79
 
80
+ fn CanvasWidgetEventMethods() type {
81
+ return runtime_canvas_widget_events.RuntimeCanvasWidgetEvents(Runtime);
82
+ }
83
+
79
84
  fn AutomationWidgetMethods() type {
80
85
  return runtime_automation_widget_dispatch.RuntimeAutomationWidgetDispatch(Runtime);
81
86
  }
@@ -226,10 +231,25 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
226
231
  log(self, "app.start", "app started", &.{trace.string("app", app.name)});
227
232
  },
228
233
  .app_activated => {
234
+ self.app_active = true;
229
235
  try dispatchEvent(self, app, .{ .lifecycle = .activate });
230
236
  emitAppLifecycleEvent(self, "app:activate") catch |err| log(self, "app.activate.emit_failed", @errorName(err), &.{});
231
237
  },
232
238
  .app_deactivated => {
239
+ // The app-active register flips FIRST — before the
240
+ // tooltip reset and before the app hears the
241
+ // lifecycle event — so a model that rebuilds FROM
242
+ // its deactivation callback adopts under a runtime
243
+ // that already knows the app is inactive: the
244
+ // adoption arm's reveal/arm paths are gated on this
245
+ // register and stay silent.
246
+ self.app_active = false;
247
+ // Deactivation drops every tooltip conversation in
248
+ // every window (see the seam's own rationale) BEFORE
249
+ // the app hears the lifecycle event, so a model that
250
+ // rebuilds on deactivate adopts against clean
251
+ // tooltip state instead of a stale shown slot.
252
+ try CanvasWidgetEventMethods().resetCanvasTooltipIntentForAppDeactivation(self);
233
253
  try dispatchEvent(self, app, .{ .lifecycle = .deactivate });
234
254
  emitAppLifecycleEvent(self, "app:deactivate") catch |err| log(self, "app.deactivate.emit_failed", @errorName(err), &.{});
235
255
  },
@@ -305,7 +325,10 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
305
325
  }
306
326
  },
307
327
  .window_focused => |window_id| {
308
- if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| WindowViewMethods().setFocusedIndex(self, index);
328
+ // setFocusedIndex is the window-key seam: the
329
+ // window LOSING key here also drops its views'
330
+ // tooltip conversations there.
331
+ if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| try WindowViewMethods().setFocusedIndex(self, index);
309
332
  self.invalidated = true;
310
333
  },
311
334
  .frame_requested => try frame(self, app),