@native-sdk/cli 0.5.3 → 0.6.0

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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -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 +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  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 +3187 -264
  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 +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -0,0 +1,1362 @@
1
+ //! Pty effect coverage: the `fx.ptySpawn` family — lifecycle (spawn,
2
+ //! coalesced output, resize, kill, the exactly-one exit), the shared
3
+ //! key space with the other keyed families, the scriptable fake pty
4
+ //! (the null platform's whole terminal story), the live transports
5
+ //! (the POSIX backend's coalescing and lossless back-pressure; the
6
+ //! Windows ConPTY backend's rendered-stream/exit-code semantics), and
7
+ //! the record/replay acceptance story: replay NEVER spawns a process —
8
+ //! the journaled output batches (bytes in the session blob store) and
9
+ //! the exit record ARE the session, fed byte-identical with no shell
10
+ //! present.
11
+
12
+ const std = @import("std");
13
+ const builtin = @import("builtin");
14
+ const geometry = @import("geometry");
15
+ const app_manifest = @import("app_manifest");
16
+ const core = @import("core.zig");
17
+ const ui_app_mod = @import("ui_app.zig");
18
+ const effects_mod = @import("effects.zig");
19
+ const platform_mod = @import("../platform/root.zig");
20
+ const pty_transport = @import("pty.zig");
21
+ const session_blobs = @import("session_blobs.zig");
22
+ const session_record = @import("session_record.zig");
23
+ const session_replay = @import("session_replay.zig");
24
+
25
+ const testing = std.testing;
26
+
27
+ /// The POSIX live-transport tests spawn /bin/sh shapes and assert
28
+ /// byte-exact child output; ConPTY output is conhost's VT RENDERING of
29
+ /// the child's screen, not the raw byte stream, so Windows gets its
30
+ /// own live suite below (containment assertions, exit-code-only
31
+ /// endings) and these gate posix-tight.
32
+ const live_posix = pty_transport.supported and builtin.os.tag != .windows;
33
+ const live_windows = builtin.os.tag == .windows;
34
+
35
+ // ---------------------------------------------------- direct-fx tests
36
+ //
37
+ // The fake pty needs no executor thread or platform: a direct
38
+ // `Effects(Msg)` instance plus `takeMsg` drives the whole vocabulary.
39
+
40
+ const DirectMsg = union(enum) {
41
+ pty: effects_mod.EffectPtyEvent,
42
+ host: effects_mod.EffectHostResult,
43
+ line: effects_mod.EffectLine,
44
+ exit: effects_mod.EffectExit,
45
+ };
46
+
47
+ const DirectFx = effects_mod.Effects(DirectMsg);
48
+
49
+ fn expectOutput(fx: *DirectFx, key: u64, bytes: []const u8) !void {
50
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
51
+ try testing.expectEqual(key, msg.pty.key);
52
+ try testing.expectEqual(effects_mod.EffectPtyEventKind.output, msg.pty.kind);
53
+ try testing.expectEqualStrings(bytes, msg.pty.bytes);
54
+ // A non-exit event carries the -1 code sentinel — the live drain's
55
+ // default. A fed (replay) output batch must match it, or an app that
56
+ // folds the code into its model diverges on replay.
57
+ try testing.expectEqual(effects_mod.effect_error_exit_code, msg.pty.code);
58
+ }
59
+
60
+ fn expectExit(fx: *DirectFx, key: u64, reason: effects_mod.EffectExitReason) !effects_mod.EffectPtyEvent {
61
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
62
+ try testing.expectEqual(key, msg.pty.key);
63
+ try testing.expectEqual(effects_mod.EffectPtyEventKind.exit, msg.pty.kind);
64
+ try testing.expectEqual(reason, msg.pty.reason);
65
+ return msg.pty;
66
+ }
67
+
68
+ test "fake pty lifecycle: spawn parks the request, feeds deliver, exit retires the key" {
69
+ var fx = DirectFx.init(testing.allocator);
70
+ defer fx.deinit();
71
+ fx.executor = .fake;
72
+
73
+ fx.ptySpawn(.{
74
+ .key = 9,
75
+ .argv = &.{ "sh", "-l" },
76
+ .cols = 120,
77
+ .rows = 40,
78
+ .on_event = DirectFx.ptyMsg(.pty),
79
+ });
80
+ try testing.expectEqual(@as(usize, 1), fx.pendingPtyCount());
81
+ const request = fx.pendingPtyAt(0) orelse return error.TestExpectedRequest;
82
+ try testing.expectEqual(@as(u64, 9), request.key);
83
+ try testing.expectEqual(@as(usize, 2), request.argv.len);
84
+ try testing.expectEqualStrings("sh", request.argv[0]);
85
+ try testing.expectEqualStrings("-l", request.argv[1]);
86
+ try testing.expectEqual(@as(u16, 120), request.cols);
87
+ try testing.expectEqual(@as(u16, 40), request.rows);
88
+ try testing.expectEqualStrings(pty_transport.default_term, request.term);
89
+
90
+ try fx.feedPtyOutput(9, "$ ");
91
+ try fx.feedPtyOutput(9, "hello\r\n");
92
+ try fx.feedPtyExit(9, 0, 0, .exited, 0);
93
+ try expectOutput(&fx, 9, "$ ");
94
+ try expectOutput(&fx, 9, "hello\r\n");
95
+ const exit = try expectExit(&fx, 9, .exited);
96
+ try testing.expectEqual(@as(i32, 0), exit.code);
97
+ try testing.expectEqual(@as(usize, 0), fx.pendingPtyCount());
98
+
99
+ // The exit delivery freed the key: a fresh spawn under it is
100
+ // accepted (the families' shared instant).
101
+ fx.ptySpawn(.{ .key = 9, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
102
+ try testing.expectEqual(@as(usize, 1), fx.pendingPtyCount());
103
+ }
104
+
105
+ test "pty admission: every refused spawn delivers exactly one rejected exit" {
106
+ var fx = DirectFx.init(testing.allocator);
107
+ defer fx.deinit();
108
+ fx.executor = .fake;
109
+
110
+ // Empty argv.
111
+ fx.ptySpawn(.{ .key = 1, .argv = &.{}, .on_event = DirectFx.ptyMsg(.pty) });
112
+ _ = try expectExit(&fx, 1, .rejected);
113
+
114
+ // argv over the entry budget.
115
+ var too_many: [effects_mod.max_effect_argv + 1][]const u8 = undefined;
116
+ for (&too_many) |*arg| arg.* = "x";
117
+ fx.ptySpawn(.{ .key = 2, .argv = &too_many, .on_event = DirectFx.ptyMsg(.pty) });
118
+ _ = try expectExit(&fx, 2, .rejected);
119
+
120
+ // argv over the byte budget.
121
+ const big = "y" ** (effects_mod.max_effect_argv_bytes + 1);
122
+ fx.ptySpawn(.{ .key = 3, .argv = &.{big}, .on_event = DirectFx.ptyMsg(.pty) });
123
+ _ = try expectExit(&fx, 3, .rejected);
124
+
125
+ // A zero dimension.
126
+ fx.ptySpawn(.{ .key = 4, .argv = &.{"sh"}, .cols = 0, .on_event = DirectFx.ptyMsg(.pty) });
127
+ _ = try expectExit(&fx, 4, .rejected);
128
+
129
+ // TERM over its bound.
130
+ const long_term = "t" ** (effects_mod.max_effect_pty_term_bytes + 1);
131
+ fx.ptySpawn(.{ .key = 5, .argv = &.{"sh"}, .term = long_term, .on_event = DirectFx.ptyMsg(.pty) });
132
+ _ = try expectExit(&fx, 5, .rejected);
133
+
134
+ // A duplicate active key.
135
+ fx.ptySpawn(.{ .key = 6, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
136
+ fx.ptySpawn(.{ .key = 6, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
137
+ _ = try expectExit(&fx, 6, .rejected);
138
+
139
+ // Table exhaustion: the table already holds key 6; filling the
140
+ // remaining slots leaves the next spawn refused.
141
+ var key: u64 = 7;
142
+ while (key < 7 + effects_mod.max_effect_ptys - 1) : (key += 1) {
143
+ fx.ptySpawn(.{ .key = key, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
144
+ }
145
+ fx.ptySpawn(.{ .key = 99, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
146
+ _ = try expectExit(&fx, 99, .rejected);
147
+ try testing.expectEqual(@as(usize, effects_mod.max_effect_ptys), fx.pendingPtyCount());
148
+ }
149
+
150
+ test "fake pty write capture, resize mirror, and kill mirror" {
151
+ var fx = DirectFx.init(testing.allocator);
152
+ defer fx.deinit();
153
+ fx.executor = .fake;
154
+
155
+ fx.ptySpawn(.{ .key = 11, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
156
+ try testing.expect(fx.ptyWrite(11, "ls -la"));
157
+ try testing.expect(fx.ptyWrite(11, "\r"));
158
+ try testing.expectEqualStrings("ls -la\r", fx.ptyWrittenBytes(11));
159
+
160
+ // Over-bound single write: refused whole (returns false), never a cut.
161
+ const oversized = "z" ** (effects_mod.max_effect_pty_write_bytes + 1);
162
+ try testing.expect(!fx.ptyWrite(11, oversized));
163
+ try testing.expectEqualStrings("ls -la\r", fx.ptyWrittenBytes(11));
164
+
165
+ fx.ptyResize(11, 200, 60);
166
+ const size = fx.ptySize(11) orelse return error.TestExpectedSize;
167
+ try testing.expectEqual(@as(u16, 200), size.cols);
168
+ try testing.expectEqual(@as(u16, 60), size.rows);
169
+
170
+ try testing.expect(!fx.ptyKillRequested(11));
171
+ fx.ptyKill(11);
172
+ try testing.expect(fx.ptyKillRequested(11));
173
+ // The scripted ending after a kill: a kill is a cancellation, not a
174
+ // signaled death, so the live transport reports reason `.cancelled`
175
+ // with no signal and the -1 code. Feeding a stray signal 9 proves
176
+ // the feed boundary clamps the tuple to that contract rather than
177
+ // journaling an event replay's damage gate would later refuse. The
178
+ // delivered drop count is the fed count plus the refusal the fake
179
+ // itself counted for the oversized write above — the counted-refusal
180
+ // contract, without the script re-deriving the tally.
181
+ try fx.feedPtyExit(11, 7, 9, .cancelled, 0);
182
+ const exit = try expectExit(&fx, 11, .cancelled);
183
+ try testing.expectEqual(@as(i32, 0), exit.signal);
184
+ try testing.expectEqual(effects_mod.effect_error_exit_code, exit.code);
185
+ try testing.expectEqual(@as(u32, 1), exit.dropped_writes);
186
+ }
187
+
188
+ test "a signaled exit carries its signal; a signaled feed with no signal is refused" {
189
+ var fx = DirectFx.init(testing.allocator);
190
+ defer fx.deinit();
191
+ fx.executor = .fake;
192
+
193
+ // The contract is a biconditional: `.signaled` REQUIRES a nonzero
194
+ // signal (and a signal is meaningful ONLY on `.signaled`). A feed
195
+ // that names `.signaled` with signal 0 could never come from the live
196
+ // transport and would journal a record replay's damage gate refuses —
197
+ // so the feed boundary refuses it loudly, before it can be recorded.
198
+ fx.ptySpawn(.{ .key = 51, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
199
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyExit(51, -1, 0, .signaled, 0));
200
+ // The slot is untouched by the refusal: a well-formed signaled exit
201
+ // then delivers, carrying its signal and the -1 code sentinel.
202
+ try fx.feedPtyExit(51, -1, 9, .signaled, 0);
203
+ const exit = try expectExit(&fx, 51, .signaled);
204
+ try testing.expectEqual(@as(i32, 9), exit.signal);
205
+ try testing.expectEqual(effects_mod.effect_error_exit_code, exit.code);
206
+
207
+ // Range gates, both axes: waitpid's status word carries exit codes
208
+ // 0..255 (plus the -1 externally-reaped sentinel) and signals
209
+ // 1..127 — a feed outside those could never come from the live
210
+ // transport and is refused before it can be journaled.
211
+ fx.ptySpawn(.{ .key = 52, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
212
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyExit(52, 300, 0, .exited, 0));
213
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyExit(52, -2, 0, .exited, 0));
214
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyExit(52, -1, 128, .signaled, 0));
215
+ // The refusals left the slot intact: the edge of the legal range
216
+ // still delivers.
217
+ try fx.feedPtyExit(52, 255, 0, .exited, 0);
218
+ const edge = try expectExit(&fx, 52, .exited);
219
+ try testing.expectEqual(@as(i32, 255), edge.code);
220
+ }
221
+
222
+ test "replay-mode ptyWrite returns the journaled verdicts, never a recomputed guess" {
223
+ var fx = DirectFx.init(testing.allocator);
224
+ defer fx.deinit();
225
+ fx.armReplay();
226
+
227
+ // The replayed spawn parks; the parked occupancy holds the key.
228
+ fx.ptySpawn(.{ .key = 81, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
229
+
230
+ // The journal recorded refuse-then-accept (a full FIFO that later
231
+ // drained). The replayed writes must return exactly that — the
232
+ // fake has no child, so recomputing admission locally would answer
233
+ // `true` for the first write and diverge any model that retained
234
+ // the refused bytes.
235
+ try fx.pushReplayPtyWriteVerdict(81, false);
236
+ try fx.pushReplayPtyWriteVerdict(81, true);
237
+ try testing.expect(!fx.ptyWrite(81, "retained bytes"));
238
+ try testing.expect(fx.ptyWrite(81, "delivered bytes"));
239
+
240
+ // Boundary alignment: an empty payload consumes no verdict (both
241
+ // sides return true before the admission decision), and a write
242
+ // past the recorded count answers optimistically with a divergence
243
+ // warning rather than trapping.
244
+ try fx.pushReplayPtyWriteVerdict(81, false);
245
+ try testing.expect(fx.ptyWrite(81, "")); // no verdict consumed
246
+ try testing.expect(!fx.ptyWrite(81, "consumes the queued refusal"));
247
+ try testing.expect(fx.ptyWrite(81, "past the recording"));
248
+ }
249
+
250
+ test "a write against a synchronously failed spawn journals the verdict replay's park consumes" {
251
+ if (comptime !pty_transport.supported) return;
252
+ const VerdictCapture = struct {
253
+ write_records: u32 = 0,
254
+ last_code: i32 = -1,
255
+
256
+ fn journal(self: *@This()) effects_mod.EffectJournal {
257
+ return .{ .context = self, .record_fn = record };
258
+ }
259
+
260
+ fn record(context: *anyopaque, rec: effects_mod.EffectResultRecord) void {
261
+ const self: *@This() = @ptrCast(@alignCast(context));
262
+ if (rec.kind == .pty and rec.pty_kind == .write) {
263
+ self.write_records += 1;
264
+ self.last_code = rec.code;
265
+ }
266
+ }
267
+ };
268
+
269
+ // LIVE: the transport fails synchronously (missing binary), the
270
+ // slot releases, but the staged spawn_failed terminal keeps the key
271
+ // occupied — a same-dispatch write refuses AND journals its verdict,
272
+ // because replay holds the same window as a parked slot where the
273
+ // write consumes one.
274
+ var capture: VerdictCapture = .{};
275
+ {
276
+ var fx = DirectFx.init(testing.allocator);
277
+ defer fx.deinit();
278
+ fx.bindJournal(capture.journal());
279
+ fx.ptySpawn(.{ .key = 91, .argv = &.{"/nonexistent-binary-for-this-test"}, .on_event = DirectFx.ptyMsg(.pty) });
280
+ try testing.expect(!fx.ptyWrite(91, "same dispatch"));
281
+ try testing.expectEqual(@as(u32, 1), capture.write_records);
282
+ try testing.expectEqual(@as(i32, 0), capture.last_code);
283
+ // The refusal LANDS in the delivered exit: the staged terminal
284
+ // has no slot left to carry drops, so the count rides the
285
+ // staged entry itself — never silence.
286
+ const exit = try expectExit(&fx, 91, .spawn_failed);
287
+ try testing.expectEqual(@as(u32, 1), exit.dropped_writes);
288
+ // Past the terminal's delivery the key is free: no slot, no
289
+ // staged terminal — a write refuses with NO verdict (replay's
290
+ // retired park matches).
291
+ try testing.expect(!fx.ptyWrite(91, "after delivery"));
292
+ try testing.expectEqual(@as(u32, 1), capture.write_records);
293
+ }
294
+
295
+ // REPLAY: the same dispatch stream — the parked spawn holds the
296
+ // key, the write consumes the journaled refusal, the fed
297
+ // spawn_failed (carrying the journaled tally) retires the park,
298
+ // and the feeds settle exactly.
299
+ {
300
+ var fx = DirectFx.init(testing.allocator);
301
+ defer fx.deinit();
302
+ fx.armReplay();
303
+ fx.ptySpawn(.{ .key = 91, .argv = &.{"/nonexistent-binary-for-this-test"}, .on_event = DirectFx.ptyMsg(.pty) });
304
+ try fx.pushReplayPtyWriteVerdict(91, false);
305
+ try testing.expect(!fx.ptyWrite(91, "same dispatch"));
306
+ try fx.feedPtyExit(91, -1, 0, .spawn_failed, 1);
307
+ const exit = try expectExit(&fx, 91, .spawn_failed);
308
+ try testing.expectEqual(@as(u32, 1), exit.dropped_writes);
309
+ try testing.expect(!fx.ptyWrite(91, "after delivery"));
310
+ try fx.settleReplayFeeds();
311
+ }
312
+ }
313
+
314
+ test "the replay verdict queue grows past its inline window and stays keyed" {
315
+ var fx = DirectFx.init(testing.allocator);
316
+ defer fx.deinit();
317
+ fx.armReplay();
318
+ fx.ptySpawn(.{ .key = 84, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
319
+
320
+ // Every verdict a dispatch recorded feeds BEFORE that dispatch
321
+ // replays, so one update that wrote thousands of chunks (a giant
322
+ // paste) queues them all at once: the queue must grow, not refuse
323
+ // its own recording. Alternate the bits so a popped verdict proves
324
+ // order survived the spill copies.
325
+ const count = effects_mod.max_effect_replay_pty_write_inline * 4 + 3;
326
+ for (0..count) |i| {
327
+ try fx.pushReplayPtyWriteVerdict(84, i % 2 == 0);
328
+ }
329
+ for (0..count) |i| {
330
+ try testing.expectEqual(i % 2 == 0, fx.ptyWrite(84, "chunk"));
331
+ }
332
+ try fx.settleReplayFeeds();
333
+ }
334
+
335
+ test "settle refuses replay write-count divergence in both directions" {
336
+ // Leftover verdicts: the replayed updates wrote FEWER times than
337
+ // the recording. No checkpoint necessarily moves (nothing consumed
338
+ // the verdict), so only the end-of-journal settle makes it loud.
339
+ {
340
+ var fx = DirectFx.init(testing.allocator);
341
+ defer fx.deinit();
342
+ fx.armReplay();
343
+ try fx.pushReplayPtyWriteVerdict(82, true);
344
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
345
+ }
346
+ // Underflow: the replayed updates wrote MORE times than the
347
+ // recording. The extra write answered optimistically (a
348
+ // fire-and-forget caller ignores it, changing no state), so again
349
+ // only settle catches it.
350
+ {
351
+ var fx = DirectFx.init(testing.allocator);
352
+ defer fx.deinit();
353
+ fx.armReplay();
354
+ fx.ptySpawn(.{ .key = 82, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
355
+ try testing.expect(fx.ptyWrite(82, "past the recording"));
356
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
357
+ }
358
+ // A write against a DIFFERENT pty than the verdict was recorded
359
+ // for: same count, same result, still divergent input — the keyed
360
+ // comparison catches what a global boolean sequence would pass.
361
+ {
362
+ var fx = DirectFx.init(testing.allocator);
363
+ defer fx.deinit();
364
+ fx.armReplay();
365
+ fx.ptySpawn(.{ .key = 82, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
366
+ fx.ptySpawn(.{ .key = 83, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
367
+ try fx.pushReplayPtyWriteVerdict(82, true);
368
+ try testing.expect(fx.ptyWrite(83, "wrong session"));
369
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
370
+ }
371
+ // The clock feed settles by the same rule: a journaled value never
372
+ // consumed (the replayed updates read the clock fewer times)...
373
+ {
374
+ var fx = DirectFx.init(testing.allocator);
375
+ defer fx.deinit();
376
+ fx.armReplay();
377
+ try fx.pushReplayClock(1_000);
378
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
379
+ }
380
+ // ...and a read past the journaled values (answered 0 optimistically,
381
+ // which need not move any checkpoint) both fail the settle.
382
+ {
383
+ var fx = DirectFx.init(testing.allocator);
384
+ defer fx.deinit();
385
+ fx.armReplay();
386
+ try testing.expectEqual(@as(i64, 0), fx.wallMs());
387
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
388
+ }
389
+ // A fed result still awaiting delivery: the journal ended before
390
+ // the event that consumed it live — truncation, not success.
391
+ {
392
+ var fx = DirectFx.init(testing.allocator);
393
+ defer fx.deinit();
394
+ fx.armReplay();
395
+ fx.ptySpawn(.{ .key = 85, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
396
+ try fx.feedPtyOutput(85, "undelivered");
397
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
398
+ // Delivered, the same feeds settle clean.
399
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
400
+ try testing.expectEqualStrings("undelivered", msg.pty.bytes);
401
+ try fx.settleReplayFeeds();
402
+ }
403
+ // Every fed family settles by the same rule, not just ptys: a fed
404
+ // LINE still queued at the journal's end is the identical
405
+ // truncation, and delivering it settles clean.
406
+ {
407
+ var fx = DirectFx.init(testing.allocator);
408
+ defer fx.deinit();
409
+ fx.armReplay();
410
+ fx.spawn(.{ .key = 86, .argv = &.{"sh"}, .on_line = DirectFx.lineMsg(.line), .on_exit = DirectFx.exitMsg(.exit) });
411
+ try fx.feedLine(86, "undelivered line");
412
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
413
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
414
+ try testing.expectEqualStrings("undelivered line", msg.line.line);
415
+ try fx.settleReplayFeeds();
416
+ }
417
+ // Journaled environment deliveries never consumed settle by the
418
+ // clock's rule too.
419
+ {
420
+ var fx = DirectFx.init(testing.allocator);
421
+ defer fx.deinit();
422
+ fx.armReplay();
423
+ try fx.pushReplayEnv("appearance", "dark");
424
+ try testing.expectError(error.ReplayDivergence, fx.settleReplayFeeds());
425
+ }
426
+ // Exact consumption settles clean.
427
+ {
428
+ var fx = DirectFx.init(testing.allocator);
429
+ defer fx.deinit();
430
+ fx.armReplay();
431
+ fx.ptySpawn(.{ .key = 83, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
432
+ try fx.pushReplayPtyWriteVerdict(83, false);
433
+ try fx.pushReplayClock(1_000);
434
+ try testing.expect(!fx.ptyWrite(83, "recorded"));
435
+ try testing.expectEqual(@as(i64, 1_000), fx.wallMs());
436
+ try fx.settleReplayFeeds();
437
+ }
438
+ }
439
+
440
+ test "a fed line against a full queue reports EffectQueueFull, never a silent drop" {
441
+ var fx = DirectFx.init(testing.allocator);
442
+ defer fx.deinit();
443
+ fx.executor = .fake;
444
+ fx.spawn(.{ .key = 87, .argv = &.{"sh"}, .on_line = DirectFx.lineMsg(.line), .on_exit = DirectFx.exitMsg(.exit) });
445
+
446
+ // Fill the completion queue without draining: the feed that finds
447
+ // it full must say so — the replay pump answers by draining through
448
+ // a wake and feeding again, so a recorded delivery is never
449
+ // silently converted into a drop.
450
+ var fed: usize = 0;
451
+ const full: anyerror!void = while (fed < effects_mod.max_effect_queue_entries + 1) : (fed += 1) {
452
+ fx.feedLine(87, "filler") catch |err| break err;
453
+ } else {};
454
+ try testing.expectError(error.EffectQueueFull, full);
455
+ // Draining frees the queue and the same feed lands — with NO drop
456
+ // recorded against the stream (the fed refusal counted nothing).
457
+ var drained: usize = 0;
458
+ while (fx.takeMsg()) |msg| {
459
+ try testing.expect(msg == .line);
460
+ try testing.expectEqual(@as(u32, 0), msg.line.dropped_before);
461
+ drained += 1;
462
+ }
463
+ try testing.expectEqual(fed, drained);
464
+ try fx.feedLine(87, "after the drain");
465
+ const landed = fx.takeMsg() orelse return error.TestExpectedMsg;
466
+ try testing.expectEqualStrings("after the drain", landed.line.line);
467
+ }
468
+
469
+ test "staged-Msg keys stay valid across a large batch (no fixed-ring clobber)" {
470
+ var fx = DirectFx.init(testing.allocator);
471
+ defer fx.deinit();
472
+
473
+ // A single Cmd.batch can stage far more keyed rejections than any
474
+ // fixed ring holds; each must keep its OWN key until delivery. Stage
475
+ // many distinct keys WITHOUT draining (the stage never empties, so no
476
+ // reclaim happens between them) and capture each returned durable
477
+ // slice.
478
+ const count = 40;
479
+ var slices: [count][]const u8 = undefined;
480
+ var scratch: [count][8]u8 = undefined;
481
+ for (0..count) |i| {
482
+ const key = std.fmt.bufPrint(&scratch[i], "k{d}", .{i}) catch unreachable;
483
+ slices[i] = fx.stageLoopKey(key);
484
+ fx.stageLoopMsg(.{ .pty = .{ .key = 0, .kind = .exit, .reason = .rejected } });
485
+ }
486
+ // Every captured slice still reads its ORIGINAL key — none clobbered
487
+ // by a later one, though the backing array grew several times past
488
+ // its initial capacity.
489
+ for (0..count) |i| {
490
+ var expect: [8]u8 = undefined;
491
+ const want = std.fmt.bufPrint(&expect, "k{d}", .{i}) catch unreachable;
492
+ try testing.expectEqualStrings(want, slices[i]);
493
+ }
494
+
495
+ // Interned: re-staging a known key returns the SAME instance-lived
496
+ // slice — repeat rejections of one key cost nothing, and a model
497
+ // that committed the earlier slice stays valid for the app's life.
498
+ const again = fx.stageLoopKey("k1");
499
+ try testing.expectEqual(slices[1].ptr, again.ptr);
500
+ }
501
+
502
+ test "a write after the fed exit is staged refuses and counts - the live rule on fakes" {
503
+ var fx = DirectFx.init(testing.allocator);
504
+ defer fx.deinit();
505
+ fx.executor = .fake;
506
+
507
+ fx.ptySpawn(.{ .key = 58, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
508
+ try testing.expect(fx.ptyWrite(58, "before"));
509
+ try fx.feedPtyExit(58, 0, 0, .exited, 0);
510
+ // The exit is staged but undelivered: the session is already over,
511
+ // so the write refuses (never a silent acceptance the real
512
+ // transport would have rejected) AND lands in the delivered tally —
513
+ // the delivery-time fold reads the slot's count, the same rule the
514
+ // live staged-exit drain follows.
515
+ try testing.expect(!fx.ptyWrite(58, "late"));
516
+ const exit = try expectExit(&fx, 58, .exited);
517
+ try testing.expectEqual(@as(u32, 1), exit.dropped_writes);
518
+ }
519
+
520
+ test "a fake pty refuses a second feed after its exit is queued" {
521
+ var fx = DirectFx.init(testing.allocator);
522
+ defer fx.deinit();
523
+ fx.executor = .fake;
524
+
525
+ fx.ptySpawn(.{ .key = 71, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
526
+ try fx.feedPtyExit(71, 0, 0, .exited, 0);
527
+ // One terminal per spawn: a feed before the exit drains is refused
528
+ // loudly, never enqueued and silently dropped.
529
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyOutput(71, "late"));
530
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyExit(71, 0, 0, .exited, 0));
531
+ _ = try expectExit(&fx, 71, .exited);
532
+ }
533
+
534
+ test "a fed output batch over the chunk bound is refused, never truncated" {
535
+ var fx = DirectFx.init(testing.allocator);
536
+ defer fx.deinit();
537
+ fx.executor = .fake;
538
+
539
+ fx.ptySpawn(.{ .key = 72, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
540
+ var over: [effects_mod.max_effect_pty_chunk_bytes + 1]u8 = undefined;
541
+ @memset(&over, 'x');
542
+ try testing.expectError(error.PtyChunkTooLarge, fx.feedPtyOutput(72, &over));
543
+ }
544
+
545
+ test "a fed output batch past the inline entry bound rides a heap payload intact" {
546
+ var fx = DirectFx.init(testing.allocator);
547
+ defer fx.deinit();
548
+ fx.executor = .fake;
549
+
550
+ fx.ptySpawn(.{ .key = 21, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
551
+ var big: [effects_mod.max_effect_line_bytes + 128]u8 = undefined;
552
+ for (&big, 0..) |*byte, index| byte.* = @intCast('a' + (index % 26));
553
+ try fx.feedPtyOutput(21, &big);
554
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
555
+ try testing.expectEqual(effects_mod.EffectPtyEventKind.output, msg.pty.kind);
556
+ try testing.expectEqualSlices(u8, &big, msg.pty.bytes);
557
+ }
558
+
559
+ test "pty keys share the keyed families' space" {
560
+ var fx = DirectFx.init(testing.allocator);
561
+ defer fx.deinit();
562
+ fx.executor = .fake;
563
+
564
+ fx.ptySpawn(.{ .key = 31, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
565
+ // A channel open under the pty's key is refused (and vice versa —
566
+ // one key space across every keyed family).
567
+ const handle = fx.openChannel(.{ .key = 31, .on_event = undefined });
568
+ try testing.expect(handle.shared == null);
569
+
570
+ // A host request under the live pty's key is rejected the same way
571
+ // (`hostRequest` enumerates the families inline for its
572
+ // replace-in-flight rule, so the pty window must be there too)...
573
+ fx.hostRequest(.{ .key = 31, .name = "probe", .on_result = DirectFx.hostMsg(.host) });
574
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
575
+ try testing.expect(rejected == .host);
576
+ try testing.expectEqual(@as(u64, 31), rejected.host.key);
577
+ try testing.expect(!rejected.host.ok);
578
+
579
+ // ...and the key frees with the exit's delivery: the same request
580
+ // then reaches the (fake) executor, parks, and answers when fed.
581
+ try fx.feedPtyExit(31, 0, 0, .exited, 0);
582
+ const exit = fx.takeMsg() orelse return error.TestExpectedMsg;
583
+ try testing.expect(exit == .pty);
584
+ fx.hostRequest(.{ .key = 31, .name = "probe", .on_result = DirectFx.hostMsg(.host) });
585
+ try testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
586
+ try fx.feedHostResult(31, true, "answered");
587
+ const answered = fx.takeMsg() orelse return error.TestExpectedMsg;
588
+ try testing.expect(answered == .host);
589
+ try testing.expect(answered.host.ok);
590
+ }
591
+
592
+ test "replay never spawns: an armed channel parks the spawn and feeds deliver the session" {
593
+ var fx = DirectFx.init(testing.allocator);
594
+ defer fx.deinit();
595
+ fx.armReplay();
596
+
597
+ fx.ptySpawn(.{ .key = 41, .argv = &.{ "sh", "-c", "echo hi" }, .on_event = DirectFx.ptyMsg(.pty) });
598
+ // Parked as a fake: no process, no io thread — the journal is the
599
+ // whole world.
600
+ try testing.expectEqual(@as(usize, 1), fx.pendingPtyCount());
601
+ try fx.feedPtyOutput(41, "hi\r\n");
602
+ try fx.feedPtyExit(41, 0, 0, .exited, 0);
603
+ try expectOutput(&fx, 41, "hi\r\n");
604
+ _ = try expectExit(&fx, 41, .exited);
605
+ try testing.expectEqual(@as(usize, 0), fx.pendingPtyCount());
606
+
607
+ // A fed start failure retires a park at the spawn's dispatch
608
+ // position (the reserved pending-order stamp).
609
+ fx.ptySpawn(.{ .key = 42, .argv = &.{"missing-binary"}, .on_event = DirectFx.ptyMsg(.pty) });
610
+ try fx.feedPtyExit(42, effects_mod.effect_error_exit_code, 0, .spawn_failed, 0);
611
+ _ = try expectExit(&fx, 42, .spawn_failed);
612
+ try testing.expectEqual(@as(usize, 0), fx.pendingPtyCount());
613
+
614
+ // Nothing feeds past a terminal: one exit per spawn.
615
+ fx.ptySpawn(.{ .key = 43, .argv = &.{"sh"}, .on_event = DirectFx.ptyMsg(.pty) });
616
+ try fx.feedPtyExit(43, 0, 0, .exited, 0);
617
+ try testing.expectError(error.ReplayDamagedRecord, fx.feedPtyOutput(43, "late"));
618
+ }
619
+
620
+ // ---------------------------------------------------- live posix tests
621
+ //
622
+ // The real transport, driven end to end through the effects channel.
623
+ // Skipped where the toolkit has no POSIX pty — libc-free builds test
624
+ // through the fake pty above, and Windows drives its ConPTY backend
625
+ // through its own live suite further down (the assertions differ where
626
+ // the platform semantics do).
627
+
628
+ fn drainUntilExit(fx: *DirectFx, budget_ms: u64) !struct {
629
+ output: std.ArrayList(u8),
630
+ records: usize,
631
+ exit: effects_mod.EffectPtyEvent,
632
+ } {
633
+ var output: std.ArrayList(u8) = .empty;
634
+ errdefer output.deinit(testing.allocator);
635
+ var records: usize = 0;
636
+ var waited: u64 = 0;
637
+ while (waited < budget_ms) {
638
+ while (fx.takeMsg()) |msg| {
639
+ switch (msg.pty.kind) {
640
+ .output => {
641
+ records += 1;
642
+ try output.appendSlice(testing.allocator, msg.pty.bytes);
643
+ },
644
+ .exit => return .{ .output = output, .records = records, .exit = msg.pty },
645
+ // Journal-only write verdicts never deliver as events.
646
+ .write => unreachable,
647
+ }
648
+ }
649
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(2), .awake);
650
+ waited += 2;
651
+ }
652
+ return error.TestPtyTimeout;
653
+ }
654
+
655
+ test "live pty end to end: output, coalescing, and the exit code" {
656
+ if (comptime !live_posix) return;
657
+ var fx = DirectFx.init(testing.allocator);
658
+ defer fx.deinit();
659
+
660
+ fx.ptySpawn(.{
661
+ .key = 51,
662
+ // 200 one-byte writes; the staging ring coalesces whatever
663
+ // lands between drains, so waiting for the child first proves
664
+ // the batch arrives as a handful of records, never 200.
665
+ .argv = &.{ "/bin/sh", "-c", "i=0; while [ $i -lt 200 ]; do printf x; i=$((i+1)); done; exit 4" },
666
+ .on_event = DirectFx.ptyMsg(.pty),
667
+ });
668
+ // Let the child finish before the first drain — every byte then
669
+ // sits in one staged backlog.
670
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(300), .awake);
671
+ var result = try drainUntilExit(&fx, 5_000);
672
+ defer result.output.deinit(testing.allocator);
673
+ try testing.expectEqual(@as(usize, 200), result.output.items.len);
674
+ try testing.expect(result.records <= 3);
675
+ try testing.expectEqual(@as(i32, 4), result.exit.code);
676
+ try testing.expectEqual(effects_mod.EffectExitReason.exited, result.exit.reason);
677
+ }
678
+
679
+ test "live pty back-pressure is lossless past the staging ring" {
680
+ if (comptime !live_posix) return;
681
+ var fx = DirectFx.init(testing.allocator);
682
+ defer fx.deinit();
683
+
684
+ // One megabyte — four times the staging ring. The reader parks when
685
+ // the ring fills and resumes as the drain frees room; every byte
686
+ // arrives, each record within the chunk bound.
687
+ const total: usize = 1024 * 1024;
688
+ fx.ptySpawn(.{
689
+ .key = 52,
690
+ .argv = &.{ "/bin/sh", "-c", "dd if=/dev/zero bs=4096 count=256 2>/dev/null | tr '\\0' 'a'" },
691
+ .on_event = DirectFx.ptyMsg(.pty),
692
+ });
693
+ var result = try drainUntilExit(&fx, 30_000);
694
+ defer result.output.deinit(testing.allocator);
695
+ try testing.expectEqual(total, result.output.items.len);
696
+ for (result.output.items) |byte| try testing.expectEqual(@as(u8, 'a'), byte);
697
+ try testing.expectEqual(effects_mod.EffectExitReason.exited, result.exit.reason);
698
+ }
699
+
700
+ test "live pty write and kill: input reaches the child, the exit reports cancelled" {
701
+ if (comptime !live_posix) return;
702
+ var fx = DirectFx.init(testing.allocator);
703
+ defer fx.deinit();
704
+
705
+ fx.ptySpawn(.{
706
+ .key = 53,
707
+ .argv = &.{"/bin/cat"},
708
+ .on_event = DirectFx.ptyMsg(.pty),
709
+ });
710
+ try testing.expect(fx.ptyWrite(53, "ping\r"));
711
+ // The line discipline echoes the input and cat writes it back;
712
+ // either way "ping" must appear in the stream.
713
+ var seen = false;
714
+ var waited: u64 = 0;
715
+ var collected: std.ArrayList(u8) = .empty;
716
+ defer collected.deinit(testing.allocator);
717
+ while (!seen and waited < 5_000) {
718
+ while (fx.takeMsg()) |msg| {
719
+ if (msg.pty.kind == .output) try collected.appendSlice(testing.allocator, msg.pty.bytes);
720
+ }
721
+ seen = std.mem.indexOf(u8, collected.items, "ping") != null;
722
+ if (!seen) {
723
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(2), .awake);
724
+ waited += 2;
725
+ }
726
+ }
727
+ try testing.expect(seen);
728
+
729
+ fx.ptyKill(53);
730
+ var result = try drainUntilExit(&fx, 5_000);
731
+ defer result.output.deinit(testing.allocator);
732
+ try testing.expectEqual(effects_mod.EffectExitReason.cancelled, result.exit.reason);
733
+ // A cancelled end carries the -1 sentinel, never a stale child code.
734
+ try testing.expectEqual(effects_mod.effect_error_exit_code, result.exit.code);
735
+ }
736
+
737
+ test "a write refused after the exit is staged still counts into dropped_writes" {
738
+ if (comptime !live_posix) return;
739
+ var fx = DirectFx.init(testing.allocator);
740
+ defer fx.deinit();
741
+
742
+ // A child that exits immediately and prints nothing: the io thread
743
+ // stages the exit; the loop has not delivered it yet.
744
+ fx.ptySpawn(.{
745
+ .key = 57,
746
+ .argv = &.{ "/bin/sh", "-c", "exit 0" },
747
+ .on_event = DirectFx.ptyMsg(.pty),
748
+ });
749
+ var waited: u64 = 0;
750
+ while (fx.pty_pending_count.load(.seq_cst) == 0 and waited < 5_000) {
751
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(2), .awake);
752
+ waited += 2;
753
+ }
754
+ try testing.expect(fx.pty_pending_count.load(.seq_cst) > 0);
755
+
756
+ // The staged-exit window: the write is refused (no io thread will
757
+ // flush it) but COUNTED — the exit event reads the drop count at
758
+ // delivery, which has not happened yet, so no refusal is silent.
759
+ try testing.expect(!fx.ptyWrite(57, "late"));
760
+ const exit = try expectExit(&fx, 57, .exited);
761
+ try testing.expectEqual(@as(i32, 0), exit.code);
762
+ try testing.expectEqual(@as(u32, 1), exit.dropped_writes);
763
+ }
764
+
765
+ test "a fed output batch over the chunk bound and NUL-bearing term/argv are refused" {
766
+ var fx = DirectFx.init(testing.allocator);
767
+ defer fx.deinit();
768
+ fx.executor = .fake;
769
+
770
+ // TERM with an embedded NUL: refused (a truncated TERM would reach
771
+ // the child as a different value than requested).
772
+ fx.ptySpawn(.{ .key = 81, .argv = &.{"sh"}, .term = "xterm\x00evil", .on_event = DirectFx.ptyMsg(.pty) });
773
+ _ = try expectExit(&fx, 81, .rejected);
774
+ // argv with an embedded NUL: refused (fake and real agree).
775
+ fx.ptySpawn(.{ .key = 82, .argv = &.{ "sh", "a\x00b" }, .on_event = DirectFx.ptyMsg(.pty) });
776
+ _ = try expectExit(&fx, 82, .rejected);
777
+ }
778
+
779
+ test "live pty resize lands as the child's window size" {
780
+ if (comptime !live_posix) return;
781
+ var fx = DirectFx.init(testing.allocator);
782
+ defer fx.deinit();
783
+
784
+ fx.ptySpawn(.{
785
+ .key = 54,
786
+ // Report the size the kernel line discipline hands back after
787
+ // the spawn declared 91x33 — proof the initial TIOCSWINSZ took.
788
+ .argv = &.{ "/bin/sh", "-c", "stty size" },
789
+ .cols = 91,
790
+ .rows = 33,
791
+ .on_event = DirectFx.ptyMsg(.pty),
792
+ });
793
+ var result = try drainUntilExit(&fx, 5_000);
794
+ defer result.output.deinit(testing.allocator);
795
+ try testing.expect(std.mem.indexOf(u8, result.output.items, "33 91") != null);
796
+ }
797
+
798
+ // ---------------------------------------------- live ConPTY (Windows)
799
+ //
800
+ // The Windows twins of the live tests above, with the two documented
801
+ // semantic differences baked into the assertions: ConPTY output is
802
+ // conhost's VT RENDERING of the child's screen (containment checks,
803
+ // never byte-exact counts), and endings carry exit codes only
804
+ // (`signal` is always 0; `.signaled` never occurs).
805
+
806
+ test "live conpty end to end: rendered output carries the child's text, the exit code is exact" {
807
+ if (comptime !live_windows) return;
808
+ var fx = DirectFx.init(testing.allocator);
809
+ defer fx.deinit();
810
+ fx.ptySpawn(.{
811
+ .key = 51,
812
+ .argv = &.{ "cmd.exe", "/d", "/c", "echo pty-effects-live-marker& exit 4" },
813
+ .on_event = DirectFx.ptyMsg(.pty),
814
+ });
815
+ var result = try drainUntilExit(&fx, 15_000);
816
+ defer result.output.deinit(testing.allocator);
817
+ try testing.expect(std.mem.indexOf(u8, result.output.items, "pty-effects-live-marker") != null);
818
+ try testing.expectEqual(@as(i32, 4), result.exit.code);
819
+ try testing.expectEqual(effects_mod.EffectExitReason.exited, result.exit.reason);
820
+ try testing.expectEqual(@as(i32, 0), result.exit.signal);
821
+ }
822
+
823
+ test "live conpty back-pressure survives output past the staging ring" {
824
+ if (comptime !live_windows) return;
825
+ var fx = DirectFx.init(testing.allocator);
826
+ defer fx.deinit();
827
+
828
+ // ~512 KiB of raw child output — twice the staging ring — so the
829
+ // reader parks and resumes across the run. Rendering makes the
830
+ // exact byte total non-deterministic; the property under test is
831
+ // that the session stays live through the parking (arrives, keeps
832
+ // flowing, exits cleanly) and every record obeys the chunk bound.
833
+ fx.ptySpawn(.{
834
+ .key = 52,
835
+ .argv = &.{
836
+ "cmd.exe",
837
+ "/d",
838
+ "/c",
839
+ "for /L %i in (1,1,8000) do @echo xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
840
+ },
841
+ .on_event = DirectFx.ptyMsg(.pty),
842
+ });
843
+ var result = try drainUntilExit(&fx, 60_000);
844
+ defer result.output.deinit(testing.allocator);
845
+ try testing.expect(result.output.items.len > effects_mod.max_effect_pty_staging_bytes);
846
+ try testing.expectEqual(effects_mod.EffectExitReason.exited, result.exit.reason);
847
+ }
848
+
849
+ test "live conpty write and kill: input reaches the child, the exit reports cancelled" {
850
+ if (comptime !live_windows) return;
851
+ var fx = DirectFx.init(testing.allocator);
852
+ defer fx.deinit();
853
+
854
+ fx.ptySpawn(.{
855
+ .key = 53,
856
+ .argv = &.{"cmd.exe"},
857
+ .on_event = DirectFx.ptyMsg(.pty),
858
+ });
859
+ try testing.expect(fx.ptyWrite(53, "echo pty-echo-marker\r"));
860
+ // The typed command echoes into the rendered stream, and cmd's
861
+ // execution of it prints the marker again — either sighting proves
862
+ // input crossed the input pipe into the child's console.
863
+ var seen = false;
864
+ var waited: u64 = 0;
865
+ var collected: std.ArrayList(u8) = .empty;
866
+ defer collected.deinit(testing.allocator);
867
+ while (!seen and waited < 15_000) {
868
+ while (fx.takeMsg()) |msg| {
869
+ if (msg.pty.kind == .output) try collected.appendSlice(testing.allocator, msg.pty.bytes);
870
+ }
871
+ seen = std.mem.indexOf(u8, collected.items, "pty-echo-marker") != null;
872
+ if (!seen) {
873
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(2), .awake);
874
+ waited += 2;
875
+ }
876
+ }
877
+ try testing.expect(seen);
878
+
879
+ fx.ptyKill(53);
880
+ var result = try drainUntilExit(&fx, 15_000);
881
+ defer result.output.deinit(testing.allocator);
882
+ try testing.expectEqual(effects_mod.EffectExitReason.cancelled, result.exit.reason);
883
+ // A cancelled end carries the -1 sentinel and no signal (Windows
884
+ // never reports one).
885
+ try testing.expectEqual(effects_mod.effect_error_exit_code, result.exit.code);
886
+ try testing.expectEqual(@as(i32, 0), result.exit.signal);
887
+ }
888
+
889
+ test "live conpty initial grid size reaches the child console" {
890
+ if (comptime !live_windows) return;
891
+ var fx = DirectFx.init(testing.allocator);
892
+ defer fx.deinit();
893
+
894
+ fx.ptySpawn(.{
895
+ .key = 54,
896
+ // `mode con` reports the console geometry the pseudoconsole
897
+ // was created with; labels are localized, digits are not.
898
+ .argv = &.{ "cmd.exe", "/d", "/c", "mode con" },
899
+ .cols = 91,
900
+ .rows = 33,
901
+ .on_event = DirectFx.ptyMsg(.pty),
902
+ });
903
+ var result = try drainUntilExit(&fx, 15_000);
904
+ defer result.output.deinit(testing.allocator);
905
+ try testing.expect(std.mem.indexOf(u8, result.output.items, "91") != null);
906
+ try testing.expect(std.mem.indexOf(u8, result.output.items, "33") != null);
907
+ }
908
+
909
+ // ------------------------------------------ live tests, both backends
910
+
911
+ /// A long-lived child per platform for the kill/teardown shapes: the
912
+ /// assertions there are about the toolkit's wind-down, not the child's
913
+ /// output, so one test serves both live transports. (An interactive
914
+ /// cmd prompt waits on stdin the way `sleep 30` waits on the clock.)
915
+ const live_long_lived_argv: []const []const u8 = if (builtin.os.tag == .windows)
916
+ &.{"cmd.exe"}
917
+ else
918
+ &.{ "/bin/sh", "-c", "sleep 30" };
919
+ const live_exec_long_lived_argv: []const []const u8 = if (builtin.os.tag == .windows)
920
+ &.{"cmd.exe"}
921
+ else
922
+ &.{ "/bin/sh", "-c", "exec sleep 30" };
923
+
924
+ test "teardown with a live pty returns promptly and reaps the child" {
925
+ if (comptime !pty_transport.supported) return;
926
+ var fx = DirectFx.init(testing.allocator);
927
+ fx.ptySpawn(.{
928
+ .key = 55,
929
+ .argv = live_long_lived_argv,
930
+ .on_event = DirectFx.ptyMsg(.pty),
931
+ });
932
+ // Give the transport a moment to start, then tear the channel down
933
+ // mid-session: the group kill converges the io thread and deinit
934
+ // returns without waiting out the sleep.
935
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(50), .awake);
936
+ fx.deinit();
937
+ }
938
+
939
+ /// Fails exactly the next channel-storage allocation and delegates
940
+ /// everything else to the page allocator (the channel suite's
941
+ /// `ChannelStorageFailingAllocator`, restated here for the pty seam).
942
+ const PtyStorageFailingAllocator = struct {
943
+ backing: std.mem.Allocator = std.heap.page_allocator,
944
+ armed: bool = false,
945
+ /// Frees observed through the seam — the abandon pin asserts
946
+ /// retirement LEAKED the staging blocks (zero frees) rather than
947
+ /// freeing them under a live io thread.
948
+ free_count: usize = 0,
949
+
950
+ const vtable: std.mem.Allocator.VTable = .{
951
+ .alloc = alloc,
952
+ .resize = resize,
953
+ .remap = remap,
954
+ .free = free,
955
+ };
956
+
957
+ fn allocator(self: *PtyStorageFailingAllocator) std.mem.Allocator {
958
+ return .{ .ptr = self, .vtable = &vtable };
959
+ }
960
+
961
+ fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
962
+ const self: *PtyStorageFailingAllocator = @ptrCast(@alignCast(ptr));
963
+ if (self.armed) {
964
+ self.armed = false;
965
+ return null;
966
+ }
967
+ return self.backing.vtable.alloc(self.backing.ptr, len, alignment, ret_addr);
968
+ }
969
+
970
+ fn resize(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
971
+ const self: *PtyStorageFailingAllocator = @ptrCast(@alignCast(ptr));
972
+ return self.backing.vtable.resize(self.backing.ptr, memory, alignment, new_len, ret_addr);
973
+ }
974
+
975
+ fn remap(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
976
+ const self: *PtyStorageFailingAllocator = @ptrCast(@alignCast(ptr));
977
+ return self.backing.vtable.remap(self.backing.ptr, memory, alignment, new_len, ret_addr);
978
+ }
979
+
980
+ fn free(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
981
+ const self: *PtyStorageFailingAllocator = @ptrCast(@alignCast(ptr));
982
+ self.free_count += 1;
983
+ self.backing.vtable.free(self.backing.ptr, memory, alignment, ret_addr);
984
+ }
985
+ };
986
+
987
+ test "a failed bind-site snapshot publication never strands a live pty's exit" {
988
+ if (comptime !pty_transport.supported) return;
989
+ // The wind-down's past-deadline arm abandons the io thread and
990
+ // deliberately leaks its transport, so the harness rides the page
991
+ // allocator instead of the leak-checking one.
992
+ var fx = DirectFx.init(std.heap.page_allocator);
993
+ defer fx.deinit();
994
+ var failing: PtyStorageFailingAllocator = .{};
995
+ fx.channel_storage_allocator = failing.allocator();
996
+ // Zero deadline: the wind-down never waits for the io thread, so
997
+ // the loop-side staging arm is what runs. (A thread that beats even
998
+ // this window stages the same cancelled exit itself — the assertion
999
+ // holds on either arm.)
1000
+ fx.spawn_join_deadline_ms = 0;
1001
+
1002
+ const null_platform = try std.heap.page_allocator.create(platform_mod.NullPlatform);
1003
+ defer std.heap.page_allocator.destroy(null_platform);
1004
+ null_platform.* = platform_mod.NullPlatform.init(.{});
1005
+ const host_platform = null_platform.platform();
1006
+
1007
+ // A long-lived, NON-READING child spawned BEFORE the bind — the one
1008
+ // shape where a running pty can meet a failed publication — with a
1009
+ // write in flight, so the io thread's outbound machinery is live
1010
+ // across the abandon.
1011
+ fx.ptySpawn(.{
1012
+ .key = 56,
1013
+ .argv = live_exec_long_lived_argv,
1014
+ .on_event = DirectFx.ptyMsg(.pty),
1015
+ });
1016
+ try testing.expect(fx.ptyWrite(56, "in-flight bytes\r"));
1017
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(50), .awake);
1018
+
1019
+ failing.armed = true;
1020
+ fx.bindServices(&host_platform.services);
1021
+ try testing.expect(fx.wake_services.load(.seq_cst) == null);
1022
+
1023
+ // The wind-down killed the child and staged the cancelled terminal —
1024
+ // loop-side past the deadline — so the exit delivers instead of
1025
+ // stranding behind a wake that can never fire.
1026
+ var result = try drainUntilExit(&fx, 5_000);
1027
+ defer result.output.deinit(testing.allocator);
1028
+ try testing.expectEqual(effects_mod.EffectExitReason.cancelled, result.exit.reason);
1029
+ try testing.expectEqual(effects_mod.effect_error_exit_code, result.exit.code);
1030
+ // The key freed with the delivery: the slot retired, nothing pends.
1031
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
1032
+ // Retirement's deferred-ownership rule, pinned as a CORRESPONDENCE
1033
+ // (the race between the abandoned thread and the delivery is
1034
+ // between two correct outcomes): when the io thread had not proved
1035
+ // completion (`io_done`) by retire, BOTH blocks leak and NOTHING
1036
+ // frees; when it had, both free and nothing leaks. Any other
1037
+ // combination — a free without the completion proof — is the
1038
+ // use-after-free this pin exists to forbid.
1039
+ if (fx.pty_blocks_leaked == 1) {
1040
+ try testing.expectEqual(@as(usize, 0), failing.free_count);
1041
+ } else {
1042
+ try testing.expectEqual(@as(usize, 0), fx.pty_blocks_leaked);
1043
+ try testing.expectEqual(@as(usize, 2), failing.free_count);
1044
+ }
1045
+ }
1046
+
1047
+ // ---------------------------------------- record/replay acceptance
1048
+
1049
+ const pty_canvas_label = "pty-session-canvas";
1050
+
1051
+ const PtySessionModel = struct {
1052
+ output_events: u32 = 0,
1053
+ exit_events: u32 = 0,
1054
+ rejected_events: u32 = 0,
1055
+ last_code: i32 = 0,
1056
+ /// Rolling order-sensitive digest of every delivered byte — a
1057
+ /// replay that reorders, drops, or alters one byte diverges here
1058
+ /// (and in the fingerprint checkpoints that pin it).
1059
+ output_digest: u64 = 0,
1060
+ output_bytes: u64 = 0,
1061
+ /// `ptyWrite` admission verdicts folded into MODEL STATE — the
1062
+ /// retain-refused-bytes pattern a real terminal uses. Replay must
1063
+ /// reproduce the recorded verdicts exactly or these counters (and
1064
+ /// the fingerprint checkpoints rendering them) diverge.
1065
+ write_accepts: u32 = 0,
1066
+ write_refusals: u32 = 0,
1067
+
1068
+ fn record(model: *PtySessionModel, event: effects_mod.EffectPtyEvent) void {
1069
+ switch (event.kind) {
1070
+ .output => {
1071
+ model.output_events += 1;
1072
+ model.output_digest = std.hash.Wyhash.hash(model.output_digest, event.bytes);
1073
+ model.output_bytes += event.bytes.len;
1074
+ },
1075
+ .exit => {
1076
+ if (event.reason == .rejected) {
1077
+ model.rejected_events += 1;
1078
+ } else {
1079
+ model.exit_events += 1;
1080
+ }
1081
+ model.last_code = event.code;
1082
+ },
1083
+ // Journal-only write verdicts never deliver as events.
1084
+ .write => unreachable,
1085
+ }
1086
+ }
1087
+
1088
+ fn recordWriteVerdict(model: *PtySessionModel, accepted: bool) void {
1089
+ if (accepted) model.write_accepts += 1 else model.write_refusals += 1;
1090
+ }
1091
+ };
1092
+
1093
+ const PtySessionMsg = union(enum) {
1094
+ spawn,
1095
+ spawn_dup,
1096
+ type_command,
1097
+ type_oversized,
1098
+ event: effects_mod.EffectPtyEvent,
1099
+ };
1100
+
1101
+ const PtySessionApp = ui_app_mod.UiApp(PtySessionModel, PtySessionMsg);
1102
+
1103
+ const session_pty_key: u64 = 61;
1104
+
1105
+ fn ptySessionUpdate(model: *PtySessionModel, msg: PtySessionMsg, fx: *PtySessionApp.Effects) void {
1106
+ switch (msg) {
1107
+ .spawn => fx.ptySpawn(.{
1108
+ .key = session_pty_key,
1109
+ .argv = &.{ "sh", "-i" },
1110
+ .cols = 100,
1111
+ .rows = 30,
1112
+ .on_event = PtySessionApp.Effects.ptyMsg(.event),
1113
+ }),
1114
+ // The duplicate spawn: refused loop-side on BOTH sides — the
1115
+ // journaled `.rejected` exit regenerates at replay.
1116
+ .spawn_dup => fx.ptySpawn(.{
1117
+ .key = session_pty_key,
1118
+ .argv = &.{"sh"},
1119
+ .on_event = PtySessionApp.Effects.ptyMsg(.event),
1120
+ }),
1121
+ // Journaled as a command dispatch; the write's BYTES are inert
1122
+ // under replay (the recorded output already carries their
1123
+ // consequences), but its admission VERDICT is executor truth the
1124
+ // journal feeds — the model folds it in so replay must take the
1125
+ // identical accept/refuse path.
1126
+ .type_command => model.recordWriteVerdict(fx.ptyWrite(session_pty_key, "ls\r")),
1127
+ // Over the per-write bound: refused live (the all-or-nothing
1128
+ // admission), and the journaled refusal must return under
1129
+ // replay too — a recomputed optimistic `true` would diverge the
1130
+ // model and the fingerprint.
1131
+ .type_oversized => model.recordWriteVerdict(fx.ptyWrite(
1132
+ session_pty_key,
1133
+ &(comptime [_]u8{'z'} ** (effects_mod.max_effect_pty_write_bytes + 1)),
1134
+ )),
1135
+ .event => |event| model.record(event),
1136
+ }
1137
+ }
1138
+
1139
+ fn ptySessionView(ui: *PtySessionApp.Ui, model: *const PtySessionModel) PtySessionApp.Ui.Node {
1140
+ // The semantic tree carries every pty-derived model fact, so the
1141
+ // fingerprint checkpoints PIN the stream — batch bytes, order,
1142
+ // and the exit taxonomy alike.
1143
+ return ui.column(.{ .gap = 4, .padding = 8 }, .{
1144
+ ui.text(.{}, ui.fmt("{d} batches / {d} bytes", .{ model.output_events, model.output_bytes })),
1145
+ ui.text(.{}, ui.fmt("digest {x}", .{model.output_digest})),
1146
+ ui.text(.{}, ui.fmt("{d} exits ({d}) {d} rejected", .{ model.exit_events, model.last_code, model.rejected_events })),
1147
+ ui.text(.{}, ui.fmt("{d} writes ok / {d} refused", .{ model.write_accepts, model.write_refusals })),
1148
+ });
1149
+ }
1150
+
1151
+ fn ptySessionCommand(name: []const u8) ?PtySessionMsg {
1152
+ if (std.mem.eql(u8, name, "pty.spawn")) return .spawn;
1153
+ if (std.mem.eql(u8, name, "pty.spawn-dup")) return .spawn_dup;
1154
+ if (std.mem.eql(u8, name, "pty.type")) return .type_command;
1155
+ if (std.mem.eql(u8, name, "pty.type-oversized")) return .type_oversized;
1156
+ return null;
1157
+ }
1158
+
1159
+ const pty_session_views = [_]app_manifest.ShellView{
1160
+ .{ .label = pty_canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
1161
+ };
1162
+ const pty_session_windows = [_]app_manifest.ShellWindow{.{
1163
+ .label = "main",
1164
+ .title = "Pty Session",
1165
+ .width = 400,
1166
+ .height = 300,
1167
+ .views = &pty_session_views,
1168
+ }};
1169
+ const pty_session_scene: app_manifest.ShellConfig = .{ .windows = &pty_session_windows };
1170
+
1171
+ fn ptySessionOptions() PtySessionApp.Options {
1172
+ return .{
1173
+ .name = "pty-session-demo",
1174
+ .scene = pty_session_scene,
1175
+ .canvas_label = pty_canvas_label,
1176
+ .update_fx = ptySessionUpdate,
1177
+ .view = ptySessionView,
1178
+ .on_command = ptySessionCommand,
1179
+ };
1180
+ }
1181
+
1182
+ const JournalBuffer = struct {
1183
+ bytes: [256 * 1024]u8 = undefined,
1184
+ len: usize = 0,
1185
+
1186
+ fn sink(self: *JournalBuffer) session_record.RecorderSink {
1187
+ return .{ .context = self, .write_fn = write };
1188
+ }
1189
+
1190
+ fn write(context: *anyopaque, bytes: []const u8) anyerror!void {
1191
+ const self: *JournalBuffer = @ptrCast(@alignCast(context));
1192
+ if (self.len + bytes.len > self.bytes.len) return error.NoSpaceLeft;
1193
+ @memcpy(self.bytes[self.len .. self.len + bytes.len], bytes);
1194
+ self.len += bytes.len;
1195
+ }
1196
+
1197
+ fn journalBytes(self: *const JournalBuffer) []const u8 {
1198
+ return self.bytes[0..self.len];
1199
+ }
1200
+ };
1201
+
1202
+ const RecordedPtySession = struct {
1203
+ model: PtySessionModel,
1204
+ fingerprint: u64,
1205
+ };
1206
+
1207
+ /// Record the pty reference session against the scriptable fake pty
1208
+ /// (the CI-deterministic shell): spawn, a prompt batch, a typed
1209
+ /// command whose echo and listing arrive as one coalesced batch, a
1210
+ /// duplicate spawn's regenerating rejection, and the exit terminal —
1211
+ /// checkpoints after every wake.
1212
+ fn recordPtySession(gpa: std.mem.Allocator, buffer: *JournalBuffer, store: *session_blobs.MemoryBlobStore) !RecordedPtySession {
1213
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
1214
+ defer std.heap.page_allocator.destroy(recorder);
1215
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
1216
+ recorder.blob_sink = store.sink();
1217
+ recorder.begin(.{ .platform_name = "test", .app_name = "pty-session-demo", .window_width = 400, .window_height = 300 });
1218
+
1219
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
1220
+ defer harness.destroy(gpa);
1221
+ harness.null_platform.gpu_surfaces = true;
1222
+ harness.runtime.options.session_recorder = recorder;
1223
+
1224
+ const app_state = try gpa.create(PtySessionApp);
1225
+ defer gpa.destroy(app_state);
1226
+ app_state.* = PtySessionApp.init(std.heap.page_allocator, .{}, ptySessionOptions());
1227
+ defer app_state.deinit();
1228
+ app_state.effects.executor = .fake;
1229
+ const app = app_state.app();
1230
+
1231
+ try harness.start(app);
1232
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1233
+ .label = pty_canvas_label,
1234
+ .size = geometry.SizeF.init(400, 300),
1235
+ .scale_factor = 2,
1236
+ .frame_index = 1,
1237
+ .timestamp_ns = 1_000_000,
1238
+ } });
1239
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1240
+
1241
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "pty.spawn", .window_id = 1 } });
1242
+ try testing.expectEqual(@as(usize, 1), app_state.effects.pendingPtyCount());
1243
+
1244
+ // The scripted shell prompt.
1245
+ try app_state.effects.feedPtyOutput(session_pty_key, "sh-5.2$ ");
1246
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1247
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1248
+ try testing.expectEqual(@as(u32, 1), app_state.model.output_events);
1249
+
1250
+ // The app types; the scripted shell answers with echo + listing in
1251
+ // one coalesced batch (what the live ring would deliver). The
1252
+ // write's admission verdict journals and lands in the model.
1253
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "pty.type", .window_id = 1 } });
1254
+ try testing.expectEqualStrings("ls\r", app_state.effects.ptyWrittenBytes(session_pty_key));
1255
+ try testing.expectEqual(@as(u32, 1), app_state.model.write_accepts);
1256
+ try app_state.effects.feedPtyOutput(session_pty_key, "ls\r\nREADME.md\r\nsrc\r\nsh-5.2$ ");
1257
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1258
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1259
+ try testing.expectEqual(@as(u32, 2), app_state.model.output_events);
1260
+
1261
+ // An over-bound write: refused live (all-or-nothing), the verdict
1262
+ // journaled — replay must take the identical refusal path.
1263
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "pty.type-oversized", .window_id = 1 } });
1264
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1265
+ try testing.expectEqual(@as(u32, 1), app_state.model.write_refusals);
1266
+
1267
+ // The duplicate spawn: one regenerating `.rejected` exit.
1268
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "pty.spawn-dup", .window_id = 1 } });
1269
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1270
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1271
+ try testing.expectEqual(@as(u32, 1), app_state.model.rejected_events);
1272
+
1273
+ // The session ends.
1274
+ try app_state.effects.feedPtyExit(session_pty_key, 0, 0, .exited, 0);
1275
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1276
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1277
+ try testing.expectEqual(@as(u32, 1), app_state.model.exit_events);
1278
+
1279
+ recorder.finish();
1280
+ try testing.expect(!recorder.failed);
1281
+ return .{
1282
+ .model = app_state.model,
1283
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
1284
+ };
1285
+ }
1286
+
1287
+ test "a recorded pty session replays fingerprint-identical offline with no shell present" {
1288
+ const gpa = testing.allocator;
1289
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
1290
+ defer std.heap.page_allocator.destroy(buffer);
1291
+ buffer.len = 0;
1292
+ var store = session_blobs.MemoryBlobStore.init(gpa);
1293
+ defer store.deinit();
1294
+
1295
+ const recorded = try recordPtySession(gpa, buffer, &store);
1296
+ try testing.expectEqual(@as(u32, 2), recorded.model.output_events);
1297
+ try testing.expectEqual(@as(u32, 1), recorded.model.exit_events);
1298
+ try testing.expectEqual(@as(u32, 1), recorded.model.rejected_events);
1299
+ try testing.expectEqual(@as(u32, 1), recorded.model.write_accepts);
1300
+ try testing.expectEqual(@as(u32, 1), recorded.model.write_refusals);
1301
+
1302
+ // The output bytes live in the blob store, not the journal — the
1303
+ // dynamic-image pipeline (two batches, two blobs).
1304
+ try testing.expect(store.count >= 2);
1305
+
1306
+ // Replay into a fresh app: no process spawns (the armed channel
1307
+ // parks every ptySpawn), the blob store supplies the recorded
1308
+ // bytes, and every fed event arrives at its recorded position.
1309
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
1310
+ defer harness.destroy(gpa);
1311
+ harness.null_platform.gpu_surfaces = true;
1312
+ const app_state = try gpa.create(PtySessionApp);
1313
+ defer gpa.destroy(app_state);
1314
+ app_state.* = PtySessionApp.init(std.heap.page_allocator, .{}, ptySessionOptions());
1315
+ defer app_state.deinit();
1316
+
1317
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
1318
+ .verify = true,
1319
+ .require_same_platform = false,
1320
+ .blobs = store.source(),
1321
+ });
1322
+ try testing.expect(report.ok());
1323
+ try testing.expect(report.checkpoints_verified > 0);
1324
+ // Two output batches, two write-admission verdicts, and the exit
1325
+ // FEED; the duplicate spawn's rejection regenerates from the
1326
+ // replayed dispatch and its record is skipped.
1327
+ try testing.expectEqual(@as(u64, 5), report.effects_fed);
1328
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
1329
+ // THE verdict pin: the replayed writes took the recorded
1330
+ // accept/refuse paths (one of each), never a recomputed guess —
1331
+ // model equality covers the counters, the fingerprint the pixels.
1332
+ try testing.expectEqual(@as(u32, 1), app_state.model.write_accepts);
1333
+ try testing.expectEqual(@as(u32, 1), app_state.model.write_refusals);
1334
+ try testing.expectEqualDeep(recorded.model, app_state.model);
1335
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
1336
+ // Nothing is left occupied: the fed exit retired the parked spawn.
1337
+ try testing.expectEqual(@as(usize, 0), app_state.effects.pendingPtyCount());
1338
+ }
1339
+
1340
+ test "replay without the blob store refuses a pty output record loudly" {
1341
+ const gpa = testing.allocator;
1342
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
1343
+ defer std.heap.page_allocator.destroy(buffer);
1344
+ buffer.len = 0;
1345
+ var store = session_blobs.MemoryBlobStore.init(gpa);
1346
+ defer store.deinit();
1347
+ _ = try recordPtySession(gpa, buffer, &store);
1348
+
1349
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
1350
+ defer harness.destroy(gpa);
1351
+ harness.null_platform.gpu_surfaces = true;
1352
+ const app_state = try gpa.create(PtySessionApp);
1353
+ defer gpa.destroy(app_state);
1354
+ app_state.* = PtySessionApp.init(std.heap.page_allocator, .{}, ptySessionOptions());
1355
+ defer app_state.deinit();
1356
+
1357
+ const result = session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
1358
+ .verify = false,
1359
+ .require_same_platform = false,
1360
+ });
1361
+ try testing.expectError(error.ReplayMissingBlob, result);
1362
+ }