@native-sdk/cli 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/build/app.zig +331 -24
  2. package/build.zig +179 -11
  3. package/native-sdk.d.ts +8 -0
  4. package/package.json +10 -10
  5. package/packages/core/compile-surface/core.ts +70 -1
  6. package/packages/core/package-lock.json +11 -11
  7. package/packages/core/package.json +2 -2
  8. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  9. package/packages/core/scripts/run_external_core_compiler.mjs +52 -7
  10. package/packages/core/scripts/run_external_service_compiler.mjs +53 -13
  11. package/packages/core/scripts/stage_external_services.mjs +1 -1
  12. package/packages/core/sdk/core.d.ts +75 -0
  13. package/packages/core/sdk/core.ts +167 -12
  14. package/packages/core/sdk/events.d.ts +53 -0
  15. package/packages/core/sdk/events.ts +78 -7
  16. package/packages/core/src/checker.ts +470 -2
  17. package/packages/core/src/cli.ts +13 -0
  18. package/packages/core/src/contract.ts +3 -1
  19. package/packages/core/src/devhost.ts +30 -1
  20. package/packages/core/src/devhost_journal.mjs +10 -8
  21. package/packages/core/src/diagnostics.ts +99 -8
  22. package/packages/core/src/frontend.ts +6 -0
  23. package/packages/core/src/infer.ts +24 -0
  24. package/skill-data/automation/SKILL.md +1 -1
  25. package/skill-data/native-ui/SKILL.md +11 -5
  26. package/skill-data/ts-core/SKILL.md +53 -20
  27. package/skill-data/ts-services/SKILL.md +4 -4
  28. package/skill-data/ts-services/references/service-surface.md +2 -1
  29. package/skill-data/zig/SKILL.md +1 -1
  30. package/src/app_runner/root.zig +29 -0
  31. package/src/app_runner/ts_core_main.zig +5 -0
  32. package/src/app_runner/ts_core_mobile.zig +241 -0
  33. package/src/automation/protocol.zig +5 -1
  34. package/src/automation/snapshot.zig +8 -6
  35. package/src/embed/app_exports.zig +1 -0
  36. package/src/embed/root.zig +1 -0
  37. package/src/embed/tests.zig +28 -0
  38. package/src/embed/ui_host.zig +68 -2
  39. package/src/platform/linux/cef_host.cpp +7 -1
  40. package/src/platform/linux/gtk_host.c +200 -5
  41. package/src/platform/linux/gtk_host.h +2 -1
  42. package/src/platform/linux/root.zig +69 -4
  43. package/src/platform/macos/appkit_host.h +11 -7
  44. package/src/platform/macos/appkit_host.m +210 -88
  45. package/src/platform/macos/cef_host.mm +210 -88
  46. package/src/platform/macos/root.zig +77 -30
  47. package/src/platform/null_platform.zig +234 -51
  48. package/src/platform/null_platform_tests.zig +39 -0
  49. package/src/platform/root.zig +10 -0
  50. package/src/platform/types.zig +105 -16
  51. package/src/platform/windows/root.zig +20 -6
  52. package/src/platform/windows/webview2_host.cpp +41 -5
  53. package/src/root.zig +7 -0
  54. package/src/runtime/api.zig +8 -0
  55. package/src/runtime/automation_commands.zig +35 -2
  56. package/src/runtime/automation_snapshot.zig +32 -24
  57. package/src/runtime/bridge_permission_tests.zig +35 -1
  58. package/src/runtime/bridge_responses.zig +1 -1
  59. package/src/runtime/builtin_bridge.zig +11 -1
  60. package/src/runtime/core.zig +12 -6
  61. package/src/runtime/effects.zig +1323 -35
  62. package/src/runtime/effects_file_tests.zig +587 -0
  63. package/src/runtime/effects_notification_tests.zig +11 -0
  64. package/src/runtime/file_access.zig +400 -0
  65. package/src/runtime/file_effect_crash_helper.zig +28 -0
  66. package/src/runtime/file_effect_crash_tests.zig +37 -0
  67. package/src/runtime/flow.zig +21 -9
  68. package/src/runtime/native_command_event_tests.zig +44 -2
  69. package/src/runtime/pty.zig +5 -2
  70. package/src/runtime/root.zig +5 -0
  71. package/src/runtime/session_blobs.zig +4 -1
  72. package/src/runtime/session_journal.zig +56 -5
  73. package/src/runtime/session_record.zig +38 -0
  74. package/src/runtime/session_replay.zig +97 -7
  75. package/src/runtime/session_tests.zig +81 -0
  76. package/src/runtime/state.zig +10 -0
  77. package/src/runtime/system_services.zig +129 -36
  78. package/src/runtime/ts_core_host.zig +281 -11
  79. package/src/runtime/ts_core_host_tests.zig +95 -1
  80. package/src/runtime/ts_ui_app.zig +461 -8
  81. package/src/runtime/ui_app.zig +321 -109
  82. package/src/runtime/ui_app_tests.zig +132 -6
  83. package/src/runtime/ui_app_window_tests.zig +61 -7
  84. package/src/runtime/validation.zig +20 -0
  85. package/src/tooling/templates.zig +28 -0
  86. package/src/tooling/ts_core.zig +83 -0
  87. package/tools/corewire/emit.zig +3 -3
  88. package/tools/corewire/emit_facade.zig +65 -5
  89. package/tools/corewire/emit_profile.zig +2 -2
  90. package/tools/corewire/emit_service.zig +2 -2
  91. package/tools/corewire/service_contract.zig +4 -4
  92. package/tools/corewire/sidecar.zig +4 -4
