跳到主要内容

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

浏览文件

macos-login.jsx

409 行 · 18.6 KB历史下载
1import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
2import { createPortal } from "react-dom";
3import { ArrowLeft, Maximize, ZoomIn } from "lucide-react";
4import { api } from "./api";
5import "./macos-login.css";
6
7// DOM physical codes and the matching ANSI key codes expected by the Apple VM keyboard.
8const keys = {
9 KeyA: 0,
10 KeyS: 1,
11 KeyD: 2,
12 KeyF: 3,
13 KeyH: 4,
14 KeyG: 5,
15 KeyZ: 6,
16 KeyX: 7,
17 KeyC: 8,
18 KeyV: 9,
19 KeyB: 11,
20 KeyQ: 12,
21 KeyW: 13,
22 KeyE: 14,
23 KeyR: 15,
24 KeyY: 16,
25 KeyT: 17,
26 Digit1: 18,
27 Digit2: 19,
28 Digit3: 20,
29 Digit4: 21,
30 Digit6: 22,
31 Digit5: 23,
32 Equal: 24,
33 Digit9: 25,
34 Digit7: 26,
35 Minus: 27,
36 Digit8: 28,
37 Digit0: 29,
38 BracketRight: 30,
39 KeyO: 31,
40 KeyU: 32,
41 BracketLeft: 33,
42 KeyI: 34,
43 KeyP: 35,
44 Enter: 36,
45 KeyL: 37,
46 KeyJ: 38,
47 Quote: 39,
48 KeyK: 40,
49 Semicolon: 41,
50 Backslash: 42,
51 Comma: 43,
52 Slash: 44,
53 KeyN: 45,
54 KeyM: 46,
55 Period: 47,
56 Tab: 48,
57 Space: 49,
58 Backquote: 50,
59 Backspace: 51,
60 Escape: 53,
61};
62const charKeys = {};
63for (const [name, code] of Object.entries(keys)) {
64 if (name.startsWith("Key")) {
65 charKeys[name.slice(-1).toLowerCase()] = [code, false];
66 charKeys[name.slice(-1)] = [code, true];
67 }
68 if (name.startsWith("Digit")) charKeys[name.slice(-1)] = [code, false];
69}
70for (const [code, pair] of Object.entries({ Digit1:"1!", Digit2:"2@", Digit3:"3#", Digit4:"4$", Digit5:"5%", Digit6:"6^", Digit7:"7&", Digit8:"8*", Digit9:"9(", Digit0:"0)", Minus:"-_", Equal:"=+", BracketLeft:"[{", BracketRight:"]}", Backslash:"\\|", Semicolon:";:", Quote:"'\"", Comma:",<", Period:".>", Slash:"/?", Backquote:"`~", Space:" " })) {
71 [...pair].forEach((ch, i) => { charKeys[ch] = [keys[code], i === 1]; });
72}
73const setupKeys = {ArrowLeft:123, ArrowRight:124, ArrowDown:125, ArrowUp:126, PageUp:116, PageDown:121};
74// Apple receives logical view coordinates; Retina PNGs may have more pixels.
75const guestWidth = 1024;
76const guestHeight = 640;
77
78function closeSession(session, endpoint, maintenance) {
79 if (session) api(endpoint, { action: "close", session, ...(maintenance ? { maintenance } : {}) }).catch(() => {});
80}
81
82export function MacOSLogin({ disabled, initialSetup = false, maintenance = "", label, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false, onSessionClosed, onSettings }) {
83 const endpoint = initialSetup ? "/macos/first-setup" : maintenance ? "/macos/maintenance" : "/macos/login";
84 const scope = maintenance ? { maintenance } : {};
85 const [opened, setOpened] = useState(false);
86 const [session, setSession] = useState("");
87 const [frame, setFrame] = useState("");
88 const [message, setMessage] = useState("");
89 const [frameError, setFrameError] = useState("");
90 const [recovery, setRecovery] = useState("");
91 const [administrator, setAdministrator] = useState("");
92 const [frameTarget, setFrameTarget] = useState(null);
93 const [authorizationPassword, setAuthorizationPassword] = useState("");
94 const [zoomed, setZoomed] = useState(!initialSetup && !maintenance);
95 const [size, setSize] = useState({ width: 0, height: 0 });
96 const [aspect, setAspect] = useState(guestWidth / guestHeight);
97 const lease = useRef(null);
98 const chain = useRef(Promise.resolve());
99 const stage = useRef(null);
100 const keyboard = useRef(null);
101 const imageRef = useRef(null);
102 const back = useRef(null);
103 const opener = useRef(null);
104 const drag = useRef(null);
105 const dragged = useRef(false);
106 const autoOpened = useRef(false);
107 const shown = useRef({ region: [0, 0, guestWidth, guestHeight], geometry: "" });
108
109 const fitWidth = Math.min(size.width, size.height * aspect);
110 // Keep a 320 × 200 logical region around the account controls visible.
111 const imageWidth = !zoomed ? fitWidth : initialSetup || maintenance ? fitWidth * 2 :
112 Math.min(size.width * guestWidth / 320, size.height * aspect * guestHeight / 200);
113 const imageHeight = imageWidth / aspect;
114 const hasFrame = Boolean(frame);
115 const visibleMessage = message || frameError;
116
117 function end(show = "") {
118 if (!lease.current) return;
119 const old = lease.current;
120 lease.current = null;
121 closeSession(old.session, endpoint, maintenance);
122 setOpened(false);
123 setSession("");
124 setFrame("");
125 setFrameTarget(null);
126 shown.current = { region: [0, 0, guestWidth, guestHeight], geometry: "" };
127 setAuthorizationPassword("");
128 setMessage(show);
129 setFrameError("");
130 }
131
132 async function open() {
133 if (lease.current) return;
134 const next = { session: "" };
135 lease.current = next;
136 chain.current = Promise.resolve();
137 setMessage("");
138 setFrameError("");
139 setRecovery("");
140 setZoomed(!initialSetup && !maintenance);
141 setOpened(true);
142 try {
143 const r = await api(endpoint, { action: "open", ...scope });
144 if (lease.current !== next) {
145 closeSession(r.session, endpoint, maintenance);
146 return;
147 }
148 if (!r.session) { setRecovery(r.recovery || ""); throw new Error(r.error || "暂时无法打开客机登录界面"); }
149 setAdministrator(r.administrator || "");
150 next.session = r.session;
151 setSession(r.session);
152 } catch (e) {
153 if (lease.current === next) end(e.message);
154 }
155 }
156
157 useEffect(() => {
158 if (autoOpen && !disabled && !autoOpened.current) {
159 autoOpened.current = true;
160 open();
161 }
162 }, [autoOpen, disabled]);
163
164 useEffect(() => {
165 if (!authorizationPassword) return;
166 const timer = setTimeout(() => setAuthorizationPassword(""),30000);
167 return () => clearTimeout(timer);
168 }, [authorizationPassword]);
169
170 useEffect(() => () => {
171 if (lease.current) {
172 closeSession(lease.current.session, endpoint, maintenance);
173 lease.current = null;
174 }
175 }, []);
176
177 useLayoutEffect(() => {
178 if (!opened) return;
179 const control = stage.current;
180 const app = document.getElementById("root");
181 const wasInert = app?.inert;
182 const overflow = document.body.style.overflow;
183 if (app) app.inert = true;
184 document.body.style.overflow = "hidden";
185 const trigger = opener.current;
186 keyboard.current?.focus({ preventScroll: true });
187 const dismiss = () => end();
188 document.addEventListener("cage-close-modal", dismiss);
189 function measure() {
190 const { width, height } = control.getBoundingClientRect();
191 setSize((old) => old.width === width && old.height === height ? old : { width, height });
192 }
193 measure();
194 const observer = new ResizeObserver(measure);
195 observer.observe(control);
196 return () => {
197 observer.disconnect();
198 document.removeEventListener("cage-close-modal", dismiss);
199 document.body.style.overflow = overflow;
200 if (app) app.inert = wasInert;
201 if (trigger?.isConnected) trigger.focus({ preventScroll: true });
202 };
203 }, [opened]);
204
205 // The account choices and password field sit near the bottom of loginwindow.
206 useLayoutEffect(() => {
207 if (!opened || !stage.current) return;
208 stage.current.scrollLeft = zoomed ? Math.max(0, (imageWidth - size.width) / 2) : 0;
209 stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * (maintenance ? 0.5 : 0.85) - size.height * 0.5) : 0;
210 }, [opened, hasFrame, zoomed, imageWidth, imageHeight, size.width, size.height]);
211
212 useEffect(() => {
213 if (!session) return;
214 let timer;
215 let alive = true;
216 const poll = async () => {
217 try {
218 const r = await api(endpoint, { action: "frame", session, ...scope });
219 if (!alive || lease.current?.session !== session) return;
220 if (r.closed) { setRecovery(r.recovery || ""); end(r.error || ""); onSessionClosed?.(); return; }
221 if (r.image) {
222 if (maintenance && (!r.geometry || !Array.isArray(r.region) || r.region.length !== 4 || !r.region.every(Number.isInteger)))
223 throw new Error("客机维护画面缺少窗口定位,请更新组件后重试");
224 setFrameTarget(maintenance ? { geometry: r.geometry, region: r.region } : null);
225 setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`);
226 setFrameError("");
227 }
228 if (r.error) setFrameError(r.error);
229 timer = setTimeout(poll, 550);
230 } catch (e) {
231 if (alive && lease.current?.session === session) end(e.message);
232 }
233 };
234 poll();
235 return () => { alive = false; clearTimeout(timer); };
236 }, [session]);
237
238 function enqueue(action, data) {
239 const owner = lease.current;
240 if (!owner?.session) return;
241 const geometry = shown.current.geometry;
242 if (maintenance && !geometry) { setMessage("请等待授权窗口画面后再操作"); return; }
243 chain.current = chain.current.then(async () => {
244 if (lease.current !== owner) return;
245 const r = await api(endpoint, { action, session: owner.session, ...scope, ...(maintenance ? { geometry } : {}), ...data });
246 if (lease.current !== owner) return;
247 if (r.closed) { end(r.error || ""); onSessionClosed?.(); }
248 else setMessage(r.error || "");
249 }).catch((e) => { if (lease.current === owner) end(e.message); });
250 }
251
252 function sendClick(e) {
253 if (dragged.current || e.button !== 0) return;
254 const rect = imageRef.current?.getBoundingClientRect();
255 if (!rect || !rect.width || !rect.height || e.clientX < rect.left || e.clientX >= rect.right ||
256 e.clientY < rect.top || e.clientY >= rect.bottom) return;
257 keyboard.current?.focus({ preventScroll: true });
258 const [x, y, width, height] = shown.current.region;
259 enqueue("click", {
260 x: x + Math.floor((e.clientX - rect.left) * width / rect.width),
261 y: y + Math.floor((e.clientY - rect.top) * height / rect.height),
262 });
263 }
264
265 function guestKey(e) {
266 if (maintenance && (e.metaKey || e.ctrlKey) && !e.altKey && e.code === "KeyA") {
267 e.preventDefault(); enqueue("select-all", {}); return;
268 }
269 const code = keys[e.code] ?? (initialSetup || maintenance ? setupKeys[e.code] : undefined);
270 if (e.metaKey || e.ctrlKey || e.altKey || code === undefined) return;
271 e.preventDefault();
272 enqueue("key", { code, shift: e.shiftKey });
273 }
274
275 useEffect(() => {
276 const element = stage.current;
277 if (!opened || (!initialSetup && !maintenance) || !element) return;
278 const scroll = (event) => {
279 const rect = imageRef.current?.getBoundingClientRect();
280 if (!rect?.width || !rect.height || event.clientX < rect.left || event.clientX >= rect.right ||
281 event.clientY < rect.top || event.clientY >= rect.bottom) return;
282 event.preventDefault();
283 const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1;
284 const bounded = (delta, scale) => Math.max(-512, Math.min(512, Math.round(delta * unit * scale)));
285 const [x, y, width, height] = shown.current.region;
286 enqueue("scroll", {
287 x: x + Math.floor((event.clientX - rect.left) * width / rect.width),
288 y: y + Math.floor((event.clientY - rect.top) * height / rect.height),
289 delta_x: bounded(event.deltaX, width / rect.width),
290 delta_y: bounded(event.deltaY, height / rect.height),
291 });
292 };
293 element.addEventListener("wheel", scroll, { passive: false });
294 return () => element.removeEventListener("wheel", scroll);
295 }, [opened, initialSetup, maintenance, session]);
296
297 function changeZoom(zoom) {
298 setZoomed(zoom);
299 keyboard.current?.focus({ preventScroll: true });
300 }
301
302 return <>
303 <button type="button" ref={opener} disabled={disabled || opened} onClick={open}>{label || (initialSetup ? "打开客机系统设置" : maintenance ? "打开客机授权设置" : "登录客机账户")}</button>
304 {!opened && message && <span role="status">{message}</span>}
305 {!opened && ["environment-update", "environment-restart"].includes(recovery) && onSettings &&
306 <button type="button" onClick={onSettings}>{recovery === "environment-update" ? "查看环境组件" : "打开环境设置"}</button>}
307 {opened && createPortal(
308 <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : maintenance ? "maintenance" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : maintenance ? "恢复客机系统权限" : "登录虚拟 Mac"}
309 onKeyDownCapture={(e) => {
310 if (e.key === "F6") {
311 e.preventDefault();
312 (document.activeElement === keyboard.current ? back.current : keyboard.current)?.focus({ preventScroll: true });
313 } else if (e.key === "Tab" && e.shiftKey && e.target === back.current) {
314 e.preventDefault();
315 keyboard.current?.focus({ preventScroll: true });
316 } else if (e.key === "Escape" && (e.shiftKey || e.target !== keyboard.current)) {
317 e.preventDefault();
318 end();
319 }
320 }}>
321 <div className="mac-login-panel">
322 <header className="mac-login-heading">
323 <h2>{initialSetup ? "虚拟 Mac 的系统设置" : maintenance ? "恢复客机系统权限" : "登录 macOS 客机"}</h2>
324 <p>{initialSetup ? "按下方提示完成当前授权,Cage 会自动检查。可以随时返回设置指引继续处理。" : maintenance ? "在当前系统设置窗口中完成授权。切换到其他客机应用或锁定后,画面会结束。" : "输入客机账户密码,按回车登录。"}</p>
325 </header>
326 <div className="mac-login-tools" role="toolbar" aria-label="画面工具">
327 <button ref={back} onClick={() => end()}><ArrowLeft size={16} aria-hidden="true" />{initialSetup ? "返回设置指引" : "返回工作台"}</button>
328 <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup || maintenance ? "适配" : "完整画面"}</button>
329 <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup || maintenance ? "放大" : "登录区域"}</button>
330 {initialSetup && setupActions}
331 {initialSetup && managedCredential && <button disabled={!session} onClick={() => enqueue("fill-password",{})}>填写授权密码</button>}
332 {!maintenance && (!initialSetup || managedCredential) && <button onClick={async () => {
333 const owner = lease.current;
334 try {
335 const result = await api(endpoint,{action:"show-password"});
336 if (lease.current !== owner) return;
337 setAuthorizationPassword(result.password); setMessage("");
338 }
339 catch (e) { if (lease.current === owner) setMessage(e.message); }
340 }}>{initialSetup ? "查看授权密码" : "查看客机密码"}</button>}
341 {authorizationPassword && <span className="mac-login-password">{authorizationPassword}<button onClick={() => setAuthorizationPassword("")}>隐藏</button></span>}
342 </div>
343 {maintenance && <div className="mac-setup-hint">
344 {maintenance === "projects" && <p>Cage 会直接打开「文件系统扩展」面板。打开 macFUSE 和 macFUSE (local) 两个开关,Cage 会自动检查并重新连接项目。</p>}
345 {administrator && <p>系统要求管理员时,用户名填写 {administrator}。选中系统授权窗口的密码框后,点击「填写管理员密码」,再由你确认授权。</p>}
346 {administrator && <button type="button" onClick={() => enqueue("fill-password", {})}>填写管理员密码</button>}
347 </div>}
348 {initialSetup && setupHint && <div className="mac-setup-hint">
349 <p>{setupHint}</p>
350 <p role={setupError ? "alert" : "status"}>{setupStatus} 查看完整步骤或进入工作台时,点击「返回设置指引」。</p>
351 </div>}
352 <input ref={keyboard} className="mac-login-keyboard" type="text" autoComplete="off" autoCapitalize="none"
353 autoCorrect="off" spellCheck={false}
354 aria-label="客机登录键盘。按 F6 切换工具栏,按 Shift 加 Escape 返回工作台。"
355 onKeyDown={guestKey}
356 onBeforeInput={(e) => e.preventDefault()}
357 onInput={(e) => { e.currentTarget.value = ""; }}
358 onPaste={(e) => {
359 e.preventDefault();
360 const text = e.clipboardData.getData("text/plain");
361 if (text.length > 256 || [...text].some((c) => !charKeys[c])) {
362 setMessage("请用键盘输入该密码。");
363 return;
364 }
365 for (const c of text) {
366 const [code, shift] = charKeys[c];
367 enqueue("key", { code, shift });
368 }
369 }} />
370 <div ref={stage} className="mac-login-stage" data-zoom={zoomed ? "account" : "fit"}
371 onPointerDown={(e) => {
372 keyboard.current?.focus({ preventScroll: true });
373 dragged.current = false;
374 if (!zoomed || e.button !== 0 || !e.isPrimary) return;
375 const el = e.currentTarget;
376 drag.current = { id: e.pointerId, x: e.clientX, y: e.clientY, left: el.scrollLeft, top: el.scrollTop };
377 }}
378 onPointerMove={(e) => {
379 const start = drag.current;
380 if (!start || start.id !== e.pointerId || !(e.buttons & 1)) return;
381 const dx = e.clientX - start.x, dy = e.clientY - start.y;
382 if (!dragged.current && Math.hypot(dx, dy) < 5) return;
383 dragged.current = true;
384 const el = e.currentTarget;
385 if (!el.hasPointerCapture(e.pointerId)) el.setPointerCapture(e.pointerId);
386 el.scrollLeft = start.left - dx;
387 el.scrollTop = start.top - dy;
388 }}
389 onPointerUp={() => { drag.current = null; }}
390 onPointerCancel={() => { drag.current = null; dragged.current = true; }}>
391 {frame && <div className="mac-login-canvas" style={{
392 width: Math.max(size.width, imageWidth), height: Math.max(size.height, imageHeight),
393 }}>
394 <img ref={imageRef} key={maintenance ? frameTarget?.geometry : undefined} alt={initialSetup ? "Apple 客机首次系统设置" : maintenance ? "客机系统设置或授权窗口" : "Apple 客机登录屏幕"} draggable={false} src={frame}
395 style={{ width: imageWidth, height: imageHeight }}
396 onLoad={(e) => {
397 if (e.currentTarget.naturalHeight) setAspect(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight);
398 if (maintenance && frameTarget) shown.current = frameTarget;
399 }} onClick={sendClick} />
400 </div>}
401 </div>
402 {(visibleMessage || !frame) && <p className="mac-login-status" role={visibleMessage ? "alert" : "status"}>
403 {visibleMessage || (initialSetup ? "正在读取客机首次设置画面…" : maintenance ? "正在确认系统授权窗口…" : "正在确认客机登录画面…")}
404 </p>}
405 {!initialSetup && !maintenance && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>}
406 </div>
407 </div>, document.body)}
408 </>;
409}