@native-sdk/cli 0.8.4 → 0.9.0

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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  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/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. 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,7 @@ 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 NativeSdkAppKitHost : NSObject <WKNavigationDelegate, NSMenuDelegate>
707
767
  @property(nonatomic, strong) NSWindow *window;
708
768
  @property(nonatomic, strong) WKWebView *webView;
709
769
  @property(nonatomic, strong) NativeSdkWindowDelegate *delegate;
@@ -927,6 +987,15 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
927
987
  @property(nonatomic, strong) dispatch_source_t sigtermSource;
928
988
  @property(nonatomic, strong) NSArray<NativeSdkShortcut *> *shortcuts;
929
989
  @property(nonatomic, strong) NSStatusItem *statusItem;
990
+ @property(nonatomic, strong) NSImage *statusItemBaseImage;
991
+ @property(nonatomic, strong) NSMenu *statusMenu;
992
+ @property(nonatomic, assign) double statusPresentationWidth;
993
+ @property(nonatomic, assign) int statusPresentationTone;
994
+ @property(nonatomic, assign) double statusPresentationIconOpacity;
995
+ @property(nonatomic, assign) BOOL statusPresentationMonospaced;
996
+ @property(nonatomic, strong) NSString *statusActivationCommand;
997
+ @property(nonatomic, strong) NSString *statusAlternateActivationCommand;
998
+ @property(nonatomic, strong) NSString *statusOpenCommand;
930
999
  @property(nonatomic, assign) native_sdk_appkit_tray_callback_t trayCallback;
931
1000
  @property(nonatomic, assign) void *trayContext;
932
1001
  @property(nonatomic, strong) NSArray<NSString *> *allowedNavigationOrigins;
@@ -998,6 +1067,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
998
1067
  - (NSMenuItem *)menuItem:(NSString *)title action:(SEL)action key:(NSString *)key modifiers:(NSEventModifierFlags)modifiers;
999
1068
  - (NSMenuItem *)commandMenuItem:(NSString *)title command:(NSString *)command key:(NSString *)key modifiers:(uint32_t)modifiers enabled:(BOOL)enabled checked:(BOOL)checked;
1000
1069
  - (void)menuCommandItemClicked:(NSMenuItem *)menuItem;
1070
+ - (void)menuWillOpen:(NSMenu *)menu;
1071
+ - (void)emitStatusCommand:(NSString *)command;
1072
+ - (void)statusItemActivated:(id)sender;
1001
1073
  - (uint64_t)activeCommandWindowId;
1002
1074
  - (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
1075
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
@@ -7713,6 +7785,12 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7713
7785
  if ((windowFlags & (1u << 1)) != 0) window.level = NSFloatingWindowLevel;
7714
7786
  if ((windowFlags & (1u << 2)) != 0) window.ignoresMouseEvents = YES;
7715
7787
  if ((windowFlags & (1u << 3)) != 0) [self.passiveShowWindows addObject:key];
7788
+ if ((windowFlags & (1u << 4)) != 0) {
7789
+ NSWindowCollectionBehavior behavior = window.collectionBehavior;
7790
+ behavior &= ~(NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorFullScreenAuxiliary);
7791
+ window.collectionBehavior = behavior | NSWindowCollectionBehaviorFullScreenNone;
7792
+ [window standardWindowButton:NSWindowZoomButton].enabled = NO;
7793
+ }
7716
7794
  [window setTitle:(title.length > 0 ? title : self.appName)];
7717
7795
  if (titlebarStyle == 1 || titlebarStyle == 2) {
7718
7796
  window.titlebarAppearsTransparent = YES;
@@ -7802,12 +7880,14 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7802
7880
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC), dispatch_get_main_queue(), ^{
7803
7881
  [weakSelf showDeferredWindowIfPending:windowId reason:"fallback-deadline"];
7804
7882
  });
7883
+ } else if (showPolicy == 2) {
7884
+ [self.policyHiddenWindows addObject:key];
7805
7885
  }
7806
7886
  if (makeMain) {
7807
7887
  self.window = window;
7808
7888
  self.delegate = delegate;
7809
7889
  self.windowLabel = label.length > 0 ? label : @"main";
7810
- } else if (showPolicy != 1) {
7890
+ } else if (showPolicy == 0) {
7811
7891
  [self orderWindowForImplicitShow:windowId];
7812
7892
  }
7813
7893
  return YES;
@@ -7824,7 +7904,7 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7824
7904
  if ([self.passiveShowWindows containsObject:@(windowId)]) {
7825
7905
  [window orderFront:nil];
7826
7906
  } else {
7827
- [NSApp activate];
7907
+ [NSApp activateIgnoringOtherApps:YES];
7828
7908
  [window makeKeyAndOrderFront:nil];
7829
7909
  }
7830
7910
  }
@@ -7896,7 +7976,8 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7896
7976
  // An explicit focus overrides a pending present-before-show defer:
7897
7977
  // the runtime asked for the window NOW.
7898
7978
  [self.deferredShowWindows removeObjectForKey:@(windowId)];