@@ -0,0 +1,400 @@
1
+ //! Runtime policy for raw file effects.
2
+ //!
3
+ //! A manifest `filesystem` grant allows any process-visible path. Without
4
+ //! that grant, raw file effects are confined to the six directories the
5
+ //! app-dir resolver owns for this app. The check canonicalizes the existing
6
+ //! target, or the deepest existing parent for a target that will be created,
7
+ //! before comparing roots. Consequently an in-root symlink that points out
8
+ //! is not an app-directory exemption.
9
+
10
+ const std = @import("std");
11
+
12
+ pub const max_roots: usize = 6;
13
+
14
+ pub const Binding = struct {
15
+ roots: []const []const u8 = &.{},
16
+ permitted: bool = false,
17
+ /// The migration seam. Shipping runners set this true; embedders may use
18
+ /// false for one warning release while still exercising normalization.
19
+ enforce: bool = true,
20
+ };
21
+
22
+ pub const Decision = enum { allow, warn, reject };
23
+
24
+ pub const Resolved = struct {
25
+ path: []u8,
26
+ decision: Decision,
27
+ /// For an app-directory exemption, the already-open parent directory
28
+ /// capability the worker must use instead of reopening `path`. `basename`
29
+ /// points into `path`. Holding this handle across the worker handoff closes
30
+ /// the canonicalize-then-open race: every parent was opened first and its
31
+ /// handle-identity path verified inside the selected root.
32
+ parent: ?std.Io.Dir = null,
33
+ basename: []const u8 = "",
34
+ /// A read/stat/delete whose parent does not exist is authorized but absent. The
35
+ /// caller returns the operation's ordinary not-found shape without ever
36
+ /// reopening the unresolved pathname.
37
+ missing: bool = false,
38
+
39
+ pub fn deinit(self: *Resolved, allocator: std.mem.Allocator, io: std.Io) void {
40
+ if (self.parent) |parent| parent.close(io);
41
+ allocator.free(self.path);
42
+ self.* = undefined;
43
+ }
44
+ };
45
+
46
+ pub const ResolveOptions = struct {
47
+ create_parents: bool = false,
48
+ /// Authorize the fully resolved target, but hand the caller the resolved
49
+ /// parent plus the request's original final component. Deletion uses this
50
+ /// so removing a symlink unlinks that directory entry rather than the file
51
+ /// it names. Both paths must be inside an app root when no filesystem
52
+ /// permission is present.
53
+ preserve_final_component: bool = false,
54
+ };
55
+
56
+ /// Normalize first, then decide authority over that exact spelling. Most
57
+ /// callers perform I/O against the resolved target. Operations that preserve
58
+ /// the final component authorize both that target and the resolved directory
59
+ /// entry they hand to the worker.
60
+ pub fn resolve(
61
+ allocator: std.mem.Allocator,
62
+ io: std.Io,
63
+ binding: Binding,
64
+ requested_path: []const u8,
65
+ ) !Resolved {
66
+ return resolveForOperation(allocator, io, binding, requested_path, .{});
67
+ }
68
+
69
+ pub fn resolveForOperation(
70
+ allocator: std.mem.Allocator,
71
+ io: std.Io,
72
+ binding: Binding,
73
+ requested_path: []const u8,
74
+ options: ResolveOptions,
75
+ ) !Resolved {
76
+ if (requested_path.len == 0 or std.mem.indexOfScalar(u8, requested_path, 0) != null) return error.InvalidPath;
77
+ const canonical_target = try canonicalizeTarget(allocator, io, requested_path);
78
+ if (!options.preserve_final_component) {
79
+ return resolveCanonicalOperation(allocator, io, binding, canonical_target, canonical_target, options);
80
+ }
81
+
82
+ defer allocator.free(canonical_target);
83
+ const operation_path = try canonicalizeFinalEntry(allocator, io, requested_path);
84
+ return resolveCanonicalOperation(allocator, io, binding, canonical_target, operation_path, options);
85
+ }
86
+
87
+ fn resolveCanonicalOperation(
88
+ allocator: std.mem.Allocator,
89
+ io: std.Io,
90
+ binding: Binding,
91
+ canonical_target: []const u8,
92
+ operation_path: []u8,
93
+ options: ResolveOptions,
94
+ ) Resolved {
95
+ if (binding.permitted) return .{ .path = operation_path, .decision = .allow };
96
+ if (options.preserve_final_component and
97
+ !canonicalIsInsideAnyRoot(allocator, io, binding.roots, canonical_target))
98
+ {
99
+ return .{ .path = operation_path, .decision = if (binding.enforce) .reject else .warn };
100
+ }
101
+
102
+ for (binding.roots) |root| {
103
+ if (root.len == 0) continue;
104
+ const canonical_root = canonicalizeTarget(allocator, io, root) catch continue;
105
+ defer allocator.free(canonical_root);
106
+ var root_dir = openCanonicalDir(io, canonical_root, options.create_parents) catch {
107
+ // A missing root can only authorize an absent read/stat/delete. Compare
108
+ // canonical lexical spellings, then return the closed absence
109
+ // result; writes created the root above and never take this path.
110
+ if (!options.create_parents and pathIsWithin(canonical_root, operation_path)) {
111
+ return .{ .path = operation_path, .decision = .allow, .missing = true };
112
+ }
113
+ continue;
114
+ };
115
+
116
+ var root_real_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
117
+ const root_real_len = root_dir.realPath(io, &root_real_storage) catch {
118
+ root_dir.close(io);
119
+ continue;
120
+ };
121
+ const root_real = root_real_storage[0..root_real_len];
122
+ if (!pathIsWithin(root_real, operation_path)) {
123
+ root_dir.close(io);
124
+ continue;
125
+ }
126
+
127
+ const relative = relativeToRoot(root_real, operation_path) orelse {
128
+ root_dir.close(io);
129
+ continue;
130
+ };
131
+ const basename = std.fs.path.basename(relative);
132
+ if (basename.len == 0 or std.mem.eql(u8, basename, ".") or std.mem.eql(u8, basename, "..")) {
133
+ root_dir.close(io);
134
+ continue;
135
+ }
136
+ const parent_path = std.fs.path.dirname(relative) orelse "";
137
+ const parent = openVerifiedParent(io, root_dir, root_real, parent_path, options.create_parents) catch |err| switch (err) {
138
+ error.FileNotFound => return .{ .path = operation_path, .decision = .allow, .missing = true },
139
+ else => continue,
140
+ };
141
+ const basename_offset = @intFromPtr(basename.ptr) - @intFromPtr(relative.ptr) +
142
+ (@intFromPtr(relative.ptr) - @intFromPtr(operation_path.ptr));
143
+ return .{
144
+ .path = operation_path,
145
+ .decision = .allow,
146
+ .parent = parent,
147
+ .basename = operation_path[basename_offset .. basename_offset + basename.len],
148
+ };
149
+ }
150
+
151
+ return .{ .path = operation_path, .decision = if (binding.enforce) .reject else .warn };
152
+ }
153
+
154
+ /// Resolve every parent component but preserve the request's final directory
155
+ /// entry. Unlike `canonicalizeTarget`, this deliberately does not follow a
156
+ /// final symlink.
157
+ fn canonicalizeFinalEntry(allocator: std.mem.Allocator, io: std.Io, requested_path: []const u8) ![]u8 {
158
+ const basename = std.fs.path.basename(requested_path);
159
+ if (basename.len == 0 or
160
+ std.mem.eql(u8, basename, ".") or
161
+ std.mem.eql(u8, basename, "..") or
162
+ std.mem.indexOfAny(u8, basename, if (@import("builtin").os.tag == .windows) "/\\" else "/") != null)
163
+ {
164
+ return error.InvalidPath;
165
+ }
166
+ const parent_path = std.fs.path.dirname(requested_path) orelse ".";
167
+ const canonical_parent = try canonicalizeTarget(allocator, io, parent_path);
168
+ defer allocator.free(canonical_parent);
169
+ return std.fs.path.resolve(allocator, &.{ canonical_parent, basename });
170
+ }
171
+
172
+ fn openCanonicalDir(io: std.Io, canonical_path: []const u8, create: bool) !std.Io.Dir {
173
+ var components = std.fs.path.componentIterator(canonical_path);
174
+ const root = components.root() orelse return error.BadPathName;
175
+ var current = try std.Io.Dir.openDirAbsolute(io, root, .{ .follow_symlinks = false });
176
+ errdefer current.close(io);
177
+ while (components.next()) |component| {
178
+ const next = current.openDir(io, component.name, .{ .follow_symlinks = false }) catch |err| switch (err) {
179
+ error.FileNotFound => if (create) create_component: {
180
+ current.createDir(io, component.name, .default_dir) catch |create_err| switch (create_err) {
181
+ error.PathAlreadyExists => {},
182
+ else => return create_err,
183
+ };
184
+ break :create_component try current.openDir(io, component.name, .{ .follow_symlinks = false });
185
+ } else return error.FileNotFound,
186
+ else => return err,
187
+ };
188
+ current.close(io);
189
+ current = next;
190
+ }
191
+ return current;
192
+ }
193
+
194
+ pub fn decide(
195
+ allocator: std.mem.Allocator,
196
+ io: std.Io,
197
+ binding: Binding,
198
+ requested_path: []const u8,
199
+ ) Decision {
200
+ const resolved = resolve(allocator, io, binding, requested_path) catch return .reject;
201
+ var owned = resolved;
202
+ defer owned.deinit(allocator, io);
203
+ return resolved.decision;
204
+ }
205
+
206
+ fn relativeToRoot(root: []const u8, target: []const u8) ?[]const u8 {
207
+ if (!pathIsWithin(root, target) or pathsEqual(root, target)) return null;
208
+ var at = root.len;
209
+ while (at < target.len and isSeparator(target[at])) at += 1;
210
+ return target[at..];
211
+ }
212
+
213
+ fn openVerifiedParent(
214
+ io: std.Io,
215
+ root_dir: std.Io.Dir,
216
+ canonical_root: []const u8,
217
+ parent_path: []const u8,
218
+ create_parents: bool,
219
+ ) !std.Io.Dir {
220
+ var current = root_dir;
221
+ errdefer current.close(io);
222
+ var components = std.fs.path.componentIterator(parent_path);
223
+ while (components.next()) |component| {
224
+ var next = current.openDir(io, component.name, .{ .follow_symlinks = true }) catch |err| switch (err) {
225
+ error.FileNotFound => if (create_parents) create: {
226
+ current.createDir(io, component.name, .default_dir) catch |create_err| switch (create_err) {
227
+ error.PathAlreadyExists => {},
228
+ else => return create_err,
229
+ };
230
+ // A component we created must still be a directory, not a
231
+ // symlink substituted between create and open.
232
+ break :create try current.openDir(io, component.name, .{ .follow_symlinks = false });
233
+ } else return error.FileNotFound,
234
+ else => return err,
235
+ };
236
+ var next_real_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
237
+ const next_real_len = next.realPath(io, &next_real_storage) catch |err| {
238
+ next.close(io);
239
+ return err;
240
+ };
241
+ if (!pathIsWithin(canonical_root, next_real_storage[0..next_real_len])) {
242
+ next.close(io);
243
+ return error.AccessDenied;
244
+ }
245
+ current.close(io);
246
+ current = next;
247
+ }
248
+ return current;
249
+ }
250
+
251
+ /// Canonicalize the target when it exists. For a new target, walk upward to
252
+ /// the deepest existing parent, canonicalize that parent (resolving every
253
+ /// symlink in the chain), then append the missing lexical suffix. Root paths
254
+ /// are canonicalized independently so aliases such as macOS `/tmp` and
255
+ /// `/private/tmp` compare correctly.
256
+ pub fn isInsideAnyRoot(
257
+ allocator: std.mem.Allocator,
258
+ io: std.Io,
259
+ roots: []const []const u8,
260
+ requested_path: []const u8,
261
+ ) bool {
262
+ if (requested_path.len == 0 or roots.len == 0 or std.mem.indexOfScalar(u8, requested_path, 0) != null) return false;
263
+ const canonical_target = canonicalizeTarget(allocator, io, requested_path) catch return false;
264
+ defer allocator.free(canonical_target);
265
+ return canonicalIsInsideAnyRoot(allocator, io, roots, canonical_target);
266
+ }
267
+
268
+ fn canonicalIsInsideAnyRoot(allocator: std.mem.Allocator, io: std.Io, roots: []const []const u8, canonical_target: []const u8) bool {
269
+ for (roots) |root| {
270
+ if (root.len == 0) continue;
271
+ const canonical_root = canonicalizeTarget(allocator, io, root) catch continue;
272
+ defer allocator.free(canonical_root);
273
+ if (pathIsWithin(canonical_root, canonical_target)) return true;
274
+ }
275
+ return false;
276
+ }
277
+
278
+ fn canonicalizeTarget(allocator: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {
279
+ const cwd = std.Io.Dir.cwd();
280
+ if (cwd.realPathFileAlloc(io, path, allocator)) |resolved| {
281
+ defer allocator.free(resolved);
282
+ return allocator.dupe(u8, resolved);
283
+ } else |_| {}
284
+
285
+ // Preserve every missing component while searching for an existing
286
+ // ancestor. `std.fs.path.resolve` then normalizes `.`/`..` in the joined
287
+ // result, after the existing prefix has been resolved through symlinks.
288
+ var ancestor = path;
289
+ var suffix: std.ArrayList([]const u8) = .empty;
290
+ defer suffix.deinit(allocator);
291
+ while (true) {
292
+ const parent = std.fs.path.dirname(ancestor) orelse break;
293
+ const base = std.fs.path.basename(ancestor);
294
+ try suffix.append(allocator, base);
295
+ if (cwd.realPathFileAlloc(io, parent, allocator)) |resolved_parent| {
296
+ defer allocator.free(resolved_parent);
297
+ var parts: std.ArrayList([]const u8) = .empty;
298
+ defer parts.deinit(allocator);
299
+ try parts.append(allocator, resolved_parent);
300
+ var index = suffix.items.len;
301
+ while (index > 0) {
302
+ index -= 1;
303
+ try parts.append(allocator, suffix.items[index]);
304
+ }
305
+ return std.fs.path.resolve(allocator, parts.items);
306
+ } else |_| {}
307
+ if (std.mem.eql(u8, parent, ancestor)) break;
308
+ ancestor = parent;
309
+ }
310
+ // A completely missing relative tail still has one existing parent: cwd.
311
+ // Resolve it explicitly and append every requested component lexically.
312
+ if (!std.fs.path.isAbsolute(path)) {
313
+ const cwd_resolved = try cwd.realPathFileAlloc(io, ".", allocator);
314
+ defer allocator.free(cwd_resolved);
315
+ return std.fs.path.resolve(allocator, &.{ cwd_resolved, path });
316
+ }
317
+ return error.FileNotFound;
318
+ }
319
+
320
+ fn pathIsWithin(root: []const u8, target: []const u8) bool {
321
+ if (pathsEqual(root, target)) return true;
322
+ if (root.len == 0 or target.len <= root.len) return false;
323
+ if (!pathPrefixEqual(root, target[0..root.len])) return false;
324
+ return isSeparator(target[root.len]) or isSeparator(root[root.len - 1]);
325
+ }
326
+
327
+ fn pathsEqual(a: []const u8, b: []const u8) bool {
328
+ if (a.len != b.len) return false;
329
+ return pathPrefixEqual(a, b);
330
+ }
331
+
332
+ fn pathPrefixEqual(a: []const u8, b: []const u8) bool {
333
+ if (@import("builtin").os.tag != .windows) return std.mem.eql(u8, a, b);
334
+ return std.ascii.eqlIgnoreCase(a, b);
335
+ }
336
+
337
+ fn isSeparator(byte: u8) bool {
338
+ return byte == '/' or (@import("builtin").os.tag == .windows and byte == '\\');
339
+ }
340
+
341
+ test "canonical containment rejects lexical escapes and symlinks that point out" {
342
+ var tmp = std.testing.tmpDir(.{});
343
+ defer tmp.cleanup();
344
+ try tmp.dir.createDirPath(std.testing.io, "app/data");
345
+ try tmp.dir.createDirPath(std.testing.io, "outside");
346
+
347
+ var root_buffer: [256]u8 = undefined;
348
+ var inside_buffer: [256]u8 = undefined;
349
+ var escape_buffer: [256]u8 = undefined;
350
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
351
+ const inside = try std.fmt.bufPrint(&inside_buffer, "{s}/nested/new.bin", .{root});
352
+ const escaped = try std.fmt.bufPrint(&escape_buffer, "{s}/../../outside/new.bin", .{root});
353
+ try std.testing.expect(isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, inside));
354
+ try std.testing.expect(!isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, escaped));
355
+
356
+ if (@import("builtin").os.tag != .windows) {
357
+ try tmp.dir.symLink(std.testing.io, "../../outside", "app/data/link", .{ .is_directory = true });
358
+ var symlink_buffer: [256]u8 = undefined;
359
+ const through_symlink = try std.fmt.bufPrint(&symlink_buffer, "{s}/link/new.bin", .{root});
360
+ try std.testing.expect(!isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, through_symlink));
361
+ }
362
+ }
363
+
364
+ test "an authorized request retains the opened parent capability" {
365
+ var tmp = std.testing.tmpDir(.{});
366
+ defer tmp.cleanup();
367
+ try tmp.dir.createDirPath(std.testing.io, "app/data/nested");
368
+ var root_buffer: [256]u8 = undefined;
369
+ var target_buffer: [256]u8 = undefined;
370
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
371
+ const target = try std.fmt.bufPrint(&target_buffer, "{s}/nested/file.bin", .{root});
372
+ var resolved = try resolveForOperation(std.testing.allocator, std.testing.io, .{ .roots = &.{root} }, target, .{ .create_parents = true });
373
+ defer resolved.deinit(std.testing.allocator, std.testing.io);
374
+ try std.testing.expectEqual(Decision.allow, resolved.decision);
375
+ try std.testing.expect(resolved.parent != null);
376
+ try std.testing.expectEqualStrings("file.bin", resolved.basename);
377
+ }
378
+
379
+ test "a retained parent capability ignores a later pathname symlink swap" {
380
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
381
+ var tmp = std.testing.tmpDir(.{});
382
+ defer tmp.cleanup();
383
+ try tmp.dir.createDirPath(std.testing.io, "app/data/nested");
384
+ try tmp.dir.createDirPath(std.testing.io, "outside");
385
+ var root_buffer: [256]u8 = undefined;
386
+ var target_buffer: [256]u8 = undefined;
387
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
388
+ const target = try std.fmt.bufPrint(&target_buffer, "{s}/nested/file.bin", .{root});
389
+ var resolved = try resolveForOperation(std.testing.allocator, std.testing.io, .{ .roots = &.{root} }, target, .{ .create_parents = true });
390
+ defer resolved.deinit(std.testing.allocator, std.testing.io);
391
+
392
+ try tmp.dir.rename("app/data/nested", tmp.dir, "app/data/retained", std.testing.io);
393
+ try tmp.dir.symLink(std.testing.io, "../../outside", "app/data/nested", .{ .is_directory = true });
394
+ try resolved.parent.?.writeFile(std.testing.io, .{ .sub_path = resolved.basename, .data = "safe" });
395
+
396
+ const retained = try tmp.dir.readFileAlloc(std.testing.io, "app/data/retained/file.bin", std.testing.allocator, .limited(16));
397
+ defer std.testing.allocator.free(retained);
398
+ try std.testing.expectEqualStrings("safe", retained);
399
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(std.testing.io, "outside/file.bin", .{}));
400
+ }
@@ -0,0 +1,28 @@
1
+ const std = @import("std");
2
+ const native_sdk = @import("native_sdk");
3
+
4
+ const Msg = union(enum) { file: native_sdk.EffectFileResult };
5
+ const Fx = native_sdk.Effects(Msg);
6
+
7
+ fn waitResult(fx: *Fx, io: std.Io) !native_sdk.EffectFileResult {
8
+ while (true) {
9
+ if (fx.takeMsg()) |msg| return msg.file;
10
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake);
11
+ }
12
+ }
13
+
14
+ pub fn main(init: std.process.Init) !void {
15
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
16
+ if (args.len != 3) return error.InvalidArguments;
17
+ const destination = args[1];
18
+ const ready = args[2];
19
+ var fx = Fx.init(init.gpa);
20
+ // Deliberately no deinit: the parent kills this process to model a hard
21
+ // crash after the temporary contains bytes but before atomic replace.
22
+ fx.writeFileStream(.{ .key = 1, .path = destination, .on_result = Fx.fileMsg(.file) });
23
+ if ((try waitResult(&fx, init.io)).outcome != .ok) return error.OpenFailed;
24
+ fx.writeFileChunk(.{ .key = 1, .bytes = "partial replacement that must never become visible", .on_result = Fx.fileMsg(.file) });
25
+ if ((try waitResult(&fx, init.io)).outcome != .ok) return error.ChunkFailed;
26
+ try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = ready, .data = "ready" });
27
+ while (true) try std.Io.sleep(init.io, std.Io.Duration.fromSeconds(60), .awake);
28
+ }
@@ -0,0 +1,37 @@
1
+ const std = @import("std");
2
+ const crash_options = @import("file_crash_options");
3
+
4
+ test "hard process death before streamed close leaves the installed file untouched" {
5
+ const io = std.testing.io;
6
+ var tmp = std.testing.tmpDir(.{});
7
+ defer tmp.cleanup();
8
+ try tmp.dir.writeFile(io, .{ .sub_path = "export.bin", .data = "previous complete generation" });
9
+
10
+ var destination_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
11
+ var ready_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
12
+ const destination = try std.fmt.bufPrint(&destination_storage, ".zig-cache/tmp/{s}/export.bin", .{tmp.sub_path[0..]});
13
+ const ready = try std.fmt.bufPrint(&ready_storage, ".zig-cache/tmp/{s}/ready", .{tmp.sub_path[0..]});
14
+ var child = try std.process.spawn(io, .{
15
+ .argv = &.{ crash_options.helper_executable, destination, ready },
16
+ .stdin = .ignore,
17
+ .stdout = .ignore,
18
+ .stderr = .inherit,
19
+ });
20
+ defer child.kill(io);
21
+
22
+ var waited_ms: usize = 0;
23
+ while (waited_ms < 20_000) : (waited_ms += 10) {
24
+ if (tmp.dir.openFile(io, "ready", .{})) |file_value| {
25
+ var file = file_value;
26
+ file.close(io);
27
+ break;
28
+ } else |_| {}
29
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
30
+ }
31
+ if (waited_ms == 20_000) return error.TestTimedOut;
32
+ child.kill(io);
33
+
34
+ const visible = try tmp.dir.readFileAlloc(io, "export.bin", std.testing.allocator, .limited(128));
35
+ defer std.testing.allocator.free(visible);
36
+ try std.testing.expectEqualStrings("previous complete generation", visible);
37
+ }
@@ -45,7 +45,7 @@ const parseAutomationWidgetKey = automation_commands.parseAutomationWidgetKey;
45
45
  const parseAutomationWidgetPinch = automation_commands.parseAutomationWidgetPinch;
