@native-sdk/cli 0.5.3 → 0.5.4

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 (79) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +223 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/src/emitter.ts +2586 -259
  10. package/skill-data/native-ui/SKILL.md +3 -2
  11. package/skill-data/ts-core/SKILL.md +9 -1
  12. package/src/app_runner/root.zig +81 -1
  13. package/src/app_runner/ts_core_main.zig +4 -0
  14. package/src/embed/tests.zig +119 -1
  15. package/src/platform/linux/gtk_host.c +112 -3
  16. package/src/platform/linux/root.zig +71 -0
  17. package/src/platform/macos/appkit_host.h +48 -2
  18. package/src/platform/macos/appkit_host.m +533 -34
  19. package/src/platform/macos/cef_host.mm +262 -10
  20. package/src/platform/macos/root.zig +92 -4
  21. package/src/platform/null_platform.zig +298 -5
  22. package/src/platform/root.zig +33 -0
  23. package/src/platform/types.zig +138 -4
  24. package/src/platform/windows/root.zig +134 -0
  25. package/src/platform/windows/webview2_host.cpp +152 -40
  26. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  27. package/src/primitives/app_manifest/root.zig +1 -0
  28. package/src/primitives/app_manifest/types.zig +32 -0
  29. package/src/primitives/canvas/tests.zig +1 -0
  30. package/src/primitives/canvas/ui.zig +11 -7
  31. package/src/primitives/canvas/ui_markup.zig +58 -34
  32. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  33. package/src/primitives/canvas/ui_markup_compiled.zig +23 -8
  34. package/src/primitives/canvas/ui_markup_compiled_tests.zig +55 -0
  35. package/src/primitives/canvas/ui_markup_contract.zig +1 -1
  36. package/src/primitives/canvas/ui_markup_contract_tests.zig +26 -0
  37. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  38. package/src/primitives/canvas/ui_markup_tests.zig +29 -9
  39. package/src/primitives/canvas/ui_markup_view.zig +29 -11
  40. package/src/primitives/canvas/ui_markup_view_tests.zig +150 -9
  41. package/src/primitives/canvas/ui_schema.zig +13 -0
  42. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  43. package/src/root.zig +7 -0
  44. package/src/runtime/api.zig +6 -4
  45. package/src/runtime/bridge_payload.zig +7 -0
  46. package/src/runtime/bridge_responses.zig +5 -0
  47. package/src/runtime/builtin_bridge.zig +9 -4
  48. package/src/runtime/canvas_font_tests.zig +439 -2
  49. package/src/runtime/canvas_fonts.zig +61 -6
  50. package/src/runtime/canvas_image_tests.zig +195 -0
  51. package/src/runtime/canvas_images.zig +45 -12
  52. package/src/runtime/core.zig +58 -11
  53. package/src/runtime/effects.zig +1664 -43
  54. package/src/runtime/effects_fetch_tests.zig +89 -1
  55. package/src/runtime/effects_file_tests.zig +41 -1
  56. package/src/runtime/effects_image_tests.zig +1304 -0
  57. package/src/runtime/effects_tests.zig +153 -0
  58. package/src/runtime/flow.zig +17 -0
  59. package/src/runtime/root.zig +11 -0
  60. package/src/runtime/session_blobs.zig +689 -0
  61. package/src/runtime/session_journal.zig +85 -21
  62. package/src/runtime/session_record.zig +27 -2
  63. package/src/runtime/session_replay.zig +168 -16
  64. package/src/runtime/session_tests.zig +1992 -0
  65. package/src/runtime/shell_layout.zig +7 -0
  66. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  67. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +439 -4
  70. package/src/runtime/ts_core_host_tests.zig +41 -0
  71. package/src/runtime/ts_ui_app.zig +7 -0
  72. package/src/runtime/ui_app.zig +111 -6
  73. package/src/runtime/ui_app_window_tests.zig +468 -0
  74. package/src/runtime/window_command_bridge_tests.zig +117 -0
  75. package/src/runtime/window_storage.zig +32 -0
  76. package/src/runtime/window_views.zig +61 -1
  77. package/src/tooling/manifest.zig +75 -0
  78. package/src/tooling/raw_manifest.zig +2 -0
  79. package/src/tooling/templates.zig +219 -1
@@ -301,6 +301,17 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
301
301
  @property(nonatomic, assign) BOOL observesContentLayout;
302
302
  @end
303
303
 
304
+ /// NSApp's delegate, installed by runWithCallback: — this host
305
+ /// otherwise drives NSApplication entirely through notification
306
+ /// observers, and staying that way for activation keeps those events
307
+ /// single-sourced (a delegate implementing applicationDidBecomeActive:
308
+ /// would ALSO receive the notification, double-emitting). The one job
309
+ /// here is the Dock-icon reopen: with no window visible, re-show the
310
+ /// windows the .hide close policy hid.
311
+ @interface NativeSdkAppDelegate : NSObject <NSApplicationDelegate>
312
+ @property(nonatomic, assign) NativeSdkAppKitHost *host;
313
+ @end
314
+
304
315
  @interface NativeSdkWebView : WKWebView <NSDraggingDestination>
305
316
  @property(nonatomic, strong) NSArray<NSValue *> *coveredMouseRects;
306
317
  @property(nonatomic, assign) NativeSdkAppKitHost *host;
@@ -662,6 +673,20 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
662
673
  /// color, packed RGBA8 per window — so residual gaps (resize slack,
663
674
  /// titlebar bands) show the app's background, never a blank default.
664
675
  @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClearColors;
676
+ /// close_policy per window (0 = quit, the default; 1 = hide). Applied
677
+ /// by native_sdk_appkit_set_window_close_policy right after create —
678
+ /// the delegate's windowShouldClose: consults it, so the user's close
679
+ /// affordance hides a .hide window instead of closing it.
680
+ @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClosePolicies;
681
+ /// Windows currently hidden BY their .hide close policy — the set the
682
+ /// Dock reopen re-shows, and the truth emitWindowFrameForWindowId's
683
+ /// hidden flag reports. Ordinary orderOut/minimize states never enter
684
+ /// it.
685
+ @property(nonatomic, strong) NSMutableSet<NSNumber *> *policyHiddenWindows;
686
+ /// Strong ref for NSApp.delegate (which is unretained): the tiny
687
+ /// delegate that turns a Dock-icon reopen into re-showing
688
+ /// policy-hidden windows.
689
+ @property(nonatomic, strong) id reopenDelegate;
665
690
  @property(nonatomic, strong) NSMutableDictionary<NSString *, WKWebView *> *childWebViews;
