| 1 | import React, { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react"; |
| 2 | import { DesktopToolbar, useDesktopZoom } from "./claude-desktop"; |
| 3 | import { MacOSLogin } from "./macos-login"; |
| 4 | import { api, native, nativeAvailable } from "./api"; |
| 5 | import { BrowserUploads } from "./browser-uploads"; |
| 6 | import { sendFiles } from "./file-transfer"; |
| 7 | import { prepareClipboardPaste, sendImage } from "./image-transfer"; |
| 8 | import { installRemoteInput } from "./remote-input"; |
| 9 | import { createMacWindowInput } from "./macos-window-input.mjs"; |
| 10 | import { copyGuestText } from "./shared-clipboard.mjs"; |
| 11 | import { useWindowVisibility } from "./window-visibility"; |
| 12 | import { createMacWindowConnection } from "./macos-window-connection.mjs"; |
| 13 | import { createMacFrameConnection } from "./macos-frame-connection.mjs"; |
| 14 | import "./macos-claude-window.css"; |
| 15 | |
| 16 | const messages = { |
| 17 | requires_gui_login: "请先登录并解锁虚拟 Mac 的图形账户。", |
| 18 | screen_recording_permission: "请在虚拟 Mac 的系统授权中,允许 Cage Guest Window 录制屏幕。", |
| 19 | accessibility_permission: "要操作窗口,请允许虚拟 Mac 中的 Cage Guest Window 使用辅助功能。", |
| 20 | not_running: "请打开虚拟 Mac 中的 Claude Desktop。", |
| 21 | no_visible_window: "Claude 尚未显示窗口,请重新打开应用。", |
| 22 | identity_error: "虚拟 Mac 中的应用未通过 Anthropic 签名检查。", |
| 23 | window_changed: "Claude 的活动窗口已变化,请打开应用并在新画面中重试。", |
| 24 | unknown_action: "客机窗口输入组件需要更新,请在环境设置中更新组件后重试。", |
| 25 | input_connection_required: "窗口输入需要重新连接,请恢复画面后重试。", |
| 26 | input_owned_by_another_view: "另一个连接正在操作此窗口,请等待它释放按键或拖动。", |
| 27 | }; |
| 28 | |
| 29 | async function windowRequest(action, fields = {}, connection) { |
| 30 | const result = connection ? await connection.request(action, fields) : await api("/macos/claude/window", { action, ...fields }); |
| 31 | if (result.error) { |
| 32 | const error = new Error(messages[result.error] || "未能读取或操作虚拟 Mac 中的应用窗口。"); |
| 33 | error.code = result.error; |
| 34 | throw error; |
| 35 | } |
| 36 | return result; |
| 37 | } |
| 38 | |
| 39 | |
| 40 | |
| 41 | function matchWindowBackground(img, pane, canvasRef) { |
| 42 | if (!pane) return; |
| 43 | if (img.clientWidth >= pane.clientWidth - 1 && img.clientHeight >= pane.clientHeight - 1) return; |
| 44 | if (!canvasRef.current) { |
| 45 | canvasRef.current = document.createElement("canvas"); |
| 46 | canvasRef.current.width = 4; |
| 47 | canvasRef.current.height = 1; |
| 48 | } |
| 49 | const canvas = canvasRef.current; |
| 50 | const ctx = canvas.getContext("2d", {willReadFrequently:true}); |
| 51 | if (!ctx) return; |
| 52 | const w = img.naturalWidth, h = img.naturalHeight; |
| 53 | if (w < 16 || h < 16) return; |
| 54 | [[8,8],[w-9,8],[8,h-9],[w-9,h-9]].forEach(([x,y],i) => |
| 55 | ctx.drawImage(img,x,y,1,1,i,0,1,1)); |
| 56 | const pixels = ctx.getImageData(0,0,4,1).data; |
| 57 | const uniform = pixels.every((value, index) => Math.abs(value - pixels[index % 4]) <= 4); |
| 58 | pane.style.backgroundColor = uniform && pixels[3] === 255 ? `rgb(${pixels[0]}, ${pixels[1]}, ${pixels[2]})` : ""; |
| 59 | } |
| 60 | |
| 61 | export function MacOSClaudeWindow({ visible, keyboard = "mac", remoteRef, sidebarCollapsed, onExpand, onConfirm, uploads = [], onStatus = () => {}, onFallback = () => {} }) { |
| 62 | const windowVisible = useWindowVisibility(); |
| 63 | const screenVisible = visible && windowVisible; |
| 64 | const connection = useRef(null); |
| 65 | const [inputChannel, setInputChannel] = useState(null); |
| 66 | const frameConnection = useRef(null); |
| 67 | const request = (action, fields) => windowRequest(action, fields, connection.current); |
| 68 | const [zoom, setZoom] = useDesktopZoom(); |
| 69 | const [state, setState] = useState(null); |
| 70 | const [error, setError] = useState(""); |
| 71 | const [fileError, setFileError] = useState(""); |
| 72 | const [transferring, setTransferring] = useState(false); |
| 73 | const [revision, refresh] = useState(0); |
| 74 | const [image, setImage] = useState(null); |
| 75 | const frame = useRef(null); |
| 76 | const surface = useRef(null); |
| 77 | const controls = useRef(null); |
| 78 | const current = useRef(null); |
| 79 | current.current = { screenVisible, keyboard, input: state?.input, onStatus, onFallback }; |
| 80 | const pane = useRef(null); |
| 81 | const backgroundSample = useRef(null); |
| 82 | const viewport = useRef(null); |
| 83 | useLayoutEffect(() => { |
| 84 | const element = pane.current; |
| 85 | if (!visible || !element) return; |
| 86 | const measure = () => { |
| 87 | const { width, height } = element.getBoundingClientRect(); |
| 88 | viewport.current = width > 0 && height > 0 ? { |
| 89 | width: Math.min(2560, Math.max(320, Math.round(width / zoom))), |
| 90 | height: Math.min(1600, Math.max(240, Math.round(height / zoom))), |
| 91 | } : null; |
| 92 | frameConnection.current?.resize(viewport.current); |
| 93 | }; |
| 94 | measure(); |
| 95 | const observer = new ResizeObserver(measure); |
| 96 | observer.observe(element); |
| 97 | return () => { observer.disconnect(); viewport.current = null; }; |
| 98 | }, [visible, zoom]); |
| 99 | const picker = useRef(null); |
| 100 | const pickerTarget = useRef(null); |
| 101 | const generation = useRef(0); |
| 102 | const launched = useRef(false); |
| 103 | |
| 104 | useEffect(() => { |
| 105 | if (!screenVisible) return; |
| 106 | const epoch = ++generation.current; |
| 107 | let timer; |
| 108 | let current, nextStatus = 0, after = "", captureSize = "", checkFrame = true; |
| 109 | const live = () => generation.current === epoch; |
| 110 | function receiveFrame(next) { |
| 111 | if (!live()) return; |
| 112 | if (frame.current?.window !== next.window || frame.current?.pid !== next.pid || frame.current?.geometry !== next.geometry) frame.current = null; |
| 113 | setImage({ |
| 114 | src: next.src || `data:${next.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${next.image}`, |
| 115 | window: next.window, pid: next.pid, |
| 116 | geometry: next.geometry, width: next.contentWidth, height: next.contentHeight, |
| 117 | acknowledge: next.acknowledge, |
| 118 | }); |
| 119 | setError(""); |
| 120 | } |
| 121 | async function poll() { |
| 122 | let delay = 2200; |
| 123 | try { |
| 124 | if (!current || Date.now() >= nextStatus) { |
| 125 | current = await request("status"); |
| 126 | checkFrame = true; |
| 127 | nextStatus = Date.now() + 2200; |
| 128 | if (live() && current.persistent && !connection.current) { |
| 129 | connection.current = createMacWindowConnection(); |
| 130 | setInputChannel(connection.current); |
| 131 | } |
| 132 | } |
| 133 | if (!live()) return; |
| 134 | setState(current); |
| 135 | |
| 136 | |
| 137 | if (current.installed && !launched.current) { |
| 138 | launched.current = true; |
| 139 | await request("launch"); |
| 140 | nextStatus = 0; |
| 141 | delay = 100; |
| 142 | return; |
| 143 | } |
| 144 | if (current.running && current.screen) { |
| 145 | if (current.push_frames && viewport.current) { |
| 146 | if (!frameConnection.current) { |
| 147 | frameConnection.current = createMacFrameConnection(receiveFrame, reason => { |
| 148 | if (!live()) return; |
| 149 | frameConnection.current = null; |
| 150 | nextStatus = 0; |
| 151 | frame.current = null; |
| 152 | setImage(null); |
| 153 | setError(messages[reason] || "未能读取虚拟 Mac 的窗口画面,请重新连接。"); |
| 154 | }); |
| 155 | } |
| 156 | frameConnection.current.resize(viewport.current); |
| 157 | return; |
| 158 | } |
| 159 | const nextSize = JSON.stringify(viewport.current); |
| 160 | if (nextSize !== captureSize) { after = ""; captureSize = nextSize; } |
| 161 | const next = await request("frame", viewport.current ? { |
| 162 | after, refresh: checkFrame, |
| 163 | ...viewport.current, scale: Math.max(1, Math.min(2, window.devicePixelRatio || 1)), |
| 164 | } : {}); |
| 165 | if (!live()) return; |
| 166 | checkFrame = false; |
| 167 | delay = current.persistent ? 50 : 350; |
| 168 | if (next.unchanged) return; |
| 169 | after = next.sequence || ""; |
| 170 | receiveFrame(next); |
| 171 | } else { frameConnection.current?.close(); frameConnection.current = null; frame.current = null; setImage(null); } |
| 172 | setError(""); |
| 173 | } catch (e) { |
| 174 | if (!live()) return; |
| 175 | connection.current?.close(); connection.current = null; |
| 176 | setInputChannel(null); |
| 177 | frameConnection.current?.close(); frameConnection.current = null; |
| 178 | current = null; after = ""; |
| 179 | if (live()) { frame.current = null; setImage(null); setError(e.message); } |
| 180 | } finally { if (live()) timer = setTimeout(poll, delay); } |
| 181 | } |
| 182 | poll(); |
| 183 | return () => { |
| 184 | generation.current++; clearTimeout(timer); frame.current = null; |
| 185 | connection.current?.close(); connection.current = null; |
| 186 | setInputChannel(null); |
| 187 | frameConnection.current?.close(); frameConnection.current = null; |
| 188 | }; |
| 189 | }, [screenVisible, revision]); |
| 190 | |
| 191 | async function action(name) { |
| 192 | try { if (name === "stop") launched.current = true; await request(name); setError(""); refresh((n) => n + 1); } |
| 193 | catch (e) { setError(e.message); } |
| 194 | } |
| 195 | useImperativeHandle(remoteRef, () => ({ |
| 196 | focus: () => controls.current?.transport.focus(), |
| 197 | edit: command => controls.current?.input.focused() ? controls.current.input.edit(command) : false, |
| 198 | copy: () => controls.current?.input.copy(), |
| 199 | paste: () => controls.current?.input.readAndPaste(), |
| 200 | pasteText: text => controls.current?.input.paste(text), |
| 201 | transfer: () => onFallback("", "可在此使用本机复制、粘贴。"), |
| 202 | })); |
| 203 | |
| 204 | useEffect(() => { |
| 205 | if (!screenVisible || !state?.input || !surface.current || !pane.current || (state.persistent && !inputChannel)) return; |
| 206 | const inputRequest = (action, fields) => windowRequest(action, fields, inputChannel); |
| 207 | const transport = createMacWindowInput({ |
| 208 | element: surface.current, |
| 209 | frame: () => frame.current, |
| 210 | active: () => Boolean(current.current.screenVisible && current.current.input && frame.current), |
| 211 | request: inputRequest, |
| 212 | onError: setError, |
| 213 | }); |
| 214 | const preparePaste = () => { |
| 215 | const lease = { target: transport.target(), epoch: generation.current, transport }; |
| 216 | return Object.assign(prepareClipboardPaste("desktop", "", { windowTarget: lease.target, valid: () => transport.valid(lease.target) }), { lease }); |
| 217 | }; |
| 218 | const input = installRemoteInput(transport, pane.current, { |
| 219 | mode: () => current.current.keyboard, |
| 220 | guestPlatform: () => "darwin", |
| 221 | systemClipboard: () => true, |
| 222 | copyText: (sendCopy, valid) => copyGuestText({ request: value => api("/clipboard/copy", value), sendCopy, valid }), |
| 223 | surface: () => surface.current, |
| 224 | inputLabel: "向 Claude Desktop 输入", |
| 225 | tabId: () => frame.current ? `${frame.current.pid}:${frame.current.window}:${frame.current.geometry}` : "", |
| 226 | isActive: () => Boolean(current.current.screenVisible && current.current.input && frame.current), |
| 227 | onStatus: text => current.current.onStatus(text), |
| 228 | onFallback: (...values) => current.current.onFallback(...values), |
| 229 | insertText: text => transport.send("text", { text }), |
| 230 | caretRect: session => inputRequest("ime", { ...frame.current, mode: "status", session }).catch(error => { |
| 231 | if (error.code === "unknown_action") setError(error.message); |
| 232 | return { available: false }; |
| 233 | }), |
| 234 | insertComposition: (_, value) => transport.send("ime", value).then(result => { |
| 235 | if (value.mode !== "cancel" && !result.available) throw new Error("输入位置已变化,请重新输入"); |
| 236 | return result; |
| 237 | }), |
| 238 | preparePaste, |
| 239 | pasteContent: (content, prepared) => receive(content, prepared?.lease || { target: transport.target(), epoch: generation.current, transport }, prepared), |
| 240 | }); |
| 241 | controls.current = { transport, input }; |
| 242 | return () => { |
| 243 | input.dispose(); transport.dispose(); |
| 244 | if (controls.current?.transport === transport) controls.current = null; |
| 245 | }; |
| 246 | }, [screenVisible, state?.input, state?.persistent, inputChannel, image?.geometry, image?.pid, image?.window]); |
| 247 | |
| 248 | function receive(content, lease, prepared) { |
| 249 | const target = lease?.target || frame.current; |
| 250 | const epoch = lease?.epoch ?? generation.current; |
| 251 | const transport = lease?.transport || controls.current?.transport; |
| 252 | const valid = () => target && epoch === generation.current && transport?.valid(target); |
| 253 | const ready = Promise.resolve(content).then(value => ({ value }), error => ({ error })); |
| 254 | if (!transport) { prepared?.dispose(); return Promise.reject(new Error("窗口尚未连接,请稍后重试")); } |
| 255 | return transport.run(async () => { |
| 256 | const { value, error } = await ready; |
| 257 | if (error) throw error; |
| 258 | if (!valid()) throw new Error("Claude 窗口已切换,请回到原窗口重新传递附件"); |
| 259 | setFileError(""); setTransferring(true); |
| 260 | if (value.files || value.fileSelection) { |
| 261 | await sendFiles(value, "desktop", "", { valid, windowTarget: target, onProgress: (loaded, total) => onStatus(total ? `正在传递附件 · ${Math.floor(loaded * 100 / total)}%` : "正在传递附件…") }); |
| 262 | } else if (value.png) { |
| 263 | await sendImage(value, "desktop", "", { prepared }); |
| 264 | } else if (value.text) { |
| 265 | await request("text", { ...target, text: value.text }); |
| 266 | } |
| 267 | if (valid()) onStatus(value.text ? "已粘贴" : "附件已交给 Claude Desktop,请在应用中确认上传结果"); |
| 268 | }).finally(() => { prepared?.dispose(); setTransferring(false); }); |
| 269 | } |
| 270 | const fileFailure = error => { setFileError(error.message); onStatus(error.message); }; |
| 271 | async function chooseFiles() { |
| 272 | const lease = { target: frame.current, epoch: generation.current, transport: controls.current?.transport }; |
| 273 | if (!nativeAvailable()) { pickerTarget.current = lease; picker.current?.click(); return; } |
| 274 | try { |
| 275 | const selected = await native("chooseUploadFiles", { multiple: true }); |
| 276 | if (!selected.canceled) await receive({ fileSelection: selected.fileSelection, kind: "paste" }, lease); |
| 277 | } catch (error) { fileFailure(error); } |
| 278 | } |
| 279 | if (!visible) return null; |
| 280 | return <section className="claude-desktop-view mac-claude" aria-label="虚拟 Mac 中的 Claude Desktop"> |
| 281 | <BrowserUploads requests={uploads} onStatus={onStatus} /> |
| 282 | <DesktopToolbar desktop={state} platform="macOS" zoom={zoom} setZoom={setZoom} onConfirm={onConfirm} |
| 283 | onStop={() => action("stop")} refresh={() => refresh(n => n+1)} sidebarCollapsed={sidebarCollapsed} onExpand={onExpand}> |
| 284 | <MacOSLogin /> |
| 285 | <button disabled={!state?.input || !image || transferring} onClick={() => void chooseFiles()}>添加附件</button> |
| 286 | <input ref={picker} type="file" multiple hidden aria-label="选择 Claude 附件" onChange={event => { const files = Array.from(event.target.files || []); event.target.value = ""; if (files.length) void receive({ files, kind: "paste" }, pickerTarget.current || undefined).catch(fileFailure); }} /> |
| 287 | {(!state?.running || error) && <button onClick={() => action("launch")} disabled={!state?.installed}>{state?.running ? "重新连接应用" : "打开应用"}</button>} |
| 288 | {state?.installed && !state.screen && <button onClick={() => action("request-screen")}>授权窗口画面</button>} |
| 289 | {state?.installed && !state.input && <button onClick={() => action("request-input")}>授权键鼠</button>} |
| 290 | </DesktopToolbar> |
| 291 | {error && <p role="alert">{error}</p>} |
| 292 | {fileError && <p role="alert">{fileError}</p>} |
| 293 | {state && !state.installed && <p>此虚拟 Mac 尚未安装官方 Claude Desktop。</p>} |
| 294 | {state?.running && !state.screen && <p>{messages.screen_recording_permission}</p>} |
| 295 | {state?.running && state.screen && !state.input && <p>{messages.accessibility_permission}</p>} |
| 296 | <div ref={pane} className="mac-claude-frame" style={{ "--desktop-zoom": zoom }}> |
| 297 | {image && <img ref={surface} key={image.geometry || `${image.pid}-${image.window}`} alt="Claude Desktop 客机窗口" src={image.src} draggable={false} |
| 298 | onLoad={e => { |
| 299 | const img = e.currentTarget; |
| 300 | const width = image.width || img.naturalWidth; |
| 301 | const height = image.height || img.naturalHeight; |
| 302 | img.style.setProperty("--frame-width", width + "px"); |
| 303 | img.style.setProperty("--frame-aspect", width / height); |
| 304 | frame.current = { window: image.window, pid: image.pid, geometry: image.geometry }; |
| 305 | matchWindowBackground(img, pane.current, backgroundSample); |
| 306 | image.acknowledge?.(); |
| 307 | }} |
| 308 | onError={() => { frameConnection.current?.close(); frameConnection.current = null; frame.current = null; setImage(null); setError("窗口画面无法解码,请重新连接。"); }} |
| 309 | />} |
| 310 | </div> |
| 311 | </section>; |
| 312 | } |