跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

Cage.swift

662 行 · 48.5 KB历史下载
1import Cocoa
2import WebKit
3import UniformTypeIdentifiers
4
5enum CageDiagnostics {
6 static func record(_ message: String) {
7 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil),
8 let data = try? JSONSerialization.data(withJSONObject: ["source":"native", "message":String(message.prefix(4096))]) else { return }
9 let process = Process(); process.executableURL = executable; process.arguments = ["diagnostic-event"]
10 let input = Pipe(); process.standardInput = input
11 process.standardOutput = FileHandle.nullDevice; process.standardError = FileHandle.nullDevice
12 do { try process.run(); try input.fileHandleForWriting.write(contentsOf: data); try input.fileHandleForWriting.close() } catch { }
13 }
14}
15
16@main
17final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandlerWithReply {
18 private var window: NSWindow!
19 private var webView: WKWebView!
20 private var nativeInput: CageNativeInput!
21 private var accountDeviceBusy = false
22 private var expectedPort = 0
23 private var allowQuit = false
24 private var nativeFilePanelOpen = false
25 private var fileSelections: [String: (paths: [String], expires: Date)] = [:]
26 private var clipboardGeneration = 0
27 private var clipboardCopies: [String: [String]] = [:]
28 private var clipboardReaders: [UUID: [String]] = [:]
29 private var clipboardPending = Set<String>()
30 private var clipboardReleasing = Set<String>()
31 private var clipboardCacheLoaded = false
32 private var clipboardCacheTimer: Timer?
33 private var loading: NSTextField!
34 private var retry: NSButton!
35 private var backdrop: NSVisualEffectView!
36 private var completeUpdateButton: NSButton!
37 private var existingEnvironmentButton: NSButton!
38 private var completeUpdateMenu: NSMenuItem!
39 private var controllerNeedsUpdate = false
40 private var appUpdater: CageAppUpdater!
41
42 private struct DesktopEntry {
43 let status: String
44 let url: URL?
45 let message: String
46 }
47
48 static func main() {
49 CageProfile.pinEnvironment()
50 if CommandLine.arguments.dropFirst().elementsEqual(["--store-trial-guest-password"]) {
51 do { try MacGuestLoginCredential.importFromPipe(); return }
52 catch { FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)); exit(1) }
53 }
54 NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") }
55 let app = NSApplication.shared
56 let delegate = CageApp()
57 app.delegate = delegate
58 app.setActivationPolicy(.regular)
59 withExtendedLifetime(delegate) { app.run() }
60 }
61 func applicationDidFinishLaunching(_ notification: Notification) {
62 let appearance = UserDefaults.standard.dictionary(forKey: "cage.windowAppearance") ?? [:]
63 let mode = appearance["mode"] as? String ?? "system"
64 NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua)
65 makeMenus()
66 window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 850), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
67 window.title = CageProfile.macGuestTrial ? "Cage macOS" : "Cage"
68 window.titlebarAppearsTransparent = false
69 window.backgroundColor = NSColor(srgbRed: 247.0/255, green: 247.0/255, blue: 247.0/255, alpha: 1)
70 window.minSize = NSSize(width: 820, height: 580)
71 window.isReleasedWhenClosed = false
72 window.delegate = self
73 window.setFrameAutosaveName("CageMainWindow")
74 window.center()
75 let config = WKWebViewConfiguration()
76 config.websiteDataStore = .default()
77 config.userContentController.addScriptMessageHandler(self, contentWorld: .page, name: "cage")
78 config.userContentController.addUserScript(WKUserScript(source: "window.cageNativeIMEAvailable = true;", injectionTime: .atDocumentStart, forMainFrameOnly: true))
79 webView = WKWebView(frame: .zero, configuration: config)
80 webView.navigationDelegate = self
81 webView.uiDelegate = self
82 webView.translatesAutoresizingMaskIntoConstraints = false
83 webView.allowsBackForwardNavigationGestures = false
84 webView.setValue(false, forKey: "drawsBackground")
85 webView.underPageBackgroundColor = .clear
86 let content = window.contentView!
87 backdrop = NSVisualEffectView(frame: content.bounds)
88 backdrop.autoresizingMask = [.width, .height]
89 backdrop.material = .sidebar
90 backdrop.blendingMode = .behindWindow
91 backdrop.state = .followsWindowActiveState
92 content.addSubview(backdrop)
93 content.addSubview(webView)
94 nativeInput = CageNativeInput(frame: .zero)
95 nativeInput.configure(web: webView)
96 content.addSubview(nativeInput)
97 NSLayoutConstraint.activate([webView.leadingAnchor.constraint(equalTo: content.leadingAnchor), webView.trailingAnchor.constraint(equalTo: content.trailingAnchor), webView.topAnchor.constraint(equalTo: content.topAnchor), webView.bottomAnchor.constraint(equalTo: content.bottomAnchor)])
98 loading = NSTextField(labelWithString: "正在启动 Cage 工作台…")
99 loading.font = NSFont.systemFont(ofSize: 16, weight: .medium)
100 loading.textColor = NSColor(srgbRed: 54.0/255, green: 54.0/255, blue: 54.0/255, alpha: 1)
101 loading.alignment = .center
102 loading.maximumNumberOfLines = 4
103 loading.translatesAutoresizingMaskIntoConstraints = false
104 content.addSubview(loading)
105 retry = NSButton(title: "重试连接", target: self, action: #selector(retryConnection))
106 retry.bezelStyle = .rounded
107 retry.translatesAutoresizingMaskIntoConstraints = false
108 retry.isHidden = true
109 content.addSubview(retry)
110 completeUpdateButton = NSButton(title: "保存后停止环境并完成更新", target: self, action: #selector(completePendingUpdate))
111 completeUpdateButton.bezelStyle = .rounded
112 completeUpdateButton.translatesAutoresizingMaskIntoConstraints = false
113 completeUpdateButton.isHidden = true
114 content.addSubview(completeUpdateButton)
115 existingEnvironmentButton = NSButton(title: "打开现有环境保存文件", target: self, action: #selector(openExistingEnvironment))
116 existingEnvironmentButton.bezelStyle = .rounded
117 existingEnvironmentButton.translatesAutoresizingMaskIntoConstraints = false
118 existingEnvironmentButton.isHidden = true
119 content.addSubview(existingEnvironmentButton)
120 NSLayoutConstraint.activate([loading.centerXAnchor.constraint(equalTo: content.centerXAnchor), loading.centerYAnchor.constraint(equalTo: content.centerYAnchor, constant: -16), loading.widthAnchor.constraint(lessThanOrEqualToConstant: 600), retry.centerXAnchor.constraint(equalTo: content.centerXAnchor), retry.topAnchor.constraint(equalTo: loading.bottomAnchor, constant: 20)])
121 NSLayoutConstraint.activate([existingEnvironmentButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), existingEnvironmentButton.topAnchor.constraint(equalTo: retry.bottomAnchor, constant: 10), completeUpdateButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), completeUpdateButton.topAnchor.constraint(equalTo: existingEnvironmentButton.bottomAnchor, constant: 10)])
122 applyAppearance(appearance)
123 appUpdater = CageAppUpdater(bundleURL: Bundle.main.bundleURL, onChange: { [weak self] state in
124 if state["phase"] as? String == "failed" { CageDiagnostics.record("App update failed: " + (state["message"] as? String ?? "unknown error")) }
125 guard let data = try? JSONSerialization.data(withJSONObject: state), let json = String(data: data, encoding: .utf8) else { return }
126 self?.webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:\(json)}));", completionHandler: nil)
127 }, quit: { [weak self] in self?.allowQuit = true; NSApp.terminate(nil) }, reconnect: { [weak self] in self?.bootstrap() })
128 window.makeKeyAndOrderFront(nil)
129 NSApp.activate(ignoringOtherApps: true)
130 bootstrap()
131 }
132 private func makeMenus() {
133 let main = NSMenu()
134 let appItem = NSMenuItem()
135 main.addItem(appItem)
136 let appMenu = NSMenu(title: "Cage")
137 appItem.submenu = appMenu
138 appMenu.addItem(withTitle: "关于 Cage", action: #selector(about), keyEquivalent: "")
139 appMenu.addItem(withTitle: "检查应用更新…", action: #selector(checkApplicationUpdate), keyEquivalent: "")
140 completeUpdateMenu = appMenu.addItem(withTitle: "完成待安装更新…", action: #selector(completePendingUpdate), keyEquivalent: "")
141 completeUpdateMenu.isHidden = true
142 appMenu.addItem(.separator())
143 if CageProfile.macGuestTrial {
144 appMenu.addItem(withTitle: "复制试用客机登录密码", action: #selector(copyGuestLoginPassword), keyEquivalent: "")
145 }
146 appMenu.addItem(withTitle: "设置…", action: #selector(settings), keyEquivalent: ",")
147 appMenu.addItem(.separator())
148 appMenu.addItem(withTitle: "隐藏 Cage", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
149 appMenu.addItem(withTitle: "显示全部", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "")
150 appMenu.addItem(.separator())
151 appMenu.addItem(withTitle: "退出 Cage…", action: #selector(requestQuit), keyEquivalent: "q")
152 let file = NSMenu(title: "文件")
153 file.addItem(withTitle: "打开项目…", action: #selector(openProject), keyEquivalent: "o")
154 file.addItem(.separator())
155 file.addItem(withTitle: "新建网页", action: #selector(newTab), keyEquivalent: "t")
156 let terminal = file.addItem(withTitle: "新建终端", action: #selector(newTerminal), keyEquivalent: "\r")
157 terminal.keyEquivalentModifierMask = [.command, .shift]
158 file.addItem(withTitle: "关闭当前标签", action: #selector(closeTab), keyEquivalent: "w")
159 file.addItem(.separator())
160 file.addItem(withTitle: "关闭窗口(保留环境)", action: #selector(closeWindow), keyEquivalent: "")
161 let fileItem = NSMenuItem(title: "文件", action: nil, keyEquivalent: "")
162 fileItem.submenu = file; main.addItem(fileItem)
163 let edit = NSMenu(title: "编辑")
164 edit.addItem(withTitle: "撤销", action: #selector(editUndo), keyEquivalent: "z")
165 let redo = edit.addItem(withTitle: "重做", action: #selector(editRedo), keyEquivalent: "z"); redo.keyEquivalentModifierMask = [.command, .shift]
166 edit.addItem(.separator())
167 edit.addItem(withTitle: "剪切", action: #selector(editCut), keyEquivalent: "x")
168 edit.addItem(withTitle: "复制", action: #selector(editCopy), keyEquivalent: "c")
169 edit.addItem(withTitle: "粘贴", action: #selector(editPaste), keyEquivalent: "v")
170 edit.addItem(withTitle: "全选", action: #selector(editSelectAll), keyEquivalent: "a")
171 let editItem = NSMenuItem(title: "编辑", action: nil, keyEquivalent: ""); editItem.submenu = edit; main.addItem(editItem)
172 let view = NSMenu(title: "窗口")
173 view.addItem(withTitle: "最小化", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
174 view.addItem(withTitle: "缩放", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "")
175 view.addItem(withTitle: "进入全屏", action: #selector(NSWindow.toggleFullScreen(_:)), keyEquivalent: "")
176 let viewItem = NSMenuItem(title: "窗口", action: nil, keyEquivalent: ""); viewItem.submenu = view; main.addItem(viewItem)
177 NSApp.mainMenu = main
178 }
179 @objc private func editUndo(){edit("undo",fallback:"undo:")}
180 @objc private func editRedo(){edit("redo",fallback:"redo:")}
181 @objc private func editCut(){edit("cut",fallback:"cut:")}
182 @objc private func editCopy(){edit("copy",fallback:"copy:")}
183 @objc private func editPaste(){edit("paste",fallback:"paste:")}
184 @objc private func editSelectAll(){edit("selectAll",fallback:"selectAll:")}
185 private func edit(_ command:String,fallback:String){
186 if nativeFilePanelOpen || window.attachedSheet != nil {
187 NSApp.sendAction(Selector(fallback), to: nil, from: self)
188 return
189 }
190 webView.evaluateJavaScript("window.cageEditAction?.('\(command)') ?? false") {result,error in
191 if (result as? Bool) != true {NSApp.sendAction(Selector(fallback),to:nil,from:self)}
192 }
193 }
194 @objc private func about() {
195 let version = Bundle.main.object(forInfoDictionaryKey: "CageVersion") as? String ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "开发版本"
196 let status = controllerNeedsUpdate ? "\n当前连接旧后台;更新尚未完成。" : ""
197 NSApp.orderFrontStandardAboutPanel(options: [.applicationName:"Cage", .applicationVersion:version, .credits:NSAttributedString(string:"本机隔离编码工作区\n基于 agent-vm、Lima、Chromium、noVNC 与 xterm.js" + status)])
198 }
199 @objc private func copyGuestLoginPassword() {
200 do { try MacGuestLoginCredential.copyForLogin() }
201 catch { let alert = NSAlert(error: error); alert.beginSheetModal(for: window) }
202 }
203 @objc private func settings() { action("settings") }
204 @objc private func openProject() { action("openProject") }
205 @objc private func newTab() { action("newTab") }
206 @objc private func newTerminal() { action("newTerminal") }
207 @objc private func closeTab() { action("closeTab") }
208 @objc private func closeWindow() { window.close() }
209 @objc private func requestQuit() { NSApp.terminate(nil) }
210 @objc private func checkApplicationUpdate() { _ = appUpdater?.handle("check") }
211 @objc private func retryConnection() { bootstrap() }
212 @objc private func openExistingEnvironment() { bootstrap(options: ["--existing"]) }
213 @objc private func completePendingUpdate() {
214 let alert = NSAlert()
215 alert.messageText = "保存文件后完成更新"
216 alert.informativeText = "这会停止现有环境和终端任务,再切换到新版后台。项目文件和登录状态会保留。请先保存编辑器中的修改。"
217 alert.addButton(withTitle: "已保存,停止并更新")
218 alert.addButton(withTitle: "继续当前工作")
219 alert.beginSheetModal(for: window) { response in
220 if response == .alertFirstButtonReturn { self.bootstrap(options: ["--complete-update"]) }
221 }
222 }
223 private func action(_ name: String) { webView.evaluateJavaScript("window.cageNativeAction?.('\(name)')", completionHandler: nil) }
224 private func requestEntry(options: [String] = [], _ completion: @escaping (Result<DesktopEntry, Error>) -> Void) {
225 if CageProfile.macGuestTrial {
226 let binding = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("macos-guest.json")
227 guard FileManager.default.fileExists(atPath: binding.path) else {
228 completion(.failure(CageUpdateError("这份试用版尚未绑定 macOS 客机,准备完成后请点重试。"))); return
229 }
230 }
231 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else {
232 completion(.failure(NSError(domain: "Cage", code: 1))); return
233 }
234 DispatchQueue.global(qos: .userInitiated).async {
235 let process = Process(); process.executableURL = executable; process.arguments = ["desktop", "--json"] + options
236 var environment = ProcessInfo.processInfo.environment
237 environment["CAGE_DESKTOP_OWNER_PID"] = String(ProcessInfo.processInfo.processIdentifier)
238 process.environment = environment
239 let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice
240 do {
241 try process.run()
242 let data = output.fileHandleForReading.readDataToEndOfFile()
243 process.waitUntilExit()
244 let result = try JSONSerialization.jsonObject(with: data) as? [String:Any]
245 let message = result?["message"] as? String ?? "工作台未能启动,请重试连接。"
246 guard process.terminationStatus == 0, let status = result?["status"] as? String else { throw NSError(domain:"Cage", code:1, userInfo:[NSLocalizedDescriptionKey:message]) }
247 if status == "upgrade_pending" {
248 DispatchQueue.main.async { completion(.success(DesktopEntry(status:status, url:nil, message:message))) }
249 return
250 }
251 guard let raw = result?["url"] as? String, let url = URL(string: raw), url.scheme == "http", url.host == "localhost", url.port != nil, url.fragment?.isEmpty == false else { throw NSError(domain:"Cage", code:1, userInfo:[NSLocalizedDescriptionKey:message]) }
252 DispatchQueue.main.async { completion(.success(DesktopEntry(status:status, url:url, message:""))) }
253 } catch { DispatchQueue.main.async { completion(.failure(error)) } }
254 }
255 }
256 private func bootstrap(options: [String] = []) {
257 loading.stringValue = options.contains("--complete-update") ? "正在停止环境并切换到新版后台…" : "正在启动 Cage 工作台…"
258 loading.isHidden = false; retry.isHidden = true; webView.isHidden = true
259 completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true
260 requestEntry(options: options) { result in
261 switch result {
262 case .success(let entry):
263 self.controllerNeedsUpdate = entry.status != "ready"
264 self.completeUpdateMenu.isHidden = !self.controllerNeedsUpdate
265 let appTitle = CageProfile.macGuestTrial ? "Cage macOS" : "Cage"
266 self.window.title = self.controllerNeedsUpdate ? "\(appTitle)(更新待完成)" : appTitle
267 if let url = entry.url { self.expectedPort = url.port!; self.webView.load(URLRequest(url: url)) }
268 else { self.showError(entry.message); self.completeUpdateButton.isHidden = false; self.existingEnvironmentButton.isHidden = false }
269 case .failure(let error):
270 CageDiagnostics.record("Workbench startup failed: \(error)")
271 let message = error.localizedDescription
272 if message.unicodeScalars.contains(where: { (0x4E00...0x9FFF).contains($0.value) }) { self.showError(message) }
273 else { self.showError("启动工作台失败:本机后台未返回可识别的原因(错误码 \((error as NSError).code))。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。") }
274 }
275 }
276 }
277 private func browserFile(_ operation: String, id: String, connection: String = "local", path: String? = nil, reply: @escaping (Any?, String?) -> Void) {
278 guard UUID(uuidString: id) != nil else { reply(nil,"下载标识无效"); return }
279 fileCommand(["browser-file", "--json", "--connection", connection, operation, id] + (path.map { [$0] } ?? []), reply: reply)
280 }
281 private func clipboardCacheCommand(_ action: String, id: String = "", reply: @escaping (Any?, String?) -> Void) {
282 guard let data = try? JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]),
283 let request = String(data: data, encoding: .utf8) else { reply(nil,"剪贴板缓存请求无效"); return }
284 fileCommand(["clipboard-files", "--json", "cache", request], replyLimit: 30 << 20, seconds: 10, reply: reply)
285 }
286 private func watchClipboardCaches() {
287 guard clipboardCacheTimer == nil else { return }
288 clipboardCacheTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.collectClipboardCaches() }
289 restoreClipboardCaches()
290 }
291 private func restoreClipboardCaches() {
292 clipboardCacheCommand("list") { result, _ in
293 self.clipboardCacheLoaded = true
294 for selection in (result as? [String:Any])?["selections"] as? [[String:Any]] ?? [] {
295 if let id = selection["cache_id"] as? String, let paths = selection["paths"] as? [String], !paths.isEmpty {
296 self.clipboardCopies[id] = paths
297 }
298 }
299 self.collectClipboardCaches()
300 }
301 }
302 private func releaseClipboardCache(_ id: String, completion: @escaping () -> Void = {}) {
303 guard !id.isEmpty else { completion(); return }
304 clipboardReleasing.insert(id)
305 clipboardCacheCommand("release", id: id) { _, error in
306 self.clipboardReleasing.remove(id)
307 if error == nil { self.clipboardCopies.removeValue(forKey: id) }
308 completion()
309 }
310 }
311 private func collectClipboardCaches() {
312 guard clipboardCacheLoaded else { return }
313 let selected = (NSPasteboard.general.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly:true]) as? [URL] ?? []).map(\.path)
314 let readers = clipboardReaders.values.flatMap { $0 }
315 for (id, paths) in clipboardCopies {
316 guard !clipboardPending.contains(id), !clipboardReleasing.contains(id), let first = paths.first else { continue }
317 let root = URL(fileURLWithPath: first).deletingLastPathComponent().standardizedFileURL.path
318 let referenced = (selected + readers).contains { path in
319 let path = URL(fileURLWithPath: path).standardizedFileURL.path
320 return path == root || path.hasPrefix(root + "/") || root.hasPrefix(path + "/")
321 }
322 if !referenced { releaseClipboardCache(id) }
323 }
324 }
325 private func fileCommand(_ arguments: [String], replyLimit: Int = 65536, seconds: TimeInterval = 1800, reply: @escaping (Any?, String?) -> Void) {
326 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return }
327 DispatchQueue.global(qos: .userInitiated).async {
328 let process = Process(); process.executableURL = executable
329 process.arguments = arguments
330 let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice
331 do {
332 try process.run()
333 let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } }
334 DispatchQueue.global().asyncAfter(deadline: .now() + seconds, execute: timeout)
335 defer { timeout.cancel() }
336 let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit()
337 guard data.count <= replyLimit, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") }
338 DispatchQueue.main.async { reply(process.terminationStatus == 0 ? result : nil, process.terminationStatus == 0 ? nil : result["message"] as? String ?? "文件操作失败") }
339 } catch { CageDiagnostics.record(error.localizedDescription); DispatchQueue.main.async { reply(nil,error.localizedDescription) } }
340 }
341 }
342 private func rememberFiles(_ urls: [URL]) throws -> [String: Any] {
343 guard !urls.isEmpty, urls.count <= 100 else { throw CageUpdateError("请选择 1 至 100 个文件") }
344 for url in urls {
345 guard url.isFileURL, url.host == nil || url.host == "" || url.host == "localhost" else { throw CageUpdateError("请选择本机文件") }
346 let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
347 guard values.isRegularFile == true, values.isSymbolicLink != true else { throw CageUpdateError("请选择普通文件,暂不支持文件夹或链接") }
348 guard let size = values.fileSize, size <= 2 * 1024 * 1024 * 1024 else { throw CageUpdateError("每个文件不能超过 2 GB") }
349 }
350 let now = Date()
351 fileSelections = fileSelections.filter { $0.value.expires > now }
352 if fileSelections.count >= 16, let oldest = fileSelections.min(by: { $0.value.expires < $1.value.expires }) { fileSelections.removeValue(forKey: oldest.key) }
353 let id = UUID().uuidString
354 fileSelections[id] = (urls.map(\.path), now.addingTimeInterval(600))
355 return ["fileSelection": id, "count": urls.count]
356 }
357 private func showError(_ text: String) { CageDiagnostics.record(text); loading.stringValue = text; loading.isHidden = false; retry.isHidden = false; webView.isHidden = true }
358 private func applyAppearance(_ value: [String:Any]) {
359 let mode = value["mode"] as? String ?? "system"
360 NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua)
361 let translucent = value["translucent"] as? Bool ?? false
362 backdrop.isHidden = !translucent
363 window.isOpaque = !translucent
364 let background = value["background"] as? String ?? "#f7f7f7"
365 let hex = UInt32(background.dropFirst(), radix: 16) ?? 0xf7f7f7
366 window.backgroundColor = NSColor(srgbRed: Double((hex >> 16) & 255)/255, green: Double((hex >> 8) & 255)/255, blue: Double(hex & 255)/255, alpha: 1)
367 loading.textColor = .labelColor
368 }
369 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loading.isHidden = true; retry.isHidden = true; completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true; webView.isHidden = false; window.makeFirstResponder(webView); publishWindowVisibility() }
370 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
371 CageDiagnostics.record("Workbench navigation failed: \(error)")
372 let failure = error as NSError
373 let reason: String
374 switch failure.code {
375 case NSURLErrorTimedOut: reason = "等待本机后台响应超时"
376 case NSURLErrorCannotConnectToHost: reason = "本机后台没有接受连接,可能尚未启动或已经退出"
377 case NSURLErrorNetworkConnectionLost: reason = "本机工作台连接在加载完成前中断"
378 default: reason = "内置网页组件未能加载本机工作台(错误码 \(failure.code))"
379 }
380 showError("打开工作台失败:\(reason)。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。")
381 }
382 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
383 CageDiagnostics.record("WebKit content process terminated"); bootstrap()
384 }
385 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
386 guard let url = navigationAction.request.url, url.scheme == "http", url.host == "localhost", url.port == expectedPort else { decisionHandler(.cancel); return }
387 decisionHandler(.allow)
388 }
389 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage, replyHandler: @escaping (Any?, String?) -> Void) {
390 let origin = message.frameInfo.securityOrigin
391 guard message.frameInfo.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, let body = message.body as? [String:Any], let action = body["action"] as? String else { replyHandler(nil,"请求来源无效"); return }
392 switch action {
393 case "remoteInput":
394 replyHandler(nativeInput.handle(body), nil)
395 case "accountDevice":
396 guard !controllerNeedsUpdate, !accountDeviceBusy,
397 let operation = body["operation"] as? String, ["status", "enable", "disable", "unlock"].contains(operation) else { replyHandler(nil,"账户操作正在进行或后台需要更新,请稍后重试"); return }
398 accountDeviceBusy = true
399 let kind = body["kind"] as? String
400 let connection = body["connection_id"] as? String ?? "local"
401 requestEntry { result in
402 guard case .success(let entry) = result, let url = entry.url else {
403 self.accountDeviceBusy = false; replyHandler(nil,"无法连接本地账户,请重新打开 Cage"); return
404 }
405 Task.detached {
406 do {
407 let client = try CageAccountDevice(entry: url, connection: connection)
408 let value = try await client.handle(operation: operation, kind: kind)
409 await MainActor.run { self.accountDeviceBusy = false; replyHandler(value,nil) }
410 } catch {
411 await MainActor.run { self.accountDeviceBusy = false; replyHandler(nil,error.localizedDescription) }
412 }
413 }
414 }
415 case "exportDiagnostics":
416 guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return }
417 let panel = NSSavePanel(); panel.title = "导出诊断包"; panel.nameFieldStringValue = "cage-diagnostics.zip"
418 panel.allowedContentTypes = [.zip]; nativeFilePanelOpen = true
419 panel.beginSheetModal(for: window) { response in
420 self.nativeFilePanelOpen = false
421 guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return }
422 self.fileCommand(["diagnostics", "--json", "--connection", body["connection_id"] as? String ?? "local", url.path], reply: replyHandler)
423 }
424 case "workbenchReady":
425 guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return }
426 appUpdater?.markLaunchReady()
427 replyHandler(true,nil)
428 case "appUpdate":
429 guard let operation = body["operation"] as? String, ["status", "check", "install", "cancel"].contains(operation) else { replyHandler(nil,"更新操作无效"); return }
430 replyHandler(appUpdater.handle(operation),nil)
431 case "appearance":
432 guard let mode = body["mode"] as? String, ["system", "light", "dark"].contains(mode), let background = body["background"] as? String, background.range(of: "^#[0-9a-fA-F]{6}$", options: .regularExpression) != nil else { replyHandler(nil,"外观参数无效"); return }
433 let value: [String:Any] = ["mode":mode,"background":background,"translucent":body["translucent"] as? Bool ?? false]
434 UserDefaults.standard.set(value, forKey: "cage.windowAppearance")
435 applyAppearance(value)
436 replyHandler(true,nil)
437 case "clipboardRead": replyHandler(NSPasteboard.general.string(forType:.string) ?? "",nil)
438 case "clipboardRevision": watchClipboardCaches(); replyHandler(NSPasteboard.general.changeCount,nil)
439 case "clipboardSyncCancel": clipboardGeneration += 1; replyHandler(true,nil)
440 case "clipboardSyncRelease":
441 guard let id = body["files"] as? String, UUID(uuidString: id) != nil else { replyHandler(nil,"剪贴板文件标识无效"); return }
442 fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "release", id], reply: replyHandler)
443 case "clipboardSyncRead":
444 watchClipboardCaches()
445 let board = NSPasteboard.general
446 let revision = board.changeCount
447 if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly:true]) as? [URL], !urls.isEmpty {
448 let reader = UUID(), generation = clipboardGeneration
449 clipboardReaders[reader] = urls.map(\.path)
450 fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "send"] + urls.map(\.path)) { result, error in
451 defer { self.clipboardReaders.removeValue(forKey: reader); self.collectClipboardCaches() }
452 guard error == nil, var payload = result as? [String:Any] else { replyHandler(nil,error ?? "剪贴板文件传递失败"); return }
453 if generation != self.clipboardGeneration || board.changeCount != revision, let id = payload["files"] as? String {
454 self.fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "release", id]) { _, _ in }
455 }
456 payload["revision"] = revision
457 replyHandler(payload,nil)
458 }
459 } else if let image = NSImage(pasteboard:board), let tiff = image.tiffRepresentation, let bitmap = NSBitmapImageRep(data:tiff) {
460 guard bitmap.pixelsWide > 0, bitmap.pixelsHigh > 0, bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh,
461 let png = bitmap.representation(using:.png,properties:[:]), png.count <= 20 * 1024 * 1024 else { replyHandler(nil,"图片不能超过 20 MB 或 4000 万像素"); return }
462 replyHandler(["revision":revision,"png":png.base64EncodedString()],nil)
463 } else { replyHandler(["revision":revision,"text":board.string(forType:.string) ?? ""],nil) }
464 case "clipboardSyncWrite":
465 watchClipboardCaches()
466 let board = NSPasteboard.general
467 let generation = clipboardGeneration
468 let expected = body["revision"] as? Int
469 let write: ([URL]?, String) -> Void = { urls, cache in
470 guard generation == self.clipboardGeneration, expected == nil || board.changeCount == expected else {
471 self.clipboardPending.remove(cache)
472 self.releaseClipboardCache(cache) { replyHandler(["superseded":true,"revision":board.changeCount],nil) }
473 return
474 }
475 defer { self.clipboardPending.remove(cache); self.collectClipboardCaches() }
476 var written = false
477 if let urls {
478 board.clearContents(); written = board.writeObjects(urls as [NSURL])
479 } else if let encoded = body["png"] as? String, let data = Data(base64Encoded:encoded), data.count <= 20 * 1024 * 1024,
480 let bitmap = NSBitmapImageRep(data:data), bitmap.pixelsHigh > 0, bitmap.pixelsWide > 0,
481 bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh {
482 let image = NSImage(size:bitmap.size); image.addRepresentation(bitmap)
483 board.clearContents(); written = board.writeObjects([image])
484 } else if let text = body["text"] as? String, text.utf8.count <= 2 * 1024 * 1024 {
485 board.clearContents(); written = board.setString(text,forType:.string)
486 } else { replyHandler(nil,"剪贴板内容格式或大小无效"); return }
487 guard written else { replyHandler(nil,"剪贴板写入失败"); return }
488 if !cache.isEmpty { self.clipboardCacheCommand("publish", id: cache) { _, _ in } }
489 replyHandler(["revision":board.changeCount],nil)
490 }
491 if let id = body["files"] as? String, UUID(uuidString:id) != nil {
492 fileCommand(["clipboard-files","--json","--connection",body["connection_id"] as? String ?? "local","receive",id]) { result, error in
493 guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { self.restoreClipboardCaches(); replyHandler(nil,error ?? "剪贴板文件读取失败"); return }
494 let cache = (result as? [String:Any])?["cache_id"] as? String ?? ""
495 if !cache.isEmpty { self.clipboardCopies[cache] = paths; self.clipboardPending.insert(cache) }
496 write(paths.map { URL(fileURLWithPath:$0) }, cache)
497 }
498 } else { write(nil, "") }
499 case "clipboardReadContent":
500 let board = NSPasteboard.general
501 if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {
502 do { replyHandler(try rememberFiles(urls), nil) }
503 catch { replyHandler(nil, error.localizedDescription) }
504 } else if let image = NSImage(pasteboard: board), let tiff = image.tiffRepresentation,
505 let bitmap = NSBitmapImageRep(data: tiff) {
506 guard bitmap.pixelsWide > 0, bitmap.pixelsHigh > 0,
507 bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh,
508 let png = bitmap.representation(using: .png, properties: [:]), png.count <= 20 * 1024 * 1024 else {
509 replyHandler(nil,"图片不能超过 20 MB 或 4000 万像素"); return
510 }
511 replyHandler(["png":png.base64EncodedString()],nil)
512 } else { replyHandler(["text":board.string(forType:.string) ?? ""],nil) }
513 case "chooseGuestMedia":
514 guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return }
515 let panel = NSOpenPanel()
516 panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.allowsMultipleSelection = false
517 panel.allowedContentTypes = [UTType(filenameExtension: "ipsw") ?? .data]
518 panel.title = "选择 Apple 恢复镜像"; nativeFilePanelOpen = true
519 panel.beginSheetModal(for: window) { response in
520 self.nativeFilePanelOpen = false
521 replyHandler(response == .OK ? (panel.url?.path ?? "") : "", nil)
522 }
523 case "chooseUploadFiles":
524 guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return }
525 let panel = NSOpenPanel()
526 panel.canChooseDirectories = false; panel.canChooseFiles = true
527 panel.allowsMultipleSelection = body["multiple"] as? Bool ?? false
528 panel.title = "选择本机文件"; panel.prompt = "选择"
529 nativeFilePanelOpen = true
530 panel.beginSheetModal(for: window) { response in
531 self.nativeFilePanelOpen = false
532 guard response == .OK else { replyHandler(["canceled":true],nil); return }
533 do { replyHandler(try self.rememberFiles(panel.urls), nil) }
534 catch { replyHandler(nil, error.localizedDescription) }
535 }
536 case "uploadHostFiles":
537 guard let selection = body["selection"] as? String,
538 let target = body["target"] as? String, ["browser", "desktop", "terminal"].contains(target),
539 let id = body["id"] as? String, (target == "terminal" ? id.range(of: "^[a-f0-9]{16}$", options: .regularExpression) != nil : UUID(uuidString: id) != nil),
540 let files = fileSelections.removeValue(forKey: selection), files.expires > Date() else {
541 replyHandler(nil,"文件选择已过期,请重新复制或选择文件"); return
542 }
543 fileCommand(["upload-files", "--json", "--connection", body["connection_id"] as? String ?? "local", target, id] + files.paths, reply: replyHandler)
544 case "clipboardWrite":
545 guard let text = body["text"] as? String else { replyHandler(nil,"缺少文本"); return }
546 NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType:.string); replyHandler(true,nil)
547 case "saveBrowserDownload":
548 guard !nativeFilePanelOpen, let id = body["id"] as? String, UUID(uuidString:id) != nil else { replyHandler(nil,"请先完成当前文件窗口"); return }
549 let panel = NSSavePanel(); panel.canCreateDirectories = true
550 panel.nameFieldStringValue = ((body["name"] as? String ?? "download") as NSString).lastPathComponent
551 panel.prompt = "保存"; panel.title = "将下载另存为到本机"
552 nativeFilePanelOpen = true
553 panel.beginSheetModal(for: window) { response in
554 self.nativeFilePanelOpen = false
555 guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return }
556 self.browserFile("save",id:id,connection:body["connection_id"] as? String ?? "local",path:url.path,reply:replyHandler)
557 }
558 case "desktopFileAction":
559 guard let id = body["id"] as? String, UUID(uuidString:id) != nil else { replyHandler(nil,"文件打开标识无效"); return }
560 fileCommand(["desktop-file", "--json", "--connection", body["connection_id"] as? String ?? "local", id], reply: replyHandler)
561 case "browserDownloadAction":
562 guard let id = body["id"] as? String, let operation = body["operation"] as? String, ["open","reveal"].contains(operation) else { replyHandler(nil,"下载操作无效"); return }
563 browserFile(operation,id:id,connection:body["connection_id"] as? String ?? "local",reply:replyHandler)
564 case "importTheme":
565 let panel = NSOpenPanel()
566 panel.allowedContentTypes = [.json]; panel.allowsMultipleSelection = false
567 panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.prompt = "导入主题"
568 nativeFilePanelOpen = true
569 panel.beginSheetModal(for: window) { response in
570 self.nativeFilePanelOpen = false
571 guard response == .OK, let url = panel.url else { replyHandler("", nil); return }
572 do {
573 let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
574 let data = try handle.read(upToCount: 256 * 1024 + 1) ?? Data()
575 guard data.count <= 256 * 1024, let text = String(data: data, encoding: .utf8) else { replyHandler(nil, "请选择不超过 256 KB 的 UTF-8 JSON 主题文件"); return }
576 replyHandler(text, nil)
577 } catch { replyHandler(nil, "无法读取主题文件,请检查文件权限") }
578 }
579 case "exportTheme":
580 guard let text = body["text"] as? String, let data = text.data(using: .utf8), data.count <= 256 * 1024,
581 let document = try? JSONSerialization.jsonObject(with: data) as? [String: Any], document["format"] as? String == "cage-theme", document["version"] as? Int == 1 else { replyHandler(nil, "主题文件格式无效"); return }
582 let panel = NSSavePanel(); panel.allowedContentTypes = [.json]; panel.canCreateDirectories = true
583 let filename = (body["filename"] as? String ?? "Cage.cage-theme.json") as NSString
584 panel.nameFieldStringValue = filename.lastPathComponent; panel.prompt = "导出主题"
585 nativeFilePanelOpen = true
586 panel.beginSheetModal(for: window) { response in
587 self.nativeFilePanelOpen = false
588 guard response == .OK, let url = panel.url else { replyHandler(false, nil); return }
589 do { try data.write(to: url, options: .atomic); replyHandler(true, nil) }
590 catch { replyHandler(nil, "主题未能导出,请检查保存位置的权限") }
591 }
592 case "shareLocalProject":
593 guard !nativeFilePanelOpen, let connection = body["connection_id"] as? String,
594 !connection.isEmpty, let mode = body["mode"] as? String, ["read","write"].contains(mode)
595 else { replyHandler(nil,"请在云端工作台重新选择项目"); return }
596 let panel = NSOpenPanel()
597 panel.canChooseDirectories = true; panel.canChooseFiles = false
598 panel.canCreateDirectories = false; panel.allowsMultipleSelection = false
599 panel.prompt = mode == "write" ? "允许云端读写" : "允许云端读取"
600 panel.message = mode == "write" ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。"
601 nativeFilePanelOpen = true
602 panel.beginSheetModal(for: window) { response in
603 self.nativeFilePanelOpen = false
604 guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return }
605 self.fileCommand(["share-project", "--json", "--connection", connection, mode, url.path], reply: replyHandler)
606 }
607 case "chooseFolder":
608 let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false
609 let storage = (body["purpose"] as? String) == "environmentStorage"
610 panel.prompt = storage ? "选择文件夹" : "共享此项目"
611 panel.message = storage ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。"
612 nativeFilePanelOpen = true
613 panel.beginSheetModal(for:window) { response in self.nativeFilePanelOpen = false; replyHandler(response == .OK ? panel.url?.path : "",nil) }
614 case "refreshSession":
615 requestEntry(options: controllerNeedsUpdate ? ["--existing"] : []) { result in
616 switch result {
617 case .success(let entry):
618 if let url = entry.url { replyHandler(["url":url.absoluteString],nil) }
619 else { replyHandler(nil,entry.message) }
620 case .failure: replyHandler(nil,"工作台会话恢复失败,请重新连接后重试。")
621 }
622 }
623 case "reconnect": replyHandler(true,nil); bootstrap()
624 case "quitNow": replyHandler(true,nil); allowQuit = true; NSApp.terminate(nil)
625 default: replyHandler(nil,"未知操作")
626 }
627 }
628 func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = NSAlert(); alert.messageText = message; alert.beginSheetModal(for:window){_ in completionHandler()} }
629 func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) {
630 let origin = frame.securityOrigin
631 guard frame.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, !nativeFilePanelOpen else { completionHandler(nil); return }
632 let panel = NSOpenPanel(); panel.canChooseFiles = true; panel.canChooseDirectories = false
633 panel.allowsMultipleSelection = parameters.allowsMultipleSelection
634 panel.title = "选择本机文件"; nativeFilePanelOpen = true
635 panel.beginSheetModal(for: window) { response in
636 self.nativeFilePanelOpen = false
637 completionHandler(response == .OK ? panel.urls : nil)
638 }
639 }
640 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = NSAlert(); alert.messageText = message; alert.addButton(withTitle:"确定"); alert.addButton(withTitle:"取消"); alert.beginSheetModal(for:window){completionHandler($0 == .alertFirstButtonReturn)} }
641 private func publishWindowVisibility(forceHidden: Bool = false) {
642 guard window != nil, webView != nil else { return }
643 let visible = !forceHidden && window.isVisible && !window.isMiniaturized && window.occlusionState.contains(.visible)
644 webView.evaluateJavaScript("window.cageWindowVisible = \(visible ? "true" : "false"); window.dispatchEvent(new Event('cage-window-visibility'));", completionHandler: nil)
645 }
646 func windowDidChangeOcclusionState(_ notification: Notification) { publishWindowVisibility() }
647 func windowDidMiniaturize(_ notification: Notification) { publishWindowVisibility() }
648 func windowDidDeminiaturize(_ notification: Notification) { publishWindowVisibility() }
649 func windowWillClose(_ notification: Notification) { publishWindowVisibility(forceHidden: true) }
650 func applicationDidHide(_ notification: Notification) { publishWindowVisibility(forceHidden: true) }
651 func applicationDidUnhide(_ notification: Notification) { publishWindowVisibility() }
652 func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { window.makeKeyAndOrderFront(nil); publishWindowVisibility(); return true }
653 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
654 func applicationWillTerminate(_ notification: Notification) { appUpdater?.cancelForTermination() }
655 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
656 if allowQuit || webView.isHidden || appUpdater?.awaitingInitialWorkbench == true {
657 if appUpdater?.prepareForTermination({ NSApp.reply(toApplicationShouldTerminate: true) }) == true { return .terminateLater }
658 return .terminateNow
659 }
660 window.makeKeyAndOrderFront(nil); action("quit"); return .terminateCancel
661 }
662}