666
691
  @property(nonatomic, strong) NSMutableDictionary<NSString *, NSView *> *nativeViews;
667
692
  /// App-owned NSViews adopted into native view containers (native-surface
@@ -764,6 +789,11 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
764
789
  @property(nonatomic, assign) void *context;
765
790
  @property(nonatomic, assign) void *bridgeContext;
766
791
  @property(nonatomic, assign) BOOL didShutdown;
792
+ /* A quit verb that arrived before [NSApp run] (see
793
+ * native_sdk_appkit_request_stop): parked here, drained at top level
794
+ * by runWithCallback's drainPendingPreRunStop calls once the pre-run
795
+ * dispatch that carried it has returned. */
796
+ @property(nonatomic, assign) BOOL pendingPreRunStop;
767
797
  @property(nonatomic, assign) BOOL observesApplicationActivation;
768
798
  @property(nonatomic, assign) BOOL observesAppearanceChanges;
769
799
  @property(nonatomic, assign) NSInteger bridgeFrameKeepalive;
@@ -783,6 +813,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
783
813
  - (void)applyWindowClearColor:(uint64_t)windowId red:(uint8_t)red green:(uint8_t)green blue:(uint8_t)blue alpha:(uint8_t)alpha;
784
814
  - (void)focusWindowWithId:(uint64_t)windowId;
785
815
  - (void)closeWindowWithId:(uint64_t)windowId;
816
+ - (void)hideWindowWithId:(uint64_t)windowId;
817
+ - (void)showWindowWithId:(uint64_t)windowId;
818
+ - (BOOL)reopenPolicyHiddenWindows;
786
819
  - (BOOL)startWindowDragWithId:(uint64_t)windowId;
787
820
  - (BOOL)chromeInsetsForWindowId:(uint64_t)windowId top:(double *)top left:(double *)left bottom:(double *)bottom right:(double *)right buttonsX:(double *)buttonsX buttonsY:(double *)buttonsY buttonsWidth:(double *)buttonsWidth buttonsHeight:(double *)buttonsHeight;
788
821
  - (WKWebView *)ensureMainWebViewForWindowId:(uint64_t)windowId;
@@ -843,6 +876,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
843
876
  - (void)setMenusWithTitles:(const char *const *)menuTitles titleLengths:(const size_t *)menuTitleLengths count:(size_t)menuCount itemMenuIndices:(const uint32_t *)itemMenuIndices itemLabels:(const char *const *)itemLabels itemLabelLengths:(const size_t *)itemLabelLengths itemCommands:(const char *const *)itemCommands itemCommandLengths:(const size_t *)itemCommandLengths itemKeys:(const char *const *)itemKeys itemKeyLengths:(const size_t *)itemKeyLengths itemModifiers:(const uint32_t *)itemModifiers itemSeparators:(const int *)itemSeparators itemEnabled:(const int *)itemEnabled itemChecked:(const int *)itemChecked itemCount:(size_t)itemCount;
844
877
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
845
878
  - (void)stop;
879
+ - (BOOL)drainPendingPreRunStop;
846
880
  - (void)emitEvent:(native_sdk_appkit_event_t)event;
847
881
  - (BOOL)emitDroppedFileURLs:(NSArray<NSURL *> *)urls windowId:(uint64_t)windowId;
848
882
  - (void)startApplicationActivationObservers;
@@ -1022,6 +1056,22 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1022
1056
  return [self.host emitDroppedFileURLs:urls windowId:self.windowId];
1023
1057
  }
1024
1058
 
