@deepseek-ai/dsh-experimental-cua-macos 0.2.2-alpha.2 → 0.2.2-alpha.3

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 (43) hide show
  1. package/README.i18n.yaml +6 -6
  2. package/README.md +14 -9
  3. package/README.zh.md +14 -9
  4. package/cua-helper.json +16 -0
  5. package/lib/index.js +190 -98
  6. package/lib/types/index.d.ts +61 -3
  7. package/lib/types/native-build.d.ts +12 -12
  8. package/lib/types/permission-guide.d.ts +23 -0
  9. package/native/DSHComputerUse.icns +0 -0
  10. package/native/Info.plist +24 -0
  11. package/native/LICENSE.computer-use-icon +18 -0
  12. package/native/README.md +24 -6
  13. package/native/README.zh.md +24 -6
  14. package/native/Sources/CuaNative/Main.swift +40 -27
  15. package/native/Sources/CuaNative/NativeProtocol.generated.swift +2 -2
  16. package/native/Sources/CuaNative/PermissionGuide.swift +404 -0
  17. package/native/Sources/CuaNative/Permissions.swift +79 -19
  18. package/native/Sources/CuaNative/RequestCoordinator.swift +10 -3
  19. package/native/Sources/CuaNative/SharedHelperProxy.swift +7 -7
  20. package/native/Sources/CuaNative/SharedHelperRuntime.swift +106 -51
  21. package/native/Sources/CuaNative/SharedHelperServer.swift +2 -2
  22. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/CodeResources +0 -0
  23. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/Info.plist +24 -0
  24. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/MacOS/dsh-cua-native +0 -0
  25. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/Resources/DSHComputerUse.icns +0 -0
  26. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/Resources/LICENSE.computer-use-icon +18 -0
  27. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/Resources/LICENSE.cua-driver +21 -0
  28. package/native/bin/darwin-arm64/007deaf0f4b6b473af03a201a5042208f8249172c41c27894bc09241e5e3f19b/DSH Computer Use.app/Contents/_CodeSignature/CodeResources +150 -0
  29. package/native/bin/darwin-arm64/current.json +1 -0
  30. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/CodeResources +0 -0
  31. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/Info.plist +24 -0
  32. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/MacOS/dsh-cua-native +0 -0
  33. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/Resources/DSHComputerUse.icns +0 -0
  34. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/Resources/LICENSE.computer-use-icon +18 -0
  35. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/Resources/LICENSE.cua-driver +21 -0
  36. package/native/bin/darwin-x64/9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2/DSH Computer Use.app/Contents/_CodeSignature/CodeResources +150 -0
  37. package/native/bin/darwin-x64/current.json +1 -0
  38. package/native/build_app.py +85 -0
  39. package/native/protocol.schema.json +38 -2
  40. package/native/tests/swift/SharedHelperTests.swift +52 -0
  41. package/native/tests/swift/SystemPermissionsTests.swift +245 -0
  42. package/native/upstream.json +1 -0
  43. package/package.json +53 -46
