ReviewOS

also looking at this

craft-native/craft

fix(ios): answer the shapes the spec answers, now that a bare false survives

#105
Merged chris wants to merge fix/ios-reply-shape-parity into main
7 files +423 -82

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

packages/ios/templates/CraftApp.swiftmodified+13-4
Changes to packages/ios/templates/CraftApp.swift
@@ -1093,11 +1093,11 @@ struct CraftWebView: UIViewRepresentable { renamed throughout
10931093 // MARK: - Siri Shortcuts
10941094 case "registerSiriShortcut":
10951095 if let phrase = body["phrase"] as? String,
1096 let action = body["action"] as? String {
1096 let action = body["shortcutAction"] as? String {
10971097 registerSiriShortcut(phrase: phrase, action: action, callbackId: callbackId)
10981098 }
10991099 case "removeSiriShortcut":
1100 if let action = body["action"] as? String {
1100 if let action = body["shortcutAction"] as? String {
11011101 removeSiriShortcut(action: action, callbackId: callbackId)
11021102 }
11031103
@@ -2194,7 +2194,15 @@ struct CraftWebView: UIViewRepresentable {
21942194 register: function(phrase, action) {
21952195 var self = window.craft;
21962196 var id = 'cb_' + (++self._callbackId);
2197 window.webkit.messageHandlers.craft.postMessage({action: 'registerSiriShortcut', phrase: phrase, action: action, callbackId: id});
2197 // `shortcutAction`, not `action`. This object had two
2198 // keys called `action` — the message's own, and the
2199 // shortcut's — and the later one wins, so every call
2200 // arrived labelled with the shortcut's identifier
2201 // instead of 'registerSiriShortcut'. No switch arm
2202 // matched, nothing answered, and these wrappers park in
2203 // `_callbacks` with no timeout: the promise never
2204 // settled at all.
2205 window.webkit.messageHandlers.craft.postMessage({action: 'registerSiriShortcut', phrase: phrase, shortcutAction: action, callbackId: id});
21982206 return new Promise(function(resolve, reject) {
21992207 self._callbacks[id] = {resolve: resolve, reject: reject};
22002208 });
@@ -2202,7 +2210,8 @@ struct CraftWebView: UIViewRepresentable {
22022210 remove: function(action) {
22032211 var self = window.craft;
22042212 var id = 'cb_' + (++self._callbackId);
2205 window.webkit.messageHandlers.craft.postMessage({action: 'removeSiriShortcut', action: action, callbackId: id});
2213 // The same duplicate key as `register` above.
2214 window.webkit.messageHandlers.craft.postMessage({action: 'removeSiriShortcut', shortcutAction: action, callbackId: id});
22062215 return new Promise(function(resolve, reject) {
22072216 self._callbacks[id] = {resolve: resolve, reject: reject};
22082217 });
packages/zig/src/bridge_mobile_display.zigmodified+39-37
Changes to packages/zig/src/bridge_mobile_display.zig
@@ -105,12 +105,18 @@ pub const DisplayBridge = struct {
105105 }
106106 }
107107
108 /// `{"count":N}` in, `{"count":<what UIKit now reports>}` out.
108 /// `{"count":N}` in, bare `true` out — what the spec resolves.
109109 ///
110 /// The reply is an object, not the bare `true` Swift resolves:
111 /// `craft-bridge.js` settles with `payload || {}`, so any falsy scalar
112 /// arrives at the page as `{}` and carries nothing. An object also lets the
113 /// value be checked, which a `true` never could.
110 /// This answered `{"count":<observed>}` until now, to work around
111 /// `craft-bridge.js` settling with `payload || {}`: a falsy scalar reached
112 /// the page as `{}` and carried nothing. That is fixed at its source
113 /// (`_orEmpty`), so the wrapper is gone and pages reading `=== true` work
114 /// again.
115 ///
116 /// The observed count goes to the log rather than the page. It was the one
117 /// thing the object shape bought, and the spec never offered it — a page
118 /// that wants the badge back has no API for it in either implementation,
119 /// so inventing one here would be a second divergence rather than a fix.
114120 fn setBadge(self: *Self, data: []const u8) !void {
115121 const requested = try badgeCountFrom(self.allocator, data);
116122 try self.replyBadge(A.set_badge, try applyBadge(requested));
@@ -125,11 +131,15 @@ pub const DisplayBridge = struct {
125131 }
126132
127133 fn replyBadge(self: *Self, action: []const u8, observed: i64) !void {
128 var buf: [48]u8 = undefined;
129 bridge_error.sendResultToJS(self.allocator, action, try renderBadgeReply(&buf, observed));
134 std.log.info("{s}: badge is now {d}", .{ action, observed });
135 bridge_error.sendResultToJS(self.allocator, action, badge_applied);
130136 }
131137
132 /// `{"enabled":<bool>}` in, `{"enabled":<what UIKit now reports>}` out.
138 /// `{"enabled":<bool>}` in, the bare observed boolean out.
139 ///
140 /// The spec resolves the `enabled` the page sent; this resolves what UIKit
141 /// reports, which is the same value whenever the write took. Bare rather
142 /// than `{"enabled":…}` for the reason recorded on `replyBadge`.
133143 ///
134144 /// Swift also stores `isKeepingAwake`, which nothing in the template ever
135145 /// reads. It is not ported: a variable with no reader cannot be wrong, and
@@ -140,11 +150,10 @@ pub const DisplayBridge = struct {
140150 const requested = try keepAwakeFrom(self.allocator, data);
141151 const observed = try applyKeepAwake(requested);
142152
143 var buf: [32]u8 = undefined;
144153 bridge_error.sendResultToJS(
145154 self.allocator,
146155 A.set_keep_awake,
147 try renderKeepAwakeReply(&buf, observed),
156 if (observed) "true" else "false",
148157 );
149158 }
150159
@@ -185,13 +194,8 @@ pub const DisplayBridge = struct {
185194/// Split out because a test that re-typed the format string would pass no
186195/// matter what the handler sent — it would be asserting that `std.fmt` works.
187196/// These are the strings the page actually receives.
188fn renderBadgeReply(buf: []u8, observed: i64) ![]const u8 {
189 return std.fmt.bufPrint(buf, "{⁠{\"count\":{d}}}", .{observed});
190}
191
192fn renderKeepAwakeReply(buf: []u8, observed: bool) ![]const u8 {
193 return std.fmt.bufPrint(buf, "{⁠{\"enabled\":{}}}", .{observed});
194}
197/// What `setBadge` and `clearBadge` resolve. A bare `true`, matching the spec.
198const badge_applied = "true";
195199
196200// =============================================================================
197201// Payload parsing
@@ -630,27 +634,25 @@ test "the orientation actions refuse, and say which kind of refusal it is" {
630634 );
631635}
632636
633test "replies are objects carrying a value, not bare scalars" {
634 // `craft-bridge.js` settles with `payload || {}`. A bare `false` — which
635 // `setKeepAwake(false)` would resolve, following Swift — arrives at the
636 // page as `{}` and loses the answer entirely.
637test "replies are the bare scalars the spec resolves" {
638 // These were objects — `{"count":N}` and `{"enabled":<bool>}` — to work
639 // around `craft-bridge.js` settling with `payload || {}`, which turned a
640 // bare `false` into a truthy `{}`. That is fixed at its source, so the
641 // wrapper is gone and the shapes match the spec again: a page doing
642 // `(await craft.setKeepAwake(false)) === false` gets `false`, and one doing
643 // `(await craft.clearBadge()) === true` gets `true`.
637644 //
638 // These call the same renderers the handlers do, so changing a key name or
639 // dropping the object wrapper fails here instead of reading as coverage.
640 var buf: [48]u8 = undefined;
641
642 try testing.expectEqualStrings("{\"count\":7}", try renderBadgeReply(&buf, 7));
643 try testing.expectEqualStrings("{\"count\":0}", try renderBadgeReply(&buf, 0));
644 try testing.expectEqualStrings("{\"enabled\":false}", try renderKeepAwakeReply(&buf, false));
645 try testing.expectEqualStrings("{\"enabled\":true}", try renderKeepAwakeReply(&buf, true));
646
647 // The stack buffers the handlers hand these are 48 and 32 bytes; the widest
648 // reply either can produce has to fit, or a legitimate count turns into a
649 // `NoSpaceLeft` the page reads as a native failure.
650 var badge_buf: [48]u8 = undefined;
651 try testing.expect((try renderBadgeReply(&badge_buf, std.math.minInt(i64))).len <= badge_buf.len);
652 var keep_buf: [32]u8 = undefined;
653 try testing.expect((try renderKeepAwakeReply(&keep_buf, false)).len <= keep_buf.len);
645 // Pinned as the literal bytes the handlers send, so re-wrapping either
646 // reply fails here rather than reading as coverage.
647 try testing.expectEqualStrings("true", badge_applied);
648
649 // Parsed, not just compared, so a literal that is not valid JSON — `True`,
650 // or a stray quote — cannot pass.
651 for ([_][]const u8{ badge_applied, "true", "false" }) |json| {
652 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
653 defer parsed.deinit();
654 try testing.expect(parsed.value == .bool);
655 }
654656}
655657
656658test "UIKit work is refused off Darwin rather than attempted" {
packages/zig/src/bridge_mobile_health.zigmodified+25-5
Changes to packages/zig/src/bridge_mobile_health.zig
@@ -1085,11 +1085,20 @@ fn routeInserted(index: u5, success: bool, err: Id) void {
10851085 const chain = call.workout orelse return;
10861086
10871087 if (!success) {
1088 // Rejects, as the spec does. Resolving here reported a workout with
1089 // `"routeId":""`, which is the shape a *successful* finish with a nil
1090 // route produces — so a page could not tell "the route saved and had no
1091 // id" from "the route did not save at all", and would file the workout
1092 // as complete with its locations silently missing.
1093 //
1094 // The id is not lost, it is logged: a fabricated success costs more
1095 // than a rejection, and this module refuses one everywhere else.
10881096 logNSError(A.save_health_workout, err);
1089 // Swift rejects. The workout is saved regardless, so the id is
1090 // reported rather than lost — losing it would leave a page unable to
1091 // reference a workout that exists.
1092 replyWithWorkout(call.ticket, chain, null);
1097 std.log.info(
1098 "saveHealthWorkout: route insert failed; the workout itself was saved as {s}",
1099 .{uuidStringOf(chain.workout) orelse "<no uuid>"},
1100 );
1101 ios_async.deliverErrorCode(call.ticket, bridge_error.BridgeError.NativeCallFailed);
10931102 chain.deinit();
10941103 return;
10951104 }
@@ -1112,8 +1121,15 @@ fn routeFinished(index: u5, route: Id, err: Id) void {
11121121 defer chain.deinit();
11131122
11141123 if (err != null) {
1124 // Same reasoning as `routeInserted`: the spec rejects on a finish
1125 // error, and resolving would be indistinguishable from the nil-route
1126 // success below.
11151127 logNSError(A.save_health_workout, err);
1116 replyWithWorkout(call.ticket, chain, null);
1128 std.log.info(
1129 "saveHealthWorkout: route finish failed; the workout itself was saved as {s}",
1130 .{uuidStringOf(chain.workout) orelse "<no uuid>"},
1131 );
1132 ios_async.deliverErrorCode(call.ticket, bridge_error.BridgeError.NativeCallFailed);
11171133 return;
11181134 }
11191135 replyWithWorkout(call.ticket, chain, route);
@@ -1124,6 +1140,10 @@ fn routeFinished(index: u5, route: Id, err: Id) void {
11241140/// Swift emits the second shape only when a route was finished, and its
11251141/// `routeId` is `route?.uuid.uuidString ?? ""` — so a finished-but-nil route
11261142/// carries an empty string rather than a missing key.
1143///
1144/// Only reached on success now. The two failure stages reject instead, because
1145/// an empty `routeId` here already means "finished, no id" and cannot also mean
1146/// "did not finish".
11271147fn replyWithWorkout(ticket: ios_async.Ticket, chain: WorkoutChain, route: Id) void {
11281148 const allocator = std.heap.c_allocator;
11291149
packages/zig/src/bridge_mobile_siri.zigmodified+9-6
Changes to packages/zig/src/bridge_mobile_siri.zig
@@ -295,7 +295,10 @@ fn readFields(
295295 else => return BridgeError.InvalidJSON,
296296 };
297297
298 const action = try requiredString(allocator, object, "action");
298 // `shortcutAction`, not `action`: the envelope's own `action` names the
299 // bridge action, and the page used to send both under that one key. See
300 // the wrapper in `CraftApp.swift`.
301 const action = try requiredString(allocator, object, "shortcutAction");
299302 errdefer allocator.free(action);
300303
301304 const phrase = if (want.phrase) try requiredString(allocator, object, "phrase") else null;
@@ -459,7 +462,7 @@ test "both fields are required for a registration, and neither hangs" {
459462 // missing phrase replies nothing at all.
460463 var fields = try readFields(
461464 testing.allocator,
462 "{\"action\":\"openVault\",\"phrase\":\"open my vault\"}",
465 "{\"shortcutAction\":\"openVault\",\"phrase\":\"open my vault\"}",
463466 .{ .phrase = true },
464467 );
465468 defer fields.deinit(testing.allocator);
@@ -468,7 +471,7 @@ test "both fields are required for a registration, and neither hangs" {
468471
469472 try testing.expectError(BridgeError.MissingData, readFields(
470473 testing.allocator,
471 "{\"action\":\"openVault\"}",
474 "{\"shortcutAction\":\"openVault\"}",
472475 .{ .phrase = true },
473476 ));
474477 try testing.expectError(BridgeError.MissingData, readFields(
@@ -478,18 +481,18 @@ test "both fields are required for a registration, and neither hangs" { renamed throughout
478481 ));
479482 try testing.expectError(BridgeError.InvalidParameter, readFields(
480483 testing.allocator,
481 "{\"action\":\"\",\"phrase\":\"p\"}",
484 "{\"shortcutAction\":\"\",\"phrase\":\"p\"}",
482485 .{ .phrase = true },
483486 ));
484487 try testing.expectError(BridgeError.InvalidParameter, readFields(
485488 testing.allocator,
486 "{\"action\":3,\"phrase\":\"p\"}",
489 "{\"shortcutAction\":3,\"phrase\":\"p\"}",
487490 .{ .phrase = true },
488491 ));
489492}
490493
491494test "a removal needs only the action" {
492 var fields = try readFields(testing.allocator, "{\"action\":\"openVault\"}", .{ .phrase = false });
495 var fields = try readFields(testing.allocator, "{\"shortcutAction\":\"openVault\"}", .{ .phrase = false });
493496 defer fields.deinit(testing.allocator);
494497 try testing.expectEqualStrings("openVault", fields.action);
495498 try testing.expect(fields.phrase == null);
packages/zig/src/bridge_mobile_system.zigmodified+30-16
Changes to packages/zig/src/bridge_mobile_system.zig
@@ -63,16 +63,23 @@ pub const capability_actions = [_]capabilities.ActionDecl{
6363///
6464/// Named rather than written inline at each `sendResultToJS`, so the test that
6565/// pins their shape reads the same bytes the handlers send instead of a copy
66/// of them that can drift. Every one is a JSON *object* carrying a boolean:
67/// `craft-bridge.js` resolves with `payload || {}`, so a bare `false` and an
68/// empty reply are the same value to the page — a fabricated success wearing
69/// the shape of an honest one.
66/// of them that can drift.
67///
68/// Bare booleans, because that is what the spec resolves — `openURL` and
69/// `requestReview` answer `true`, and `share` answers the `completed` flag
70/// from the activity handler. These were objects until now, and the reason is
71/// worth recording: `craft-bridge.js` settled with `payload || {}`, which
72/// turns a truthful `false` into a truthy `{}`, so a bare boolean could not
73/// carry a negative answer. Wrapping it was the workaround. The bug is fixed
74/// at its source (`_orEmpty`), so the wrapper is gone and a cancelled share
75/// reads as `false` again instead of `{completed:false}`, which every page
76/// written against the spec reads as success.
7077const R = struct {
71 const opened = "{\"opened\":true}";
72 const not_opened = "{\"opened\":false}";
73 const completed = "{\"completed\":true}";
74 const not_completed = "{\"completed\":false}";
75 const requested = "{\"requested\":true}";
78 const opened = "true";
79 const not_opened = "false";
80 const completed = "true";
81 const not_completed = "false";
82 const requested = "true";
7683
7784 const all = [_][]const u8{ opened, not_opened, completed, not_completed, requested };
7885};
@@ -1031,19 +1038,26 @@ test "every reply is a JSON object naming what happened, never a bare boolean" {
10311038 // `craft-bridge.js` resolves with `payload || {}`, so a bare `false` and an
10321039 // empty reply are the same value to the page.
10331040 for (R.all) |json| {
1034 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1041 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{
1042 // A bare `true` is a JSON fragment, not a document. The spec
1043 // serialises with `.fragmentsAllowed` for the same reason.
1044 .allocate = .alloc_if_needed,
1045 });
10351046 defer parsed.deinit();
1036 try testing.expect(parsed.value == .object);
1037 try testing.expectEqual(@as(usize, 1), parsed.value.object.count());
10381047
1039 // And the member is a boolean the caller can branch on, not a string or
1040 // a number that reads as truthy whatever it says.
1041 var it = parsed.value.object.iterator();
1042 try testing.expect(it.next().?.value_ptr.* == .bool);
1048 // A boolean the caller can branch on — not a string, not a number, and
1049 // not an object, which is what these were while `payload || {}` made a
1050 // bare `false` unrepresentable.
1051 try testing.expect(parsed.value == .bool);
10431052 }
10441053
10451054 // Non-vacuity: every assertion above is satisfied by an empty list.
10461055 try testing.expectEqual(@as(usize, 5), R.all.len);
10471056 try testing.expect(!std.mem.eql(u8, R.opened, R.not_opened));
10481057 try testing.expect(!std.mem.eql(u8, R.completed, R.not_completed));
1058
1059 // The negative answers really are `false`, which is the whole point of the
1060 // change: an object here read as success to every page that branched on it.
1061 try testing.expectEqualStrings("false", R.not_opened);
1062 try testing.expectEqualStrings("false", R.not_completed);
10491063}
packages/zig/src/bridge_mobile_vision.zigmodified+20-2
Changes to packages/zig/src/bridge_mobile_vision.zig
@@ -416,15 +416,33 @@ fn shapeResults(allocator: std.mem.Allocator, kind: Kind, request: Id) ![]u8 {
416416 const count = try arrayCount(results);
417417 const limit = if (kind == .classify) @min(count, max_classifications) else count;
418418
419 // `written`, not `i`, decides the separator. A recognition observation with
420 // no candidate is skipped rather than emitted, exactly as the spec does, so
421 // the reply can be shorter than the observation list — and keying the comma
422 // off the loop index would then leave a leading or doubled one and hand the
423 // page invalid JSON.
424 var written: usize = 0;
419425 var i: usize = 0;
420426 while (i < limit) : (i += 1) {
421427 const observation = try arrayObjectAt(results, i);
422 if (i != 0) try out.append(allocator, ',');
428 const mark = out.items.len;
429 if (written != 0) try out.append(allocator, ',');
423430 switch (kind) {
424431 .classify => try appendClassification(allocator, &out, observation),
425432 .detect => try appendDetection(allocator, &out, observation),
426 .recognize => try appendRecognizedText(allocator, &out, observation),
433 // The one skippable case. Swift reads `topCandidates(1).first` and
434 // drops the observation when it is nil; rejecting the whole call
435 // instead loses every line that *did* recognise, which is the
436 // answer the page asked for.
437 .recognize => appendRecognizedText(allocator, &out, observation) catch |err| switch (err) {
438 error.NoCandidates => {
439 out.shrinkRetainingCapacity(mark);
440 continue;
441 },
442 else => return err,
443 },
427444 }
445 written += 1;
428446 }
429447
430448 try out.append(allocator, ']');
packages/zig/src/js/craft-bridge.jsmodified+11-2
Changes to packages/zig/src/js/craft-bridge.js
@@ -65,6 +65,15 @@
6565 }
6666 }
6767
68 // `payload || {}` was wrong for every action whose answer is a bare boolean:
69 // it turned a truthful `false` into `{}`, which is truthy, so a page reading
70 // `if (await craft.share(...))` took the success branch on a cancelled share.
71 // Only genuinely absent payloads become `{}`; `false`, `0` and `""` are
72 // answers and survive.
73 function _orEmpty(payload) {
74 return payload === undefined || payload === null ? {} : payload
75 }
76
6877 // Native's answer to one call. `id` is the `i` we sent, echoed back; a reply
6978 // raised outside any dispatch has none and falls back to the action queue.
7079 window.__craftBridgeResult = function (action, payload, id) {
@@ -77,7 +86,7 @@
7786 // call's own, with nothing to indicate anything had gone wrong.
7887 if (!e) return
7988 _forget(e)
80 if (e.resolve) e.resolve(payload || {})
89 if (e.resolve) e.resolve(_orEmpty(payload))
8190 return
8291 }
8392
@@ -87,7 +96,7 @@
8796 if (!q || q.length === 0) return
8897 const e = q[0]
8998 _forget(e)
90 if (e.resolve) e.resolve(payload || {})
99 if (e.resolve) e.resolve(_orEmpty(payload))
91100 }
92101
93102 // Native calls this when an action fails.