1059
+ // close_policy .hide: the USER's close affordance (the red button,
1060
+ // cmd+W — anything routed through performClose:) hides the window
1061
+ // instead of closing it, and the app keeps running behind its status
1062
+ // item. Runtime-initiated closes bypass this hook deliberately
1063
+ // (closeWindowWithId: calls -close directly for .hide windows), so an
1064
+ // app that decides to really close its window still can. A future
1065
+ // .event tier would land here too — the delegate forwarding the close
1066
+ // request to the model instead of deciding — the enum keeps that room.
1067
+ - (BOOL)windowShouldClose:(NSWindow *)sender {
1068
+ (void)sender;
1069
+ NSNumber *policy = self.host.windowClosePolicies[@(self.windowId)];
1070
+ if (policy.intValue != 1) return YES;
1071
+ [self.host hideWindowWithId:self.windowId];
1072
+ return NO;
1073
+ }
1074
+
1025
1075
  - (void)windowWillClose:(NSNotification *)notification {
1026
1076
  (void)notification;
1027
1077
  if (self.observesContentLayout) {
@@ -1029,6 +1079,10 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1029
1079
  [window removeObserver:self forKeyPath:@"contentLayoutRect"];
1030
1080
  self.observesContentLayout = NO;
1031
1081
  }
1082
+ // A really-closing window is closed, not hidden: leave the
1083
+ // policy-hidden set before the frame emit so open=false never
1084
+ // carries a stale hidden=true.
1085
+ [self.host.policyHiddenWindows removeObject:@(self.windowId)];
1032
1086
  [self.host emitWindowFrameForWindowId:self.windowId open:NO];
1033
1087
  [self.host closeWebViewsInWindow:self.windowId];
1034
1088
  [self.host closeNativeViewsInWindow:self.windowId];
@@ -1041,6 +1095,7 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1041
1095
  [self.host.windowLabels removeObjectForKey:key];
1042
1096
  [self.host.deferredShowWindows removeObjectForKey:key];
1043
1097
  [self.host.windowClearColors removeObjectForKey:key];
1098
+ [self.host.windowClosePolicies removeObjectForKey:key];
1044
1099
  if (self.host.windows.count == 0) {
1045
1100
  [self.host emitShutdown];
1046
1101
  [self.host stop];
@@ -1049,6 +1104,20 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1049
1104
 
1050
1105
  @end
1051
1106
 
1107
+ @implementation NativeSdkAppDelegate
1108
+
1109
+ // Clicking the Dock icon with every window gone from the glass: when
1110
+ // policy-hidden windows exist, re-show them and answer NO (the reopen
1111
+ // is handled); otherwise answer YES so AppKit keeps its default
1112
+ // behavior (deminiaturizing, ordering in) untouched.
1113
+ - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
1114
+ (void)sender;
1115
+ if (flag) return YES;
1116
+ return ![self.host reopenPolicyHiddenWindows];
1117
+ }
1118
+
1119
+ @end
1120
+
1052
1121
  @implementation NativeSdkWebView
1053
1122
 
1054
1123
  - (BOOL)pointIsCovered:(NSPoint)point {
@@ -1763,19 +1832,122 @@ static NSMutableDictionary<NSNumber *, id> *NativeSdkRegisteredFontDescriptors(v
1763
1832
  return table;
1764
1833
  }
1765
1834
 
1766
- // The registered face for a canvas font id at `size`, or nil when the id
1767
- // has no registered face. Checked BEFORE the built-in candidates and
1768
- // their cache so a registered id can never be masked by a font resolved
1769
- // for that id earlier (ids are engine-validated and permanent, so cached
1770
- // NSFonts here never go stale).
1771
- static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
1772
- NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1773
- static NSMutableDictionary<NSString *, NSFont *> *sizeCache = nil;
1835
+ // The per-(id, size) NSFont cache for registered faces, keyed "id/size".
1836
+ // Ids are permanent within ONE runtime (`error.FontIdInUse` guards
1837
+ // re-use for a runtime's lifetime), but this cache is per-PROCESS and
1838
+ // runtimes are not: an embedder that destroys its runtime
1839
+ // (`Runtime.deinit`) and registers a DIFFERENT face under the same
1840
+ // valid id in a new runtime is inside the documented lifecycle. Entries
1841
+ // therefore go stale exactly when an id's descriptor is (re)installed,
1842
+ // so `native_sdk_appkit_register_font` evicts the id's cached sizes
1843
+ // before installing the new descriptor. The measured-width NSCache
1844
+ // (`NativeSdkMeasuredWidthCache`) goes stale at the same moment but
1845
+ // cannot be prefix-evicted (NSCache does not enumerate keys), so it is
1846
+ // invalidated by registration token instead — see
1847
+ // NativeSdkRegisteredFontTokens below. Accessed only under the
1848
+ // descriptor table's @synchronized guard, like the descriptors.
1849
+ static NSMutableDictionary<NSString *, NSFont *> *NativeSdkRegisteredFontSizeCache(void) {
1850
+ static NSMutableDictionary<NSString *, NSFont *> *cache = nil;
1774
1851
  static dispatch_once_t onceToken;
1775
1852
  dispatch_once(&onceToken, ^{
1776
- sizeCache = [[NSMutableDictionary alloc] init];
1853
+ cache = [[NSMutableDictionary alloc] init];
1854
+ });
1855
+ return cache;
1856
+ }
1857
+
1858
+ // Per-id registration tokens, the invalidation handle for the
1859
+ // measured-width NSCache (`NativeSdkMeasuredWidthCache`). That
1860
+ // cache has the same lifetime hazard as the size cache above (per-
1861
+ // process cache, per-runtime id permanence) but no way to evict an
1862
+ // id's entries — NSCache cannot enumerate keys — so every registration
1863
+ // stamps its id with the next value of ONE process-global monotonic
1864
+ // counter and the width-cache key includes the stamp. Tokens never
1865
+ // repeat, so no registration can ever reach widths a previous life of
1866
+ // its id cached (re-registration leaves those unreachable entries to
1867
+ // age out under the cache's count limit; unregistration clears the
1868
+ // cache outright — see `native_sdk_appkit_unregister_font`) — which is
1869
+ // exactly what makes an id's record REMOVABLE at unregister, retaining
1870
+ // zero state per retired id.
1871
+ // A per-id bump counter could not offer that: deleting a per-id count
1872
+ // would let a future registration of the id restart at 1 and collide
1873
+ // with the retired life's still-cached widths, so retired ids would
1874
+ // each pin a record for the process lifetime. Ids never registered
1875
+ // (the built-in faces) have no record and measure under token 0 — the
1876
+ // same value an unregistered id returns to, honest because both states
1877
+ // resolve through the same built-in candidates. Accessed only under
1878
+ // the descriptor table's @synchronized guard, like the descriptors.
1879
+ static NSMutableDictionary<NSNumber *, NSNumber *> *NativeSdkRegisteredFontTokens(void) {
1880
+ static NSMutableDictionary<NSNumber *, NSNumber *> *table = nil;
1881
+ static dispatch_once_t onceToken;
1882
+ dispatch_once(&onceToken, ^{
1883
+ table = [[NSMutableDictionary alloc] init];
1884
+ });
1885
+ return table;
1886
+ }
1887
+
1888
+ // The process-global registration token counter: pre-incremented at
1889
+ // every registration, so 0 is never a live token and stays the honest
1890
+ // "no registered face" value. Mutated only under the descriptor
1891
+ // table's @synchronized guard, like every table here.
1892
+ static unsigned long long NativeSdkRegisteredFontTokenCounter = 0;
1893
+
1894
+ // The measured-width NSCache `native_sdk_appkit_measure_text` memoizes
1895
+ // shaped widths in, hoisted out of that function (exactly the shared-
1896
+ // accessor shape the NSFont size cache above took) so
1897
+ // `native_sdk_appkit_unregister_font` can reach it at teardown: a
1898
+ // retiring token's entries can never be SERVED again (tokens never
1899
+ // repeat) but a function-local static left them RESIDENT — up to the
1900
+ // full count limit of keys, each carrying the measured text itself —
1901
+ // until memory pressure. NSCache is thread-safe, so unlike the
1902
+ // dictionaries above this cache is deliberately NOT confined to the
1903
+ // descriptor table's @synchronized guard: measure_text shapes outside
1904
+ // the critical section on purpose (see the snapshot comment) and
1905
+ // re-enters the guard only to recheck the token before a
1906
+ // registered-token write (see the recheck comment in measure_text).
1907
+ static NSCache<NSString *, NSNumber *> *NativeSdkMeasuredWidthCache(void) {
1908
+ static NSCache<NSString *, NSNumber *> *cache = nil;
1909
+ static dispatch_once_t onceToken;
1910
+ dispatch_once(&onceToken, ^{
1911
+ cache = [[NSCache alloc] init];
1912
+ cache.countLimit = 16384;
1777
1913
  });
1914
+ return cache;
1915
+ }
1916
+
1917
+ // The id's current registration token AND the registered face that
1918
+ // token resolves to, snapshotted under ONE acquisition of the
1919
+ // descriptor table's @synchronized guard. The pair must be atomic
1920
+ // because measure_text keys its width memoization by (id, token): with
1921
+ // the token read and the face resolved under SEPARATE acquisitions, a
1922
+ // registration landing between them pairs token 0 with the NEW
1923
+ // registered face and caches a registered-face width under the
1924
+ // reusable token-0 key — served again after the registration is torn
1925
+ // down, when token 0 honestly means built-in resolution. One critical
1926
+ // section makes a torn pair unrepresentable; the width computation
1927
+ // itself stays outside the lock (see measure_text), because a
1928
+ // stale-but-consistent pair is harmless: measure_text rechecks the
1929
+ // token under the guard before caching, so a pair retired mid-shape
1930
+ // is never even written. Returns nil with
1931
+ // *out_token = 0 when the id holds no registration, so token 0 only
1932
+ // ever pairs with built-in resolution. (A registered descriptor whose
1933
+ // CTFont creation fails also answers nil, under its live token: the
1934
+ // built-in fallback then caches under that token — still one
1935
+ // consistent resolution per registration life, since the failure is a
1936
+ // property of the installed descriptor.)
1937
+ //
1938
+ // The registered-face NSFonts cached here stay honest because
1939
+ // registration evicts an id's entries when its descriptor changes (see
1940
+ // NativeSdkRegisteredFontSizeCache) — an id is only permanent within
1941
+ // one runtime, and this cache outlives runtimes. Registered faces are
1942
+ // checked BEFORE the built-in candidates and their cache so a
1943
+ // registered id can never be masked by a font resolved for that id
1944
+ // earlier.
1945
+ static NSFont *NativeSdkRegisteredFontSnapshot(unsigned long long value, CGFloat size, unsigned long long *out_token) {
1946
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1947
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
1778
1948
  @synchronized (table) {
1949
+ NSNumber *tokenNumber = NativeSdkRegisteredFontTokens()[@(value)];
1950
+ *out_token = tokenNumber ? tokenNumber.unsignedLongLongValue : 0;
1779
1951
  id descriptorObject = table[@(value)];
1780
1952
  if (!descriptorObject) return nil;
1781
1953
  NSString *key = [NSString stringWithFormat:@"%llu/%.3f", value, (double)size];
@@ -1789,36 +1961,133 @@ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat si
1789
1961
  }
1790
1962
  }
1791
1963
 
1964
+ // The registered face for a canvas font id at `size`, or nil when the id
1965
+ // has no registered face — the snapshot above for callers that resolve
1966
+ // but do not memoize by token (packet drawing, the advances batch).
1967
+ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
1968
+ unsigned long long token = 0;
1969
+ return NativeSdkRegisteredFontSnapshot(value, size, &token);
1970
+ }
1971
+
1792
1972
  // Engine-validated TrueType bytes for a registered canvas font id: parse
1793
1973
  // them into a font descriptor once and key it by id, so measurement and
1794
1974
  // packet text drawing resolve the id to this exact face. Returns 1 on
1795
1975
  // success, 0 when CoreText rejects the data — the engine already parsed
1796
1976
  // the face, so a rejection here is surfaced as a loud registration
1797
- // error engine-side, never a silent fallback at draw time.
1798
- int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len) {
1799
- if (font_id == 0 || !bytes || bytes_len == 0) return 0;
1977
+ // error engine-side, never a silent fallback at draw time. On success
1978
+ // `*out_token` reports the registration token minted below — the
1979
+ // ownership handle unregister_font matches against, so a teardown can
1980
+ // only remove the registration it owns.
1981
+ int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len, uint64_t *out_token) {
1982
+ if (out_token) *out_token = 0;
1983
+ if (font_id == 0 || !bytes || bytes_len == 0 || !out_token) return 0;
1800
1984
  @autoreleasepool {
1801
1985
  NSData *data = [NSData dataWithBytes:bytes length:bytes_len];
1802
1986
  CTFontDescriptorRef descriptor = CTFontManagerCreateFontDescriptorFromData((__bridge CFDataRef)data);
1803
1987
  if (!descriptor) return 0;
1804
1988
  NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1805
1989
  @synchronized (table) {
1990
+ // Evict the id's cached NSFonts BEFORE installing the new
1991
+ // descriptor: the process may still hold fonts a PREVIOUS
1992
+ // runtime resolved for this id (ids are per-runtime
1993
+ // permanent, the cache is per-process), and serving them
1994
+ // would measure and draw the old face under the new id.
1995
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
1996
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
1997
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
1998
+ for (NSString *cachedKey in cachedKeys) {
1999
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2000
+ }
2001
+ // The measured-width cache holds the same stale state but
2002
+ // cannot be enumerated for eviction, so stamp the id with a
2003
+ // fresh process-global token instead: width-cache keys
2004
+ // include the token, tokens never repeat, and everything
2005
+ // cached under any previous stamp becomes unreachable. The
2006
+ // stamp doubles as the registration's ownership token,
2007
+ // reported to the caller so its teardown can name exactly
2008
+ // this registration.
2009
+ unsigned long long token = ++NativeSdkRegisteredFontTokenCounter;
2010
+ NativeSdkRegisteredFontTokens()[@(font_id)] = @(token);
1806
2011
  table[@(font_id)] = (__bridge_transfer id)descriptor;
2012
+ *out_token = token;
1807
2013
  }
1808
2014
  return 1;
1809
2015
  }
1810
2016
  }