46
46
  const parseAutomationWidgetPointerDrag = automation_commands.parseAutomationWidgetPointerDrag;
47
47
  const parseAutomationResizeCommand = automation_commands.parseAutomationResizeCommand;
48
- const parseAutomationTrayItemId = automation_commands.parseAutomationTrayItemId;
48
+ const parseAutomationTrayTarget = automation_commands.parseAutomationTrayTarget;
49
49
  const parseAutomationScreenshotCommand = automation_commands.parseAutomationScreenshotCommand;
50
50
  const canvas = @import("canvas");
51
51
 
@@ -362,12 +362,13 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
362
362
  },
363
363
  .frame_requested => try frame(self, app),
364
364
  .bridge_message => |message| try handleBridgeMessage(self, app, message),
365
- .tray_action => |item_id| {
366
- log(self, "tray.action", "tray item selected", &.{trace.uint("item_id", item_id)});
365
+ .tray_action => |action| {
366
+ log(self, "tray.action", "tray item selected", &.{ trace.uint("status_item_id", action.status_item_id), trace.uint("item_id", action.item_id) });
367
367
  try dispatchCommand(self, app, .{
368
- .name = SystemServiceMethods().trayCommandNameForItem(self, item_id),
368
+ .name = SystemServiceMethods().statusItemCommandNameForItem(self, action.status_item_id, action.item_id),
369
369
  .source = .tray,
370
- .tray_item_id = item_id,
370
+ .status_item_id = action.status_item_id,
371
+ .tray_item_id = action.item_id,
371
372
  });
372
373
  },
373
374
  .shortcut => |shortcut| {
@@ -450,6 +451,14 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
450
451
  .name = command.name,
451
452
  .source = .tray,
452
453
  .window_id = command.window_id,
454
+ .status_item_id = command.status_item_id,
455
+ });
456
+ },
457
+ .notification_command => |command| {
458
+ try dispatchCommand(self, app, .{
459
+ .name = command.name,
460
+ .source = .notification,
461
+ .window_id = command.window_id,
453
462
  });
454
463
  },
