ReviewOS

also looking at this

craft-native/craft

feat(ios): the Zig runtime, offered to a Swift-hosted app

#103
Merged glennmichael123 wants to merge feat/ios-swift-host-seam into main
7 files +868 -59
packages/zig/src/ios_dispatch.zigmodified+399-53
Changes to packages/zig/src/ios_dispatch.zig
@@ -3,6 +3,7 @@ const builtin = @import("builtin");
33const objc_runtime = @import("objc_runtime.zig");
44const request_context = @import("request_context.zig");
55const bridge_error = @import("bridge_error.zig");
6const capabilities = @import("capabilities.zig");
67pub const ios_async = @import("ios_async.zig");
78pub const ios_events = @import("ios_events.zig");
89pub const ios_delegate = @import("ios_delegate.zig");
@@ -65,13 +66,24 @@ const objc = objc_runtime.objc;
6566/// One slot, because iOS has one webview. When multi-window arrives this
6667/// becomes a lookup keyed by the same request id the reply already carries —
6768/// the id is threaded through `request_context` for exactly that reason.
68var global_webview: ?objc.id = null;
69/// `objc.id`, not `?objc.id`. The extra optional was a real defect, not
70/// redundancy: `objc.id` is already `?*anyopaque`, so a double optional made
71/// `setWebView(null)` store a *present* outer value wrapping a nil webview,
72/// and `global_webview orelse return error.NoWebView` below then unwrapped
73/// only the outer one and sailed past. Every reply after such a call went to
74/// `objc_msgSend(nil, …)`, which is a silent no-op — the action ran, it
75/// worked, and the page heard nothing, with no error anywhere to say so.
76///
77/// One optional means "no webview" has one spelling and `orelse` catches it.
78/// (`macos.zig:4075` still holds the two-level version. It is unreachable
79/// there today because nothing passes nil, but it is the same shape.)
80var global_webview: objc.id = null;
6981
7082pub fn setWebView(webview: objc.id) void {
7183 global_webview = webview;
7284}
7385
74pub fn getWebView() ?objc.id {
86pub fn getWebView() objc.id {
7587 return global_webview;
7688}
7789
@@ -184,62 +196,86 @@ fn payloadOf(root: std.json.ObjectMap) ![]const u8 {
184196/// the page's timeout fires, and thirty seconds of nothing is the worst
185197/// diagnostic a bridge can give.
186198fn route(allocator: std.mem.Allocator, msg_type: []const u8, action: []const u8, data: []const u8) !void {
187 if (std.mem.eql(u8, msg_type, "mobile")) {
188 // The app's own configuration, before anything else. An action the
189 // spec gates on a `config.enable*` flag is refused here when that flag
190 // is off, rather than served — which is what every one of these did
191 // until `ios_config.zig` existed, because Zig had no way to read the
192 // flag.
193 //
194 // Only actions this file's modules serve are gated. `gateFor` returns
195 // null for the rest, so an action still on the shim keeps whatever
196 // answer the shim gives it: Zig refusing on Swift's behalf would mean
197 // deciding, from Zig's parse of the config, a question the arm that
198 // owns the action is about to decide from its own.
199 if (ios_config.gateFor(action)) |feature| {
200 if (!ios_config.isEnabled(feature)) {
201 std.log.info(
202 "ios: refusing {s}; {s} is not enabled in craft.config.json",
203 .{ action, feature.jsonKey() },
204 );
205 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.CapabilityDisabled);
206 return bridge_error.BridgeError.CapabilityDisabled;
207 }
208 }
199 if (!std.mem.eql(u8, msg_type, "mobile")) {
200 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.UnknownAction);
201 return error.UnknownNamespace;
202 }
209203
210 // First module that recognises the action wins. UnknownAction means
211 // "not mine, ask the next"; any other error means a handler ran and
212 // failed, and its answer is final — retrying the same action against
213 // another module (or the shim) would replace a specific failure with
214 // whatever the next thing happens to say.
215 //
216 // `test/ios_conformance_test.zig` fails the build if one action is
217 // declared by two modules, so first-match is deterministic rather than
218 // dependent on the order of this tuple. That check was claimed here
219 // before it existed; it exists now.
220 inline for (mobile_bridges) |Bridge| {
221 var bridge = Bridge.init(allocator);
222 defer bridge.deinit();
223
224 if (bridge.handleMessage(action, data)) |_| {
225 return;
226 } else |err| switch (err) {
227 bridge_error.BridgeError.UnknownAction => {},
228 else => {
229 bridge_error.sendErrorToJS(allocator, action, asBridgeError(err));
230 return err;
231 },
232 }
233 }
204 switch (try offerToModules(allocator, action, data)) {
205 .answered => return,
206 .not_ours => {},
207 }
234208
235 if (try handOffToHost(action, data)) return;
209 if (try handOffToHost(action, data)) return;
236210
237 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.UnknownAction);
238 return error.UnknownAction;
211 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.UnknownAction);
212 return error.UnknownAction;
213}
214
215/// Whether the Zig modules took responsibility for an action.
216///
217/// The distinction the hand-off is built on, and the one a Swift-hosted app
218/// needs too: `answered` means the page will hear back from Zig and nobody
219/// else may reply, `not_ours` means nothing here recognised the action and
220/// whoever asked must serve it themselves.
221///
222/// A refusal is `answered`. Every path that calls `sendErrorToJS` has settled
223/// the page's promise, so treating "refused" as "not mine" would let a second
224/// arm answer the same call — the double-reply this envelope exists to
225/// prevent.
226const Offer = enum { answered, not_ours };
227
228/// The capability gate, then the module chain. Shared by the two entry points
229/// so they cannot drift: `route` for a message Zig received itself, and
230/// `craft_ios_handle_action` for one a Swift host received and passed over.
231fn offerToModules(allocator: std.mem.Allocator, action: []const u8, data: []const u8) !Offer {
232 // The app's own configuration, before anything else. An action the spec
233 // gates on a `config.enable*` flag is refused here when that flag is off,
234 // rather than served — which is what every one of these did until
235 // `ios_config.zig` existed, because Zig had no way to read the flag.
236 //
237 // Only actions this file's modules serve are gated. `gateFor` returns null
238 // for the rest, so an action still on the shim keeps whatever answer the
239 // shim gives it: Zig refusing on Swift's behalf would mean deciding, from
240 // Zig's parse of the config, a question the arm that owns the action is
241 // about to decide from its own.
242 if (ios_config.gateFor(action)) |feature| {
243 if (!ios_config.isEnabled(feature)) {
244 std.log.info(
245 "ios: refusing {s}; {s} is not enabled in craft.config.json",
246 .{ action, feature.jsonKey() },
247 );
248 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.CapabilityDisabled);
249 return bridge_error.BridgeError.CapabilityDisabled;
250 }
239251 }
240252
241 bridge_error.sendErrorToJS(allocator, action, bridge_error.BridgeError.UnknownAction);
242 return error.UnknownNamespace;
253 // First module that recognises the action wins. UnknownAction means
254 // "not mine, ask the next"; any other error means a handler ran and
255 // failed, and its answer is final — retrying the same action against
256 // another module (or the shim) would replace a specific failure with
257 // whatever the next thing happens to say.
258 //
259 // `test/ios_conformance_test.zig` fails the build if one action is
260 // declared by two modules, so first-match is deterministic rather than
261 // dependent on the order of this tuple. That check was claimed here
262 // before it existed; it exists now.
263 inline for (mobile_bridges) |Bridge| {
264 var bridge = Bridge.init(allocator);
265 defer bridge.deinit();
266
267 if (bridge.handleMessage(action, data)) |_| {
268 return .answered;
269 } else |err| switch (err) {
270 bridge_error.BridgeError.UnknownAction => {},
271 else => {
272 bridge_error.sendErrorToJS(allocator, action, asBridgeError(err));
273 return err;
274 },
275 }
276 }
277
278 return .not_ours;
243279}
244280
245281/// Every Zig module serving the `mobile` namespace, in dispatch order.
@@ -284,6 +320,83 @@ const mobile_bridges = .{
284320 bridge_mobile_speech.SpeechBridge,
285321};
286322
323/// The same modules again, as their capability manifests.
324///
325/// A second spelling of `mobile_bridges` is not something to want, but the two
326/// cannot be one: `mobile_bridges` holds bridge *types* and `capability_actions`
327/// is declared at module scope, so there is no way to reach a module's manifest
328/// from its struct. The comptime length check below is what keeps them in step
329/// — a module added to one list and not the other fails the build.
330const mobile_manifests = [_][]const capabilities.ActionDecl{
331 &bridge_mobile.capability_actions,
332 &bridge_mobile_clipboard.capability_actions,
333 &bridge_mobile_haptics.capability_actions,
334 &bridge_mobile_device.capability_actions,
335 &bridge_mobile_system.capability_actions,
336 &bridge_mobile_display.capability_actions,
337 &bridge_mobile_storage.capability_actions,
338 &bridge_mobile_misc.capability_actions,
339 &bridge_mobile_shortcuts.capability_actions,
340 &bridge_mobile_securestore.capability_actions,
341 &bridge_mobile_biometric.capability_actions,
342 &bridge_mobile_permissions.capability_actions,
343 &bridge_mobile_db.capability_actions,
344 &bridge_mobile_notifcancel.capability_actions,
345 &bridge_mobile_notifications.capability_actions,
346 &bridge_mobile_bgtasks.capability_actions,
347 &bridge_mobile_watch.capability_actions,
348 &bridge_mobile_location.capability_actions,
349 &bridge_mobile_locrecording.capability_actions,
350 &bridge_mobile_motion.capability_actions,
351 &bridge_mobile_imagepicker.capability_actions,
352 &bridge_mobile_filepicker.capability_actions,
353 &bridge_mobile_contactpicker.capability_actions,
354 &bridge_mobile_calendar.capability_actions,
355 &bridge_mobile_contacts.capability_actions,
356 &bridge_mobile_vision.capability_actions,
357 &bridge_mobile_auth.capability_actions,
358 &bridge_mobile_siri.capability_actions,
359 &bridge_mobile_pdf.capability_actions,
360 &bridge_mobile_bluetooth.capability_actions,
361 &bridge_mobile_audiorec.capability_actions,
362 &bridge_mobile_health.capability_actions,
363 &bridge_mobile_speech.capability_actions,
364};
365
366comptime {
367 if (mobile_manifests.len != mobile_bridges.len) {
368 @compileError("mobile_manifests and mobile_bridges must list the same modules");
369 }
370}
371
372/// Whether a host that offered this action has to serve it itself.
373///
374/// `.status = .unavailable` in a module's manifest means the handler is
375/// reachable and refuses, deliberately, because Zig cannot do the thing
376/// correctly — `haptic` cannot see `config.enableHaptics`, and the rest say
377/// why in their own `reason`.
378///
379/// In the Zig-hosted app that refusal is the honest end of the line: `route`
380/// tries `handOffToHost` next, and the shim is what actually serves it. The
381/// host-offered path has no such fallback — `craft_ios_handle_action`
382/// deliberately does not consult `handOffToHost`, because there the host *is*
383/// the caller. So claiming one of these would not be a refusal instead of an
384/// answer, it would be a refusal instead of the *host's working answer*: an app
385/// that has haptics today would stop buzzing the moment the runtime was linked,
386/// and the page would get a rejection where it used to get silence-and-a-buzz.
387///
388/// `test/ios_conformance_test.zig` already treats falling through as better
389/// than `.unavailable`. This is that rule, applied to the one path that had no
390/// way to fall through.
391fn hostServesItself(action: []const u8) bool {
392 for (mobile_manifests) |manifest| {
393 for (manifest) |decl| {
394 if (decl.status == .unavailable and std.mem.eql(u8, decl.name, action)) return true;
395 }
396 }
397 return false;
398}
399
287400/// Narrow an arbitrary handler error to one the page's error codes can express.
288401///
289402/// A handler's error set is wider than `BridgeError` — it picks up allocation
@@ -340,6 +453,110 @@ fn handOffToHost(action: []const u8, data: []const u8) !bool {
340453 return func(shim, sel, ns_action, ns_payload, request_id);
341454}
342455
456/// Hand the Zig runtime the webview its replies are evaluated against.
457///
458/// The one thing a Swift-hosted app must do before any message is offered
459/// below. In the Zig-hosted app `ios.zig` sets this itself while building the
460/// webview; when SwiftUI owns the `WKWebView`, Zig never sees it and every
461/// reply would reach `error.NoWebView` — an action that ran, worked, and told
462/// nobody.
463///
464/// Not retained. The caller owns the webview and outlives the runtime: it is
465/// the app's own root view. Retaining it here would create a cycle with
466/// nothing to break it, since this pointer is never cleared except by a second
467/// call.
468export fn craft_ios_set_webview(webview: ?*anyopaque) callconv(.c) void {
469 setWebView(webview);
470}
471
472/// Forget the webview, if it is still the one the caller installed.
473///
474/// The other half of `craft_ios_set_webview`, and the reason it is needed:
475/// Zig holds the webview unretained, so once SwiftUI tears the view down the
476/// pointer is dangling and every later reply is an `objc_msgSend` into freed
477/// memory. `UIViewRepresentable` has a `dismantleUIView` hook for exactly this
478/// moment, and this is what it calls.
479///
480/// Compare-and-clear, not an unconditional reset. SwiftUI is free to build the
481/// replacement view *before* dismantling the old one — during a state-driven
482/// rebuild it usually does — and a blind clear on dismantle would blank the
483/// pointer the new view had already installed, leaving a live app whose
484/// replies all reach `error.NoWebView`. Clearing only when the pointer still
485/// matches makes the two orders equivalent.
486export fn craft_ios_clear_webview(webview: ?*anyopaque) callconv(.c) void {
487 if (global_webview == webview) global_webview = null;
488}
489
490/// Offer one already-parsed page message to the Zig dispatcher.
491///
492/// The entry point for a **Swift-hosted** app, where `WKScriptMessageHandler`
493/// belongs to SwiftUI and Zig is a library rather than the thing that owns
494/// `UIApplicationMain`. The caller has already parsed the page's message, so
495/// this takes the three fields routing needs directly instead of re-parsing an
496/// envelope Zig never saw.
497///
498/// Returns **true when Zig has taken responsibility** — the page will hear
499/// back from Zig and the caller must not answer. Returns **false only when no
500/// Zig module recognised the action**, which is the caller's signal to serve
501/// it themselves.
502///
503/// A refusal returns true. `offerToModules` calls `sendErrorToJS` before it
504/// reports a failure, so the promise is already settled; answering again from
505/// the Swift side would resolve a callback that has been deleted at best, and
506/// deliver two contradictory answers to one call at worst.
507///
508/// `handOffToHost` is deliberately **not** consulted here. In this direction
509/// the host is the caller, so handing back to `CraftSwiftShim` would take a
510/// round trip through the Objective-C runtime to reach the same `dispatch`
511/// method the caller is about to call anyway — and would do it under a
512/// synthetic `zig:` callback id, routing the reply back through Zig for no
513/// reason. `false` says the same thing in one word.
514///
515/// `request_id` is negative for a page message with no callback waiting on it,
516/// matching the null the `{t,a,d,i}` envelope carries in that case.
517export fn craft_ios_handle_action(
518 action_ptr: [*]const u8,
519 action_len: usize,
520 payload_ptr: [*]const u8,
521 payload_len: usize,
522 request_id: i64,
523) callconv(.c) bool {
524 const action = action_ptr[0..action_len];
525 const payload = payload_ptr[0..payload_len];
526
527 // Pushed for the whole call, exactly as `handleMessage` does: a reply
528 // formatted after this frame is gone reads `request_context.current()` and
529 // would stamp null, falling back to action-name correlation and handing
530 // one caller's answer to another.
531 request_context.push(if (request_id < 0) null else @intCast(request_id));
532 defer request_context.pop();
533
534 // The same line `handleMessage` logs, and for the same reason: on a device
535 // this is the only window into the bridge. `t=mobile` is spelled out
536 // rather than taken from an envelope, because a host-offered message has
537 // no envelope — this path is only ever the mobile namespace.
538 std.log.info("craft-bridge dispatch t=mobile a={s} i={?d}", .{
539 action,
540 request_context.current(),
541 });
542
543 // Before the gate and the module chain, because this is not a question
544 // about what the config allows or what a handler would do — it is a
545 // question about which arm owns the action at all, and the answer is the
546 // caller's own.
547 if (hostServesItself(action)) {
548 std.log.info("ios: {s} is declared unavailable; leaving it to the host", .{action});
549 return false;
550 }
551
552 const offer = offerToModules(std.heap.c_allocator, action, payload) catch {
553 // A module ran and failed, and answered the page on its way out. That
554 // is a served action with an unhappy result, not an unserved one.
555 return true;
556 };
557 return offer == .answered;
558}
559
343560/// Deliver a result the host shim produced.
344561///
345562/// Exported for the shim to call. Everything after this point is the same path
@@ -582,3 +799,132 @@ test "a shim error with no request id omits the id field entirely" {
582799 try buildShimError(testing.allocator, &out, "share", "m", "E", -1);
583800 try testing.expect(std.mem.indexOf(u8, out.items, "\"id\"") == null);
584801}
802
803test "a host offer that no module recognises comes back as the host's problem" {
804 // The whole contract of `craft_ios_handle_action` in one assertion. A
805 // Swift-hosted app calls this first and serves the action itself when the
806 // answer is false; if an unrecognised action ever returned true, that
807 // action would silently stop working in every generated app — the page's
808 // promise would hang with nobody having agreed to answer it.
809 try testing.expect(!craft_ios_handle_action("noSuchAction", "noSuchAction".len, "{}", 2, 7));
810}
811
812test "a host offer for a served action is claimed, not handed back" {
813 // `getDeviceInfo` is served by `bridge_mobile_device.zig` on every
814 // platform this test runs on. The reply cannot arrive — there is no
815 // webview in a test binary, so `sendResultToJS` reaches
816 // `error.NoWebView` — but claiming is the half under test: true means Zig
817 // has taken responsibility, and a caller that also answered would be the
818 // double-reply this return value exists to prevent.
819 //
820 // Off Darwin the action still routes; it just fails inside the handler,
821 // which is `answered` too. Either way the answer is true, and that is the
822 // point: "claimed" is about ownership, never about success.
823 try testing.expect(craft_ios_handle_action("getDeviceInfo", "getDeviceInfo".len, "{}", 2, 1));
824}
825
826test "a host offer for a disabled capability is claimed and refused, not handed back" {
827 // The trap this return value is shaped around. `clipboardRead` is served
828 // by Zig and gated on `enableClipboard`; a test binary has no bundled
829 // craft.config.json, so `isEnabled` is false and the gate refuses.
830 //
831 // The refusal already called `sendErrorToJS`, so the page's promise is
832 // settled. Returning false here would invite the Swift arm to answer the
833 // same call a second time — and Swift's own arm for a disabled capability
834 // has no `else`, so the page would get one rejection and one silence.
835 try testing.expect(craft_ios_handle_action("clipboardRead", "clipboardRead".len, "{}", 2, 3));
836}
837
838test "a negative request id means no callback is waiting" {
839 // Mirrors `craft_ios_deliver_result`'s reading of the same sentinel. The
840 // id is pushed for the duration of the call and popped after, so a stack
841 // that leaked a frame would be visible here as a non-empty context once
842 // the call has returned.
843 try testing.expect(request_context.current() == null);
844 _ = craft_ios_handle_action("noSuchAction", "noSuchAction".len, "{}", 2, -1);
845 try testing.expect(request_context.current() == null);
846}
847
848test "setting the webview from a host is what makes replies reachable" {
849 // The one call a Swift-hosted app must make before offering anything.
850 // Without it every reply lands on `error.NoWebView`: the action runs, it
851 // works, and the page never hears. Restored afterwards so the ordering of
852 // tests in this file cannot matter.
853 const saved = getWebView();
854 defer setWebView(saved);
855
856 setWebView(null);
857 try testing.expectError(error.NoWebView, evalJS("1"));
858
859 var fake: u8 = 0;
860 craft_ios_set_webview(&fake);
861 try testing.expect(getWebView() == @as(objc.id, @ptrCast(&fake)));
862
863 // And clearing it is reachable again, which is the half that was broken:
864 // a host that hands over nil must leave the runtime saying "no webview"
865 // rather than quietly addressing every reply to it.
866 craft_ios_set_webview(null);
867 try testing.expectError(error.NoWebView, evalJS("1"));
868}
869
870test "an action declared unavailable is left to the host, not claimed" {
871 // The regression this guards. Each of these has a working Swift arm and a
872 // Zig handler that refuses on purpose; before the host-offered path knew
873 // the difference, linking the runtime replaced the working answer with a
874 // rejection. `false` here is what sends the call back to Swift's switch.
875 const declared_unavailable = [_][]const u8{
876 "haptic",
877 "getNetworkStatus",
878 "lockOrientation",
879 "unlockOrientation",
880 };
881 for (declared_unavailable) |action| {
882 try testing.expect(hostServesItself(action));
883 try testing.expect(!craft_ios_handle_action(action.ptr, action.len, "{}", 2, 11));
884 }
885}
886
887test "the fall-through is read from the manifests, not from a list kept beside them" {
888 // `hostServesItself` must answer for exactly the actions the modules
889 // declare `.unavailable` — no more, or a working Zig action is handed away;
890 // no fewer, or the regression comes back for whichever one was missed. So
891 // count the declarations rather than trusting the test above's literals.
892 var declared: usize = 0;
893 for (mobile_manifests) |manifest| {
894 for (manifest) |decl| {
895 if (decl.status == .unavailable) {
896 declared += 1;
897 try testing.expect(hostServesItself(decl.name));
898 }
899 }
900 }
901 try testing.expectEqual(@as(usize, 4), declared);
902}
903
904test "a live action is still claimed, unavailable is not a blanket hand-back" {
905 // The other half: `vibrate` sits in the same module as `haptic` and is
906 // `.live`, so the seam must keep claiming it. A fall-through that widened
907 // to whole modules would silently un-migrate everything beside a refusal.
908 try testing.expect(!hostServesItself("vibrate"));
909 try testing.expect(!hostServesItself("setKeepAwake"));
910 try testing.expect(!hostServesItself("getDeviceInfo"));
911 try testing.expect(!hostServesItself("noSuchAction"));
912}
913
914test "clearing the webview only forgets the one the caller named" {
915 // The rebuild order that makes a blind clear wrong: SwiftUI builds the
916 // replacement, then dismantles the original. If dismantling cleared
917 // unconditionally, the live view installed a moment earlier would be
918 // dropped and every reply after it would reach `error.NoWebView`.
919 const first: *anyopaque = @ptrFromInt(0x1000);
920 const second: *anyopaque = @ptrFromInt(0x2000);
921 defer setWebView(null);
922
923 craft_ios_set_webview(first);
924 craft_ios_set_webview(second); // the replacement arrives first
925 craft_ios_clear_webview(first); // then the original is dismantled
926 try testing.expect(getWebView() == second);
927
928 craft_ios_clear_webview(second);
929 try testing.expect(getWebView() == null);
930}