@@ -0,0 +1,404 @@
1
+ // A helper-owned drag source accompanies System Settings without requiring Accessibility access.
2
+ import AppKit
3
+ import ApplicationServices
4
+ import Foundation
5
+
6
+ struct PermissionGuideText: Sendable {
7
+ let instruction: String
8
+ let backLabel: String
9
+ let finderLabel: String
10
+ let unavailableMessage: String
11
+ let settingsMessage: String
12
+ }
13
+
14
+ struct PermissionGuideApplication: Sendable {
15
+ let url: URL
16
+ let identifier: String
17
+ var name: String { url.lastPathComponent }
18
+
19
+ func validatedURL() throws(NativeFailure) -> URL {
20
+ guard url.isFileURL, url.pathExtension == "app",
21
+ let application = InstalledApplication.read(url), application.bundleID == identifier,
22
+ FileManager.default.isExecutableFile(atPath: application.executablePath) else {
23
+ throw NativeFailure(code: "APPLICATION_UNAVAILABLE", message: "The permission application is unavailable; enable Computer Use again")
24
+ }
25
+ return url
26
+ }
27
+ }
28
+
29
+ @MainActor protocol PermissionGuidePresenting: AnyObject {
30
+ func show(application: PermissionGuideApplication, text: PermissionGuideText, owner: UUID,
31
+ interval: TimeInterval, granted: @escaping @MainActor () -> Bool) throws(NativeFailure)
32
+ func reportSettingsFailure()
33
+ func dismiss()
34
+ func close(owner: UUID)
35
+ }
36
+
37
+ struct PermissionGuideWindow {
38
+ let id: CGWindowID
39
+ let frame: CGRect
40
+ }
41
+
42
+ enum PermissionGuidePlacement {
43
+ /// Bind to the largest settings window once; dialogs never replace an existing anchor.
44
+ static func target(in windows: [PermissionGuideWindow], pinned: CGWindowID?) -> PermissionGuideWindow? {
45
+ if let pinned { return windows.first { $0.id == pinned } }
46
+ return windows.max { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height }
47
+ }
48
+
49
+ /// Keep the guide adjacent to its parent without repeating an already satisfied WindowServer order.
50
+ static func needsOrdering(guide: CGWindowID, above target: CGWindowID, frontToBack: [CGWindowID]) -> Bool {
51
+ guard let targetIndex = frontToBack.firstIndex(of: target) else { return false }
52
+ guard let guideIndex = frontToBack.firstIndex(of: guide) else { return true }
53
+ return guideIndex + 1 != targetIndex
54
+ }
55
+
56
+ /// AppKit coordinates; the guide overlays the settings window's lower margin and stays on screen.
57
+ static func frame(settings: CGRect?, visible: CGRect, size: CGSize) -> CGRect {
58
+ let width = min(size.width, max(1, visible.width - 24))
59
+ let height = min(size.height, max(1, visible.height - 24))
60
+ let x = min(max((settings?.midX ?? visible.midX) - width / 2, visible.minX + 12), visible.maxX - width - 12)
61
+ let y = min(max((settings?.minY ?? visible.minY) + 8, visible.minY + 12), visible.maxY - height - 12)
62
+ return CGRect(x: x, y: y, width: width, height: height)
63
+ }
64
+ }
65
+
66
+ @MainActor final class PermissionGuide: NSObject, PermissionGuidePresenting, NSWindowDelegate {
67
+ private var panel: PermissionGuidePanel?
68
+ private var timer: Timer?
69
+ private var owner: UUID?
70
+ private var returnApplication: NSRunningApplication?
71
+ private var granted: (@MainActor () -> Bool)?
72
+ private var failureLabel: NSTextField?
73
+ private var instructionLabel: NSTextField?
74
+ private var text: PermissionGuideText?
75
+ private var settingsWindowID: CGWindowID?
76
+ private var dragging = false
77
+ private var settingsOpenFailed = false
78
+
79
+ func show(application: PermissionGuideApplication, text: PermissionGuideText, owner: UUID,
80
+ interval: TimeInterval, granted: @escaping @MainActor () -> Bool) throws(NativeFailure) {
81
+ let previousApplication = NSWorkspace.shared.frontmostApplication
82
+ dismiss(activatePrevious: false)
83
+ _ = try application.validatedURL()
84
+ self.owner = owner
85
+ self.text = text
86
+ self.granted = granted
87
+ returnApplication = previousApplication?.bundleIdentifier == "com.apple.systempreferences" ? nil : previousApplication
88
+ settingsWindowID = nil
89
+ dragging = false
90
+ settingsOpenFailed = false
91
+
92
+ let panel = PermissionGuidePanel(contentRect: NSRect(x: 0, y: 0, width: 620, height: 128),
93
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
94
+ panel.delegate = self
95
+ panel.title = application.name
96
+ panel.isReleasedWhenClosed = false
97
+ panel.isOpaque = false
98
+ panel.backgroundColor = .clear
99
+ panel.hasShadow = true
100
+ panel.level = .normal
101
+ panel.isFloatingPanel = false
102
+ panel.hidesOnDeactivate = false
103
+ panel.becomesKeyOnlyIfNeeded = true
104
+ panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary]
105
+ panel.onDismiss = { [weak self] in self?.dismiss(activatePrevious: true) }
106
+ panel.setAccessibilityLabel(text.instruction.replacingOccurrences(of: "{application}", with: application.name))
107
+
108
+ let surface = NSVisualEffectView()
109
+ surface.material = .popover
110
+ surface.blendingMode = .behindWindow
111
+ surface.state = .active
112
+ surface.wantsLayer = true
113
+ surface.layer?.cornerRadius = 18
114
+ surface.layer?.borderWidth = 0.5
115
+ surface.layer?.borderColor = NSColor.separatorColor.cgColor
116
+ surface.layer?.masksToBounds = true
117
+ surface.maskImage = PermissionGuideAppearance.materialMask()
118
+ panel.contentView = surface
119
+
120
+ let arrow = NSImageView()
121
+ arrow.image = NSImage(systemSymbolName: "arrow.up", accessibilityDescription: nil)?
122
+ .withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 27, weight: .semibold))
123
+ arrow.contentTintColor = .systemBlue
124
+ arrow.translatesAutoresizingMaskIntoConstraints = false
125
+ let instruction = NSTextField(wrappingLabelWithString:
126
+ text.instruction.replacingOccurrences(of: "{application}", with: application.name))
127
+ instruction.font = .systemFont(ofSize: 14)
128
+ instruction.textColor = .secondaryLabelColor
129
+ instruction.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
130
+ let headingInset = NSView()
131
+ headingInset.translatesAutoresizingMaskIntoConstraints = false
132
+ let heading = NSStackView(views: [headingInset, arrow, instruction])
133
+ heading.orientation = .horizontal
134
+ heading.alignment = .centerY
135
+ heading.spacing = 10
136
+
137
+ let back = NSButton(image: NSImage(systemSymbolName: "chevron.left", accessibilityDescription: text.backLabel) ?? NSImage(),
138
+ target: self, action: #selector(goBack))
139
+ back.bezelStyle = .circular
140
+ back.toolTip = text.backLabel
141
+ back.setAccessibilityLabel(text.backLabel)
142
+ back.translatesAutoresizingMaskIntoConstraints = false
143
+ let item = PermissionApplicationView(application: application, finderLabel: text.finderLabel,
144
+ dragBegan: { [weak self, weak panel] in
145
+ guard let self, let panel, self.panel === panel else { return }
146
+ self.dragging = true
147
+ panel.orderOut(nil)
148
+ }, dragEnded: { [weak self, weak panel] operation in
149
+ guard let self, let panel, self.panel === panel else { return }
150
+ self.dragging = false
151
+ if operation.isEmpty { self.update() }
152
+ else { self.dismiss(activatePrevious: false) }
153
+ }, reportFailure: { [weak self] in self?.showFailure(text.unavailableMessage) })
154
+ panel.initialFirstResponder = item
155
+ let row = NSStackView(views: [back, item])
156
+ row.orientation = .horizontal
157
+ row.alignment = .centerY
158
+ row.spacing = 12
159
+ let failure = NSTextField(wrappingLabelWithString: "")
160
+ failure.font = .systemFont(ofSize: 12)
161
+ failure.textColor = .systemRed
162
+ failure.isHidden = true
163
+ let content = NSStackView(views: [heading, row, failure])
164
+ content.orientation = .vertical
165
+ content.alignment = .leading
166
+ content.spacing = 10
167
+ content.translatesAutoresizingMaskIntoConstraints = false
168
+ surface.addSubview(content)
169
+ NSLayoutConstraint.activate([
170
+ content.leadingAnchor.constraint(equalTo: surface.leadingAnchor, constant: 16),
171
+ content.trailingAnchor.constraint(equalTo: surface.trailingAnchor, constant: -16),
172
+ content.topAnchor.constraint(equalTo: surface.topAnchor, constant: 14),
173
+ content.bottomAnchor.constraint(lessThanOrEqualTo: surface.bottomAnchor, constant: -14),
174
+ heading.widthAnchor.constraint(equalTo: content.widthAnchor),
175
+ row.widthAnchor.constraint(equalTo: content.widthAnchor),
176
+ failure.widthAnchor.constraint(equalTo: content.widthAnchor),
177
+ headingInset.widthAnchor.constraint(equalToConstant: 42),
178
+ arrow.widthAnchor.constraint(equalToConstant: 28), arrow.heightAnchor.constraint(equalToConstant: 32),
179
+ back.widthAnchor.constraint(equalToConstant: 30), back.heightAnchor.constraint(equalToConstant: 30),
180
+ item.heightAnchor.constraint(equalToConstant: 44),
181
+ ])
182
+ self.panel = panel
183
+ failureLabel = failure
184
+ instructionLabel = instruction
185
+ update()
186
+ guard self.panel === panel else { return }
187
+ let timer = Timer(timeInterval: interval, repeats: true) { [weak self] _ in
188
+ MainActor.assumeIsolated { self?.update() }
189
+ }
190
+ self.timer = timer
191
+ RunLoop.main.add(timer, forMode: .common)
192
+ }
193
+
194
+ func reportSettingsFailure() {
195
+ settingsOpenFailed = true
196
+ if let text { showFailure(text.settingsMessage) }
197
+ }
198
+
199
+ func dismiss() { dismiss(activatePrevious: false) }
200
+
201
+ func close(owner: UUID) {
202
+ guard self.owner == owner else { return }
203
+ dismiss(activatePrevious: false)
204
+ }
205
+
206
+ func windowWillClose(_ notification: Notification) {
207
+ guard let window = notification.object as? NSWindow, window === panel else { return }
208
+ dismiss(activatePrevious: false)
209
+ }
210
+
211
+ @objc private func goBack() { dismiss(activatePrevious: true) }
212
+
213
+ private func dismiss(activatePrevious: Bool) {
214
+ timer?.invalidate()
215
+ timer = nil
216
+ let previous = returnApplication
217
+ returnApplication = nil
218
+ let window = panel
219
+ panel = nil
220
+ owner = nil
221
+ granted = nil
222
+ failureLabel = nil
223
+ instructionLabel = nil
224
+ text = nil
225
+ settingsWindowID = nil
226
+ dragging = false
227
+ settingsOpenFailed = false
228
+ window?.close()
229
+ if activatePrevious, let previous, !previous.isTerminated { _ = previous.activate(options: []) }
230
+ }
231
+
232
+ private func showFailure(_ message: String) {
233
+ failureLabel?.stringValue = message
234
+ failureLabel?.isHidden = false
235
+ updatePosition()
236
+ }
237
+
238
+ private func update() {
239
+ guard panel != nil, !dragging else { return }
240
+ if granted?() == true { dismiss(activatePrevious: false); return }
241
+ updatePosition()
242
+ }
243
+
244
+ private func updatePosition() {
245
+ guard let panel, !dragging, let primary = NSScreen.screens.first else { return }
246
+ let snapshot = Self.settingsWindows(primaryHeight: primary.frame.height)
247
+ let target = PermissionGuidePlacement.target(in: snapshot.targets, pinned: settingsWindowID)
248
+ if let target { settingsWindowID = target.id }
249
+ else if settingsWindowID != nil { dismiss(activatePrevious: false); return }
250
+ else if !settingsOpenFailed { return }
251
+ let settings = target?.frame
252
+ let screen = NSScreen.screens.max { left, right in
253
+ let target = settings ?? primary.frame
254
+ let a = left.frame.intersection(target), b = right.frame.intersection(target)
255
+ return (a.isNull ? 0 : a.width * a.height) < (b.isNull ? 0 : b.width * b.height)
256
+ } ?? primary
257
+ let width = min(620, max(360, (settings?.width ?? screen.visibleFrame.width) - 48), screen.visibleFrame.width - 24)
258
+ instructionLabel?.preferredMaxLayoutWidth = width - 122
259
+ failureLabel?.preferredMaxLayoutWidth = width - 32
260
+ let headingHeight = max(32, instructionLabel?.fittingSize.height ?? 32)
261
+ let failureHeight = failureLabel?.isHidden == false ? 10 + (failureLabel?.fittingSize.height ?? 0) : 0
262
+ let height = max(128, ceil(headingHeight + 10 + 44 + 28 + failureHeight))
263
+ let frame = PermissionGuidePlacement.frame(settings: settings, visible: screen.visibleFrame, size: CGSize(width: width, height: height))
264
+ if panel.frame != frame {
265
+ panel.setFrame(frame, display: true)
266
+ panel.invalidateShadow()
267
+ }
268
+ if let target {
269
+ if PermissionGuidePlacement.needsOrdering(guide: CGWindowID(panel.windowNumber), above: target.id, frontToBack: snapshot.order) {
270
+ panel.order(.above, relativeTo: Int(target.id))
271
+ }
272
+ } else if !panel.isVisible { panel.orderFrontRegardless() }
273
+ }
274
+
275
+ private static func settingsWindows(primaryHeight: CGFloat) -> (targets: [PermissionGuideWindow], order: [CGWindowID]) {
276
+ guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.systempreferences").first,
277
+ let windows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { return ([], []) }
278
+ let order = windows.compactMap { window -> CGWindowID? in
279
+ guard (window[kCGWindowLayer as String] as? NSNumber)?.intValue == 0 else { return nil }
280
+ return (window[kCGWindowNumber as String] as? NSNumber)?.uint32Value
281
+ }
282
+ let targets = windows.compactMap { window -> PermissionGuideWindow? in
283
+ guard (window[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == app.processIdentifier,
284
+ (window[kCGWindowLayer as String] as? NSNumber)?.intValue == 0,
285
+ let id = window[kCGWindowNumber as String] as? NSNumber,
286
+ let bounds = window[kCGWindowBounds as String] as? [String: Any],
287
+ let frame = CGRect(dictionaryRepresentation: bounds as CFDictionary), frame.width > 200, frame.height > 200 else { return nil }
288
+ return PermissionGuideWindow(id: id.uint32Value,
289
+ frame: CGRect(x: frame.minX, y: primaryHeight - frame.maxY, width: frame.width, height: frame.height))
290
+ }
291
+ return (targets, order)
292
+ }
293
+ }
294
+
295
+ @MainActor enum PermissionGuideAppearance {
296
+ /// The material mask also defines the window shadow; layer clipping alone leaves the backdrop rectangular.
297
+ static func materialMask() -> NSImage {
298
+ let radius: CGFloat = 18
299
+ let size = NSSize(width: radius * 2 + 1, height: radius * 2 + 1)
300
+ let image = NSImage(size: size, flipped: false) { rect in
301
+ NSColor.black.setFill()
302
+ NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill()
303
+ return true
304
+ }
305
+ image.capInsets = NSEdgeInsets(top: radius, left: radius, bottom: radius, right: radius)
306
+ image.resizingMode = .stretch
307
+ return image
308
+ }
309
+ }
310
+
311
+ @MainActor private final class PermissionGuidePanel: NSPanel {
312
+ var onDismiss: (() -> Void)?
313
+ override var canBecomeKey: Bool { true }
314
+ override func cancelOperation(_ sender: Any?) { onDismiss?() }
315
+ }
316
+
317
+ @MainActor private final class PermissionApplicationView: NSView, NSDraggingSource {
318
+ private let application: PermissionGuideApplication
319
+ private let reportFailure: () -> Void
320
+ private let dragBegan: () -> Void
321
+ private let dragEnded: (NSDragOperation) -> Void
322
+ private let icon: NSImage
323
+
324
+ init(application: PermissionGuideApplication, finderLabel: String, dragBegan: @escaping () -> Void,
325
+ dragEnded: @escaping (NSDragOperation) -> Void, reportFailure: @escaping () -> Void) {
326
+ self.application = application
327
+ self.reportFailure = reportFailure
328
+ self.dragBegan = dragBegan
329
+ self.dragEnded = dragEnded
330
+ icon = NSWorkspace.shared.icon(forFile: application.url.path)
331
+ super.init(frame: .zero)
332
+ translatesAutoresizingMaskIntoConstraints = false
333
+ wantsLayer = true
334
+ layer?.backgroundColor = NSColor.controlBackgroundColor.cgColor
335
+ layer?.cornerRadius = 8
336
+ layer?.borderWidth = 0.5
337
+ layer?.borderColor = NSColor.separatorColor.cgColor
338
+ let image = NSImageView(image: icon)
339
+ let label = NSTextField(labelWithString: application.name)
340
+ label.font = .systemFont(ofSize: 15)
341
+ image.translatesAutoresizingMaskIntoConstraints = false
342
+ label.translatesAutoresizingMaskIntoConstraints = false
343
+ addSubview(image)
344
+ addSubview(label)
345
+ NSLayoutConstraint.activate([
346
+ image.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
347
+ image.centerYAnchor.constraint(equalTo: centerYAnchor),
348
+ image.widthAnchor.constraint(equalToConstant: 30), image.heightAnchor.constraint(equalToConstant: 30),
349
+ label.leadingAnchor.constraint(equalTo: image.trailingAnchor, constant: 10),
350
+ label.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -10),
351
+ label.centerYAnchor.constraint(equalTo: centerYAnchor),
352
+ ])
353
+ setAccessibilityElement(true)
354
+ setAccessibilityRole(.button)
355
+ setAccessibilityLabel(application.name)
356
+ setAccessibilityHelp(finderLabel)
357
+ let menu = NSMenu()
358
+ let reveal = NSMenuItem(title: finderLabel, action: #selector(showInFinder), keyEquivalent: "")
359
+ reveal.target = self
360
+ menu.addItem(reveal)
361
+ self.menu = menu
362
+ }
363
+
364
+ required init?(coder: NSCoder) { return nil }
365
+ override var acceptsFirstResponder: Bool { true }
366
+ override var needsPanelToBecomeKey: Bool { true }
367
+ override func hitTest(_ point: NSPoint) -> NSView? { super.hitTest(point) == nil ? nil : self }
368
+ override func resetCursorRects() { addCursorRect(bounds, cursor: .openHand) }
369
+ override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); updateColors() }
370
+ override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance(); updateColors() }
371
+
372
+ private func updateColors() {
373
+ effectiveAppearance.performAsCurrentDrawingAppearance {
374
+ layer?.backgroundColor = NSColor.controlBackgroundColor.cgColor
375
+ layer?.borderColor = NSColor.separatorColor.cgColor
376
+ }
377
+ }
378
+
379
+ override func mouseDown(with event: NSEvent) { window?.makeFirstResponder(self) }
380
+
381
+ override func mouseDragged(with event: NSEvent) {
382
+ do {
383
+ let item = NSDraggingItem(pasteboardWriter: try application.validatedURL() as NSURL)
384
+ item.setDraggingFrame(NSRect(x: 10, y: 7, width: 30, height: 30), contents: icon)
385
+ beginDraggingSession(with: [item], event: event, source: self)
386
+ } catch { reportFailure() }
387
+ }
388
+
389
+ override func accessibilityPerformPress() -> Bool { showInFinder(); return true }
390
+ override func keyDown(with event: NSEvent) {
391
+ if event.keyCode == 36 || event.keyCode == 49 { showInFinder() }
392
+ else { super.keyDown(with: event) }
393
+ }
394
+
395
+ func draggingSession(_ session: NSDraggingSession, willBeginAt screenPoint: NSPoint) { dragBegan() }
396
+ func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { dragEnded(operation) }
397
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .copy }
398
+ func ignoreModifierKeys(for session: NSDraggingSession) -> Bool { true }
399
+
400
+ @objc private func showInFinder() {
401
+ do { NSWorkspace.shared.activateFileViewerSelecting([try application.validatedURL()]) }
402
+ catch { reportFailure() }
403
+ }
404
+ }
@@ -1,49 +1,103 @@
1
- // System consent is requested only by the Host's user-facing permission controls.
1
+ // System permission guidance belongs to the native application whose bundle the user authorizes.
2
2
  import AppKit