455
464
  .timer => |timer_event| {
@@ -1002,9 +1011,12 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
1002
1011
  // UiApp's window fallback are all the real path. A
1003
1012
  // stale or unknown item id is loud driver misuse,
1004
1013
  // like widget-click on an unmounted widget.
1005
- const item_id = try parseAutomationTrayItemId(command.value);
1006
- if (!self.tray_created or !SystemServiceMethods().trayItemExists(self, item_id)) return error.InvalidCommand;
1007
- try dispatchPlatformEvent(self, app, .{ .tray_action = item_id });
1014
+ const target = try parseAutomationTrayTarget(command.value);
1015
+ if (!SystemServiceMethods().statusItemMenuItemExists(self, target.status_item_id, target.item_id)) return error.InvalidCommand;
1016
+ try dispatchPlatformEvent(self, app, .{ .tray_action = .{
1017
+ .status_item_id = target.status_item_id,
1018
+ .item_id = target.item_id,
1019
+ } });
1008
1020
  },
1009
1021
  .focus_view => {
1010
1022
  try WindowViewMethods().focusView(self, 1, try parseAutomationViewLabel(command.value));
@@ -1186,7 +1198,7 @@ pub fn RuntimeFlow(comptime Runtime: type) type {
1186
1198
  else if (is_credentials)
1187
1199
  dispatchCredentialBridgeCommand(self, request, &result_buffer, &response_buffer)
1188
1200
  else
1189
- dispatchOsBridgeCommand(self, request, &result_buffer, &response_buffer);
1201
+ dispatchOsBridgeCommand(self, request, message.origin, &result_buffer, &response_buffer);
1190
1202
 
1191
1203
  try completeBridgeResponse(self, message.window_id, message.webview_label, result);
1192
1204
  self.invalidateFor(.command, null);
@@ -289,13 +289,13 @@ test "runtime dispatches tray item commands" {
289
289
  .{ .id = 8, .label = "Legacy" },
290
290
  } });