1811
2017
 
1812
- // Resolves a canvas font id to the NSFont presentation draws with. Both
1813
- // packet text drawing and native_sdk_appkit_measure_text go through this
1814
- // single function so measured layout and drawn glyphs share font
1815
- // resolution. Ids 3-6 are the reserved sans span variants (medium, bold,
1816
- // italic, bold italic); everything else keeps the regular sans/mono
1817
- // candidates. Registered faces win first (see above). Resolved
1818
- // built-in fonts are cached per (font id, size).
1819
- static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1820
- NSFont *registered = NativeSdkRegisteredFontForId(value, size);
1821
- if (registered) return registered;
2018
+ // Teardown twin of the registration above, called by Runtime.deinit for
2019
+ // each id the dying runtime registered: font ids are per-runtime but
2020
+ // every table here is per-process, so without this removal an embedder
2021
+ // cycling runtimes with fresh ids grows the descriptor table (and its
2022
+ // caches) for the process lifetime. Removal drops EVERYTHING the
2023
+ // registration installed: the id's cached NSFonts (the same prefix
2024
+ // eviction re-registration runs), the id's registration token record,
2025
+ // the descriptor itself, and — by clearing the measured-width NSCache
2026
+ // wholesale, the only eviction NSCache permits — the widths measured
2027
+ // under the retiring token. Zero retained state per retired id, so
2028
+ // runtime cycles truly do not accumulate host entries. Deleting the
2029
+ // token record (rather than bumping it) is safe precisely because
2030
+ // tokens come from one process-global monotonic counter: a future
2031
+ // registration of this id takes a fresh, never-repeated token, so no
2032
+ // per-id record has to survive to keep this life's width-cache keys
2033
+ // unreachable. An id
2034
+ // with no installed descriptor (never registered host-side, or already
2035
+ // returned) is a no-op accept.
2036
+ //
2037
+ // Removal is token-guarded: `token` is the ownership handle the id's
2038
+ // register call reported, and state comes out ONLY while the id's
2039
+ // current registration still carries it. Font ids are per-runtime while
2040
+ // this state is per-process, so a later runtime may have re-registered
2041
+ // the id (last wins — its face is the live one measurement and drawing
2042
+ // resolve); an id-keyed removal here would let the OLDER runtime's
2043
+ // deinit delete the newer runtime's descriptor and caches, dropping its
2044
+ // host text to the default family while its engine still holds the
2045
+ // face. A stale token is a no-op accept, not an error: the registration
2046
+ // it owned is already gone, which is exactly the state its owner asked
2047
+ // this call to establish.
2048
+ int native_sdk_appkit_unregister_font(uint64_t font_id, uint64_t token) {
2049
+ if (font_id == 0) return 0;
2050
+ @autoreleasepool {
2051
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2052
+ @synchronized (table) {
2053
+ NSNumber *current = NativeSdkRegisteredFontTokens()[@(font_id)];
2054
+ if (!current || current.unsignedLongLongValue != token) return 1;
2055
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
2056
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
2057
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
2058
+ for (NSString *cachedKey in cachedKeys) {
2059
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2060
+ }
2061
+ [NativeSdkRegisteredFontTokens() removeObjectForKey:@(font_id)];
2062
+ [table removeObjectForKey:@(font_id)];
2063
+ // The retiring token's measured widths can never be served
2064
+ // again (tokens never repeat) but would otherwise stay
2065
+ // resident until memory pressure. NSCache cannot enumerate
2066
+ // keys, so a per-id eviction is impossible and clearing the
2067
+ // WHOLE cache is the only honest release. The collateral is
2068
+ // cheap where it lands: unregistration is a teardown-
2069
+ // frequency event, and every other live id re-warms each
2070
+ // width it still needs in one measure call. The clear runs
2071
+ // only on this token-matched path — a stale-token no-op
2072
+ // above must not cost live registrations their warm cache.
2073
+ // A measurement in flight during this teardown cannot
2074
+ // repopulate the cleared cache: measure_text rechecks the
2075
+ // id's token under this same guard before caching, and this
2076
+ // removal already retired the token it snapshotted.
2077
+ [NativeSdkMeasuredWidthCache() removeAllObjects];
2078
+ }
2079
+ return 1;
2080
+ }
2081
+ }
2082
+
2083
+ // The built-in-candidates half of font resolution: never consults the
2084
+ // registered tables, so callers that already hold a registered-face
2085
+ // snapshot (measure_text) fall back here without re-reading state the
2086
+ // snapshot fixed. Ids 3-6 are the reserved sans span variants (medium,
2087
+ // bold, italic, bold italic); everything else keeps the regular
2088
+ // sans/mono candidates. Resolved built-in fonts are cached per
2089
+ // (font id, size).
2090
+ static NSFont *NativeSdkBuiltInFontForFontId(unsigned long long value, CGFloat size) {
1822
2091
  static NSCache<NSString *, NSFont *> *cache = nil;
1823
2092
  static dispatch_once_t onceToken;
1824
2093
  dispatch_once(&onceToken, ^{
@@ -1866,6 +2135,19 @@ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1866
2135
  return font;
1867
2136
  }
1868
2137
 
2138
+ // Resolves a canvas font id to the NSFont presentation draws with. Both
2139
+ // packet text drawing and native_sdk_appkit_measure_text go through this
2140
+ // resolution order (registered faces win, then the built-in candidates)
2141
+ // so measured layout and drawn glyphs share font resolution —
2142
+ // measure_text inlines the two halves around its width cache because it
2143
+ // must key that cache by the registration-token snapshot the first half
2144
+ // fixes.
2145
+ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
2146
+ NSFont *registered = NativeSdkRegisteredFontForId(value, size);
2147
+ if (registered) return registered;
2148
+ return NativeSdkBuiltInFontForFontId(value, size);
2149
+ }
2150
+
1869
2151
  static NSFont *NativeSdkPacketPreferredFont(NSDictionary *text, CGFloat size) {
1870
2152
  NSNumber *fontId = [text[@"font"] isKindOfClass:[NSNumber class]] ? text[@"font"] : nil;
1871
2153
  unsigned long long value = fontId ? fontId.unsignedLongLongValue : 1;
@@ -1883,19 +2165,58 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1883
2165
  @autoreleasepool {
1884
2166
  NSString *value = [[NSString alloc] initWithBytes:text length:text_len encoding:NSUTF8StringEncoding];
1885
2167
  if (!value) return -1;
1886
- static NSCache<NSString *, NSNumber *> *widthCache = nil;
1887
- static dispatch_once_t onceToken;
1888
- dispatch_once(&onceToken, ^{
1889
- widthCache = [[NSCache alloc] init];
1890
- widthCache.countLimit = 16384;
1891
- });
1892
- NSString *key = [NSString stringWithFormat:@"%llu/%.3f/%@", (unsigned long long)font_id, (double)clamped, value];
2168
+ NSCache<NSString *, NSNumber *> *widthCache = NativeSdkMeasuredWidthCache();
2169
+ // The key carries the id's registration token so a face
2170
+ // re-registered under the same id (a new runtime in this
2171
+ // process) never serves a previous face's widths — see
2172
+ // NativeSdkRegisteredFontTokens for why token, not eviction,
2173
+ // invalidates this cache. Token and registered face come from
2174
+ // ONE snapshot (one critical section — see
2175
+ // NativeSdkRegisteredFontSnapshot): reading them under separate
2176
+ // acquisitions let a registration land between the reads and
2177
+ // cache the new face's width under the reusable token-0 key,
2178
+ // serving stale registered widths in the unregistered state
2179
+ // after teardown.
2180
+ unsigned long long token = 0;
2181
+ NSFont *registered = NativeSdkRegisteredFontSnapshot((unsigned long long)font_id, clamped, &token);
2182
+ NSString *key = [NSString stringWithFormat:@"%llu/%llu/%.3f/%@", (unsigned long long)font_id, token, (double)clamped, value];
1893
2183
  NSNumber *cached = [widthCache objectForKey:key];
1894
2184
  if (cached) return cached.doubleValue;
1895
- NSFont *font = NativeSdkFontForFontId(font_id, clamped);
2185
+ // A nil snapshot means built-in resolution — with token 0 by the
2186
+ // snapshot's contract unless a live descriptor's CTFont creation
2187
+ // failed, so token 0 only ever keys built-in widths. Shaping
2188
+ // stays OUTSIDE the critical section: a registration or
2189
+ // unregistration landing after the snapshot leaves this width
2190
+ // stale but consistent, and the token recheck below drops the
2191
+ // write instead of caching it.
2192
+ NSFont *font = registered ?: NativeSdkBuiltInFontForFontId(font_id, clamped);
1896
2193
  if (!font) return -1;
1897
2194
  double width = [value sizeWithAttributes:@{ NSFontAttributeName : font }].width;
1898
- [widthCache setObject:@(width) forKey:key];
2195
+ if (token == 0) {
2196
+ // Token 0 is built-in resolution: built-in faces are never
2197
+ // registered, so no unregister can ever clear widths keyed
2198
+ // under it — this write needs no recheck.
2199
+ [widthCache setObject:@(width) forKey:key];
2200
+ return width;
2201
+ }
2202
+ // A registered-token width is cached only after RECHECKING the
2203
+ // token under the guard. Unregister's only possible eviction is
2204
+ // clearing the whole width cache, and shaping ran outside the
2205
+ // critical section: an unconditional write here would land AFTER
2206
+ // that clear whenever the teardown ran inside the shaping window,
2207
+ // repopulating the cleared cache with a retired-token entry — one
2208
+ // no lookup can ever serve (tokens never repeat) but that stays
2209
+ // resident until memory pressure. A mismatch means the
2210
+ // registration was torn down (or replaced) mid-shape — dropping
2211
+ // the write costs one re-measure of a face that is already gone,
2212
+ // and keeps teardown's cleared cache actually clear.
2213
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2214
+ @synchronized (table) {
2215
+ NSNumber *currentToken = NativeSdkRegisteredFontTokens()[@(font_id)];
2216
+ if (currentToken && currentToken.unsignedLongLongValue == token) {
2217
+ [widthCache setObject:@(width) forKey:key];
2218
+ }
2219
+ }
1899
2220
  return width;
1900
2221
  }
1901
2222
  }
@@ -1910,6 +2231,14 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1910
2231
  // call per text run replaces one measure_text round-trip per cluster of
1911
2232
  // every growing line prefix — the engine caches the batch, so a run is
1912
2233
  // typically shaped here once per content change, not once per frame.
2234
+ //
2235
+ // Unlike measure_text this needs no registration-token snapshot: it
2236
+ // memoizes nothing host-side (the engine caches the batch and
2237
+ // invalidates it by its own measure generation, bumped at every
2238
+ // registration), so each call resolves the font once and uses it
2239
+ // immediately — there is no (token, face) pairing that could tear
2240
+ // across lock acquisitions or outlive the registration it was read
2241
+ // from.
1913
2242
  int native_sdk_appkit_measure_text_advances(uint64_t font_id, double size, const char *text, size_t text_len, float *advances) {
1914
2243
  if (!text || text_len == 0 || !advances) return 0;
1915
2244
  CGFloat clamped = MAX(1, size);
@@ -6407,6 +6736,8 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6407
6736
  self.windowLabels = [[NSMutableDictionary alloc] init];
6408
6737
  self.deferredShowWindows = [[NSMutableDictionary alloc] init];
6409
6738
  self.windowClearColors = [[NSMutableDictionary alloc] init];
6739
+ self.windowClosePolicies = [[NSMutableDictionary alloc] init];
6740
+ self.policyHiddenWindows = [[NSMutableSet alloc] init];
6410
6741
  self.childWebViews = [[NSMutableDictionary alloc] init];
6411
6742
  self.nativeViews = [[NSMutableDictionary alloc] init];
6412
6743
  self.adoptedViewSurfaces = [[NSMutableDictionary alloc] init];
@@ -6424,6 +6755,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6424
6755
 
6425
6756
  [self createWindowWithId:1 title:(windowTitle.length > 0 ? windowTitle : self.appName) label:self.windowLabel x:x y:y width:width height:height restoreFrame:restoreFrame resizable:resizable titlebarStyle:titlebarStyle showPolicy:showPolicy makeMain:YES];
6426
6757
  self.didShutdown = NO;
6758
+ self.pendingPreRunStop = NO;
6427
6759
  self.observesApplicationActivation = NO;
6428
6760
 
6429
6761
  return self;
@@ -6633,6 +6965,14 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6633
6965
  - (void)closeWindowWithId:(uint64_t)windowId {
6634
6966
  NSWindow *window = self.windows[@(windowId)];
6635
6967
  if (!window) return;
6968
+ // A runtime-initiated close is the app DECIDING to close: it must
6969
+ // not bounce off the window's own .hide close policy, so it skips
6970
+ // performClose: (which runs windowShouldClose:) and closes
6971
+ // directly — the full windowWillClose teardown still runs.
6972
+ if ([self.windowClosePolicies[@(windowId)] intValue] == 1) {
6973
+ [window close];
6974
+ return;
6975
+ }
6636
6976
  // performClose: simulates the titlebar close button, which a
6637
6977
  // chromeless (borderless) window does not have — AppKit just beeps.
6638
6978
  // Closing directly runs the same delegate teardown
@@ -6644,6 +6984,50 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6644
6984
  [window performClose:nil];
6645
6985
  }
6646
6986
 
6987
+ // close_policy .hide, the hiding half: order the window out (it keeps
6988
+ // its views, its webviews, and its host records — nothing tears down),
6989
+ // remember it as policy-hidden, and report the state on the frame
6990
+ // channel so the runtime's window table and the session journal both
6991
+ // carry the truth. orderOut composes with the host's bookkeeping where
6992
+ // close would not: the windows dictionary still owns the window, so
6993
+ // the count never reaches zero and no shutdown emits.
6994
+ - (void)hideWindowWithId:(uint64_t)windowId {
6995
+ NSWindow *window = self.windows[@(windowId)];
6996
+ if (!window) return;
6997
+ [self.policyHiddenWindows addObject:@(windowId)];
6998
+ [window orderOut:nil];
6999
+ [self emitWindowFrameForWindowId:windowId open:YES];
7000
+ }
7001
+
7002
+ // The counterpart show verb: bring a hidden (or merely unfocused)
7003
+ // window back to the glass and activate the app — the tray-menu
7004
+ // "Open" consequence and the Dock reopen both land here. Also clears a
7005
+ // pending present-before-show defer and a minimize, for the same
7006
+ // reason focusWindowWithId: does: the runtime asked for the window NOW.
7007
+ - (void)showWindowWithId:(uint64_t)windowId {
7008
+ NSWindow *window = self.windows[@(windowId)];
7009
+ if (!window) return;
7010
+ [self.policyHiddenWindows removeObject:@(windowId)];
7011
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7012
+ if (window.miniaturized) [window deminiaturize:nil];
7013
+ [window makeKeyAndOrderFront:nil];
7014
+ [NSApp activate];
7015
+ [self emitWindowFrameForWindowId:windowId open:YES];
7016
+ [self scheduleFrame];
7017
+ }
7018
+
7019
+ // The Dock-icon reopen consequence: with no window visible, re-show
7020
+ // every window the .hide close policy hid. Returns whether any window
7021
+ // was re-shown (the app delegate then suppresses AppKit's default
7022
+ // reopen handling for exactly that case).
7023
+ - (BOOL)reopenPolicyHiddenWindows {
7024
+ if (self.policyHiddenWindows.count == 0) return NO;
7025
+ for (NSNumber *key in [self.policyHiddenWindows copy]) {
7026
+ [self showWindowWithId:key.unsignedLongLongValue];
7027
+ }
7028
+ return YES;
7029
+ }
7030
+
6647
7031
  // The real OS minimize verb, for app-drawn window controls (chromeless
6648
7032
  // windows have no traffic lights to click): the window genies into the
6649
7033
  // Dock exactly like the yellow button. miniaturize: is used over
@@ -8225,6 +8609,16 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8225
8609
  self.callback = callback;
8226
8610
  self.context = context;
8227
8611
 
8612
+ // The Dock-reopen delegate (close_policy .hide's re-show path).
8613
+ // NSApp.delegate is free in this host — everything else rides
8614
+ // notification observers — and NSApp does not retain it.
8615
+ if (!NSApp.delegate) {
8616
+ NativeSdkAppDelegate *reopenDelegate = [[NativeSdkAppDelegate alloc] init];
8617
+ reopenDelegate.host = self;
8618
+ self.reopenDelegate = reopenDelegate;
8619
+ NSApp.delegate = reopenDelegate;
8620
+ }
8621
+
8228
8622
  // Present-before-show: a deferred startup window stays ordered out
8229
8623
  // here and appears when its first canvas present lands (or the
8230
8624
  // create-time fallback deadline fires).
@@ -8250,9 +8644,20 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8250
8644
  [self startAppearanceObservers];
8251
8645
 
8252
8646
  [self emitEvent:(native_sdk_appkit_event_t){ .kind = NATIVE_SDK_APPKIT_EVENT_START }];
8647
+ // A VALID quit can arrive during the START dispatch (an update that
8648
+ // returns fx.quitApp() at boot). Pre-run there is no queue turn to
8649
+ // defer it to, so native_sdk_appkit_request_stop parked it — and
8650
+ // THIS is its drain point: emitShutdown + stop run at top level,
8651
+ // after the START dispatch has committed to the session recorder,
8652
+ // never nested inside it (a nested emit seals the journal before
8653
+ // the start record commits and replay refuses the recording).
8654
+ [self drainPendingPreRunStop];
8253
8655
  // A failed START handler requests shutdown synchronously, before the
8254
8656
  // run loop exists — [NSApp stop:] is a no-op there. Honor the request
8255
- // here instead of stranding a live app behind a blank window.
8657
+ // here instead of stranding a live app behind a blank window. (That
8658
+ // request is the HOST side's native_sdk_appkit_stop, which keeps its
8659
+ // inline pre-run emit — distinct from the quit verb's pending flag
8660
+ // drained above.)
8256
8661
  if (self.didShutdown) return;
8257
8662
  [self emitAppearanceChanged];
8258
8663
  [self emitResize];
@@ -8269,6 +8674,14 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8269
8674
  }
8270
8675
  }
