Skip to content

Commit 2b0da0e

Browse files
authored
refactor(macos): single-owner hybrid status menu with live session cards and exec approvals (#130041)
* test(macos): add OPENCLAW_DEBUG_OPEN_MENU screenshot hook * feat(macos): add live execution approval queue * refactor(macos): replace menu injectors with owned status menu * fix(macos): keep unconfigured menu header calm * fix(macos): route status-item right-clicks through a local event monitor NSControl's send-action mask ignores right mouse buttons, so the previous sendAction(on: [.rightMouseUp]) wiring never fired and the menu was unreachable by pointer. A local monitor now owns pointer routing (left = dashboard, right = menu) — the same mechanism the shipped StatusItemMouseRouter used — and menuWillOpen gained the re-entrancy guard the old injector carried, since reconciling tracked rows can re-enter the callback without a close. * chore(i18n): refresh native inventory for status menu strings * chore(macos): remove menu-refactor dead code Periphery flagged the orphans the status-menu refactor left behind: the ExecApprovalQuickMode enum and AppState's entire quick-mode read/retry surface (its only consumer was the deleted menu picker; the Settings pane owns exec-approval policy UI), SessionMenuLabelView, TrackingAreaSupport, NodeMenuMultilineView, UpdateStatus.disabled, and two fixture-only initializers. StatusMenuController.stop() is now wired into applicationWillTerminate. The menu-highlight environment key moved from the deleted view file into MenuItemHighlightColors. * chore(macos): fix status-menu lint style and refresh i18n inventory * fix(macos): converge approval cards after losing a resolution race The status-menu queue and the modal prompter intentionally share the gateway approval event stream: the gateway resolves each approval exactly once, the resolved broadcast removes the card, and the modal stays the active presentation owner while the menu is the passive, ambient one. What was missing: when the menu's resolve loses the race (modal or another client answered first), the gateway rejection left a zombie card if the resolved event was dropped. Resolve failures now re-list from the authoritative queue. Regression test simulates the race at the socket boundary and fails pre-fix.
1 parent 6a8278d commit 2b0da0e

42 files changed

Lines changed: 4165 additions & 4483 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/.i18n/native-source.json‎

Lines changed: 151 additions & 102 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/macos/Package.resolved‎

Lines changed: 0 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/macos/Package.swift‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ let package = Package(
1616
],
1717
dependencies: [
1818
.package(url: "https://github.com/sindresorhus/KeyboardShortcuts", exact: "3.0.1"),
19-
.package(url: "https://github.com/orchetect/MenuBarExtraAccess", exact: "1.3.1"),
2019
.package(url: "https://github.com/swiftlang/swift-subprocess.git", from: "1.0.0"),
2120
.package(url: "https://github.com/apple/swift-log.git", from: "1.15.0"),
2221
.package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.9.6"),
@@ -65,7 +64,6 @@ let package = Package(
6564
.product(name: "OpenClawMLXTTSProtocol", package: "OpenClawMLXTTSProtocol"),
6665
.product(name: "OpenClawProtocol", package: "OpenClawKit"),
6766
.product(name: "SwabbleKit", package: "swabble"),
68-
.product(name: "MenuBarExtraAccess", package: "MenuBarExtraAccess"),
6967
.product(name: "Subprocess", package: "swift-subprocess"),
7068
.product(name: "Logging", package: "swift-log"),
7169
.product(name: "Sparkle", package: "Sparkle"),
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
import Darwin
2+
import Dispatch
3+
import Foundation
4+
import Observation
5+
import Security
6+
7+
enum AppInstanceLockAcquisition {
8+
case acquired(AppInstanceLock)
9+
case busy
10+
case failed(String)
11+
}
12+
13+
final class AppInstanceLock {
14+
/// Keep the descriptor open for the process lifetime. Never unlink the path:
15+
/// another opener could then lock a different inode and admit a duplicate.
16+
private let descriptor: Int32
17+
18+
private init(descriptor: Int32) {
19+
self.descriptor = descriptor
20+
}
21+
22+
static func acquire(url: URL, waitMilliseconds: Int = 0) -> AppInstanceLockAcquisition {
23+
if let error = self.preparePrivateStateRoot(url.deletingLastPathComponent()) {
24+
return .failed(error)
25+
}
26+
let descriptor = Darwin.open(url.path, O_CREAT | O_RDWR | O_CLOEXEC | O_NOFOLLOW, 0o600)
27+
guard descriptor >= 0 else { return .failed(String(cString: strerror(errno))) }
28+
var status = stat()
29+
guard fstat(descriptor, &status) == 0,
30+
status.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG),
31+
status.st_uid == geteuid()
32+
else {
33+
Darwin.close(descriptor)
34+
return .failed("Instance lock is not a safe file owned by the current user.")
35+
}
36+
_ = fchmod(descriptor, 0o600)
37+
let deadline = DispatchTime.now() + .milliseconds(max(0, waitMilliseconds))
38+
while flock(descriptor, LOCK_EX | LOCK_NB) != 0 {
39+
guard errno == EWOULDBLOCK, DispatchTime.now() < deadline else {
40+
let result: AppInstanceLockAcquisition = errno == EWOULDBLOCK
41+
? .busy
42+
: .failed(String(cString: strerror(errno)))
43+
Darwin.close(descriptor)
44+
return result
45+
}
46+
usleep(50000)
47+
}
48+
return .acquired(AppInstanceLock(descriptor: descriptor))
49+
}
50+
51+
private static func preparePrivateStateRoot(_ root: URL) -> String? {
52+
var status = stat()
53+
if lstat(root.path, &status) != 0 {
54+
guard errno == ENOENT else { return String(cString: strerror(errno)) }
55+
guard mkdir(root.path, 0o700) == 0 else { return String(cString: strerror(errno)) }
56+
guard lstat(root.path, &status) == 0 else { return String(cString: strerror(errno)) }
57+
}
58+
guard status.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR),
59+
status.st_uid == geteuid(),
60+
status.st_mode & 0o777 == 0o700
61+
else {
62+
return "App profile state directory must be an owner-only 0700 directory."
63+
}
64+
return nil
65+
}
66+
67+
deinit {
68+
_ = flock(self.descriptor, LOCK_UN)
69+
Darwin.close(self.descriptor)
70+
}
71+
}
72+
73+
@MainActor
74+
protocol UpdaterProviding: AnyObject {
75+
var automaticallyChecksForUpdates: Bool { get set }
76+
var automaticallyDownloadsUpdates: Bool { get set }
77+
var isAvailable: Bool { get }
78+
var updateStatus: UpdateStatus { get }
79+
func start()
80+
func startAfterResolvingGatewayUpdateChannel()
81+
func checkForUpdates(_ sender: Any?)
82+
}
83+
84+
extension UpdaterProviding {
85+
func start() {}
86+
87+
func startAfterResolvingGatewayUpdateChannel() {
88+
self.start()
89+
}
90+
}
91+
92+
/// No-op updater used for debug/dev runs to suppress Sparkle dialogs.
93+
final class DisabledUpdaterController: UpdaterProviding {
94+
var automaticallyChecksForUpdates: Bool = false
95+
var automaticallyDownloadsUpdates: Bool = false
96+
let isAvailable: Bool = false
97+
let updateStatus = UpdateStatus()
98+
func checkForUpdates(_: Any?) {}
99+
}
100+
101+
@MainActor
102+
@Observable
103+
final class UpdateStatus {
104+
var isUpdateReady: Bool
105+
106+
init(isUpdateReady: Bool = false) {
107+
self.isUpdateReady = isUpdateReady
108+
}
109+
}
110+
111+
#if canImport(Sparkle)
112+
import Sparkle
113+
114+
@MainActor
115+
final class SparkleUpdaterController: NSObject, UpdaterProviding {
116+
private lazy var controller = SPUStandardUpdaterController(
117+
startingUpdater: false,
118+
updaterDelegate: self,
119+
userDriverDelegate: nil)
120+
let updateStatus = UpdateStatus()
121+
private var started = false
122+
private var gatewayUpdateChannel: String?
123+
private var resolvingGatewayUpdateChannel = false
124+
private let gatewayUpdateChannelResolver: @MainActor @Sendable () async throws -> String?
125+
private let onStart: (() -> Void)?
126+
127+
init(
128+
savedAutoUpdate: Bool,
129+
gatewayUpdateChannelResolver: (@MainActor @Sendable () async throws -> String?)? = nil,
130+
onStart: (() -> Void)? = nil)
131+
{
132+
self.gatewayUpdateChannelResolver = gatewayUpdateChannelResolver ?? {
133+
struct UpdateStatusResponse: Decodable {
134+
let effectiveChannel: String?
135+
}
136+
guard let data = try? await GatewayConnection.shared.requestRaw(
137+
method: "update.status",
138+
timeoutMs: 5000),
139+
let response = try? JSONDecoder().decode(UpdateStatusResponse.self, from: data)
140+
else { return nil }
141+
return OpenClawConfigFile.normalizedGatewayUpdateChannel(response.effectiveChannel)
142+
}
143+
self.onStart = onStart
144+
super.init()
145+
let updater = self.controller.updater
146+
updater.automaticallyChecksForUpdates = savedAutoUpdate
147+
updater.automaticallyDownloadsUpdates = savedAutoUpdate
148+
}
149+
150+
func start() {
151+
guard !self.started else { return }
152+
self.started = true
153+
if let onStart = self.onStart {
154+
onStart()
155+
} else {
156+
self.controller.startUpdater()
157+
}
158+
}
159+
160+
func startAfterResolvingGatewayUpdateChannel() {
161+
guard !self.started, !self.resolvingGatewayUpdateChannel else { return }
162+
self.resolvingGatewayUpdateChannel = true
163+
Task { @MainActor [weak self] in
164+
guard let self else { return }
165+
defer { self.resolvingGatewayUpdateChannel = false }
166+
self.gatewayUpdateChannel = try? await self.gatewayUpdateChannelResolver()
167+
// Older or unreachable Gateways cannot report effectiveChannel. Preserve
168+
// their existing stable Sparkle behavior instead of disabling updates.
169+
self.start()
170+
}
171+
}
172+
173+
var automaticallyChecksForUpdates: Bool {
174+
get { self.controller.updater.automaticallyChecksForUpdates }
175+
set { self.controller.updater.automaticallyChecksForUpdates = newValue }
176+
}
177+
178+
var automaticallyDownloadsUpdates: Bool {
179+
get { self.controller.updater.automaticallyDownloadsUpdates }
180+
set { self.controller.updater.automaticallyDownloadsUpdates = newValue }
181+
}
182+
183+
var isAvailable: Bool {
184+
self.started
185+
}
186+
187+
func checkForUpdates(_ sender: Any?) {
188+
guard self.started else { return }
189+
self.controller.checkForUpdates(sender)
190+
}
191+
192+
func updater(_: SPUUpdater, didDownloadUpdate _: SUAppcastItem) {
193+
self.updateStatus.isUpdateReady = true
194+
}
195+
196+
func updater(_: SPUUpdater, failedToDownloadUpdate _: SUAppcastItem, error _: Error) {
197+
self.updateStatus.isUpdateReady = false
198+
}
199+
200+
func userDidCancelDownload(_: SPUUpdater) {
201+
self.updateStatus.isUpdateReady = false
202+
}
203+
204+
// periphery:ignore - Sparkle invokes this optional Objective-C delegate callback dynamically.
205+
func updater(
206+
_: SPUUpdater,
207+
userDidMakeChoice choice: SPUUserUpdateChoice,
208+
forUpdate _: SUAppcastItem,
209+
state: SPUUserUpdateState)
210+
{
211+
switch choice {
212+
case .install, .skip:
213+
self.updateStatus.isUpdateReady = false
214+
case .dismiss:
215+
self.updateStatus.isUpdateReady = (state.stage == .downloaded)
216+
@unknown default:
217+
self.updateStatus.isUpdateReady = false
218+
}
219+
}
220+
}
221+
222+
func allowedSparkleChannels(forGatewayUpdateChannel channel: String?) -> Set<String> {
223+
switch channel {
224+
case "beta", "dev":
225+
["beta"]
226+
case "extended-stable":
227+
["extended-stable"]
228+
default:
229+
[]
230+
}
231+
}
232+
233+
func isSparkleUpdateAllowed(itemChannel: String?, forGatewayUpdateChannel channel: String?) -> Bool {
234+
channel != "extended-stable" || itemChannel == "extended-stable"
235+
}
236+
237+
extension SparkleUpdaterController: SPUUpdaterDelegate {
238+
func allowedChannels(for _: SPUUpdater) -> Set<String> {
239+
allowedSparkleChannels(
240+
forGatewayUpdateChannel: self.gatewayUpdateChannel ?? OpenClawConfigFile.gatewayUpdateChannel())
241+
}
242+
243+
func bestValidUpdate(in appcast: SUAppcast, for _: SPUUpdater) -> SUAppcastItem? {
244+
guard self.gatewayUpdateChannel ?? OpenClawConfigFile.gatewayUpdateChannel() == "extended-stable" else {
245+
return nil
246+
}
247+
let comparator = SUStandardVersionComparator.default
248+
let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
249+
// Sparkle always admits the default channel. Filter it here so an
250+
// extended-stable Gateway is never prompted to leave its release train.
251+
let eligibleItems = appcast.items.filter {
252+
guard isSparkleUpdateAllowed(
253+
itemChannel: $0.channel,
254+
forGatewayUpdateChannel: "extended-stable")
255+
else { return false }
256+
guard let currentVersion else { return true }
257+
return comparator.compareVersion(
258+
$0.versionString,
259+
toVersion: currentVersion) == .orderedDescending
260+
}
261+
return eligibleItems.max { left, right in
262+
comparator.compareVersion(left.versionString, toVersion: right.versionString) == .orderedAscending
263+
}
264+
}
265+
266+
func updater(_: SPUUpdater, willInstallUpdate item: SUAppcastItem) {
267+
guard let currentVersion = GatewayEnvironment.appVersionString() else { return }
268+
PostAppUpdateReceiptStore.record(
269+
fromVersion: currentVersion,
270+
toVersion: item.displayVersionString)
271+
}
272+
}
273+
274+
private func isDeveloperIDSigned(bundleURL: URL) -> Bool {
275+
var staticCode: SecStaticCode?
276+
guard SecStaticCodeCreateWithPath(bundleURL as CFURL, SecCSFlags(), &staticCode) == errSecSuccess,
277+
let code = staticCode
278+
else { return false }
279+
280+
var infoCF: CFDictionary?
281+
guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &infoCF) == errSecSuccess,
282+
let info = infoCF as? [String: Any],
283+
let certs = info[kSecCodeInfoCertificates as String] as? [SecCertificate],
284+
let leaf = certs.first
285+
else {
286+
return false
287+
}
288+
289+
if let summary = SecCertificateCopySubjectSummary(leaf) as String? {
290+
return summary.hasPrefix("Developer ID Application:")
291+
}
292+
return false
293+
}
294+
295+
@MainActor
296+
func makeUpdaterController() -> UpdaterProviding {
297+
guard AppProfile.current.validationError == nil, !AppProfile.current.isActive else {
298+
return DisabledUpdaterController()
299+
}
300+
let bundleURL = Bundle.main.bundleURL
301+
let isBundledApp = bundleURL.pathExtension == "app"
302+
guard isBundledApp, isDeveloperIDSigned(bundleURL: bundleURL) else { return DisabledUpdaterController() }
303+
304+
let defaults = AppDefaults.standard
305+
let autoUpdateKey = "autoUpdateEnabled"
306+
// Default to true; honor the user's last choice otherwise.
307+
let savedAutoUpdate = (defaults.object(forKey: autoUpdateKey) as? Bool) ?? true
308+
return SparkleUpdaterController(savedAutoUpdate: savedAutoUpdate)
309+
}
310+
#else
311+
@MainActor
312+
func makeUpdaterController() -> UpdaterProviding {
313+
DisabledUpdaterController()
314+
}
315+
#endif

0 commit comments

Comments
 (0)