7899
- [NSApp activate];
7979
+ [self.policyHiddenWindows removeObject:@(windowId)];
7980
+ [NSApp activateIgnoringOtherApps:YES];
7900
7981
  [window makeKeyAndOrderFront:nil];
7901
7982
  [self emitWindowFrameForWindowId:windowId open:YES];
7902
7983
  [self scheduleFrame];
@@ -7934,6 +8015,9 @@ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, c
7934
8015
  - (void)hideWindowWithId:(uint64_t)windowId {
7935
8016
  NSWindow *window = self.windows[@(windowId)];
7936
8017
  if (!window) return;
8018
+ // Hiding is an explicit policy decision and therefore supersedes a
8019
+ // pending first-present reveal and its fallback deadline.
8020
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7937
8021
  [self.policyHiddenWindows addObject:@(windowId)];
7938
8022
  [window orderOut:nil];
7939
8023
  [self emitWindowFrameForWindowId:windowId open:YES];
@@ -9523,6 +9607,11 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9523
9607
  }];
9524
9608
  }
9525
9609
 
9610
+ - (void)menuWillOpen:(NSMenu *)menu {
9611
+ if (!self.statusItem || menu != self.statusMenu) return;
9612
+ [self emitStatusCommand:self.statusOpenCommand];
9613
+ }
9614
+
9526
9615
  - (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
9616
  if (menuCount == 0) {
9528
9617
  [self buildMenuBar];
@@ -9571,7 +9660,7 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9571
9660
  // Present-before-show: a deferred startup window stays ordered out
9572
9661
  // here and appears when its first canvas present lands (or the
9573
9662
  // create-time fallback deadline fires).
9574
- if (!self.deferredShowWindows[@1]) {
9663
+ if (!self.deferredShowWindows[@1] && ![self.policyHiddenWindows containsObject:@1]) {
9575
9664
  [self orderWindowForImplicitShow:1];
9576
9665
  }
9577
9666
  if (!self.shortcutEventMonitor) {
@@ -11831,6 +11920,27 @@ static void NativeSdkVideoFittedSize(double naturalWidth, double naturalHeight,
11831
11920
  }
11832
11921
  }
11833
11922
 
11923
+ - (void)emitStatusCommand:(NSString *)command {
11924
+ if (command.length == 0) return;
11925
+ const char *bytes = command.UTF8String;
11926
+ [self emitEvent:(native_sdk_appkit_event_t){
11927
+ .kind = NATIVE_SDK_APPKIT_EVENT_TRAY_COMMAND,
11928
+ .window_id = [self activeCommandWindowId],
11929
+ .command_name = bytes,
11930
+ .command_name_len = [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
11931
+ }];
11932
+ }
11933
+
11934
+ - (void)statusItemActivated:(id)sender {
11935
+ (void)sender;
11936
+ if ((NSEvent.modifierFlags & NSEventModifierFlagOption) != 0 && self.statusAlternateActivationCommand.length > 0) {
11937
+ [self emitStatusCommand:self.statusAlternateActivationCommand];
11938
+ return;
11939
+ }
11940
+ [self emitStatusCommand:self.statusActivationCommand];
11941
+ if (self.statusMenu) [self.statusItem popUpStatusItemMenu:self.statusMenu];
11942
+ }
11943
+
11834
11944
  @end
11835
11945
 
11836
11946
  static NSArray<NSString *> *NativeSdkPolicyListFromBytes(const char *bytes, size_t len, NSArray<NSString *> *fallback) {
@@ -12396,6 +12506,13 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
12396
12506
  return 1;
12397
12507
  }
12398
12508
 
12509
+ int native_sdk_appkit_hide_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
12510
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12511
+ if (!object.windows[@(window_id)]) return 0;
12512
+ [object hideWindowWithId:window_id];
12513
+ return 1;
12514
+ }
12515
+
12399
12516
  int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
12400
12517
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12401
12518
  if (!object.windows[@(window_id)]) return 0;
@@ -12403,6 +12520,23 @@ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t windo
12403
12520
  return 1;
12404
12521
  }
12405
12522
 
12523
+ int native_sdk_appkit_set_dock_presence(native_sdk_appkit_host_t *host, int visible) {
12524
+ (void)host;
12525
+ NSApplicationActivationPolicy policy = visible ? NSApplicationActivationPolicyRegular : NSApplicationActivationPolicyAccessory;
12526
+ BOOL changed = [NSApp setActivationPolicy:policy];
12527
+ return changed || NSApp.activationPolicy == policy ? 1 : 0;
12528
+ }
12529
+
12530
+ int native_sdk_appkit_launch_at_login_status(native_sdk_appkit_host_t *host) {
12531
+ (void)host;
12532
+ return NativeSdkLaunchAtLoginStatus();
12533
+ }
12534
+
12535
+ int native_sdk_appkit_set_launch_at_login(native_sdk_appkit_host_t *host, int enabled) {
12536
+ (void)host;
12537
+ return NativeSdkSetLaunchAtLogin(enabled != 0);
12538
+ }
12539
+
12406
12540
  int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
12407
12541
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12408
12542
  if (!object.windows[@(window_id)]) return 0;
@@ -12677,7 +12811,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12677
12811
  @autoreleasepool {
12678
12812
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12679
12813
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12680
- if (serviceString.length == 0 || accountString.length == 0 || !secret || secret_len == 0) return 0;
12814
+ if (serviceString.length == 0 || accountString.length == 0 || (!secret && secret_len > 0)) return 0;
12681
12815
  NSData *secretData = [NSData dataWithBytes:secret length:secret_len];
12682
12816
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12683
12817
  NSDictionary *update = @{ (__bridge id)kSecValueData: secretData };
@@ -12686,7 +12820,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12686
12820
  query[(__bridge id)kSecValueData] = secretData;
12687
12821
  status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
12688
12822
  }
12689
- return status == errSecSuccess ? 1 : 0;
12823
+ return NativeSdkCredentialStatus(status, -1);
12690
12824
  }
12691
12825
  }
