@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,150 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>files</key>
6
+ <dict>
7
+ <key>Resources/DSHComputerUse.icns</key>
8
+ <data>
9
+ 7FCrxo1Uv0dYad1G3oM0yStPJZs=
10
+ </data>
11
+ <key>Resources/LICENSE.computer-use-icon</key>
12
+ <data>
13
+ FfKCYFLo9JZ0Tk/wJPaU5dX8i/U=
14
+ </data>
15
+ <key>Resources/LICENSE.cua-driver</key>
16
+ <data>
17
+ 6q0FpB2ebvJFkwbiAsA5y+Pfi48=
18
+ </data>
19
+ </dict>
20
+ <key>files2</key>
21
+ <dict>
22
+ <key>Resources/DSHComputerUse.icns</key>
23
+ <dict>
24
+ <key>hash2</key>
25
+ <data>
26
+ tLLz1flFp1R7wlOOhp1Fn9435AAzCwHb4w/KWnv0z+Q=
27
+ </data>
28
+ </dict>
29
+ <key>Resources/LICENSE.computer-use-icon</key>
30
+ <dict>
31
+ <key>hash2</key>
32
+ <data>
33
+ 7lIpf469xyYpyq+d0jfAyz/XivUSOcRoToRtNG5YnLs=
34
+ </data>
35
+ </dict>
36
+ <key>Resources/LICENSE.cua-driver</key>
37
+ <dict>
38
+ <key>hash2</key>
39
+ <data>
40
+ wHeSkMHUeDFpqj2/tV/rUF5WPvigBLv1UpjO/8+9qNk=
41
+ </data>
42
+ </dict>
43
+ </dict>
44
+ <key>rules</key>
45
+ <dict>
46
+ <key>^Resources/</key>
47
+ <true/>
48
+ <key>^Resources/.*\.lproj/</key>
49
+ <dict>
50
+ <key>optional</key>
51
+ <true/>
52
+ <key>weight</key>
53
+ <real>1000</real>
54
+ </dict>
55
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
56
+ <dict>
57
+ <key>omit</key>
58
+ <true/>
59
+ <key>weight</key>
60
+ <real>1100</real>
61
+ </dict>
62
+ <key>^Resources/Base\.lproj/</key>
63
+ <dict>
64
+ <key>weight</key>
65
+ <real>1010</real>
66
+ </dict>
67
+ <key>^version.plist$</key>
68
+ <true/>
69
+ </dict>
70
+ <key>rules2</key>
71
+ <dict>
72
+ <key>.*\.dSYM($|/)</key>
73
+ <dict>
74
+ <key>weight</key>
75
+ <real>11</real>
76
+ </dict>
77
+ <key>^(.*/)?\.DS_Store$</key>
78
+ <dict>
79
+ <key>omit</key>
80
+ <true/>
81
+ <key>weight</key>
82
+ <real>2000</real>
83
+ </dict>
84
+ <key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
85
+ <dict>
86
+ <key>nested</key>
87
+ <true/>
88
+ <key>weight</key>
89
+ <real>10</real>
90
+ </dict>
91
+ <key>^.*</key>
92
+ <true/>
93
+ <key>^Info\.plist$</key>
94
+ <dict>
95
+ <key>omit</key>
96
+ <true/>
97
+ <key>weight</key>
98
+ <real>20</real>
99
+ </dict>
100
+ <key>^PkgInfo$</key>
101
+ <dict>
102
+ <key>omit</key>
103
+ <true/>
104
+ <key>weight</key>
105
+ <real>20</real>
106
+ </dict>
107
+ <key>^Resources/</key>
108
+ <dict>
109
+ <key>weight</key>
110
+ <real>20</real>
111
+ </dict>
112
+ <key>^Resources/.*\.lproj/</key>
113
+ <dict>
114
+ <key>optional</key>
115
+ <true/>
116
+ <key>weight</key>
117
+ <real>1000</real>
118
+ </dict>
119
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
120
+ <dict>
121
+ <key>omit</key>
122
+ <true/>
123
+ <key>weight</key>
124
+ <real>1100</real>
125
+ </dict>
126
+ <key>^Resources/Base\.lproj/</key>
127
+ <dict>
128
+ <key>weight</key>
129
+ <real>1010</real>
130
+ </dict>
131
+ <key>^[^/]+$</key>
132
+ <dict>
133
+ <key>nested</key>
134
+ <true/>
135
+ <key>weight</key>
136
+ <real>10</real>
137
+ </dict>
138
+ <key>^embedded\.provisionprofile$</key>
139
+ <dict>
140
+ <key>weight</key>
141
+ <real>20</real>
142
+ </dict>
143
+ <key>^version\.plist$</key>
144
+ <dict>
145
+ <key>weight</key>
146
+ <real>20</real>
147
+ </dict>
148
+ </dict>
149
+ </dict>
150
+ </plist>
@@ -0,0 +1 @@
1
+ {"bundle":"9f6e6dedbc05279505e36b140ddd74a7d143b31838e17ba22ad3115fc14c55b2"}
@@ -0,0 +1,85 @@
1
+ """Build, sign and publish immutable Computer Use application generations."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import platform
8
+ import shutil
9
+ import subprocess
10
+ import tempfile
11
+
12
+
13
+ def bundle_digest(application):
14
+ """Hash bundle membership and bytes; generated bundles contain only regular files."""
15
+ if application.is_symlink() or not application.is_dir():
16
+ raise ValueError(f"Helper application is not a real directory: {application}")
17
+ digest = hashlib.sha256()
18
+ for path in sorted(application.rglob("*")):
19
+ if path.is_symlink():
20
+ raise ValueError(f"Helper application contains a symbolic link: {path}")
21
+ if path.is_file():
22
+ digest.update(path.relative_to(application).as_posix().encode() + b"\0")
23
+ digest.update(hashlib.sha256(path.read_bytes()).digest())
24
+ digest.update(bytes([bool(path.stat().st_mode & 0o111)]))
25
+ elif not path.is_dir():
26
+ raise ValueError(f"Helper application contains a non-regular entry: {path}")
27
+ return digest.hexdigest()
28
+
29
+
30
+ def publish(binary, output, identity, plist):
31
+ """Publish a complete signed bundle before atomically selecting its generation."""
32
+ output.mkdir(parents=True, exist_ok=True)
33
+ with tempfile.TemporaryDirectory(prefix=".prepare-", dir=output) as temporary:
34
+ staged = Path(temporary) / "DSH Computer Use.app"
35
+ executable = staged / "Contents/MacOS/dsh-cua-native"
36
+ executable.parent.mkdir(parents=True)
37
+ shutil.copy2(binary, executable)
38
+ shutil.copy2(plist, staged / "Contents/Info.plist")
39
+ resources = staged / "Contents/Resources"
40
+ resources.mkdir()
41
+ for filename in ["DSHComputerUse.icns", "LICENSE.computer-use-icon", "LICENSE.cua-driver"]:
42
+ shutil.copy2(plist.with_name(filename), resources / filename)
43
+ subprocess.run(["/usr/bin/codesign", "--force", "--sign", identity, "--options", "runtime",
44
+ "--timestamp=none" if identity == "-" else "--timestamp", str(staged)], check=True)
45
+ subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(staged)], check=True)
46
+ key = bundle_digest(staged)
47
+ generation = output / key
48
+ application = generation / staged.name
49
+ if application.exists():
50
+ if bundle_digest(application) != key:
51
+ raise ValueError(f"Retained helper application does not match its content digest: {application}")
52
+ else:
53
+ generation.mkdir(exist_ok=True)
54
+ try:
55
+ staged.rename(application)
56
+ except OSError:
57
+ # Independent packagers can publish the same immutable generation.
58
+ if not application.is_dir() or bundle_digest(application) != key:
59
+ raise
60
+ receipt = Path(temporary) / "current.json"
61
+ receipt.write_text(json.dumps({"bundle": key}) + "\n")
62
+ os.replace(receipt, output / "current.json")
63
+ return application / "Contents/MacOS/dsh-cua-native"
64
+
65
+
66
+ def main():
67
+ root = Path(__file__).resolve().parent
68
+ parser = argparse.ArgumentParser(description=__doc__)
69
+ parser.add_argument("--arch", choices=["arm64", "x86_64"], default=platform.machine())
70
+ parser.add_argument("--scratch-path", type=Path)
71
+ parser.add_argument("--output-directory", type=Path)
72
+ parser.add_argument("--identity", default="-", help="codesign identity; '-' produces a local ad-hoc build")
73
+ args = parser.parse_args()
74
+ architecture = "x64" if args.arch == "x86_64" else "arm64"
75
+ scratch = args.scratch_path or root / ".build" / f"runtime-{architecture}"
76
+ output = args.output_directory or root / "bin" / f"darwin-{architecture}"
77
+ subprocess.run(["/usr/bin/xcrun", "swift", "build", "--package-path", str(root),
78
+ "--scratch-path", str(scratch), "--configuration", "release",
79
+ "--product", "dsh-cua-native", "--arch", args.arch], check=True)
80
+ executable = publish(scratch / "release/dsh-cua-native", output, args.identity, root / "Info.plist")
81
+ print(executable)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
@@ -1114,10 +1114,41 @@
1114
1114
  "accessibility",
1115
1115
  "screenRecording"
1116
1116
  ]
1117
+ },
1118
+ "settingsMessage": {
1119
+ "type": "string",
1120
+ "minLength": 1
1121
+ },
1122
+ "instruction": {
1123
+ "type": "string",
1124
+ "minLength": 1
1125
+ },
1126
+ "backLabel": {
1127
+ "type": "string",
1128
+ "minLength": 1
1129
+ },
1130
+ "finderLabel": {
1131
+ "type": "string",
1132
+ "minLength": 1
1133
+ },
1134
+ "unavailableMessage": {
1135
+ "type": "string",
1136
+ "minLength": 1
1137
+ },
1138
+ "pollIntervalMs": {
1139
+ "type": "integer",
1140
+ "minimum": 100,
1141
+ "maximum": 2147483647
1117
1142
  }
1118
1143
  },
1119
1144
  "required": [
1120
- "permission"
1145
+ "permission",
1146
+ "settingsMessage",
1147
+ "instruction",
1148
+ "backLabel",
1149
+ "finderLabel",
1150
+ "unavailableMessage",
1151
+ "pollIntervalMs"
1121
1152
  ],
1122
1153
  "additionalProperties": false
1123
1154
  }
@@ -1148,10 +1179,15 @@
1148
1179
  "accessibility",
1149
1180
  "screenRecording"
1150
1181
  ]
1182
+ },
1183
+ "settingsMessage": {
1184
+ "type": "string",
1185
+ "minLength": 1
1151
1186
  }
1152
1187
  },
1153
1188
  "required": [
1154
- "permission"
1189
+ "permission",
1190
+ "settingsMessage"
1155
1191
  ],
1156
1192
  "additionalProperties": false
1157
1193
  }
@@ -94,9 +94,61 @@ func refusesInvalidSharedConfiguration(_ name: String, _ value: JSONValue) throw
94
94
  for arguments in [
95
95
  ["--ensure-shared", "--runtime-key", "invalid", "--runtime-directory", "/tmp/cua", "--startup-timeout-ms", "1000"],
96
96
  ["--serve", "--runtime-key", runtimeKey, "--runtime-directory", "relative", "--startup-timeout-ms", "1000"],
97
+ ["--serve", "--runtime-key", runtimeKey, "--runtime-directory", "/tmp/cua", "--startup-timeout-ms", "1000", "--startup-id", "invalid"],
98
+ ["--ensure-shared", "--runtime-key", runtimeKey, "--runtime-directory", "/tmp/cua", "--startup-timeout-ms", "1000", "--startup-id", UUID().uuidString],
97
99
  ["--serve", "--runtime-key", runtimeKey, "--runtime-directory", "/tmp/cua", "--startup-timeout-ms", "0"],
98
100
  ["--serve", "--runtime-key", runtimeKey, "--runtime-directory", "/" + String(repeating: "x", count: 100), "--startup-timeout-ms", "1000"],
99
101
  ] {
100
102
  #expect(throws: NativeFailure.self) { try SharedHelperOptions(arguments: arguments) }
101
103
  }
102
104
  }
105
+
106
+ @Test func startupFailuresAreScopedToOneLaunchAttempt() throws {
107
+ let directory = "/tmp/cua-\(UUID().uuidString.prefix(12))"
108
+ let arguments = ["--serve", "--runtime-key", runtimeKey, "--runtime-directory", directory,
109
+ "--startup-timeout-ms", "5000", "--startup-id"]
110
+ let options = try SharedHelperOptions(arguments: arguments + [UUID().uuidString])
111
+ try options.prepareDirectory()
112
+ defer { try? FileManager.default.removeItem(atPath: directory) }
113
+ let other = try SharedHelperOptions(arguments: arguments + [UUID().uuidString])
114
+ try options.recordStartupFailure(NativeFailure(code: "NATIVE_RUNTIME_CONFLICT", message: "path is occupied"))
115
+ let failure = try SharedHelperOptions.startupFailure(at: options.failurePath)
116
+ #expect(failure?.code == "NATIVE_RUNTIME_CONFLICT")
117
+ #expect(failure?.message == "path is occupied")
118
+ #expect(try SharedHelperOptions.startupFailure(at: other.failurePath) == nil)
119
+ var info = stat()
120
+ #expect(lstat(try #require(options.failurePath), &info) == 0)
121
+ #expect(info.st_mode & 0o777 == 0o600)
122
+ }
123
+
124
+ @Test func readinessUsesTheRemainingStartupBudget() throws {
125
+ let directory = "/tmp/cua-\(UUID().uuidString.prefix(12))"
126
+ let options = try SharedHelperOptions(arguments: ["--ensure-shared", "--runtime-key", runtimeKey,
127
+ "--runtime-directory", directory, "--startup-timeout-ms", "5000"])
128
+ try options.prepareDirectory()
129
+ defer { try? FileManager.default.removeItem(atPath: directory) }
130
+ let start = DispatchTime.now().uptimeNanoseconds
131
+ do {
132
+ _ = try options.existingReady(deadline: start)
133
+ Issue.record("Expired startup returned readiness")
134
+ } catch let error as NativeFailure { #expect(error.code == "NATIVE_STARTUP_TIMEOUT") }
135
+ #expect(DispatchTime.now().uptimeNanoseconds - start < 1_000_000_000)
136
+ }
137
+
138
+ @Test func exitedStartupProcessFailsWithoutRunningTheMainRunLoop() throws {
139
+ let directory = "/tmp/cua-\(UUID().uuidString.prefix(12))"
140
+ let options = try SharedHelperOptions(arguments: ["--ensure-shared", "--runtime-key", runtimeKey,
141
+ "--runtime-directory", directory, "--startup-timeout-ms", "5000"])
142
+ try options.prepareDirectory()
143
+ defer { try? FileManager.default.removeItem(atPath: directory) }
144
+ let child = Process()
145
+ child.executableURL = URL(fileURLWithPath: "/usr/bin/true")
146
+ try child.run()
147
+ child.waitUntilExit()
148
+ let start = DispatchTime.now().uptimeNanoseconds
149
+ do {
150
+ _ = try options.existingReady(deadline: options.startupDeadline(), launchedPID: child.processIdentifier)
151
+ Issue.record("Exited startup returned readiness")
152
+ } catch let error as NativeFailure { #expect(error.code == "NATIVE_STARTUP") }
153
+ #expect(DispatchTime.now().uptimeNanoseconds - start < 1_000_000_000)
154
+ }
@@ -0,0 +1,245 @@
1
+ // Permission control tests replace native presentation and never change the machine's grants.
2
+ import AppKit
3
+ import Foundation
4
+ import Testing
5
+ @testable import CuaNative
6
+
7
+ @MainActor private final class GuideFixture: PermissionGuidePresenting {
8
+ var isOpen = false
9
+ var owner: UUID?
10
+ var application: PermissionGuideApplication?
11
+ var text: PermissionGuideText?
12
+ var granted: (@MainActor () -> Bool)?
13
+ var settingsFailure = false
14
+ var showFailure: NativeFailure?
15
+ func show(application: PermissionGuideApplication, text: PermissionGuideText, owner: UUID,
16
+ interval: TimeInterval, granted: @escaping @MainActor () -> Bool) throws(NativeFailure) {
17
+ if let showFailure { throw showFailure }
18
+ self.application = application
19
+ self.text = text
20
+ self.owner = owner
21
+ self.granted = granted
22
+ isOpen = true
23
+ }
24
+ func reportSettingsFailure() { settingsFailure = true }
25
+ func dismiss() { isOpen = false; granted = nil; owner = nil }
26
+ func close(owner: UUID) {
27
+ if self.owner == owner { dismiss() }
28
+ }
29
+ }
30
+
31
+ private let copy = PermissionGuideText(instruction: "Drag {application} to allow access", backLabel: "Back",
32
+ finderLabel: "Show in Finder", unavailableMessage: "Application unavailable", settingsMessage: "Open System Settings manually")
33
+ private let application = JSONValue.object(["name": .string("Helper.app"), "path": .string("/generation/Helper.app"), "bundleId": .string("test.helper")])
34
+
35
+ @MainActor @Test(arguments: ["accessibility", "screenRecording"])
36
+ func permissionRequestOpensTheNativeGuideAndMatchingSettings(permission: String) throws {
37
+ var opened: [URL] = []
38
+ var allowed = false
39
+ let guide = GuideFixture()
40
+ let owner = UUID()
41
+ let actions = SystemPermissionActions(accessibility: { allowed }, screenRecording: { allowed }, open: { opened.append($0); return true })
42
+ let permissions = SystemPermissions(application: application, actions: actions, guide: guide)
43
+ #expect(!guide.isOpen)
44
+ let state = try permissions.request(permission, owner: owner, text: copy, interval: 1)
45
+ #expect(state[permission] == .bool(false))
46
+ #expect(state["launchApplication"]["name"] == .string("Helper.app"))
47
+ #expect(state["launchApplication"]["bundleId"] == .null)
48
+ #expect(guide.isOpen)
49
+ #expect(guide.application?.url.path == "/generation/Helper.app")
50
+ #expect(guide.text?.instruction == copy.instruction)
51
+ let pane = permission == "accessibility" ? "Privacy_Accessibility" : "Privacy_ScreenCapture"
52
+ #expect(opened.first?.absoluteString == "x-apple.systempreferences:com.apple.preference.security?\(pane)")
53
+ allowed = true
54
+ #expect(guide.granted?() == true)
55
+ #expect(permissions.status()[permission] == .bool(true))
56
+ permissions.closeGuide(owner: UUID())
57
+ #expect(guide.isOpen)
58
+ permissions.closeGuide(owner: owner)
59
+ #expect(!guide.isOpen)
60
+ }
61
+
62
+ @MainActor @Test
63
+ func settingsFailureRetainsTheNativeGuideWithManualInstructions() throws {
64
+ let guide = GuideFixture()
65
+ let permissions = SystemPermissions(application: application,
66
+ actions: SystemPermissionActions(accessibility: { false }, screenRecording: { false }, open: { _ in false }), guide: guide)
67
+ do {
68
+ _ = try permissions.request("accessibility", owner: UUID(), text: copy, interval: 1)
69
+ Issue.record("Settings-open failure was accepted")
70
+ } catch let failure as NativeFailure {
71
+ #expect(failure.code == "SETTINGS_UNAVAILABLE")
72
+ #expect(failure.message == copy.settingsMessage)
73
+ }
74
+ #expect(guide.isOpen && guide.settingsFailure)
75
+ }
76
+
77
+ @MainActor @Test
78
+ func grantedPermissionsOpenSettingsWithoutCreatingAGuide() throws {
79
+ let guide = GuideFixture()
80
+ var opened = false
81
+ guide.isOpen = true
82
+ let permissions = SystemPermissions(application: application,
83
+ actions: SystemPermissionActions(accessibility: { true }, screenRecording: { true }, open: { _ in opened = true; return true }), guide: guide)
84
+ #expect(try permissions.request("screenRecording", owner: UUID(), text: copy, interval: 1)["screenRecording"] == .bool(true))
85
+ #expect(opened && !guide.isOpen)
86
+ }
87
+
88
+ @MainActor @Test(arguments: [false, true])
89
+ func unavailablePermissionApplicationsStillOpenSettings(identified: Bool) throws {
90
+ let guide = GuideFixture()
91
+ guide.showFailure = NativeFailure(code: "APPLICATION_UNAVAILABLE", message: "Native bundle validation failed")
92
+ var opened: [URL] = []
93
+ let permissions = SystemPermissions(application: identified ? application : nil,
94
+ actions: SystemPermissionActions(accessibility: { false }, screenRecording: { false }, open: { opened.append($0); return true }),
95
+ guide: guide)
96
+ do {
97
+ _ = try permissions.request("accessibility", owner: UUID(), text: copy, interval: 1)
98
+ Issue.record("Unavailable application was accepted")
99
+ } catch let failure as NativeFailure {
100
+ #expect(failure.code == "APPLICATION_UNAVAILABLE")
101
+ #expect(failure.message == copy.unavailableMessage)
102
+ }
103
+ #expect(opened.map(\.absoluteString) == ["x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"])
104
+ #expect(!guide.isOpen)
105
+ }
106
+
107
+ @MainActor @Test func simultaneousGuideAndSettingsFailuresKeepBothRecoveryInstructions() throws {
108
+ let guide = GuideFixture()
109
+ var openCalls = 0
110
+ let permissions = SystemPermissions(application: nil,
111
+ actions: SystemPermissionActions(accessibility: { false }, screenRecording: { false }, open: { _ in openCalls += 1; return false }),
112
+ guide: guide)
113
+ do {
114
+ _ = try permissions.request("screenRecording", owner: UUID(), text: copy, interval: 1)
115
+ Issue.record("Failed settings navigation was accepted")
116
+ } catch let failure as NativeFailure {
117
+ #expect(failure.code == "SETTINGS_UNAVAILABLE")
118
+ #expect(failure.message == copy.unavailableMessage + "\n" + copy.settingsMessage)
119
+ }
120
+ #expect(openCalls == 1 && !guide.isOpen)
121
+ }
122
+
123
+ @MainActor @Test func explicitSettingsNavigationDismissesThePreviousPermissionGuide() throws {
124
+ let guide = GuideFixture()
125
+ guide.isOpen = true
126
+ let permissions = SystemPermissions(application: application,
127
+ actions: SystemPermissionActions(accessibility: { false }, screenRecording: { true }, open: { _ in true }), guide: guide)
128
+ #expect(try permissions.openSettings("screenRecording", failureMessage: copy.settingsMessage)["opened"] == .bool(true))
129
+ #expect(!guide.isOpen)
130
+ }
131
+
132
+ @Test func theGuideOverlaysTheSettingsBottomAndStaysWithinItsDisplay() {
133
+ let visible = CGRect(x: 0, y: 25, width: 1440, height: 850)
134
+ let settings = CGRect(x: 300, y: 100, width: 800, height: 700)
135
+ let frame = PermissionGuidePlacement.frame(settings: settings, visible: visible, size: CGSize(width: 620, height: 128))
136
+ #expect(frame.midX == settings.midX)
137
+ #expect(frame.minY == settings.minY + 8)
138
+ #expect(visible.contains(frame))
139
+ let secondary = CGRect(x: -800, y: -600, width: 800, height: 600)
140
+ let outside = PermissionGuidePlacement.frame(settings: CGRect(x: -1000, y: -800, width: 700, height: 700),
141
+ visible: secondary, size: CGSize(width: 620, height: 128))
142
+ #expect(secondary.contains(outside))
143
+ let fallback = PermissionGuidePlacement.frame(settings: nil, visible: secondary, size: CGSize(width: 1200, height: 900))
144
+ #expect(secondary.contains(fallback))
145
+ }
146
+
147
+ @Test func theDragSourceRejectsReplacedAndMissingApplications() throws {
148
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("dsh-guide-" + UUID().uuidString)
149
+ defer { try? FileManager.default.removeItem(at: root) }
150
+ let app = root.appendingPathComponent("Helper.app")
151
+ let contents = app.appendingPathComponent("Contents")
152
+ let executable = contents.appendingPathComponent("MacOS/helper")
153
+ try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true)
154
+ try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executable)
155
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path)
156
+ let info = ["CFBundleIdentifier": "test.helper", "CFBundleExecutable": "helper", "CFBundlePackageType": "APPL"]
157
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: contents.appendingPathComponent("Info.plist"))
158
+ let target = PermissionGuideApplication(url: app, identifier: "test.helper")
159
+ #expect(try target.validatedURL().path == app.path)
160
+ #expect(target.name == "Helper.app")
161
+ #expect(throws: (any Error).self) { try PermissionGuideApplication(url: app, identifier: "test.other").validatedURL() }
162
+ let cached = try #require(Bundle(url: app))
163
+ #expect(cached.bundleIdentifier == "test.helper")
164
+ try withExtendedLifetime(cached) {
165
+ var replacement = info
166
+ replacement["CFBundleIdentifier"] = "test.replacement"
167
+ try PropertyListSerialization.data(fromPropertyList: replacement, format: .xml, options: 0)
168
+ .write(to: contents.appendingPathComponent("Info.plist"), options: .atomic)
169
+ #expect(InstalledApplication.read(app)?.bundleID == "test.replacement")
170
+ #expect(throws: NativeFailure.self) { try target.validatedURL() }
171
+ #expect(try PermissionGuideApplication(url: app, identifier: "test.replacement").validatedURL().path == app.path)
172
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
173
+ .write(to: contents.appendingPathComponent("Info.plist"), options: .atomic)
174
+ #expect(try target.validatedURL().path == app.path)
175
+ }
176
+ try FileManager.default.removeItem(at: app)
177
+ #expect(throws: (any Error).self) { try target.validatedURL() }
178
+ }
179
+
180
+ @Test func permissionGuideChoosesTheSettingsMainWindowBehindAuthentication() {
181
+ let main = PermissionGuideWindow(id: 10, frame: CGRect(x: 100, y: 80, width: 800, height: 700))
182
+ let authentication = PermissionGuideWindow(id: 11, frame: CGRect(x: 300, y: 250, width: 260, height: 340))
183
+ #expect(PermissionGuidePlacement.target(in: [authentication, main], pinned: nil)?.id == main.id)
184
+ #expect(PermissionGuidePlacement.target(in: [main, authentication], pinned: nil)?.id == main.id)
185
+ #expect(PermissionGuidePlacement.target(in: [], pinned: nil) == nil)
186
+ }
187
+
188
+ @Test func permissionGuideKeepsItsWindowIdentityAcrossDialogsAndResizing() {
189
+ let resized = PermissionGuideWindow(id: 10, frame: CGRect(x: -800, y: 50, width: 600, height: 500))
190
+ let other = PermissionGuideWindow(id: 11, frame: CGRect(x: 100, y: 80, width: 1200, height: 900))
191
+ #expect(PermissionGuidePlacement.target(in: [other, resized], pinned: resized.id)?.frame == resized.frame)
192
+ #expect(PermissionGuidePlacement.target(in: [other], pinned: resized.id) == nil)
193
+ }
194
+
195
+ @MainActor @Test(arguments: [NSSize(width: 360, height: 160), NSSize(width: 620, height: 128)])
196
+ func permissionGuideMaterialKeepsTransparentCornersWhenResized(size: NSSize) throws {
197
+ let bitmap = try #require(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height),
198
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
199
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
200
+ let context = try #require(NSGraphicsContext(bitmapImageRep: bitmap))
201
+ NSGraphicsContext.saveGraphicsState()
202
+ defer { NSGraphicsContext.restoreGraphicsState() }
203
+ NSGraphicsContext.current = context
204
+ PermissionGuideAppearance.materialMask().draw(in: NSRect(origin: .zero, size: size),
205
+ from: .zero, operation: .copy, fraction: 1)
206
+ for x in [0, bitmap.pixelsWide - 1] {
207
+ for y in [0, bitmap.pixelsHigh - 1] {
208
+ #expect(try #require(bitmap.colorAt(x: x, y: y)).alphaComponent == 0)
209
+ }
210
+ }
211
+ #expect(try #require(bitmap.colorAt(x: bitmap.pixelsWide / 2, y: bitmap.pixelsHigh / 2)).alphaComponent == 1)
212
+ #expect(try #require(bitmap.colorAt(x: 25, y: 0)).alphaComponent == 1)
213
+ #expect(try #require(bitmap.colorAt(x: 0, y: 25)).alphaComponent == 1)
214
+ }
215
+
216
+ @Test func permissionGuideLeavesStableWindowOrderUntouched() {
217
+ #expect(!PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [20, 10]))
218
+ #expect(!PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [30, 20, 10]))
219
+ #expect(!PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [20, 30]))
220
+ }
221
+
222
+ @Test func permissionGuideRestoresItsPositionBelowDialogsAndAboveSettings() {
223
+ #expect(PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [10, 20]))
224
+ #expect(PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [20, 30, 10]))
225
+ #expect(PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [30, 10]))
226
+ #expect(!PermissionGuidePlacement.needsOrdering(guide: 20, above: 10, frontToBack: [30, 20, 10]))
227
+ }
228
+
229
+ @MainActor @Test(arguments: ["accessibility", "invalid"])
230
+ func explicitSettingsFailuresPreserveValidationAndLocalizeNavigation(permission: String) throws {
231
+ let permissions = SystemPermissions(application: application,
232
+ actions: SystemPermissionActions(accessibility: { false }, screenRecording: { false }, open: { _ in false }),
233
+ guide: GuideFixture())
234
+ do {
235
+ _ = try permissions.openSettings(permission, failureMessage: "请手动打开系统设置中的辅助功能")
236
+ Issue.record("Failed settings navigation was accepted")
237
+ } catch let failure as NativeFailure {
238
+ if permission == "accessibility" {
239
+ #expect(failure.code == "SETTINGS_UNAVAILABLE")
240
+ #expect(failure.message == "请手动打开系统设置中的辅助功能")
241
+ } else {
242
+ #expect(failure.code == "INVALID_ARGUMENT")
243
+ }
244
+ }
245
+ }
@@ -44,6 +44,7 @@
44
44
  "Sources/CuaNative/ClipboardPaste.swift",
45
45
  "Sources/CuaNative/Main.swift",
46
46
  "Sources/CuaNative/NativeProtocol.generated.swift",
47
+ "Sources/CuaNative/PermissionGuide.swift",
47
48
  "Sources/CuaNative/Protocol.swift",
48
49
  "Sources/CuaNative/RequestAdmission.swift",
49
50
  "Sources/CuaNative/RequestCoordinator.swift",