8271
8676
 
8677
+ // The appearance/resize/window-frame emits and the synchronous
8678
+ // first canvas frame above are pre-run dispatches too — a boot
8679
+ // command's update (a TS core's first-frame command included) can
8680
+ // return the quit verb during any of them. Drain the parked quit
8681
+ // here at top level before the run-loop machinery arms; when it
8682
+ // drains, the app never enters [NSApp run].
8683
+ if ([self drainPendingPreRunStop]) return;
8684
+
8272
8685
  // Terminations that bypass the host's own stop path — cmd+Q's
8273
8686
  // default NSApp terminate, an AppleScript quit — must still deliver
8274
8687
  // the shutdown event synchronously before the process exits: the
@@ -8331,6 +8744,22 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8331
8744
  [NSApp postEvent:event atStart:NO];
8332
8745
  }
8333
8746
 
8747
+ /* Drain the quit verb a pre-run dispatch parked (see
8748
+ * native_sdk_appkit_request_stop): emitShutdown + stop at TOP LEVEL,
8749
+ * strictly after the requesting dispatch returned, so the session
8750
+ * recorder commits the requesting event before the shutdown record
8751
+ * seals the journal. Answers YES only when it drained; a request that
8752
+ * raced an already-emitted shutdown (a failed emit's inline stop) is
8753
+ * consumed without a second emit. */
8754
+ - (BOOL)drainPendingPreRunStop {
8755
+ if (!self.pendingPreRunStop) return NO;
8756
+ self.pendingPreRunStop = NO;
8757
+ if (self.didShutdown) return NO;
8758
+ [self emitShutdown];
8759
+ [self stop];
8760
+ return YES;
8761
+ }
8762
+
8334
8763
  - (void)emitEvent:(native_sdk_appkit_event_t)event {
8335
8764
  if (self.callback) {
8336
8765
  self.callback(self.context, &event);
@@ -8477,6 +8906,10 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8477
8906
  .scale = window.backingScaleFactor,
8478
8907
  .open = open ? 1 : 0,
8479
8908
  .focused = window.isKeyWindow ? 1 : 0,
8909
+ // The hidden flag reports host truth, not a parameter: every
8910
+ // frame emit while a window sits in the policy-hidden set
8911
+ // carries it, and hide/show flip the set before they emit.
8912
+ .hidden = [self.policyHiddenWindows containsObject:@(windowId)] ? 1 : 0,
8480
8913
  .label = label.UTF8String,
8481
8914
  .label_len = [label lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
8482
8915
  }];
@@ -9895,8 +10328,58 @@ void native_sdk_appkit_wake(native_sdk_appkit_host_t *host) {
9895
10328
 
9896
10329
  void native_sdk_appkit_stop(native_sdk_appkit_host_t *host) {
9897
10330
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
9898
- [object emitShutdown];
9899
- [object stop];
10331
+ /* The HOST side's shutdown request — a failed event emit asks for
10332
+ * the teardown (see RunState.emit's catch in macos/root.zig). Not
10333
+ * the quit verb's landing point: that is
10334
+ * native_sdk_appkit_request_stop below. Queued while the run loop
10335
+ * is live, so the emit lands on the next turn at top level; [NSApp
10336
+ * run] drains the main queue and stop's posted wake event unwinds
10337
+ * it, so a stop that is the last thing an app ever does still
10338
+ * exits promptly. */
10339
+ if (!NSApp.running) {
10340
+ /* Before [NSApp run] there is no loop to drain the queue — a
10341
+ * failed START handler requests shutdown synchronously (see
10342
+ * runWithCallback's didShutdown check) and must keep getting
10343
+ * the inline emit, or the request would strand until a run
10344
+ * loop that may never start. */
10345
+ [object emitShutdown];
10346
+ [object stop];
10347
+ return;
10348
+ }
10349
+ dispatch_async(dispatch_get_main_queue(), ^{
10350
+ [object emitShutdown];
10351
+ [object stop];
10352
+ });
10353
+ }
10354
+
10355
+ void native_sdk_appkit_request_stop(native_sdk_appkit_host_t *host) {
10356
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10357
+ /* The quit VERB's landing point (fx.quitApp). The verb arrives MID
10358
+ * DISPATCH — some update returned it, so the runtime is still
10359
+ * inside that event's dispatch. Emitting SHUTDOWN here would nest
10360
+ * the shutdown dispatch inside the requester's: the session
10361
+ * recorder commits nested events innermost-first and seals the
10362
+ * journal on shutdown, so the nested seal makes the OUTER commit a
10363
+ * no-op and the journal loses the very event (and model mutation)
10364
+ * that quit the app — replay diverges. While the run loop is live,
10365
+ * one main-queue hop delivers the identical emitShutdown + stop on
10366
+ * the next loop turn, after the requesting dispatch has committed.
10367
+ * Before [NSApp run] there is no queue turn that would drain in
10368
+ * time — a quit from App.start's update, or from a boot command
10369
+ * during the synchronous first canvas frame, must NOT fall back to
10370
+ * an inline emit (the same nesting bug, just pre-run) — so the
10371
+ * request parks in pendingPreRunStop and runWithCallback drains it
10372
+ * at top level once the pre-run dispatch that carried it returns.
10373
+ * (The inline pre-run emit lives only in native_sdk_appkit_stop
10374
+ * above, for the host-side failed-START request.) */
10375
+ if (!NSApp.running) {
10376
+ object.pendingPreRunStop = YES;
10377
+ return;
10378
+ }
10379
+ dispatch_async(dispatch_get_main_queue(), ^{
10380
+ [object emitShutdown];
10381
+ [object stop];
10382
+ });
9900
10383
  }
9901
10384
 
9902
10385
  void native_sdk_appkit_load_webview(native_sdk_appkit_host_t *host, const char *source, size_t source_len, int source_kind, const char *asset_root, size_t asset_root_len, const char *asset_entry, size_t asset_entry_len, const char *asset_origin, size_t asset_origin_len, int spa_fallback) {
@@ -10006,6 +10489,22 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
10006
10489
  return 1;
10007
10490
  }
10008
10491
 
10492
+ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
10493
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10494
+ if (!object.windows[@(window_id)]) return 0;
10495
+ [object showWindowWithId:window_id];
10496
+ return 1;
10497
+ }
10498
+
10499
+ int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
10500
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10501
+ if (!object.windows[@(window_id)]) return 0;
10502
+ // Applied right after create, like the content min-size floor —
10503
+ // close handling is host window state fixed for the window's life.
10504
+ object.windowClosePolicies[@(window_id)] = @(close_policy);
10505
+ return 1;
10506
+ }
10507
+
10009
10508
  int native_sdk_appkit_start_window_drag(native_sdk_appkit_host_t *host, uint64_t window_id) {
10010
10509
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10011
10510
  return [object startWindowDragWithId:window_id] ? 1 : 0;