12692
12826
 
@@ -12695,13 +12829,16 @@ size_t native_sdk_appkit_get_credential(native_sdk_appkit_host_t *host, const ch
12695
12829
  @autoreleasepool {
12696
12830
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12697
12831
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12698
- if (serviceString.length == 0 || accountString.length == 0 || !buffer) return 0;
12832
+ if (serviceString.length == 0 || accountString.length == 0 || (!buffer && buffer_len > 0)) return SIZE_MAX - 1;
12699
12833
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12700
12834
  query[(__bridge id)kSecReturnData] = @YES;
12701
12835
  query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
12702
12836
  CFTypeRef result = NULL;
12703
12837
  OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
12704
- if (status != errSecSuccess || !result) return 0;
12838
+ if (status == errSecItemNotFound) return SIZE_MAX;
12839
+ if (status == errSecInteractionNotAllowed || status == errSecNotAvailable) return SIZE_MAX - 2;
12840
+ if (status == errSecAuthFailed || status == errSecUserCanceled || status == errSecMissingEntitlement) return SIZE_MAX - 3;
12841
+ if (status != errSecSuccess || !result) return SIZE_MAX - 1;
12705
12842
  NSData *data = CFBridgingRelease(result);
12706
12843
  if (data.length > buffer_len) return data.length;
12707
12844
  memcpy(buffer, data.bytes, data.length);
@@ -12717,7 +12854,26 @@ int native_sdk_appkit_delete_credential(native_sdk_appkit_host_t *host, const ch
12717
12854
  if (serviceString.length == 0 || accountString.length == 0) return 0;
12718
12855
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12719
12856
  OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
12720
- return status == errSecSuccess ? 1 : 0;
12857
+ return NativeSdkCredentialStatus(status, 0);
12858
+ }
12859
+ }
12860
+
12861
+ 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) {
12862
+ (void)host;
12863
+ if (!buffer || buffer_len == 0 || style < 0 || style > 2) return 0;
12864
+ @autoreleasepool {
12865
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)timestamp_ms / 1000.0];
12866
+ if (!date) return 0;
12867
+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
12868
+ formatter.locale = [NSLocale autoupdatingCurrentLocale];
12869
+ formatter.timeZone = [NSTimeZone localTimeZone];
12870
+ formatter.dateStyle = (style == 0 || style == 2) ? NSDateFormatterShortStyle : NSDateFormatterNoStyle;
12871
+ formatter.timeStyle = (style == 1 || style == 2) ? NSDateFormatterMediumStyle : NSDateFormatterNoStyle;
12872
+ NSString *text = [formatter stringFromDate:date];
12873
+ NSData *utf8 = [text dataUsingEncoding:NSUTF8StringEncoding];
12874
+ if (!utf8 || utf8.length == 0 || utf8.length > buffer_len) return 0;
12875
+ memcpy(buffer, utf8.bytes, utf8.length);
12876
+ return utf8.length;
12721
12877
  }
12722
12878
  }
12723
12879
 
@@ -12855,43 +13011,315 @@ int native_sdk_appkit_show_message_dialog(native_sdk_appkit_host_t *host, const
12855
13011
  }
12856
13012
  }