3
3
  @preconcurrency import ApplicationServices
4
4
  import Darwin
5
5
  import Foundation
6
6
 
7
- @MainActor struct SystemPermissions {
7
+ @MainActor struct SystemPermissionActions {
8
+ var accessibility: @MainActor () -> Bool
9
+ var screenRecording: @MainActor () -> Bool
10
+ var open: (URL) -> Bool
11
+
12
+ static func system() -> Self {
13
+ Self(accessibility: { AXIsProcessTrusted() }, screenRecording: { CGPreflightScreenCaptureAccess() },
14
+ open: { NSWorkspace.shared.open($0) })
15
+ }
16
+ }
17
+
18
+ @MainActor final class SystemPermissions {
19
+ /// Captured at startup because a launcher can exit before permission is requested.
8
20
  private let launchApplication: JSONValue?
21
+ private let actions: SystemPermissionActions
22
+ private let guide: any PermissionGuidePresenting
9
23
 
10
- // Capture the system-reported responsible app before startup completes and the launcher can exit.
11
- init() { launchApplication = Self.responsibleApplication(for: getpid()) }
24
+ init() {
25
+ launchApplication = Self.responsibleApplication(for: getpid())
26
+ ?? Self.application(Bundle.main.bundleURL, identifier: Bundle.main.bundleIdentifier)
27
+ actions = .system()
28
+ guide = PermissionGuide()
29
+ }
30
+
31
+ init(application: JSONValue?, actions: SystemPermissionActions, guide: any PermissionGuidePresenting) {
32
+ launchApplication = application
33
+ self.actions = actions
34
+ self.guide = guide
35
+ }
12
36
 
13
37
  func status() -> JSONValue {
14
38
  var result: [String: JSONValue] = [
15
- "accessibility": .bool(AXIsProcessTrusted()),
16
- "screenRecording": .bool(CGPreflightScreenCaptureAccess()),
39
+ "accessibility": .bool(actions.accessibility()),
40
+ "screenRecording": .bool(actions.screenRecording()),
17
41
  "helper": Self.process(getpid()),
18
42
  "parent": Self.process(getppid()),
19
43
  ]
20
- if let launchApplication { result["launchApplication"] = launchApplication }
44
+ if let launchApplication, case .object(var application) = launchApplication {
45
+ application.removeValue(forKey: "bundleId")
46
+ result["launchApplication"] = .object(application)
47
+ }
21
48
  return .object(result)
22
49
  }
23
50
 
24
- func request(_ permission: String) throws -> JSONValue {
51
+ func request(_ permission: String, owner: UUID, text: PermissionGuideText, interval: TimeInterval) throws -> JSONValue {
52
+ let observe: @MainActor () -> Bool
25
53
  switch permission {
26
- case "accessibility":
27
- if !AXIsProcessTrusted() {
28
- let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
29
- _ = AXIsProcessTrustedWithOptions(options)
30
- }
31
- case "screenRecording":
32
- if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }
54
+ case "accessibility": observe = actions.accessibility
55
+ case "screenRecording": observe = actions.screenRecording
33
56
  default: throw RequestParameters.invalid("permission must be accessibility or screenRecording")
34
57
  }
58
+ var guideFailure: NativeFailure?
59
+ if !observe() {
60
+ do throws(NativeFailure) {
61
+ guard let path = launchApplication?["path"].string, let identifier = launchApplication?["bundleId"].string else {
62
+ throw NativeFailure(code: "APPLICATION_UNAVAILABLE", message: text.unavailableMessage)
63
+ }
64
+ try guide.show(application: PermissionGuideApplication(url: URL(fileURLWithPath: path), identifier: identifier),
65
+ text: text, owner: owner, interval: interval, granted: observe)
66
+ } catch {
67
+ guide.dismiss()
68
+ guideFailure = error.code == "APPLICATION_UNAVAILABLE"
69
+ ? NativeFailure(code: error.code, message: text.unavailableMessage) : error
70
+ }
71
+ } else { guide.dismiss() }
72
+ do { _ = try openPane(permission) }
73
+ catch {
74
+ guide.reportSettingsFailure()
75
+ let message = guideFailure.map { $0.message + "\n" } ?? ""
76
+ throw NativeFailure(code: error.code, message: message + text.settingsMessage)
77
+ }
78
+ if let guideFailure { throw guideFailure }
35
79
  return status()
36
80
  }
37
81
 
38
- func openSettings(_ permission: String) throws -> JSONValue {
82
+ func closeGuide(owner: UUID) { guide.close(owner: owner) }
83
+
84
+ func openSettings(_ permission: String, failureMessage: String) throws(NativeFailure) -> JSONValue {
85
+ guide.dismiss()
86
+ do { return try openPane(permission) }
87
+ catch {
88
+ guard error.code == "SETTINGS_UNAVAILABLE" else { throw error }
89
+ throw NativeFailure(code: error.code, message: failureMessage)
90
+ }
91
+ }
92
+
93
+ private func openPane(_ permission: String) throws(NativeFailure) -> JSONValue {
39
94
  let pane: String
40
95
  switch permission {
41
96
  case "accessibility": pane = "Privacy_Accessibility"
42
97
  case "screenRecording": pane = "Privacy_ScreenCapture"
43
98
  default: throw RequestParameters.invalid("permission must be accessibility or screenRecording")
44
99
  }
45
- guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?\(pane)"),
46
- NSWorkspace.shared.open(url) else {
100
+ guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?\(pane)"), actions.open(url) else {
47
101
  throw NativeFailure(code: "SETTINGS_UNAVAILABLE", message: "Open System Settings > Privacy & Security manually")
48
102
  }
49
103
  return .object(["opened": .bool(true)])
@@ -54,7 +108,13 @@ import Foundation
54
108
  guard let responsible = NativePlatform.responsiblePID(pid),
55
109
  let app = NSRunningApplication(processIdentifier: responsible), !app.isTerminated,
56
110
  let bundle = app.bundleURL else { return nil }
57
- var result: [String: JSONValue] = ["name": .string(bundle.lastPathComponent), "path": .string(bundle.path)]
111
+ return application(bundle, identifier: app.bundleIdentifier)
112
+ }
113
+
114
+ private static func application(_ bundle: URL, identifier: String?) -> JSONValue? {
115
+ guard bundle.pathExtension == "app", let identifier else { return nil }
116
+ var result: [String: JSONValue] = ["name": .string(bundle.lastPathComponent), "path": .string(bundle.path),
117
+ "bundleId": .string(identifier)]
58
118
  if let icon = ApplicationCatalog.icon(at: bundle.path) { result["icon"] = .string(icon) }
59
119
  return .object(result)
60
120
  }
@@ -10,6 +10,7 @@ import Darwin
10
10
  private let worker: AXWorker
11
11
  private let capture: WindowCapture
12
12
  private let permissions: SystemPermissions
13
+ private let permissionOwner: UUID
13
14
  private let clipboard = ClipboardPaste()
14
15
  private let input: JSONLInput
15
16
  private let writer: JSONLWriter
@@ -28,12 +29,13 @@ import Darwin
28
29
  private var nextCancelled = false
29
30
 
30
31
  init(configuration: HelperConfiguration, capture: WindowCapture, channel: SharedSocket,
31
- cancellation: CancellationLatch, scheduler: RequestScheduler, writer: JSONLWriter, permissions: SystemPermissions,
32
+ cancellation: CancellationLatch, scheduler: RequestScheduler, writer: JSONLWriter, permissions: SystemPermissions, permissionOwner: UUID,
32
33
  onClose: @escaping @MainActor @Sendable () -> Void,
33
34
  onFatal: @escaping @Sendable (NativeFailure, Double) -> Void) {
34
35
  self.configuration = configuration
35
36
  self.capture = capture
36
37
  self.permissions = permissions
38
+ self.permissionOwner = permissionOwner
37
39
  self.cancellation = cancellation
38
40
  self.channel = channel
39
41
  self.scheduler = scheduler
@@ -176,9 +178,13 @@ import Darwin
176
178
  }
177
179
  result = .object(icons)
178
180
  } else if request.method == "requestPermission" {
179
- result = try permissions.request(params.string("permission"))
181
+ let text = try PermissionGuideText(instruction: params.string("instruction"), backLabel: params.string("backLabel"),
182
+ finderLabel: params.string("finderLabel"), unavailableMessage: params.string("unavailableMessage"),
183
+ settingsMessage: params.string("settingsMessage"))
184
+ result = try permissions.request(params.string("permission"), owner: permissionOwner, text: text,
185
+ interval: Double(params.integer("pollIntervalMs", in: 100...Int(Int32.max))) / 1000)
180
186
  } else if request.method == "openPermissionSettings" {
181
- result = try permissions.openSettings(params.string("permission"))
187
+ result = try permissions.openSettings(params.string("permission"), failureMessage: params.string("settingsMessage"))
182
188
  } else if request.method == "findApps" {
183
189
  result = .array(try ApplicationDiscovery.applications(matching: params.string("query"), exact: false,
184
190
  limit: params.integer("maxAppMatches", in: 1...1000), cancellation: cancellation).map { $0.json(catalog: catalog) })
@@ -250,6 +256,7 @@ import Darwin
250
256
  private func shutdown() {
251
257
  guard !stopping else { return }
252
258
  stopping = true
259
+ permissions.closeGuide(owner: permissionOwner)
253
260
  cancellation.cancel()
254
261
  deadline?.cancel()
255
262
  deadline = nil
@@ -3,14 +3,14 @@ import Foundation
3
3
  import CryptoKit
4
4
  import Darwin
5
5
 
6
- enum SharedHelperProxy {
7
- static func run(configuration: HelperConfiguration) throws {
6
+ @MainActor enum SharedHelperProxy {
7
+ static func run(configuration: HelperConfiguration) async throws {
8
8
  guard let executable = NativePlatform.executablePath(getpid()) else { throw SharedSocket.failure("Resolving helper executable") }
9
9
  let digest = SHA256.hash(data: try Data(contentsOf: URL(fileURLWithPath: executable), options: .mappedIfSafe))
10
10
  .map { String(format: "%02x", $0) }.joined()
11
11
  let options = try SharedHelperOptions(arguments: ["--ensure-shared", "--runtime-key", digest,
12
12
  "--runtime-directory", "/tmp/dsh-cua-\(getuid())", "--startup-timeout-ms", String(configuration.timeoutSeconds * 1000)])
13
- let channel = try connect(options)
13
+ let channel = try await connect(options)
14
14
  defer { channel.shutdown() }
15
15
  let hello = JSONValue.object(["type": .string("hello"), "protocol": .number(1), "runtimeKey": .string(digest), "config": .object([
16
16
  "maxRequestBytes": .number(Double(configuration.maxRequestBytes)), "maxResponseBytes": .number(Double(configuration.maxResponseBytes)),
@@ -67,10 +67,10 @@ enum SharedHelperProxy {
67
67
  return true
68
68
  }
69
69
 
70
- private static func connect(_ options: SharedHelperOptions) throws -> SharedSocket {
71
- let started = DispatchTime.now().uptimeNanoseconds
70
+ private static func connect(_ options: SharedHelperOptions) async throws -> SharedSocket {
71
+ let deadline = options.startupDeadline()
72
72
  repeat {
73
- try SharedHelperLauncher.ensure(options, publishReady: false)
73
+ try await SharedHelperLauncher.ensure(options, publishReady: false, deadline: deadline)
74
74
  let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
75
75
  guard descriptor >= 0 else { throw SharedSocket.failure("Creating stdio client socket") }
76
76
  let channel = SharedSocket(descriptor: descriptor)
@@ -85,7 +85,7 @@ enum SharedHelperProxy {
85
85
  let error = errno
86
86
  guard error == ENOENT || error == ECONNREFUSED else { throw SharedSocket.failure("Connecting stdio client") }
87
87
  usleep(10_000)
88
- } while Double(DispatchTime.now().uptimeNanoseconds - started) / 1_000_000_000 < options.startupTimeout
88
+ } while DispatchTime.now().uptimeNanoseconds < deadline
89
89
  throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Shared helper did not accept the stdio client")
90
90
  }
91
91