@native-sdk/cli 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -24,6 +24,7 @@
24
24
  #include <stdint.h>
25
25
  #include <stdlib.h>
26
26
  #include <string.h>
27
+ #include <time.h>
27
28
 
28
29
  @class NativeSdkAppKitHost;
29
30
  @class NativeSdkAudioCaptureTarget;
@@ -38,6 +39,53 @@ static const uint32_t NativeSdkShortcutModifierCommand = 1u << 1;
38
39
  static const uint32_t NativeSdkShortcutModifierControl = 1u << 2;
39
40
  static const uint32_t NativeSdkShortcutModifierOption = 1u << 3;
40
41
  static const uint32_t NativeSdkShortcutModifierShift = 1u << 4;
42
+
43
+ // SMAppService is resolved dynamically so the host keeps its existing
44
+ // deployment target. Class lookup alone does not load the framework, so
45
+ // load it explicitly on first use; older macOS releases simply leave the
46
+ // class unavailable and report unsupported.
47
+ static id NativeSdkMainAppService(void) {
48
+ static void *serviceManagementHandle = NULL;
49
+ static dispatch_once_t serviceManagementOnce;
50
+ dispatch_once(&serviceManagementOnce, ^{
51
+ serviceManagementHandle = dlopen(
52
+ "/System/Library/Frameworks/ServiceManagement.framework/ServiceManagement",
53
+ RTLD_LAZY | RTLD_LOCAL);
54
+ });
55
+ if (!serviceManagementHandle) return nil;
56
+ Class serviceClass = NSClassFromString(@"SMAppService");
57
+ SEL selector = NSSelectorFromString(@"mainApp");
58
+ if (!serviceClass || ![serviceClass respondsToSelector:selector]) return nil;
59
+ IMP implementation = [serviceClass methodForSelector:selector];
60
+ return ((id (*)(id, SEL))implementation)(serviceClass, selector);
61
+ }
62
+
63
+ static int NativeSdkLaunchAtLoginStatus(void) {
64
+ id service = NativeSdkMainAppService();
65
+ SEL selector = NSSelectorFromString(@"status");
66
+ if (!service || ![service respondsToSelector:selector]) return -1;
67
+ IMP implementation = [service methodForSelector:selector];
68
+ return (int)((NSInteger (*)(id, SEL))implementation)(service, selector);
69
+ }
70
+
71
+ static int NativeSdkSetLaunchAtLogin(BOOL enabled) {
72
+ id service = NativeSdkMainAppService();
73
+ if (!service) return -1;
74
+ int before = NativeSdkLaunchAtLoginStatus();
75
+ // Requires-approval is already registered in the requested enabled
76
+ // direction. Re-registering it returns kSMErrorAlreadyRegistered or
77
+ // kSMErrorLaunchDeniedByUser instead of advancing the user's consent.
78
+ if ((enabled && (before == 1 || before == 2)) || (!enabled && before == 0)) return before;
79
+ SEL selector = NSSelectorFromString(enabled ? @"registerAndReturnError:" : @"unregisterAndReturnError:");
80
+ if (![service respondsToSelector:selector]) return -1;
81
+ NSError *error = nil;
82
+ IMP implementation = [service methodForSelector:selector];
83
+ BOOL succeeded = ((BOOL (*)(id, SEL, NSError **))implementation)(service, selector, &error);
84
+ // -1 is reserved for an unavailable service/API. A supported service
85
+ // refusing the operation is a real failure so the TypeScript effect can
86
+ // distinguish "failed" from "unsupported".
87
+ return succeeded ? NativeSdkLaunchAtLoginStatus() : -2;
88
+ }
41
89
  static void *NativeSdkAppKitAppearanceObservationContext = &NativeSdkAppKitAppearanceObservationContext;
42
90
  /* KVO contexts for the app's single audio player: the AVPlayerItem's
43
91
  * load status (readyToPlay -> the LOADED acknowledgment; failed -> one
@@ -119,7 +167,10 @@ static BOOL NativeSdkAppKitHighContrastEnabled(void) {
119
167
  }
120
168
 
121
169
  static uint64_t NativeSdkTimestampNanoseconds(void) {
122
- return (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000000000.0);
170
+ /* GPU input, frame pacing, and present-completion latency are duration
171
+ * math. CLOCK_MONOTONIC matches the runtime's monotonicNanoseconds seam
172
+ * and cannot jump when the wall clock is adjusted. */
173
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC);
123
174
  }
124
175
 
125
176
  static uint64_t NativeSdkRetainedFrameIntervalNanoseconds(NSScreen *screen) {
@@ -283,6 +334,15 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
283
334
  } mutableCopy];
284
335
  }
285
336
 
337
+ // Preserve the closed core-effect failure classes across the C seam.
338
+ static int NativeSdkCredentialStatus(OSStatus status, int missingCode) {
339
+ if (status == errSecSuccess) return 1;
340
+ if (status == errSecItemNotFound) return missingCode;
341
+ if (status == errSecInteractionNotAllowed || status == errSecNotAvailable) return -2;
342
+ if (status == errSecAuthFailed || status == errSecUserCanceled || status == errSecMissingEntitlement) return -3;
343
+ return -1;
344
+ }
345
+
286
346
  /// The chromeless (titlebarStyle 3) window class: a borderless NSWindow
287
347
  /// refuses key/main status by default, which would leave a fully-skinned
288
348
  /// app deaf to the keyboard — this subclass restores both. Used only for
@@ -703,7 +763,22 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
703
763
  @property(nonatomic, assign) uint32_t modifiers;
704
764
  @end
705
765
 
706
- @interface NativeSdkAppKitHost : NSObject <WKNavigationDelegate>
766
+ @interface NativeSdkStatusItemEntry : NSObject
767
+ @property(nonatomic, assign) uint32_t identifier;
768
+ @property(nonatomic, strong) NSStatusItem *item;
769
+ @property(nonatomic, strong) NSImage *baseImage;
770
+ @property(nonatomic, strong) NSMenu *menu;
771
+ @property(nonatomic, strong) NSString *presentationTitle;
772
+ @property(nonatomic, assign) double presentationWidth;
773
+ @property(nonatomic, assign) int presentationTone;
774
+ @property(nonatomic, assign) double presentationIconOpacity;
775
+ @property(nonatomic, assign) BOOL presentationMonospaced;
776
+ @property(nonatomic, strong) NSString *activationCommand;
777
+ @property(nonatomic, strong) NSString *alternateActivationCommand;
778
+ @property(nonatomic, strong) NSString *openCommand;
779
+ @end
780
+
781
+ @interface NativeSdkAppKitHost : NSObject <WKNavigationDelegate, NSMenuDelegate, NSUserNotificationCenterDelegate>
707
782
  @property(nonatomic, strong) NSWindow *window;
708
783
  @property(nonatomic, strong) WKWebView *webView;
709
784
  @property(nonatomic, strong) NativeSdkWindowDelegate *delegate;
@@ -765,6 +840,12 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
765
840
  * block starts still gets its own turn. */
766
841
  @property(atomic, assign) BOOL crossThreadFramePending;
767
842
  @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSTimer *> *appTimers;