12857
13013
 
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) {
13014
+ static NSImage *NativeSdkTrayImageWithOpacity(NSImage *source, double opacity) {
13015
+ if (!source) return nil;
13016
+ const CGFloat fraction = MAX(0.0, MIN(1.0, opacity));
13017
+ if (fraction >= 1.0) return source;
13018
+ NSImage *image = [[NSImage alloc] initWithSize:source.size];
13019
+ [image lockFocus];
13020
+ [source drawInRect:NSMakeRect(0, 0, source.size.width, source.size.height)
13021
+ fromRect:NSZeroRect
13022
+ operation:NSCompositingOperationSourceOver
13023
+ fraction:fraction
13024
+ respectFlipped:YES
13025
+ hints:nil];
13026
+ [image unlockFocus];
13027
+ image.template = YES;
13028
+ return image;
13029
+ }
13030
+
13031
+ static void NativeSdkApplyTrayPresentation(NativeSdkAppKitHost *object, NSString *requestedTitle, double width, int tone, double iconOpacity, BOOL monospaced) {
13032
+ if (!object.statusItem) return;
13033
+ object.statusPresentationWidth = width;
13034
+ object.statusPresentationTone = tone;
13035
+ object.statusPresentationIconOpacity = iconOpacity;
13036
+ object.statusPresentationMonospaced = monospaced;
13037
+ NSString *title = requestedTitle ?: @"";
13038
+ if (!object.statusItemBaseImage && title.length == 0) {
13039
+ title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
13040
+ }
13041
+ NSFont *font = monospaced
13042
+ ? ([NSFont fontWithName:@"Geist Mono" size:11] ?: [NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightRegular])
13043
+ : [NSFont systemFontOfSize:11];
13044
+ NSStatusBarButton *button = object.statusItem.button;
13045
+ if (tone == 0) {
13046
+ button.title = title;
13047
+ button.font = font;
13048
+ button.contentTintColor = nil;
13049
+ } else {
13050
+ NSColor *color = tone == 1 ? NSColor.systemOrangeColor : NSColor.systemRedColor;
13051
+ button.attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:@{
13052
+ NSForegroundColorAttributeName: color,
13053
+ NSFontAttributeName: font,
13054
+ }];
13055
+ button.contentTintColor = color;
13056
+ }
13057
+ button.image = NativeSdkTrayImageWithOpacity(object.statusItemBaseImage, iconOpacity);
13058
+ object.statusItem.length = width > 0 ? width : (requestedTitle.length > 0 ? NSVariableStatusItemLength : NSSquareStatusItemLength);
13059
+ }
13060
+
13061
+ 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, 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
13062
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12860
13063
  @autoreleasepool {
12861
13064
  if (object.statusItem) {
12862
13065
  [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
12863
13066
  }
12864
- // A titled menu-bar extra needs variable width; icon-only status
12865
- // items keep the classic square well.
13067
+ object.statusMenu = nil;
12866
13068
  BOOL hasTitle = title != NULL && title_len > 0;
12867
13069
  object.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:hasTitle ? NSVariableStatusItemLength : NSSquareStatusItemLength];
13070
+ object.statusItemBaseImage = nil;
12868
13071
 
12869
13072
  if (icon_path && icon_path_len > 0) {
12870
13073
  NSString *path = [[NSString alloc] initWithBytes:icon_path length:icon_path_len encoding:NSUTF8StringEncoding];
12871
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
13074
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:NativeSdkResolvedAssetFilePath(path)];
12872
13075
  if (image) {
12873
13076
  image.template = YES;
12874
13077
  image.size = NSMakeSize(18, 18);
12875
- object.statusItem.button.image = image;
13078
+ object.statusItemBaseImage = image;
12876
13079
  }
12877
13080
  }
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
- }
13081
+ NSString *titleString = hasTitle ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
12884
13082
  if (tooltip && tooltip_len > 0) {
12885
13083
  object.statusItem.button.toolTip = [[NSString alloc] initWithBytes:tooltip length:tooltip_len encoding:NSUTF8StringEncoding];
12886
13084
  }