291
291
 
292
- try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .tray_action = 7 });
292
+ try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .tray_action = .{ .item_id = 7 } });
293
293
  try std.testing.expectEqual(@as(u32, 1), app_state.command_count);
294
294
  try std.testing.expectEqualStrings("app.refresh", app_state.last_name);
295
295
  try std.testing.expectEqual(CommandSource.tray, app_state.last_source);
296
296
  try std.testing.expectEqual(@as(platform.TrayItemId, 7), app_state.last_tray_item_id);
297
297
 
298
- try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .tray_action = 8 });
298
+ try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .tray_action = .{ .item_id = 8 } });
299
299
  try std.testing.expectEqual(@as(u32, 2), app_state.command_count);
300
300
  try std.testing.expectEqualStrings("tray.action", app_state.last_name);
301
301
  try std.testing.expectEqual(@as(platform.TrayItemId, 8), app_state.last_tray_item_id);
@@ -349,6 +349,48 @@ test "runtime dispatches named tray lifecycle commands with tray source" {
349
349
  try std.testing.expectEqual(@as(platform.WindowId, 3), app_state.last_window_id);
350
350
  }
351
351
 
352
+ test "runtime dispatches notification actions through the normal command path" {
353
+ const TestApp = struct {
354
+ command_count: u32 = 0,
355
+ last_name: []const u8 = "",
356
+ last_source: CommandSource = .runtime,
357
+ last_window_id: platform.WindowId = 0,
358
+
359
+ fn app(self: *@This()) App {
360
+ return .{ .context = self, .name = "notification-command", .source = platform.WebViewSource.html("<p>Notification</p>"), .event_fn = event };
361
+ }
362
+
363
+ fn event(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
364
+ _ = runtime;
365
+ const self: *@This() = @ptrCast(@alignCast(context));
366
+ switch (event_value) {
367
+ .command => |command| {
368
+ self.command_count += 1;
369
+ self.last_name = command.name;
370
+ self.last_source = command.source;
371
+ self.last_window_id = command.window_id;
372
+ },
373
+ else => {},
374
+ }
375
+ }
376
+ };
377
+
378
+ const harness = try TestHarness().create(std.testing.allocator, .{});
379
+ defer harness.destroy(std.testing.allocator);
380
+ var app_state: TestApp = .{};
381
+ try harness.start(app_state.app());
382
+
383
+ try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .notification_command = .{
384
+ .name = "build.open",
385
+ .window_id = 4,
386
+ } });
387
+
388
+ try std.testing.expectEqual(@as(u32, 1), app_state.command_count);
389
+ try std.testing.expectEqualStrings("build.open", app_state.last_name);
390
+ try std.testing.expectEqual(CommandSource.notification, app_state.last_source);
391
+ try std.testing.expectEqual(@as(platform.WindowId, 4), app_state.last_window_id);
392
+ }
393
+
352
394
  test "runtime dispatches file drop events to app and window bridge" {
353
395
  const TestApp = struct {
354
396
  drop_count: u32 = 0,
@@ -924,7 +924,9 @@ const f_dupfd_cloexec: c_int = switch (builtin.os.tag) {
924
924
  fn errnoValue() c_int {
925
925
  return switch (builtin.os.tag) {
926
926
  .macos => c.__error().*,
927
- .linux => c.__errno_location().*,
927
+ // Bionic spells the errno accessor `__errno`; glibc and musl agree
928
+ // on `__errno_location`.
929
+ .linux => if (comptime builtin.abi.isAndroid()) c.__errno().* else c.__errno_location().*,
928
930
  else => 0,
929
931
  };
930
932
  }
@@ -962,7 +964,8 @@ const c = struct {
962
964
  extern "c" fn fcntl(fd: c_int, cmd: c_int, ...) c_int;
963
965
  extern "c" fn poll(fds: [*]Pollfd, nfds: c_uint, timeout: c_int) c_int;
964
966
  extern "c" fn __error() *c_int; // Darwin errno
965
- extern "c" fn __errno_location() *c_int; // Linux errno
967
+ extern "c" fn __errno_location() *c_int; // Linux errno (glibc/musl)
968
+ extern "c" fn __errno() *c_int; // Bionic errno
966
969
  };
967
970
 
968
971
  /// A nudge pipe for the io thread: [read end, write end]. BOTH ends are
@@ -80,8 +80,12 @@ pub const max_effect_fetch_payload_bytes = runtime_effects.max_effect_fetch_payl
80
80
  pub const max_effect_body_bytes = runtime_effects.max_effect_body_bytes;
81
81
  pub const default_effect_fetch_timeout_ms = runtime_effects.default_effect_fetch_timeout_ms;
82
82
  pub const EffectFileOp = runtime_effects.EffectFileOp;
83
+ pub const EffectFileEvent = runtime_effects.EffectFileEvent;
83
84
  pub const EffectFileOutcome = runtime_effects.EffectFileOutcome;
84
85
  pub const EffectFileResult = runtime_effects.EffectFileResult;
86
+ pub const FileAccessBinding = runtime_effects.FileAccessBinding;
87
+ pub const effect_file_stream_chunk_bytes = runtime_effects.effect_file_stream_chunk_bytes;
88
+ pub const max_effect_file_streams = runtime_effects.max_effect_file_streams;
85
89
  pub const EffectCredentialsOperation = runtime_effects.EffectCredentialsOperation;
86
90
  pub const EffectCredentialsOutcome = runtime_effects.EffectCredentialsOutcome;
87
91
  pub const EffectCredentialsResult = runtime_effects.EffectCredentialsResult;
@@ -185,6 +189,7 @@ pub const ts_core_spawn_key_base = runtime_ts_core_host.spawn_key_base;
185
189
  pub const ts_core_audio_key_base = runtime_ts_core_host.audio_key_base;
186
190
  pub const ts_core_video_key_base = runtime_ts_core_host.video_key_base;
187
191
  pub const ts_core_db_key_base = runtime_ts_core_host.db_key_base;
192
+ pub const ts_core_file_stream_key_base = runtime_ts_core_host.file_stream_key_base;
188
193
 
189
194
  const runtime_ts_ui_app = @import("ts_ui_app.zig");
190
195
  pub const TsUiApp = runtime_ts_ui_app.TsUiApp;
@@ -39,7 +39,10 @@ pub const hash_len: usize = runtime_effects.effect_image_blob_hash_len;
39
39
 
40
40
  /// The largest payload one blob may hold — the largest journaled effect
41
41
  /// payload that goes out of line (an image load's encoded source).
42
- pub const max_blob_bytes: usize = @max(runtime_effects.max_effect_image_bytes, runtime_effects.max_effect_persist_snapshot_bytes);
42
+ pub const max_blob_bytes: usize = @max(
43
+ runtime_effects.effect_file_stream_chunk_bytes,
44
+ @max(runtime_effects.max_effect_image_bytes, runtime_effects.max_effect_persist_snapshot_bytes),
45
+ );
43
46
 
44
47
  pub const BlobHash = [hash_len]u8;
45
48