843
+ /* Notification userInfo persists with the delivered notification, so it
844
+ * carries only a per-process token. Commands remain in this live host;
845
+ * stale notifications from an earlier execution cannot dispatch into a
846
+ * later one. The identifier map invalidates same-id replacements. */
847
+ @property(nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *notificationActionCommands;
848
+ @property(nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *notificationActionTokensByIdentifier;
768
849
  /* The app's single audio player and its position-tick timer. One player
769
850
  * is the whole surface: a music app plays one track at a time, and a
770
851
  * second concurrent stream would be mixer design the platform seam has
@@ -926,7 +1007,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
926
1007
  @property(nonatomic, strong) id willTerminateObserver;
927
1008
  @property(nonatomic, strong) dispatch_source_t sigtermSource;
928
1009
  @property(nonatomic, strong) NSArray<NativeSdkShortcut *> *shortcuts;
929
- @property(nonatomic, strong) NSStatusItem *statusItem;
1010
+ @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NativeSdkStatusItemEntry *> *statusItems;
930
1011
  @property(nonatomic, assign) native_sdk_appkit_tray_callback_t trayCallback;
931
1012
  @property(nonatomic, assign) void *trayContext;
932
1013
  @property(nonatomic, strong) NSArray<NSString *> *allowedNavigationOrigins;
@@ -998,6 +1079,11 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
998
1079
  - (NSMenuItem *)menuItem:(NSString *)title action:(SEL)action key:(NSString *)key modifiers:(NSEventModifierFlags)modifiers;
999
1080
  - (NSMenuItem *)commandMenuItem:(NSString *)title command:(NSString *)command key:(NSString *)key modifiers:(uint32_t)modifiers enabled:(BOOL)enabled checked:(BOOL)checked;
1000
1081
  - (void)menuCommandItemClicked:(NSMenuItem *)menuItem;
1082
+ - (void)menuWillOpen:(NSMenu *)menu;
1083
+ - (NativeSdkStatusItemEntry *)statusEntryForId:(uint32_t)identifier;
1084
+ - (NativeSdkStatusItemEntry *)statusEntryForMenu:(NSMenu *)menu;
1085
+ - (void)emitStatusCommand:(NSString *)command statusItemId:(uint32_t)statusItemId;
1086
+ - (void)statusItemActivated:(id)sender;
1001
1087
  - (uint64_t)activeCommandWindowId;
1002
1088
  - (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;
1003
1089
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
@@ -1009,6 +1095,8 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
1009
1095
  - (void)stopApplicationActivationObservers;
1010
1096
  - (void)applicationDidBecomeActive:(NSNotification *)notification;
1011
1097
  - (void)applicationDidResignActive:(NSNotification *)notification;
1098
+ - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification;
1099
+ - (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;
1012
1100
  - (void)startAppearanceObservers;
1013
1101
  - (void)stopAppearanceObservers;
1014
1102
  - (void)emitAppearanceChanged;
@@ -7264,6 +7352,9 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7264
7352
  @implementation NativeSdkShortcut
7265
7353
  @end
7266
7354
 
7355
+ @implementation NativeSdkStatusItemEntry
7356
+ @end
7357
+
7267
7358
  /* ------------------------------------------------------- audio capture
7268
7359
  * Both native sources feed this one converter/quiescence target. AVAudioEngine
7269
7360
  * and ScreenCaptureKit normally hand us planar float PCM; the converter also
@@ -7632,6 +7723,9 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7632
7723
  self.nativeViewExplicitTextKeys = [[NSMutableSet alloc] init];
7633
7724
  self.bridgeEnabledChildWebViewKeys = [[NSMutableSet alloc] init];
7634
7725
  self.appTimers = [[NSMutableDictionary alloc] init];
7726
+ self.notificationActionCommands = [[NSMutableDictionary alloc] init];
7727
+ self.notificationActionTokensByIdentifier = [[NSMutableDictionary alloc] init];
7728
+ self.statusItems = [[NSMutableDictionary alloc] init];
7635
7729
  self.allowedNavigationOrigins = @[ @"zero://app", @"zero://inline" ];
7636
7730
  self.allowedExternalURLs = @[];
7637
7731
  self.externalLinkAction = 0;
@@ -7713,6 +7807,12 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7713
7807
  if ((windowFlags & (1u << 1)) != 0) window.level = NSFloatingWindowLevel;
7714
7808
  if ((windowFlags & (1u << 2)) != 0) window.ignoresMouseEvents = YES;
7715
7809
  if ((windowFlags & (1u << 3)) != 0) [self.passiveShowWindows addObject:key];
7810
+ if ((windowFlags & (1u << 4)) != 0) {
7811
+ NSWindowCollectionBehavior behavior = window.collectionBehavior;
7812
+ behavior &= ~(NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorFullScreenAuxiliary);
7813
+ window.collectionBehavior = behavior | NSWindowCollectionBehaviorFullScreenNone;
7814
+ [window standardWindowButton:NSWindowZoomButton].enabled = NO;
7815
+ }
7716
7816
  [window setTitle:(title.length > 0 ? title : self.appName)];
7717
7817
  if (titlebarStyle == 1 || titlebarStyle == 2) {
7718
7818
  window.titlebarAppearsTransparent = YES;
@@ -7802,12 +7902,14 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7802
7902
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC), dispatch_get_main_queue(), ^{
7803
7903
  [weakSelf showDeferredWindowIfPending:windowId reason:"fallback-deadline"];
7804
7904
  });
7905
+ } else if (showPolicy == 2) {
7906
+ [self.policyHiddenWindows addObject:key];
7805
7907
  }
7806
7908
  if (makeMain) {
7807
7909
  self.window = window;
7808
7910
  self.delegate = delegate;
7809
7911
  self.windowLabel = label.length > 0 ? label : @"main";
7810
- } else if (showPolicy != 1) {
7912
+ } else if (showPolicy == 0) {
7811
7913
  [self orderWindowForImplicitShow:windowId];
7812
7914
  }
7813
7915
  return YES;
@@ -7824,7 +7926,7 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7824
7926
  if ([self.passiveShowWindows containsObject:@(windowId)]) {
7825
7927
  [window orderFront:nil];
7826
7928
  } else {
7827
- [NSApp activate];
7929
+ [NSApp activateIgnoringOtherApps:YES];
7828
7930
  [window makeKeyAndOrderFront:nil];
7829
7931
  }
7830
7932
  }
@@ -7864,6 +7966,8 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7864
7966
  }
7865
7967
 
7866
7968
  - (void)dealloc {
7969
+ NSUserNotificationCenter *notificationCenter = [NSUserNotificationCenter defaultUserNotificationCenter];
7970
+ if (notificationCenter.delegate == self) notificationCenter.delegate = nil;
7867
7971
  [self invalidateAppTimers];
7868
7972
  [self audioCaptureStopSource:0];
7869
7973
  [self audioCaptureStopSource:1];
@@ -7896,7 +8000,8 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7896
8000
  // An explicit focus overrides a pending present-before-show defer:
7897
8001
  // the runtime asked for the window NOW.
7898
8002
  [self.deferredShowWindows removeObjectForKey:@(windowId)];
7899
- [NSApp activate];
8003
+ [self.policyHiddenWindows removeObject:@(windowId)];
8004
+ [NSApp activateIgnoringOtherApps:YES];
7900
8005
  [window makeKeyAndOrderFront:nil];
7901
8006
  [self emitWindowFrameForWindowId:windowId open:YES];
7902
8007
  [self scheduleFrame];
@@ -7934,6 +8039,9 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7934
8039
  - (void)hideWindowWithId:(uint64_t)windowId {
7935
8040
  NSWindow *window = self.windows[@(windowId)];
7936
8041
  if (!window) return;
8042
+ // Hiding is an explicit policy decision and therefore supersedes a
8043
+ // pending first-present reveal and its fallback deadline.
8044
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7937
8045
  [self.policyHiddenWindows addObject:@(windowId)];
7938
8046
  [window orderOut:nil];
7939
8047
  [self emitWindowFrameForWindowId:windowId open:YES];
@@ -9158,7 +9266,7 @@ static NSString *NativeSdkAppKitBridgeScript(void) {
9158
9266
  "});"
9159
9267
  "var os=Object.freeze({"
9160
9268
  "openUrl:function(value){var options=typeof value==='string'?{url:value}:(value||{});return invoke('native-sdk.os.openUrl',{url:ensureString(options.url,'url')});},"
9161
- "showNotification:function(value){var options=typeof value==='string'?{title:value}:(value||{});var payload={title:ensureString(options.title,'title')};if(options.subtitle!=null){payload.subtitle=ensureString(options.subtitle,'subtitle');}if(options.body!=null){payload.body=ensureString(options.body,'body');}return invoke('native-sdk.os.showNotification',payload);},"
9269
+ "showNotification:function(value){var options=typeof value==='string'?{title:value}:(value||{});var payload={title:ensureString(options.title,'title')};if(options.id!=null){payload.id=ensureString(options.id,'id');}if(options.subtitle!=null){payload.subtitle=ensureString(options.subtitle,'subtitle');}if(options.body!=null){payload.body=ensureString(options.body,'body');}if(options.actionLabel!=null){payload.actionLabel=ensureString(options.actionLabel,'actionLabel');}if(options.actionCommand!=null){payload.actionCommand=ensureString(options.actionCommand,'actionCommand');}return invoke('native-sdk.os.showNotification',payload);},"
9162
9270
  "revealPath:function(value){var options=typeof value==='string'?{path:value}:(value||{});return invoke('native-sdk.os.revealPath',{path:ensureString(options.path,'path')});},"
9163
9271
  "addRecentDocument:function(value){var options=typeof value==='string'?{path:value}:(value||{});return invoke('native-sdk.os.addRecentDocument',{path:ensureString(options.path,'path')});},"
9164
9272
  "clearRecentDocuments:function(){return invoke('native-sdk.os.clearRecentDocuments',{});}"
@@ -9523,6 +9631,12 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9523
9631
  }];
9524
9632
  }
9525
9633
 
9634
+ - (void)menuWillOpen:(NSMenu *)menu {
9635
+ NativeSdkStatusItemEntry *entry = [self statusEntryForMenu:menu];
9636
+ if (!entry) return;
9637
+ [self emitStatusCommand:entry.openCommand statusItemId:entry.identifier];
9638
+ }
9639
+
9526
9640
  - (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 {
9527
9641
  if (menuCount == 0) {
9528
9642
  [self buildMenuBar];
@@ -9571,7 +9685,7 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9571
9685
  // Present-before-show: a deferred startup window stays ordered out
9572
9686
  // here and appears when its first canvas present lands (or the
9573
9687
  // create-time fallback deadline fires).
9574
- if (!self.deferredShowWindows[@1]) {
9688
+ if (!self.deferredShowWindows[@1] && ![self.policyHiddenWindows containsObject:@1]) {
9575
9689
  [self orderWindowForImplicitShow:1];
9576
9690
  }
9577
9691
  if (!self.shortcutEventMonitor) {
@@ -9776,6 +9890,38 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9776
9890
  [self emitEvent:(native_sdk_appkit_event_t){ .kind = NATIVE_SDK_APPKIT_EVENT_APP_DEACTIVATED }];
9777
9891
  }
9778
9892
 
9893
+ - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
9894
+ (void)center;
9895
+ (void)notification;
9896
+ return YES;
9897
+ }
9898
+
9899
+ - (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
9900
+ NSInteger activation = notification.activationType;
9901
+ if (activation != NSUserNotificationActivationTypeActionButtonClicked) return;
9902
+ NSString *token = [notification.userInfo[@"native-sdk-action-token"] isKindOfClass:[NSString class]]
9903
+ ? notification.userInfo[@"native-sdk-action-token"] : @"";
9904
+ NSString *command = token.length > 0 ? self.notificationActionCommands[token] : @"";
9905
+ if (command.length == 0) {
9906
+ [center removeDeliveredNotification:notification];
9907
+ return;
9908
+ }
9909
+ NSString *identifier = notification.identifier ?: @"";
9910
+ if (identifier.length > 0 &&
9911
+ [self.notificationActionTokensByIdentifier[identifier] isEqualToString:token]) {
9912
+ [self.notificationActionTokensByIdentifier removeObjectForKey:identifier];
9913
+ }
9914
+ [self.notificationActionCommands removeObjectForKey:token];
9915
+ const char *commandBytes = command.UTF8String ?: "";
9916
+ [self emitEvent:(native_sdk_appkit_event_t){
9917
+ .kind = NATIVE_SDK_APPKIT_EVENT_NOTIFICATION_COMMAND,
9918
+ .window_id = [self activeCommandWindowId],
9919
+ .command_name = commandBytes,
9920
+ .command_name_len = [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
9921
+ }];
9922
+ [center removeDeliveredNotification:notification];
9923
+ }
9924
+
9779
9925
  - (void)startAppearanceObservers {
9780
9926
  if (self.observesAppearanceChanges) {
9781
9927
  return;
@@ -11827,8 +11973,44 @@ static void NativeSdkVideoFittedSize(double naturalWidth, double naturalHeight,
11827
11973
 
11828
11974
  - (void)trayMenuItemClicked:(NSMenuItem *)menuItem {
11829
11975
  if (self.trayCallback) {
11830
- self.trayCallback(self.trayContext, (uint32_t)menuItem.tag);
11976
+ uint64_t packed = (uint64_t)(NSUInteger)menuItem.tag;
11977
+ self.trayCallback(self.trayContext, (uint32_t)(packed >> 32), (uint32_t)packed);
11978
+ }
11979
+ }
11980
+
11981
+ - (NativeSdkStatusItemEntry *)statusEntryForId:(uint32_t)identifier {
11982
+ return self.statusItems[@(identifier)];
11983
+ }
11984
+
11985
+ - (NativeSdkStatusItemEntry *)statusEntryForMenu:(NSMenu *)menu {
11986
+ for (NativeSdkStatusItemEntry *entry in self.statusItems.allValues) {
11987
+ if (entry.menu == menu) return entry;
11988
+ }
11989
+ return nil;
11990
+ }
11991
+
11992
+ - (void)emitStatusCommand:(NSString *)command statusItemId:(uint32_t)statusItemId {
11993
+ if (command.length == 0) return;
11994
+ const char *bytes = command.UTF8String;
11995
+ [self emitEvent:(native_sdk_appkit_event_t){
11996
+ .kind = NATIVE_SDK_APPKIT_EVENT_TRAY_COMMAND,
11997
+ .window_id = [self activeCommandWindowId],
11998
+ .status_item_id = statusItemId,
11999
+ .command_name = bytes,
12000
+ .command_name_len = [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
12001
+ }];
12002
+ }
12003
+
12004
+ - (void)statusItemActivated:(id)sender {
12005
+ NSStatusBarButton *button = [sender isKindOfClass:[NSStatusBarButton class]] ? sender : nil;
12006
+ NativeSdkStatusItemEntry *entry = button ? [self statusEntryForId:(uint32_t)button.tag] : nil;
12007
+ if (!entry) return;
12008
+ if ((NSEvent.modifierFlags & NSEventModifierFlagOption) != 0 && entry.alternateActivationCommand.length > 0) {
12009
+ [self emitStatusCommand:entry.alternateActivationCommand statusItemId:entry.identifier];
12010
+ return;
11831
12011
  }
12012
+ [self emitStatusCommand:entry.activationCommand statusItemId:entry.identifier];
12013
+ if (entry.menu) [entry.item popUpStatusItemMenu:entry.menu];
11832
12014
  }
11833
12015
 
11834
12016
  @end
@@ -12396,6 +12578,13 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
12396
12578
  return 1;
12397
12579
  }
12398
12580
 
12581
+ int native_sdk_appkit_hide_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
12582
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12583
+ if (!object.windows[@(window_id)]) return 0;
12584
+ [object hideWindowWithId:window_id];
12585
+ return 1;
12586
+ }
12587
+
12399
12588
  int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
12400
12589
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12401
12590
  if (!object.windows[@(window_id)]) return 0;
@@ -12403,6 +12592,23 @@ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t windo
12403
12592
  return 1;
12404
12593
  }
12405
12594
 
12595
+ int native_sdk_appkit_set_dock_presence(native_sdk_appkit_host_t *host, int visible) {
12596
+ (void)host;
12597
+ NSApplicationActivationPolicy policy = visible ? NSApplicationActivationPolicyRegular : NSApplicationActivationPolicyAccessory;
12598
+ BOOL changed = [NSApp setActivationPolicy:policy];
12599
+ return changed || NSApp.activationPolicy == policy ? 1 : 0;
12600
+ }
12601
+
12602
+ int native_sdk_appkit_launch_at_login_status(native_sdk_appkit_host_t *host) {
12603
+ (void)host;
12604
+ return NativeSdkLaunchAtLoginStatus();
12605
+ }
12606
+
12607
+ int native_sdk_appkit_set_launch_at_login(native_sdk_appkit_host_t *host, int enabled) {
12608
+ (void)host;
12609
+ return NativeSdkSetLaunchAtLogin(enabled != 0);
12610
+ }
12611
+
12406
12612
  int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
12407
12613
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12408
12614
  if (!object.windows[@(window_id)]) return 0;
@@ -12623,17 +12829,42 @@ int native_sdk_appkit_clipboard_write_data(native_sdk_appkit_host_t *host, const
12623
12829
  return [pasteboard setData:data forType:type] ? 1 : 0;
12624
12830
  }
12625
12831
 
12626
- int native_sdk_appkit_show_notification(native_sdk_appkit_host_t *host, const char *title, size_t title_len, const char *subtitle, size_t subtitle_len, const char *body, size_t body_len) {
12627
- (void)host;
12832
+ int native_sdk_appkit_show_notification(native_sdk_appkit_host_t *host, const char *title, size_t title_len, const char *subtitle, size_t subtitle_len, const char *body, size_t body_len, const char *notification_id, size_t notification_id_len, const char *action_label, size_t action_label_len, const char *action_command, size_t action_command_len) {
12833
+ if (!host || ((action_label_len == 0) != (action_command_len == 0))) return 0;
12834
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12628
12835
  NSString *titleString = title ? [[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] : @"";
12629
12836
  if (titleString.length == 0) return 0;
12630
12837
  NSString *subtitleString = subtitle ? [[NSString alloc] initWithBytes:subtitle length:subtitle_len encoding:NSUTF8StringEncoding] : @"";
12631
12838
  NSString *bodyString = body ? [[NSString alloc] initWithBytes:body length:body_len encoding:NSUTF8StringEncoding] : @"";
12839
+ NSString *identifier = notification_id ? [[NSString alloc] initWithBytes:notification_id length:notification_id_len encoding:NSUTF8StringEncoding] : @"";
12840
+ NSString *actionLabel = action_label ? [[NSString alloc] initWithBytes:action_label length:action_label_len encoding:NSUTF8StringEncoding] : @"";
12841
+ NSString *actionCommand = action_command ? [[NSString alloc] initWithBytes:action_command length:action_command_len encoding:NSUTF8StringEncoding] : @"";
12842
+ if (identifier.length > 0) {
12843
+ NSString *oldToken = object.notificationActionTokensByIdentifier[identifier];
12844
+ if (oldToken.length > 0) [object.notificationActionCommands removeObjectForKey:oldToken];
12845
+ [object.notificationActionTokensByIdentifier removeObjectForKey:identifier];
12846
+ }
12632
12847
  NSUserNotification *notification = [[NSUserNotification alloc] init];
12633
12848
  notification.title = titleString;
12634
12849
  if (subtitleString.length > 0) notification.subtitle = subtitleString;
12635
12850
  if (bodyString.length > 0) notification.informativeText = bodyString;
12636
- [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
12851
+ if (identifier.length > 0) notification.identifier = identifier;
12852
+ if (actionCommand.length > 0) {
12853
+ NSString *actionToken = [NSUUID UUID].UUIDString;
12854
+ object.notificationActionCommands[actionToken] = actionCommand;
12855
+ if (identifier.length > 0) object.notificationActionTokensByIdentifier[identifier] = actionToken;
12856
+ notification.hasActionButton = YES;
12857
+ notification.actionButtonTitle = actionLabel;
12858
+ notification.userInfo = @{ @"native-sdk-action-token": actionToken };
12859
+ }
12860
+ NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
12861
+ center.delegate = object;
12862
+ if (identifier.length > 0) {
12863
+ for (NSUserNotification *delivered in center.deliveredNotifications) {
12864
+ if ([delivered.identifier isEqualToString:identifier]) [center removeDeliveredNotification:delivered];
12865
+ }
12866
+ }
12867
+ [center deliverNotification:notification];
12637
12868
  return 1;
12638
12869
  }
12639
12870
 
@@ -12677,7 +12908,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12677
12908
  @autoreleasepool {
12678
12909
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12679
12910
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12680
- if (serviceString.length == 0 || accountString.length == 0 || !secret || secret_len == 0) return 0;
12911
+ if (serviceString.length == 0 || accountString.length == 0 || (!secret && secret_len > 0)) return 0;
12681
12912
  NSData *secretData = [NSData dataWithBytes:secret length:secret_len];
12682
12913
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12683
12914
  NSDictionary *update = @{ (__bridge id)kSecValueData: secretData };
@@ -12686,7 +12917,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12686
12917
  query[(__bridge id)kSecValueData] = secretData;
12687
12918
  status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
12688
12919
  }
12689
- return status == errSecSuccess ? 1 : 0;
12920
+ return NativeSdkCredentialStatus(status, -1);
12690
12921
  }
12691
12922
  }
12692
12923
 
@@ -12695,13 +12926,16 @@ size_t native_sdk_appkit_get_credential(native_sdk_appkit_host_t *host, const ch
12695
12926
  @autoreleasepool {
12696
12927
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12697
12928
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12698
- if (serviceString.length == 0 || accountString.length == 0 || !buffer) return 0;
12929
+ if (serviceString.length == 0 || accountString.length == 0 || (!buffer && buffer_len > 0)) return SIZE_MAX - 1;
12699
12930
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12700
12931
  query[(__bridge id)kSecReturnData] = @YES;
12701
12932
  query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
12702
12933
  CFTypeRef result = NULL;
12703
12934
  OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
12704
- if (status != errSecSuccess || !result) return 0;
12935
+ if (status == errSecItemNotFound) return SIZE_MAX;
12936
+ if (status == errSecInteractionNotAllowed || status == errSecNotAvailable) return SIZE_MAX - 2;
12937
+ if (status == errSecAuthFailed || status == errSecUserCanceled || status == errSecMissingEntitlement) return SIZE_MAX - 3;
12938
+ if (status != errSecSuccess || !result) return SIZE_MAX - 1;
12705
12939
  NSData *data = CFBridgingRelease(result);
12706
12940
  if (data.length > buffer_len) return data.length;
12707
12941
  memcpy(buffer, data.bytes, data.length);
@@ -12717,7 +12951,26 @@ int native_sdk_appkit_delete_credential(native_sdk_appkit_host_t *host, const ch
12717
12951
  if (serviceString.length == 0 || accountString.length == 0) return 0;
12718
12952
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12719
12953
  OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
12720
- return status == errSecSuccess ? 1 : 0;
12954
+ return NativeSdkCredentialStatus(status, 0);
12955
+ }
12956
+ }
12957
+
12958
+ size_t native_sdk_appkit_format_local_time(native_sdk_appkit_host_t *host, int64_t timestamp_ms, int style, char *buffer, size_t buffer_len) {
12959
+ (void)host;
12960
+ if (!buffer || buffer_len == 0 || style < 0 || style > 2) return 0;
12961
+ @autoreleasepool {
12962
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)timestamp_ms / 1000.0];
12963
+ if (!date) return 0;
12964
+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
12965
+ formatter.locale = [NSLocale autoupdatingCurrentLocale];
12966
+ formatter.timeZone = [NSTimeZone localTimeZone];
12967
+ formatter.dateStyle = (style == 0 || style == 2) ? NSDateFormatterShortStyle : NSDateFormatterNoStyle;
12968
+ formatter.timeStyle = (style == 1 || style == 2) ? NSDateFormatterMediumStyle : NSDateFormatterNoStyle;
12969
+ NSString *text = [formatter stringFromDate:date];
12970
+ NSData *utf8 = [text dataUsingEncoding:NSUTF8StringEncoding];
12971
+ if (!utf8 || utf8.length == 0 || utf8.length > buffer_len) return 0;
12972
+ memcpy(buffer, utf8.bytes, utf8.length);
12973
+ return utf8.length;
12721
12974
  }
12722
12975
  }
12723
12976
 
@@ -12855,43 +13108,337 @@ int native_sdk_appkit_show_message_dialog(native_sdk_appkit_host_t *host, const
12855
13108
  }
12856
13109
  }
12857
13110
 
12858
- void native_sdk_appkit_create_tray(native_sdk_appkit_host_t *host, const char *icon_path, size_t icon_path_len, const char *title, size_t title_len, const char *tooltip, size_t tooltip_len) {
13111
+ static NSImage *NativeSdkTrayImageWithOpacity(NSImage *source, double opacity) {
13112
+ if (!source) return nil;
13113
+ const CGFloat fraction = MAX(0.0, MIN(1.0, opacity));
13114
+ if (fraction >= 1.0) return source;
13115
+ NSImage *image = [[NSImage alloc] initWithSize:source.size];
13116
+ [image lockFocus];
13117
+ [source drawInRect:NSMakeRect(0, 0, source.size.width, source.size.height)
13118
+ fromRect:NSZeroRect
13119
+ operation:NSCompositingOperationSourceOver
13120
+ fraction:fraction
13121
+ respectFlipped:YES
13122
+ hints:nil];
13123
+ [image unlockFocus];
13124
+ image.template = YES;
13125
+ return image;
13126
+ }
13127
+
13128
+ static void NativeSdkApplyTrayPresentation(NativeSdkAppKitHost *object, NativeSdkStatusItemEntry *entry, NSString *requestedTitle, double width, int tone, double iconOpacity, BOOL monospaced) {
13129
+ if (!entry.item) return;
13130
+ entry.presentationTitle = requestedTitle ?: @"";
13131
+ entry.presentationWidth = width;
13132
+ entry.presentationTone = tone;
13133
+ entry.presentationIconOpacity = iconOpacity;
13134
+ entry.presentationMonospaced = monospaced;
13135
+ NSString *title = requestedTitle ?: @"";
13136
+ if (!entry.baseImage && title.length == 0) {
13137
+ title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
13138
+ }
13139
+ NSFont *font = monospaced
13140
+ ? ([NSFont fontWithName:@"Geist Mono" size:11] ?: [NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightRegular])
13141
+ : [NSFont systemFontOfSize:11];
13142
+ NSStatusBarButton *button = entry.item.button;
13143
+ if (tone == 0) {
13144
+ button.title = title;
13145
+ button.font = font;
13146
+ button.contentTintColor = nil;
13147
+ } else {
13148
+ NSColor *color = tone == 1 ? NSColor.systemOrangeColor : NSColor.systemRedColor;
13149
+ button.attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:@{
13150
+ NSForegroundColorAttributeName: color,
13151
+ NSFontAttributeName: font,
13152
+ }];
13153
+ button.contentTintColor = color;
13154
+ }
13155
+ button.image = NativeSdkTrayImageWithOpacity(entry.baseImage, iconOpacity);
13156
+ entry.item.length = width > 0 ? width : (requestedTitle.length > 0 ? NSVariableStatusItemLength : NSSquareStatusItemLength);
13157
+ }
13158
+
13159
+ static void NativeSdkApplyTrayShell(NativeSdkAppKitHost *object, NativeSdkStatusItemEntry *entry, const char *icon_path, size_t icon_path_len, const char *tooltip, size_t tooltip_len, int visible, const char *activation_command, size_t activation_command_len, const char *alternate_activation_command, size_t alternate_activation_command_len, const char *open_command, size_t open_command_len) {
13160
+ entry.baseImage = nil;
13161
+ if (icon_path && icon_path_len > 0) {
13162
+ NSString *path = [[NSString alloc] initWithBytes:icon_path length:icon_path_len encoding:NSUTF8StringEncoding];
13163
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:NativeSdkResolvedAssetFilePath(path)];
13164
+ if (image) {
13165
+ image.template = YES;
13166
+ image.size = NSMakeSize(18, 18);
13167
+ entry.baseImage = image;
13168
+ }
13169
+ }
13170
+ entry.item.button.toolTip = tooltip && tooltip_len > 0 ? ([[NSString alloc] initWithBytes:tooltip length:tooltip_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13171
+ entry.activationCommand = activation_command ? ([[NSString alloc] initWithBytes:activation_command length:activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13172
+ entry.alternateActivationCommand = alternate_activation_command ? ([[NSString alloc] initWithBytes:alternate_activation_command length:alternate_activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13173
+ entry.openCommand = open_command ? ([[NSString alloc] initWithBytes:open_command length:open_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13174
+ NSStatusBarButton *button = entry.item.button;
13175
+ button.tag = (NSInteger)entry.identifier;
13176
+ button.target = object;
13177
+ button.action = (entry.activationCommand.length > 0 || entry.alternateActivationCommand.length > 0) ? @selector(statusItemActivated:) : NULL;
13178
+ if (button.action) [button sendActionOn:NSEventMaskLeftMouseUp];
13179
+ entry.item.visible = visible != 0;
13180
+ }
13181
+
13182
+ void native_sdk_appkit_create_tray(native_sdk_appkit_host_t *host, uint32_t status_item_id, const char *icon_path, size_t icon_path_len, const char *title, size_t title_len, const char *tooltip, size_t tooltip_len, int visible, double width, int tone, double icon_opacity, int monospaced, const char *activation_command, size_t activation_command_len, const char *alternate_activation_command, size_t alternate_activation_command_len, const char *open_command, size_t open_command_len) {
12859
13183
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12860
13184
  @autoreleasepool {
12861
- if (object.statusItem) {
12862
- [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
13185
+ NSNumber *key = @(status_item_id);
13186
+ NativeSdkStatusItemEntry *entry = object.statusItems[key];
13187
+ if (entry) {
13188
+ [[NSStatusBar systemStatusBar] removeStatusItem:entry.item];
13189
+ } else {
13190
+ entry = [[NativeSdkStatusItemEntry alloc] init];
13191
+ entry.identifier = status_item_id;
13192
+ object.statusItems[key] = entry;
12863
13193
  }
12864
- // A titled menu-bar extra needs variable width; icon-only status
12865
- // items keep the classic square well.
13194
+ entry.menu = nil;
12866
13195
  BOOL hasTitle = title != NULL && title_len > 0;
12867
- object.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:hasTitle ? NSVariableStatusItemLength : NSSquareStatusItemLength];
12868
-
12869
- if (icon_path && icon_path_len > 0) {
12870
- NSString *path = [[NSString alloc] initWithBytes:icon_path length:icon_path_len encoding:NSUTF8StringEncoding];
12871
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
12872
- if (image) {
12873
- image.template = YES;
12874
- image.size = NSMakeSize(18, 18);
12875
- object.statusItem.button.image = image;
12876
- }
12877
- }
12878
- if (hasTitle) {
12879
- object.statusItem.button.title = [[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"";
12880
- }
12881
- if (!object.statusItem.button.image && object.statusItem.button.title.length == 0) {
12882
- object.statusItem.button.title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
12883
- }
12884
- if (tooltip && tooltip_len > 0) {
12885
- object.statusItem.button.toolTip = [[NSString alloc] initWithBytes:tooltip length:tooltip_len encoding:NSUTF8StringEncoding];
12886
- }
13196
+ entry.item = [[NSStatusBar systemStatusBar] statusItemWithLength:hasTitle ? NSVariableStatusItemLength : NSSquareStatusItemLength];
13197
+ NSString *titleString = hasTitle ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13198
+ NativeSdkApplyTrayShell(object, entry, icon_path, icon_path_len, tooltip, tooltip_len, visible, activation_command, activation_command_len, alternate_activation_command, alternate_activation_command_len, open_command, open_command_len);
13199
+ NativeSdkApplyTrayPresentation(object, entry, titleString, width, tone, icon_opacity, monospaced != 0);
13200
+ }
13201
+ }
13202
+
13203
+ void native_sdk_appkit_update_tray_shell(native_sdk_appkit_host_t *host, uint32_t status_item_id, const char *icon_path, size_t icon_path_len, const char *tooltip, size_t tooltip_len, int visible, const char *activation_command, size_t activation_command_len, const char *alternate_activation_command, size_t alternate_activation_command_len, const char *open_command, size_t open_command_len) {
13204
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
13205
+ @autoreleasepool {
13206
+ NativeSdkStatusItemEntry *entry = [object statusEntryForId:status_item_id];
13207
+ if (!entry) return;
13208
+ NativeSdkApplyTrayShell(object, entry, icon_path, icon_path_len, tooltip, tooltip_len, visible, activation_command, activation_command_len, alternate_activation_command, alternate_activation_command_len, open_command, open_command_len);
13209
+ NativeSdkApplyTrayPresentation(object, entry, entry.presentationTitle, entry.presentationWidth, entry.presentationTone, entry.presentationIconOpacity, entry.presentationMonospaced);
13210
+ if (entry.activationCommand.length == 0 && entry.alternateActivationCommand.length == 0) entry.item.menu = entry.menu;
13211
+ else entry.item.menu = nil;
13212
+ }
13213
+ }
13214
+
13215
+ enum {
13216
+ NativeSdkTrayRoleCommand = 0,
13217
+ NativeSdkTrayRoleInfo = 1,
13218
+ NativeSdkTrayRoleHeader = 2,
13219
+ NativeSdkTrayRoleHero = 3,
13220
+ NativeSdkTrayRoleAgent = 4,
13221
+ NativeSdkTrayRoleContext = 5,
13222
+ };
13223
+
13224
+ static NSView *NativeSdkTrayHeroView(NSString *headline, NSString *quota) {
13225
+ NSArray<NSString *> *parts = [headline componentsSeparatedByString:@"\n"];
13226
+ NSString *value = parts.count > 0 ? parts[0] : @"";
13227
+ NSString *account = parts.count > 1 ? parts[1] : @"";
13228
+ NSString *stale = parts.count > 2 ? parts[2] : @"";
13229
+ NSString *reset = parts.count > 3 ? parts[3] : @"";
13230
+ CGFloat height = quota.length > 0 ? 56 : 32;
13231
+ if (stale.length > 0) height += 14;
13232
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, height)];
13233
+ NSTextField *amount = [NSTextField labelWithString:value ?: @""];
13234
+ amount.font = [NSFont fontWithName:@"Geist Mono" size:20] ?: [NSFont monospacedDigitSystemFontOfSize:20 weight:NSFontWeightMedium];
13235
+ amount.translatesAutoresizingMaskIntoConstraints = NO;
13236
+ NSTextField *caption = [NSTextField labelWithString:(reset.length > 0 ? [NSString stringWithFormat:@"today · %@", reset] : @"today")];
13237
+ caption.font = [NSFont systemFontOfSize:11];
13238
+ caption.textColor = NSColor.secondaryLabelColor;
13239
+ caption.translatesAutoresizingMaskIntoConstraints = NO;
13240
+ [view addSubview:amount];
13241
+ [view addSubview:caption];
13242
+ [NSLayoutConstraint activateConstraints:@[
13243
+ [amount.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13244
+ [amount.topAnchor constraintEqualToAnchor:view.topAnchor constant:3],
13245
+ [caption.leadingAnchor constraintEqualToAnchor:amount.trailingAnchor constant:6],
13246
+ [caption.firstBaselineAnchor constraintEqualToAnchor:amount.firstBaselineAnchor],
13247
+ ]];
13248
+ if (account.length > 0) {
13249
+ NSTextField *accountLabel = [NSTextField labelWithString:account];
13250
+ accountLabel.font = [NSFont systemFontOfSize:10];
13251
+ accountLabel.textColor = NSColor.secondaryLabelColor;
13252
+ accountLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13253
+ accountLabel.translatesAutoresizingMaskIntoConstraints = NO;
13254
+ [view addSubview:accountLabel];
13255
+ [NSLayoutConstraint activateConstraints:@[
13256
+ [accountLabel.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13257
+ [accountLabel.firstBaselineAnchor constraintEqualToAnchor:caption.firstBaselineAnchor],
13258
+ [accountLabel.leadingAnchor constraintGreaterThanOrEqualToAnchor:caption.trailingAnchor constant:12],
13259
+ ]];
13260
+ }
13261
+ if (quota.length > 0) {
13262
+ NSProgressIndicator *progress = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect];
13263
+ progress.style = NSProgressIndicatorStyleBar;
13264
+ progress.controlSize = NSControlSizeMini;
13265
+ progress.indeterminate = NO;
13266
+ progress.minValue = 0;
13267
+ progress.maxValue = 100;
13268
+ NSScanner *scanner = [NSScanner scannerWithString:quota];
13269
+ double percent = 0;
13270
+ [scanner scanDouble:&percent];
13271
+ progress.doubleValue = MIN(MAX(percent, 0), 100);
13272
+ progress.translatesAutoresizingMaskIntoConstraints = NO;
13273
+ NSTextField *quotaLabel = [NSTextField labelWithString:quota];
13274
+ quotaLabel.font = [NSFont systemFontOfSize:11];
13275
+ quotaLabel.textColor = NSColor.secondaryLabelColor;
13276
+ quotaLabel.translatesAutoresizingMaskIntoConstraints = NO;
13277
+ [view addSubview:progress];
13278
+ [view addSubview:quotaLabel];
13279
+ [NSLayoutConstraint activateConstraints:@[
13280
+ [progress.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13281
+ [progress.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13282
+ [progress.topAnchor constraintEqualToAnchor:amount.bottomAnchor constant:4],
13283
+ [progress.heightAnchor constraintEqualToConstant:5],
13284
+ [quotaLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13285
+ [quotaLabel.topAnchor constraintEqualToAnchor:progress.bottomAnchor constant:2],
13286
+ ]];
13287
+ }
13288
+ if (stale.length > 0) {
13289
+ NSTextField *staleLabel = [NSTextField labelWithString:stale];
13290
+ staleLabel.font = [NSFont systemFontOfSize:10];
13291
+ staleLabel.textColor = NSColor.tertiaryLabelColor;
13292
+ staleLabel.translatesAutoresizingMaskIntoConstraints = NO;
13293
+ [view addSubview:staleLabel];
13294
+ [NSLayoutConstraint activateConstraints:@[
13295
+ [staleLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13296
+ [staleLabel.bottomAnchor constraintEqualToAnchor:view.bottomAnchor constant:-6],
13297
+ ]];
13298
+ }
13299
+ view.accessibilityLabel = quota.length > 0 ? [NSString stringWithFormat:@"%@ today, %@", value ?: @"", quota] : [NSString stringWithFormat:@"%@ today", value ?: @""];
13300
+ view.accessibilityRole = NSAccessibilityGroupRole;
13301
+ return view;
13302
+ }
13303
+
13304
+ static NSView *NativeSdkTrayAgentsView(NativeSdkAppKitHost *object, uint32_t statusItemId, const uint32_t *itemIds, NSArray<NSString *> *labels, NSArray<NSString *> *states, NSArray<NSNumber *> *enabled, NSArray<NSString *> *keys, NSArray<NSNumber *> *modifiers) {
13305
+ NSStackView *row = [[NSStackView alloc] initWithFrame:NSMakeRect(0, 0, 320, 32)];
13306
+ row.orientation = NSUserInterfaceLayoutOrientationHorizontal;
13307
+ row.alignment = NSLayoutAttributeCenterY;
13308
+ row.spacing = 8;
13309
+ row.edgeInsets = NSEdgeInsetsMake(5, 14, 5, 14);
13310
+ NSString *appearance = [NSApp.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
13311
+ BOOL dark = [appearance isEqualToString:NSAppearanceNameDarkAqua];
13312
+ NSColor *warningColor = dark ? NSColor.systemOrangeColor : [NSColor colorWithSRGBRed:0.54 green:0.23 blue:0.00 alpha:1.0];
13313
+ NSColor *successColor = dark ? NSColor.systemGreenColor : [NSColor colorWithSRGBRed:0.06 green:0.42 blue:0.20 alpha:1.0];
13314
+ for (NSUInteger index = 0; index < labels.count; index++) {
13315
+ NSString *state = states[index];
13316
+ // `detail` is presentation text as well as the semantic state. The
13317
+ // documented examples append a glyph ("configured ✓", "warning ⚠"),
13318
+ // so classify the leading token instead of requiring the whole label
13319
+ // to be the bare state name.
13320
+ BOOL configured = [state isEqualToString:@"configured"] || [state hasPrefix:@"configured "];
13321
+ BOOL warning = [state isEqualToString:@"warning"] || [state hasPrefix:@"warning "];
13322
+ NSString *title = [NSString stringWithFormat:@"%@ %@", configured ? @"✓" : warning ? @"⚠" : @"○", labels[index]];
13323
+ NSView *control = [[NSView alloc] initWithFrame:NSZeroRect];
13324
+ NSTextField *label = [NSTextField labelWithString:title];
13325
+ label.font = [NSFont systemFontOfSize:11];
13326
+ label.textColor = configured ? successColor : warning ? warningColor : NSColor.secondaryLabelColor;
13327
+ label.translatesAutoresizingMaskIntoConstraints = NO;
13328
+ label.accessibilityElement = NO;
13329
+ NSButton *button = [NSButton buttonWithTitle:@"" target:object action:@selector(trayMenuItemClicked:)];
13330
+ button.tag = (NSInteger)(((uint64_t)statusItemId << 32) | itemIds[index]);
13331
+ button.bordered = NO;
13332
+ button.transparent = YES;
13333
+ button.enabled = enabled[index].boolValue;
13334
+ NSString *key = keys[index];
13335
+ if (key.length > 0) {
13336
+ button.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13337
+ button.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[index].unsignedIntValue);
13338
+ }
13339
+ button.translatesAutoresizingMaskIntoConstraints = NO;
13340
+ button.accessibilityLabel = title;
13341
+ [control addSubview:label];
13342
+ [control addSubview:button];
13343
+ [NSLayoutConstraint activateConstraints:@[
13344
+ [label.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13345
+ [label.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13346
+ [label.centerYAnchor constraintEqualToAnchor:control.centerYAnchor],
13347
+ [button.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13348
+ [button.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13349
+ [button.topAnchor constraintEqualToAnchor:control.topAnchor],
13350
+ [button.bottomAnchor constraintEqualToAnchor:control.bottomAnchor],
13351
+ ]];
13352
+ [row addArrangedSubview:control];
13353
+ }
13354
+ [row.heightAnchor constraintEqualToConstant:32].active = YES;
13355
+ [row.widthAnchor constraintEqualToConstant:320].active = YES;
13356
+ return row;
13357
+ }
13358
+
13359
+ static NSView *NativeSdkTrayContextView(NSString *primary, NSString *secondary) {
13360
+ NSArray<NSString *> *parts = [secondary componentsSeparatedByString:@"\n"];
13361
+ NSString *quota = parts.count > 0 ? parts[0] : @"";
13362
+ NSString *windows = parts.count > 1 ? parts[1] : @"";
13363
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, 58)];
13364
+ NSTextField *primaryLabel = [NSTextField labelWithString:primary ?: @""];
13365
+ primaryLabel.font = [NSFont systemFontOfSize:11 weight:NSFontWeightMedium];
13366
+ primaryLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13367
+ primaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13368
+ NSTextField *secondaryLabel = [NSTextField labelWithString:quota ?: @""];
13369
+ secondaryLabel.font = [NSFont systemFontOfSize:10];
13370
+ secondaryLabel.textColor = NSColor.secondaryLabelColor;
13371
+ secondaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13372
+ NSTextField *windowsLabel = [NSTextField labelWithString:windows ?: @""];
13373
+ windowsLabel.font = [NSFont systemFontOfSize:10];
13374
+ windowsLabel.textColor = NSColor.secondaryLabelColor;
13375
+ windowsLabel.translatesAutoresizingMaskIntoConstraints = NO;
13376
+ [view addSubview:primaryLabel];
13377
+ [view addSubview:secondaryLabel];
13378
+ [view addSubview:windowsLabel];
13379
+ [NSLayoutConstraint activateConstraints:@[
13380
+ [primaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13381
+ [primaryLabel.trailingAnchor constraintLessThanOrEqualToAnchor:view.trailingAnchor constant:-14],
13382
+ [primaryLabel.topAnchor constraintEqualToAnchor:view.topAnchor constant:6],
13383
+ [secondaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13384
+ [secondaryLabel.topAnchor constraintEqualToAnchor:primaryLabel.bottomAnchor constant:2],
13385
+ [windowsLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13386
+ [windowsLabel.topAnchor constraintEqualToAnchor:secondaryLabel.bottomAnchor constant:2],
13387
+ ]];
13388
+ view.accessibilityLabel = secondary.length > 0 ? [NSString stringWithFormat:@"%@, %@", primary ?: @"", [secondary stringByReplacingOccurrencesOfString:@"\n" withString:@", "]] : primary ?: @"";
13389
+ view.accessibilityRole = NSAccessibilityGroupRole;
13390
+ return view;
13391
+ }
13392
+
13393
+ static NSView *NativeSdkTrayReadoutView(NSString *label, NSString *value, BOOL isHeader) {
13394
+ NSFont *bodyFont = [NSFont menuFontOfSize:0];
13395
+ NSTextField *labelField = [NSTextField labelWithString:label ?: @""];
13396
+ labelField.font = isHeader ? [NSFont systemFontOfSize:bodyFont.pointSize - 2 weight:NSFontWeightSemibold] : bodyFont;
13397
+ labelField.textColor = isHeader ? NSColor.secondaryLabelColor : NSColor.labelColor;
13398
+ labelField.translatesAutoresizingMaskIntoConstraints = NO;
13399
+ NSView *row = [[NSView alloc] initWithFrame:NSZeroRect];
13400
+ row.translatesAutoresizingMaskIntoConstraints = NO;
13401
+ [row addSubview:labelField];
13402
+ NSMutableArray<NSLayoutConstraint *> *constraints = [NSMutableArray arrayWithArray:@[
13403
+ [labelField.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
13404
+ [labelField.topAnchor constraintEqualToAnchor:row.topAnchor constant:3],
13405
+ [labelField.bottomAnchor constraintEqualToAnchor:row.bottomAnchor constant:-3],
13406
+ ]];
13407
+ if (value.length > 0) {
13408
+ NSTextField *valueField = [NSTextField labelWithString:value];
13409
+ valueField.font = [NSFont monospacedDigitSystemFontOfSize:bodyFont.pointSize weight:NSFontWeightRegular];
13410
+ valueField.textColor = NSColor.secondaryLabelColor;
13411
+ valueField.translatesAutoresizingMaskIntoConstraints = NO;
13412
+ [row addSubview:valueField];
13413
+ [constraints addObjectsFromArray:@[
13414
+ [valueField.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14],
13415
+ [valueField.firstBaselineAnchor constraintEqualToAnchor:labelField.firstBaselineAnchor],
13416
+ [valueField.leadingAnchor constraintGreaterThanOrEqualToAnchor:labelField.trailingAnchor constant:28],
13417
+ ]];
13418
+ row.accessibilityLabel = [NSString stringWithFormat:@"%@, %@", label ?: @"", value];
13419
+ } else {
13420
+ [constraints addObject:[labelField.trailingAnchor constraintLessThanOrEqualToAnchor:row.trailingAnchor constant:-14]];
13421
+ row.accessibilityLabel = label ?: @"";
12887
13422
  }
13423
+ [NSLayoutConstraint activateConstraints:constraints];
13424
+ row.accessibilityRole = NSAccessibilityStaticTextRole;
13425
+ return row;
12888
13426
  }
12889
13427
 
12890
- void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *host, const uint32_t *item_ids, const char *const *labels, const size_t *label_lens, const int *separators, const int *enabled_flags, size_t count) {
13428
+ void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *host, uint32_t status_item_id, const uint32_t *item_ids, const char *const *labels, const size_t *label_lens, const int *separators, const int *enabled_flags, const char *const *details, const size_t *detail_lens, const int *roles, const char *const *keys, const size_t *key_lens, const uint32_t *modifiers, size_t count) {
12891
13429
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12892
13430
  @autoreleasepool {
12893
- if (!object.statusItem) return;
12894
- NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
13431
+ NativeSdkStatusItemEntry *entry = [object statusEntryForId:status_item_id];
13432
+ if (!entry) return;
13433
+ NSMenu *menu = entry.menu;
13434
+ if (menu == nil) {
13435
+ menu = [[NSMenu alloc] initWithTitle:@""];
13436
+ entry.menu = menu;
13437
+ } else {
13438
+ [menu removeAllItems];
13439
+ }
13440
+ menu.autoenablesItems = NO;
13441
+ NSMutableArray<NSView *> *readoutRows = [NSMutableArray array];
12895
13442
  for (size_t i = 0; i < count; i++) {
12896
13443
  if (separators[i]) {
12897
13444
  [menu addItem:[NSMenuItem separatorItem]];
@@ -12901,41 +13448,116 @@ void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *host, const ui
12901
13448
  NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:label ?: @""
12902
13449
  action:@selector(trayMenuItemClicked:)
12903
13450
  keyEquivalent:@""];
12904
- item.tag = (NSInteger)item_ids[i];
13451
+ item.tag = (NSInteger)(((uint64_t)status_item_id << 32) | item_ids[i]);
12905
13452
  item.target = object;
12906
13453
  item.enabled = enabled_flags[i] != 0;
13454
+ if (keys[i] && key_lens[i] > 0) {
13455
+ NSString *key = [[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"";
13456
+ item.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13457
+ item.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[i]);
13458
+ }
13459
+ NSString *detail = details[i] && detail_lens[i] > 0 ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"";
13460
+ if (roles[i] == NativeSdkTrayRoleHero) {
13461
+ item.action = NULL;
13462
+ item.target = nil;
13463
+ item.view = NativeSdkTrayHeroView(label, detail);
13464
+ [menu addItem:item];
13465
+ continue;
13466
+ }
13467
+ if (roles[i] == NativeSdkTrayRoleAgent) {
13468
+ NSMutableArray<NSString *> *agentLabels = [NSMutableArray array];
13469
+ NSMutableArray<NSString *> *agentStates = [NSMutableArray array];
13470
+ NSMutableArray<NSNumber *> *agentEnabled = [NSMutableArray array];
13471
+ NSMutableArray<NSString *> *agentKeys = [NSMutableArray array];
13472
+ NSMutableArray<NSNumber *> *agentModifiers = [NSMutableArray array];
13473
+ uint32_t agentIds[32] = {0};
13474
+ size_t agentCount = 0;
13475
+ while (i < count && roles[i] == NativeSdkTrayRoleAgent && agentCount < 32) {
13476
+ [agentLabels addObject:(labels[i] ? [[NSString alloc] initWithBytes:labels[i] length:label_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13477
+ [agentStates addObject:(details[i] ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13478
+ [agentEnabled addObject:@(enabled_flags[i] != 0)];
13479
+ [agentKeys addObject:(keys[i] ? ([[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"") : @"")];
13480
+ [agentModifiers addObject:@(modifiers[i])];
13481
+ agentIds[agentCount++] = item_ids[i];
13482
+ i++;
13483
+ }
13484
+ i--;
13485
+ item.action = NULL;
13486
+ item.target = nil;
13487
+ // The custom buttons own every agent equivalent. Leaving the
13488
+ // first row's equivalent on this actionless wrapper would let
13489
+ // NSMenu consume it before the button can dispatch its id.
13490
+ item.keyEquivalent = @"";
13491
+ item.keyEquivalentModifierMask = 0;
13492
+ item.view = NativeSdkTrayAgentsView(object, status_item_id, agentIds, agentLabels, agentStates, agentEnabled, agentKeys, agentModifiers);
13493
+ [menu addItem:item];
13494
+ continue;
13495
+ }
13496
+ if (roles[i] == NativeSdkTrayRoleContext) {
13497
+ item.action = NULL;
13498
+ item.target = nil;
13499
+ item.view = NativeSdkTrayContextView(label, detail);
13500
+ [menu addItem:item];
13501
+ continue;
13502
+ }
13503
+ if (roles[i] == NativeSdkTrayRoleHeader || roles[i] == NativeSdkTrayRoleInfo) {
13504
+ item.action = NULL;
13505
+ item.target = nil;
13506
+ NSView *view = NativeSdkTrayReadoutView(label, roles[i] == NativeSdkTrayRoleInfo ? detail : @"", roles[i] == NativeSdkTrayRoleHeader);
13507
+ item.view = view;
13508
+ [readoutRows addObject:view];
13509
+ }
12907
13510
  [menu addItem:item];
12908
13511
  }
12909
- object.statusItem.menu = menu;
13512
+ if (readoutRows.count > 0) {
13513
+ CGFloat widest = 0;
13514
+ for (NSView *row in readoutRows) widest = MAX(widest, row.fittingSize.width);
13515
+ for (NSView *row in readoutRows) [row.widthAnchor constraintEqualToConstant:widest].active = YES;
13516
+ }
13517
+ menu.delegate = object;
13518
+ if (entry.activationCommand.length == 0 && entry.alternateActivationCommand.length == 0) {
13519
+ entry.item.menu = menu;
13520
+ }
12910
13521
  }
12911
13522
  }
12912
13523
 
12913
- void native_sdk_appkit_update_tray_title(native_sdk_appkit_host_t *host, const char *title, size_t title_len) {
13524
+ void native_sdk_appkit_update_tray_title(native_sdk_appkit_host_t *host, uint32_t status_item_id, const char *title, size_t title_len) {
12914
13525
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12915
13526
  @autoreleasepool {
12916
- if (!object.statusItem) return;
12917
- BOOL hasTitle = title != NULL && title_len > 0;
12918
- NSString *value = hasTitle ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
12919
- object.statusItem.button.title = value;
12920
- if (!object.statusItem.button.image && value.length == 0) {
12921
- // Same fallback as create: a bare status item must still show
12922
- // SOMETHING to stay clickable.
12923
- object.statusItem.button.title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
12924
- }
12925
- // Titled extras need variable width; icon-only ones keep the
12926
- // classic square well (mirrors create's length choice).
12927
- object.statusItem.length = object.statusItem.button.title.length > 0 ? NSVariableStatusItemLength : NSSquareStatusItemLength;
13527
+ NativeSdkStatusItemEntry *entry = [object statusEntryForId:status_item_id];
13528
+ if (!entry) return;
13529
+ NSString *value = title && title_len > 0 ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13530
+ NativeSdkApplyTrayPresentation(
13531
+ object,
13532
+ entry,
13533
+ value,
13534
+ entry.presentationWidth,
13535
+ entry.presentationTone,
13536
+ entry.presentationIconOpacity,
13537
+ entry.presentationMonospaced
13538
+ );
12928
13539
  }
12929
13540
  }
12930
13541
 
12931
- void native_sdk_appkit_remove_tray(native_sdk_appkit_host_t *host) {
13542
+ void native_sdk_appkit_update_tray_presentation(native_sdk_appkit_host_t *host, uint32_t status_item_id, const char *title, size_t title_len, double width, int tone, double icon_opacity, int monospaced) {
12932
13543
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12933
- if (object.statusItem) {
12934
- [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
12935
- object.statusItem = nil;
13544
+ @autoreleasepool {
13545
+ NativeSdkStatusItemEntry *entry = [object statusEntryForId:status_item_id];
13546
+ if (!entry) return;
13547
+ NSString *value = title ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13548
+ NativeSdkApplyTrayPresentation(object, entry, value, width, tone, icon_opacity, monospaced != 0);
12936
13549
  }
12937
13550
  }
12938
13551
 
13552
+ void native_sdk_appkit_remove_tray(native_sdk_appkit_host_t *host, uint32_t status_item_id) {
13553
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
13554
+ NSNumber *key = @(status_item_id);
13555
+ NativeSdkStatusItemEntry *entry = object.statusItems[key];
13556
+ if (!entry) return;
13557
+ [[NSStatusBar systemStatusBar] removeStatusItem:entry.item];
13558
+ [object.statusItems removeObjectForKey:key];
13559
+ }
13560
+
12939
13561
  void native_sdk_appkit_set_tray_callback(native_sdk_appkit_host_t *host, native_sdk_appkit_tray_callback_t callback, void *context) {
12940
13562
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12941
13563
  object.trayCallback = callback;