13085
+ object.statusActivationCommand = activation_command ? ([[NSString alloc] initWithBytes:activation_command length:activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13086
+ object.statusAlternateActivationCommand = alternate_activation_command ? ([[NSString alloc] initWithBytes:alternate_activation_command length:alternate_activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13087
+ object.statusOpenCommand = open_command ? ([[NSString alloc] initWithBytes:open_command length:open_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13088
+ if (object.statusActivationCommand.length > 0 || object.statusAlternateActivationCommand.length > 0) {
13089
+ object.statusItem.button.target = object;
13090
+ object.statusItem.button.action = @selector(statusItemActivated:);
13091
+ [object.statusItem.button sendActionOn:NSEventMaskLeftMouseUp];
13092
+ }
13093
+ NativeSdkApplyTrayPresentation(object, titleString, width, tone, icon_opacity, monospaced != 0);
13094
+ }
13095
+ }
13096
+
13097
+ enum {
13098
+ NativeSdkTrayRoleCommand = 0,
13099
+ NativeSdkTrayRoleInfo = 1,
13100
+ NativeSdkTrayRoleHeader = 2,
13101
+ NativeSdkTrayRoleHero = 3,
13102
+ NativeSdkTrayRoleAgent = 4,
13103
+ NativeSdkTrayRoleContext = 5,
13104
+ };
13105
+
13106
+ static NSView *NativeSdkTrayHeroView(NSString *headline, NSString *quota) {
13107
+ NSArray<NSString *> *parts = [headline componentsSeparatedByString:@"\n"];
13108
+ NSString *value = parts.count > 0 ? parts[0] : @"";
13109
+ NSString *account = parts.count > 1 ? parts[1] : @"";
13110
+ NSString *stale = parts.count > 2 ? parts[2] : @"";
13111
+ NSString *reset = parts.count > 3 ? parts[3] : @"";
13112
+ CGFloat height = quota.length > 0 ? 56 : 32;
13113
+ if (stale.length > 0) height += 14;
13114
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, height)];
13115
+ NSTextField *amount = [NSTextField labelWithString:value ?: @""];
13116
+ amount.font = [NSFont fontWithName:@"Geist Mono" size:20] ?: [NSFont monospacedDigitSystemFontOfSize:20 weight:NSFontWeightMedium];
13117
+ amount.translatesAutoresizingMaskIntoConstraints = NO;
13118
+ NSTextField *caption = [NSTextField labelWithString:(reset.length > 0 ? [NSString stringWithFormat:@"today · %@", reset] : @"today")];
13119
+ caption.font = [NSFont systemFontOfSize:11];
13120
+ caption.textColor = NSColor.secondaryLabelColor;
13121
+ caption.translatesAutoresizingMaskIntoConstraints = NO;
13122
+ [view addSubview:amount];
13123
+ [view addSubview:caption];
13124
+ [NSLayoutConstraint activateConstraints:@[
13125
+ [amount.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13126
+ [amount.topAnchor constraintEqualToAnchor:view.topAnchor constant:3],
13127
+ [caption.leadingAnchor constraintEqualToAnchor:amount.trailingAnchor constant:6],
13128
+ [caption.firstBaselineAnchor constraintEqualToAnchor:amount.firstBaselineAnchor],
13129
+ ]];
13130
+ if (account.length > 0) {
13131
+ NSTextField *accountLabel = [NSTextField labelWithString:account];
13132
+ accountLabel.font = [NSFont systemFontOfSize:10];
13133
+ accountLabel.textColor = NSColor.secondaryLabelColor;
13134
+ accountLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13135
+ accountLabel.translatesAutoresizingMaskIntoConstraints = NO;
13136
+ [view addSubview:accountLabel];
13137
+ [NSLayoutConstraint activateConstraints:@[
13138
+ [accountLabel.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13139
+ [accountLabel.firstBaselineAnchor constraintEqualToAnchor:caption.firstBaselineAnchor],
13140
+ [accountLabel.leadingAnchor constraintGreaterThanOrEqualToAnchor:caption.trailingAnchor constant:12],
13141
+ ]];
13142
+ }
13143
+ if (quota.length > 0) {
13144
+ NSProgressIndicator *progress = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect];
13145
+ progress.style = NSProgressIndicatorStyleBar;
13146
+ progress.controlSize = NSControlSizeMini;
13147
+ progress.indeterminate = NO;
13148
+ progress.minValue = 0;
13149
+ progress.maxValue = 100;
13150
+ NSScanner *scanner = [NSScanner scannerWithString:quota];
13151
+ double percent = 0;
13152
+ [scanner scanDouble:&percent];
13153
+ progress.doubleValue = MIN(MAX(percent, 0), 100);
13154
+ progress.translatesAutoresizingMaskIntoConstraints = NO;
13155
+ NSTextField *quotaLabel = [NSTextField labelWithString:quota];
13156
+ quotaLabel.font = [NSFont systemFontOfSize:11];
13157
+ quotaLabel.textColor = NSColor.secondaryLabelColor;
13158
+ quotaLabel.translatesAutoresizingMaskIntoConstraints = NO;
13159
+ [view addSubview:progress];
13160
+ [view addSubview:quotaLabel];
13161
+ [NSLayoutConstraint activateConstraints:@[
13162
+ [progress.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13163
+ [progress.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13164
+ [progress.topAnchor constraintEqualToAnchor:amount.bottomAnchor constant:4],
13165
+ [progress.heightAnchor constraintEqualToConstant:5],
13166
+ [quotaLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13167
+ [quotaLabel.topAnchor constraintEqualToAnchor:progress.bottomAnchor constant:2],
13168
+ ]];
13169
+ }
13170
+ if (stale.length > 0) {
13171
+ NSTextField *staleLabel = [NSTextField labelWithString:stale];
13172
+ staleLabel.font = [NSFont systemFontOfSize:10];
13173
+ staleLabel.textColor = NSColor.tertiaryLabelColor;
13174
+ staleLabel.translatesAutoresizingMaskIntoConstraints = NO;
13175
+ [view addSubview:staleLabel];
13176
+ [NSLayoutConstraint activateConstraints:@[
13177
+ [staleLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13178
+ [staleLabel.bottomAnchor constraintEqualToAnchor:view.bottomAnchor constant:-6],
13179
+ ]];
13180
+ }
13181
+ view.accessibilityLabel = quota.length > 0 ? [NSString stringWithFormat:@"%@ today, %@", value ?: @"", quota] : [NSString stringWithFormat:@"%@ today", value ?: @""];
13182
+ view.accessibilityRole = NSAccessibilityGroupRole;
13183
+ return view;
13184
+ }
13185
+
13186
+ static NSView *NativeSdkTrayAgentsView(NativeSdkAppKitHost *object, const uint32_t *itemIds, NSArray<NSString *> *labels, NSArray<NSString *> *states, NSArray<NSNumber *> *enabled, NSArray<NSString *> *keys, NSArray<NSNumber *> *modifiers) {
13187
+ NSStackView *row = [[NSStackView alloc] initWithFrame:NSMakeRect(0, 0, 320, 32)];
13188
+ row.orientation = NSUserInterfaceLayoutOrientationHorizontal;
13189
+ row.alignment = NSLayoutAttributeCenterY;
13190
+ row.spacing = 8;
13191
+ row.edgeInsets = NSEdgeInsetsMake(5, 14, 5, 14);
13192
+ NSString *appearance = [NSApp.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
13193
+ BOOL dark = [appearance isEqualToString:NSAppearanceNameDarkAqua];
13194
+ NSColor *warningColor = dark ? NSColor.systemOrangeColor : [NSColor colorWithSRGBRed:0.54 green:0.23 blue:0.00 alpha:1.0];
13195
+ NSColor *successColor = dark ? NSColor.systemGreenColor : [NSColor colorWithSRGBRed:0.06 green:0.42 blue:0.20 alpha:1.0];
13196
+ for (NSUInteger index = 0; index < labels.count; index++) {
13197
+ NSString *state = states[index];
13198
+ // `detail` is presentation text as well as the semantic state. The
13199
+ // documented examples append a glyph ("configured ✓", "warning ⚠"),
13200
+ // so classify the leading token instead of requiring the whole label
13201
+ // to be the bare state name.
13202
+ BOOL configured = [state isEqualToString:@"configured"] || [state hasPrefix:@"configured "];
13203
+ BOOL warning = [state isEqualToString:@"warning"] || [state hasPrefix:@"warning "];
13204
+ NSString *title = [NSString stringWithFormat:@"%@ %@", configured ? @"✓" : warning ? @"⚠" : @"○", labels[index]];
13205
+ NSView *control = [[NSView alloc] initWithFrame:NSZeroRect];
13206
+ NSTextField *label = [NSTextField labelWithString:title];
13207
+ label.font = [NSFont systemFontOfSize:11];
13208
+ label.textColor = configured ? successColor : warning ? warningColor : NSColor.secondaryLabelColor;
13209
+ label.translatesAutoresizingMaskIntoConstraints = NO;
13210
+ label.accessibilityElement = NO;
13211
+ NSButton *button = [NSButton buttonWithTitle:@"" target:object action:@selector(trayMenuItemClicked:)];
13212
+ button.tag = itemIds[index];
13213
+ button.bordered = NO;
13214
+ button.transparent = YES;
13215
+ button.enabled = enabled[index].boolValue;
13216
+ NSString *key = keys[index];
13217
+ if (key.length > 0) {
13218
+ button.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13219
+ button.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[index].unsignedIntValue);
13220
+ }
13221
+ button.translatesAutoresizingMaskIntoConstraints = NO;
13222
+ button.accessibilityLabel = title;
13223
+ [control addSubview:label];
13224
+ [control addSubview:button];
13225
+ [NSLayoutConstraint activateConstraints:@[
13226
+ [label.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13227
+ [label.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13228
+ [label.centerYAnchor constraintEqualToAnchor:control.centerYAnchor],
13229
+ [button.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13230
+ [button.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13231
+ [button.topAnchor constraintEqualToAnchor:control.topAnchor],
13232
+ [button.bottomAnchor constraintEqualToAnchor:control.bottomAnchor],
13233
+ ]];
13234
+ [row addArrangedSubview:control];
13235
+ }
13236
+ [row.heightAnchor constraintEqualToConstant:32].active = YES;
13237
+ [row.widthAnchor constraintEqualToConstant:320].active = YES;
13238
+ return row;
13239
+ }
13240
+
13241
+ static NSView *NativeSdkTrayContextView(NSString *primary, NSString *secondary) {
13242
+ NSArray<NSString *> *parts = [secondary componentsSeparatedByString:@"\n"];
13243
+ NSString *quota = parts.count > 0 ? parts[0] : @"";
13244
+ NSString *windows = parts.count > 1 ? parts[1] : @"";
13245
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, 58)];
13246
+ NSTextField *primaryLabel = [NSTextField labelWithString:primary ?: @""];
13247
+ primaryLabel.font = [NSFont systemFontOfSize:11 weight:NSFontWeightMedium];
13248
+ primaryLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13249
+ primaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13250
+ NSTextField *secondaryLabel = [NSTextField labelWithString:quota ?: @""];
13251
+ secondaryLabel.font = [NSFont systemFontOfSize:10];
13252
+ secondaryLabel.textColor = NSColor.secondaryLabelColor;
13253
+ secondaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13254
+ NSTextField *windowsLabel = [NSTextField labelWithString:windows ?: @""];
13255
+ windowsLabel.font = [NSFont systemFontOfSize:10];
13256
+ windowsLabel.textColor = NSColor.secondaryLabelColor;
13257
+ windowsLabel.translatesAutoresizingMaskIntoConstraints = NO;
13258
+ [view addSubview:primaryLabel];
13259
+ [view addSubview:secondaryLabel];
13260
+ [view addSubview:windowsLabel];
13261
+ [NSLayoutConstraint activateConstraints:@[
13262
+ [primaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13263
+ [primaryLabel.trailingAnchor constraintLessThanOrEqualToAnchor:view.trailingAnchor constant:-14],
13264
+ [primaryLabel.topAnchor constraintEqualToAnchor:view.topAnchor constant:6],
13265
+ [secondaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13266
+ [secondaryLabel.topAnchor constraintEqualToAnchor:primaryLabel.bottomAnchor constant:2],
13267
+ [windowsLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13268
+ [windowsLabel.topAnchor constraintEqualToAnchor:secondaryLabel.bottomAnchor constant:2],
13269
+ ]];
13270
+ view.accessibilityLabel = secondary.length > 0 ? [NSString stringWithFormat:@"%@, %@", primary ?: @"", [secondary stringByReplacingOccurrencesOfString:@"\n" withString:@", "]] : primary ?: @"";
13271
+ view.accessibilityRole = NSAccessibilityGroupRole;
13272
+ return view;
13273
+ }
13274
+
13275
+ static NSView *NativeSdkTrayReadoutView(NSString *label, NSString *value, BOOL isHeader) {
13276
+ NSFont *bodyFont = [NSFont menuFontOfSize:0];
13277
+ NSTextField *labelField = [NSTextField labelWithString:label ?: @""];
13278
+ labelField.font = isHeader ? [NSFont systemFontOfSize:bodyFont.pointSize - 2 weight:NSFontWeightSemibold] : bodyFont;
13279
+ labelField.textColor = isHeader ? NSColor.secondaryLabelColor : NSColor.labelColor;
13280
+ labelField.translatesAutoresizingMaskIntoConstraints = NO;
13281
+ NSView *row = [[NSView alloc] initWithFrame:NSZeroRect];
13282
+ row.translatesAutoresizingMaskIntoConstraints = NO;
13283
+ [row addSubview:labelField];
13284
+ NSMutableArray<NSLayoutConstraint *> *constraints = [NSMutableArray arrayWithArray:@[
13285
+ [labelField.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
13286
+ [labelField.topAnchor constraintEqualToAnchor:row.topAnchor constant:3],
13287
+ [labelField.bottomAnchor constraintEqualToAnchor:row.bottomAnchor constant:-3],
13288
+ ]];
13289
+ if (value.length > 0) {
13290
+ NSTextField *valueField = [NSTextField labelWithString:value];
13291
+ valueField.font = [NSFont monospacedDigitSystemFontOfSize:bodyFont.pointSize weight:NSFontWeightRegular];
13292
+ valueField.textColor = NSColor.secondaryLabelColor;
13293
+ valueField.translatesAutoresizingMaskIntoConstraints = NO;
13294
+ [row addSubview:valueField];
13295
+ [constraints addObjectsFromArray:@[
13296
+ [valueField.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14],
13297
+ [valueField.firstBaselineAnchor constraintEqualToAnchor:labelField.firstBaselineAnchor],
13298
+ [valueField.leadingAnchor constraintGreaterThanOrEqualToAnchor:labelField.trailingAnchor constant:28],
13299
+ ]];
13300
+ row.accessibilityLabel = [NSString stringWithFormat:@"%@, %@", label ?: @"", value];
13301
+ } else {
13302
+ [constraints addObject:[labelField.trailingAnchor constraintLessThanOrEqualToAnchor:row.trailingAnchor constant:-14]];
13303
+ row.accessibilityLabel = label ?: @"";
12887
13304
  }
13305
+ [NSLayoutConstraint activateConstraints:constraints];
13306
+ row.accessibilityRole = NSAccessibilityStaticTextRole;
13307
+ return row;
12888
13308
  }
12889
13309
 
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) {
13310
+ 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, 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
13311
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12892
13312
  @autoreleasepool {
12893
13313
  if (!object.statusItem) return;
12894
- NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
13314
+ NSMenu *menu = object.statusMenu;
13315
+ if (menu == nil) {
13316
+ menu = [[NSMenu alloc] initWithTitle:@""];
13317
+ object.statusMenu = menu;
13318
+ } else {
13319
+ [menu removeAllItems];
13320
+ }
13321
+ menu.autoenablesItems = NO;
13322
+ NSMutableArray<NSView *> *readoutRows = [NSMutableArray array];
12895
13323
  for (size_t i = 0; i < count; i++) {
12896
13324
  if (separators[i]) {
12897
13325
  [menu addItem:[NSMenuItem separatorItem]];
@@ -12904,9 +13332,73 @@ void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *host, const ui
12904
13332
  item.tag = (NSInteger)item_ids[i];
12905
13333
  item.target = object;
12906
13334
  item.enabled = enabled_flags[i] != 0;
13335
+ if (keys[i] && key_lens[i] > 0) {
13336
+ NSString *key = [[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"";
13337
+ item.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13338
+ item.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[i]);
13339
+ }
13340
+ NSString *detail = details[i] && detail_lens[i] > 0 ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"";
13341
+ if (roles[i] == NativeSdkTrayRoleHero) {
13342
+ item.action = NULL;
13343
+ item.target = nil;
13344
+ item.view = NativeSdkTrayHeroView(label, detail);
13345
+ [menu addItem:item];
13346
+ continue;
13347
+ }
13348
+ if (roles[i] == NativeSdkTrayRoleAgent) {
13349
+ NSMutableArray<NSString *> *agentLabels = [NSMutableArray array];
13350
+ NSMutableArray<NSString *> *agentStates = [NSMutableArray array];
13351
+ NSMutableArray<NSNumber *> *agentEnabled = [NSMutableArray array];
13352
+ NSMutableArray<NSString *> *agentKeys = [NSMutableArray array];
13353
+ NSMutableArray<NSNumber *> *agentModifiers = [NSMutableArray array];
13354
+ uint32_t agentIds[32] = {0};
13355
+ size_t agentCount = 0;
13356
+ while (i < count && roles[i] == NativeSdkTrayRoleAgent && agentCount < 32) {
13357
+ [agentLabels addObject:(labels[i] ? [[NSString alloc] initWithBytes:labels[i] length:label_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13358
+ [agentStates addObject:(details[i] ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13359
+ [agentEnabled addObject:@(enabled_flags[i] != 0)];
13360
+ [agentKeys addObject:(keys[i] ? ([[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"") : @"")];
13361
+ [agentModifiers addObject:@(modifiers[i])];
13362
+ agentIds[agentCount++] = item_ids[i];
13363
+ i++;
13364
+ }
13365
+ i--;
13366
+ item.action = NULL;
13367
+ item.target = nil;
13368
+ // The custom buttons own every agent equivalent. Leaving the
13369
+ // first row's equivalent on this actionless wrapper would let
13370
+ // NSMenu consume it before the button can dispatch its id.
13371
+ item.keyEquivalent = @"";
13372
+ item.keyEquivalentModifierMask = 0;
13373
+ item.view = NativeSdkTrayAgentsView(object, agentIds, agentLabels, agentStates, agentEnabled, agentKeys, agentModifiers);
13374
+ [menu addItem:item];
13375
+ continue;
13376
+ }
13377
+ if (roles[i] == NativeSdkTrayRoleContext) {
13378
+ item.action = NULL;
13379
+ item.target = nil;
13380
+ item.view = NativeSdkTrayContextView(label, detail);
13381
+ [menu addItem:item];
13382
+ continue;
13383
+ }
13384
+ if (roles[i] == NativeSdkTrayRoleHeader || roles[i] == NativeSdkTrayRoleInfo) {
13385
+ item.action = NULL;
13386
+ item.target = nil;
13387
+ NSView *view = NativeSdkTrayReadoutView(label, roles[i] == NativeSdkTrayRoleInfo ? detail : @"", roles[i] == NativeSdkTrayRoleHeader);
13388
+ item.view = view;
13389
+ [readoutRows addObject:view];
13390
+ }
12907
13391
  [menu addItem:item];
12908
13392
  }
12909
- object.statusItem.menu = menu;
13393
+ if (readoutRows.count > 0) {
13394
+ CGFloat widest = 0;
13395
+ for (NSView *row in readoutRows) widest = MAX(widest, row.fittingSize.width);
13396
+ for (NSView *row in readoutRows) [row.widthAnchor constraintEqualToConstant:widest].active = YES;
13397
+ }
13398
+ menu.delegate = object;
13399
+ if (object.statusActivationCommand.length == 0 && object.statusAlternateActivationCommand.length == 0) {
13400
+ object.statusItem.menu = menu;
13401
+ }
12910
13402
  }
12911
13403
  }
12912
13404
 
@@ -12914,17 +13406,23 @@ void native_sdk_appkit_update_tray_title(native_sdk_appkit_host_t *host, const c
12914
13406
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12915
13407
  @autoreleasepool {
12916
13408
  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;
13409
+ NSString *value = title && title_len > 0 ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13410
+ NativeSdkApplyTrayPresentation(
13411
+ object,
13412
+ value,
13413
+ object.statusPresentationWidth,
13414
+ object.statusPresentationTone,
13415
+ object.statusPresentationIconOpacity,
13416
+ object.statusPresentationMonospaced
13417
+ );
13418
+ }
13419
+ }
13420
+
13421
+ void native_sdk_appkit_update_tray_presentation(native_sdk_appkit_host_t *host, const char *title, size_t title_len, double width, int tone, double icon_opacity, int monospaced) {
13422
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
13423
+ @autoreleasepool {
13424
+ NSString *value = title ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13425
+ NativeSdkApplyTrayPresentation(object, value, width, tone, icon_opacity, monospaced != 0);
12928
13426
  }
12929
13427
  }
12930
13428
 
@@ -12933,6 +13431,8 @@ void native_sdk_appkit_remove_tray(native_sdk_appkit_host_t *host) {
12933
13431
  if (object.statusItem) {
12934
13432
  [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
12935
13433
  object.statusItem = nil;
13434
+ object.statusItemBaseImage = nil;
13435
+ object.statusMenu = nil;
12936
13436
  }
12937
13437
  }
12938
13438