| 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | import { Check, LoaderCircle } from "lucide-react"; |
| 3 | import { api, native, nativeAvailable } from "./api"; |
| 4 | import { useAccount } from "./account"; |
| 5 | import { MacOSLogin } from "./macos-login"; |
| 6 | import { DiagnosticSettings } from "./diagnostics.jsx"; |
| 7 | import { Modal } from "./modal"; |
| 8 | import "./initialization.css"; |
| 9 | |
| 10 | const steps = [ |
| 11 | { id: "screen", label: "窗口录制", hint: "打开 Cage Guest Window 的窗口录制开关。如果提示「退出并重新打开」,按提示操作。" }, |
| 12 | { id: "input", label: "辅助功能", hint: "打开 Cage Guest Window 的辅助功能开关,允许 Cage 操作客机窗口。" }, |
| 13 | { id: "projects", label: "文件系统扩展", hint: "打开 macFUSE 和 macFUSE (local) 两个开关,用于在客机中访问你选择的项目。" }, |
| 14 | ]; |
| 15 | |
| 16 | export function MacOSFirstSetup() { |
| 17 | const { account, refresh } = useAccount(); |
| 18 | const [permissionPage, setPermissionPage] = useState("screen"); |
| 19 | const [state, setState] = useState(null); |
| 20 | const [permissions, setPermissions] = useState({}); |
| 21 | const [error, setError] = useState(""); |
| 22 | const [readError, setReadError] = useState(""); |
| 23 | const [completionFailed, setCompletionFailed] = useState(false); |
| 24 | const [busy, setBusy] = useState(false); |
| 25 | const [diagnostics, setDiagnostics] = useState(false); |
| 26 | const [details, setDetails] = useState(false); |
| 27 | const current = useRef({ account, refresh }); |
| 28 | current.current = { account, refresh }; |
| 29 | const control = useRef({ active: false, inFlight: false, started: false, finished: false, requested: "", pending: "" }); |
| 30 | |
| 31 | async function request(action) { |
| 32 | const lifecycle = action === "start" || action === "stop"; |
| 33 | const signal = AbortSignal.timeout(action === "finish" ? 60000 : 30000); |
| 34 | let result; |
| 35 | try { |
| 36 | result = await api(lifecycle ? `/${action}` : "/macos/first-setup", action === "start" ? { guest_system: "macos" } : action === "stop" ? {} : { action }, undefined, {}, { signal }); |
| 37 | } catch (e) { |
| 38 | if (signal.aborted) throw new Error("等待客机响应超时。请重新检查状态,确认刚才的操作是否已完成后继续。"); |
| 39 | |
| 40 | if (e.status === 410) await current.current.refresh(); |
| 41 | throw e; |
| 42 | } |
| 43 | if (result.error) throw new Error(result.error); |
| 44 | return result; |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | async function check() { |
| 50 | const c = control.current; |
| 51 | if (c.inFlight || !c.active) return; |
| 52 | c.inFlight = true; |
| 53 | setBusy(true); |
| 54 | try { |
| 55 | const next = await api("/status", undefined, undefined, {}, { signal: AbortSignal.timeout(15000) }); |
| 56 | if (!c.active) return; |
| 57 | setState(next); |
| 58 | const credentialsPending = current.current.account.macos_password_pending; |
| 59 | if ((!next.vm_running || credentialsPending) && !next.job?.running && !next.job?.error && !next.job?.canceled && !c.started) { |
| 60 | c.started = true; |
| 61 | setBusy(true); |
| 62 | try { await request("start"); } |
| 63 | catch (e) { if (c.active) setError(e.message); } |
| 64 | return; |
| 65 | } |
| 66 | if (!next.ready || next.job?.running || credentialsPending) { setReadError(""); return; } |
| 67 | const measured = await request("permissions"); |
| 68 | if (!c.active) return; |
| 69 | setReadError(""); |
| 70 | setPermissions(measured); |
| 71 | const pending = steps.find(({ id }) => !measured[id]); |
| 72 | if (pending && c.pending !== pending.id) { |
| 73 | c.pending = pending.id; |
| 74 | setPermissionPage(pending.id); |
| 75 | } |
| 76 | if (measured.managed_credential && pending && c.requested !== pending.id) { |
| 77 | c.requested = pending.id; |
| 78 | setPermissionPage(pending.id); |
| 79 | setBusy(true); |
| 80 | try { await request(pending.id); setError(""); } |
| 81 | catch (e) { if (c.active) setError(e.message); } |
| 82 | } |
| 83 | if (!pending && !c.finished) { |
| 84 | c.finished = true; |
| 85 | setBusy(true); |
| 86 | try { await request("finish"); if (c.active) await current.current.refresh(); } |
| 87 | catch (e) { if (c.active) { setCompletionFailed(true); setError(e.message); } } |
| 88 | } |
| 89 | } catch (e) { if (c.active) setReadError(e.name === "TimeoutError" ? "读取客机状态超时。请重新检查状态;已有安装进度会保留。" : e.message); } |
| 90 | finally { c.inFlight = false; if (c.active) setBusy(false); } |
| 91 | } |
| 92 | |
| 93 | useEffect(() => { |
| 94 | const c = control.current; |
| 95 | c.active = true; |
| 96 | let timer; |
| 97 | async function poll() { |
| 98 | await check(); |
| 99 | if (c.active) timer = setTimeout(poll, 2000); |
| 100 | } |
| 101 | poll(); |
| 102 | window.cageWorkbenchAction = async command => { |
| 103 | if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal")); |
| 104 | if (command === "quit") await native("quitNow"); |
| 105 | }; |
| 106 | window.cageEditAction = () => false; |
| 107 | if (nativeAvailable()) native("workbenchReady").catch(() => {}); |
| 108 | return () => { c.active = false; clearTimeout(timer); delete window.cageWorkbenchAction; delete window.cageEditAction; }; |
| 109 | }, []); |
| 110 | |
| 111 | async function act(action) { |
| 112 | const c = control.current; |
| 113 | if (c.inFlight) return; |
| 114 | c.inFlight = true; |
| 115 | if (action === "stop") c.started = true; |
| 116 | if (steps.some(({ id }) => id === action)) { setPermissionPage(action); c.requested = action; } |
| 117 | setBusy(true); setError(""); |
| 118 | try { |
| 119 | await request(action); |
| 120 | if (action === "finish") { await current.current.refresh(); setCompletionFailed(false); } |
| 121 | } catch (e) { |
| 122 | if (action === "finish") setCompletionFailed(true); |
| 123 | setError(e.message); |
| 124 | } finally { c.inFlight = false; if (c.active) { setBusy(false); void check(); } } |
| 125 | } |
| 126 | |
| 127 | const pending = steps.find(({ id }) => !permissions[id]); |
| 128 | const selected = steps.find(({ id }) => id === permissionPage); |
| 129 | const running = Boolean(state?.job?.running); |
| 130 | const canOperate = Boolean(state?.vm_running && !running && !busy); |
| 131 | const canFinish = Boolean(state?.ready && !account.macos_password_pending && !pending && !readError); |
| 132 | const progress = !state ? "正在读取安装进度…" : running ? state.job.message || "正在启动和配置虚拟 Mac…" : |
| 133 | account.macos_password_pending ? "客机密码尚未同步,请重试同步后继续授权。" : !state.vm_running ? "虚拟 Mac 尚未启动,可从已有磁盘继续。" : |
| 134 | !state.ready ? "虚拟 Mac 已启动,正在等待客机连接。若停在登录画面,请打开客机画面完成登录。" : |
| 135 | readError ? "暂时无法确认权限状态,已显示的结果供参考。恢复连接后会继续检查。" : |
| 136 | pending ? `当前需要确认「${pending.label}」。完成后 Cage 会自动检查并继续。` : |
| 137 | completionFailed ? "三项权限已验证,最后的设置收尾未完成。请重试完成设置。" : "三项权限已验证,正在保存设置;随后继续工作区授权和联网检查。"; |
| 138 | const controls = <button type="button" className="primary" disabled={!canOperate} onClick={() => act(pending?.id || permissionPage)}> |
| 139 | {busy ? "正在处理…" : `打开${pending?.label || selected.label}`} |
| 140 | </button>; |
| 141 | const failure = error || readError || (!running && state?.job?.error) || (!state?.ready && state?.environment_update_error); |
| 142 | |
| 143 | return <main className="initialization"><section className="initialization-content mac-setup-content"> |
| 144 | <div className="initialization-title"><p className="mac-setup-eyebrow">安装与检查 · macOS 系统权限</p><h1>完成虚拟 Mac 的系统授权</h1> |
| 145 | <p>安装文件和客机磁盘已保留。下面三项授权在虚拟 Mac 内完成,每项验证通过后会自动继续。</p></div> |
| 146 | <ol className="mac-setup-checklist" aria-label="系统授权进度"> |
| 147 | {steps.map(({ id, label }, index) => <li key={id} data-complete={Boolean(permissions[id])} aria-current={pending?.id === id ? "step" : undefined}> |
| 148 | <span className="mac-setup-marker">{permissions[id] ? <Check size={16} aria-hidden="true" /> : index + 1}</span> |
| 149 | <span>{label}</span><small>{permissions[id] ? "已验证" : pending?.id === id ? "等待确认" : "稍后确认"}</small> |
| 150 | </li>)} |
| 151 | </ol> |
| 152 | <section className="initialization-operation mac-setup-task" aria-label="当前设置步骤"> |
| 153 | <h2>{!state?.ready ? "连接虚拟 Mac" : pending ? `确认${pending.label}` : "完成系统设置"}</h2> |
| 154 | <p role="status">{busy && <LoaderCircle size={16} className="spin" aria-hidden="true" />} {progress}</p> |
| 155 | {pending && state?.ready && <><p>{selected.hint}</p>{pending.id === "projects" && permissions.projects_error && <p>{permissions.projects_error}</p>}</>} |
| 156 | <div className="initialization-recovery"> |
| 157 | {state && !running && (!state.ready || account.macos_password_pending || state.job?.error) && <button className="primary" disabled={busy} onClick={() => act("start")}>{account.macos_password_pending ? "重试同步客机密码" : "继续启动并连接"}</button>} |
| 158 | {pending && state?.ready && controls} |
| 159 | {completionFailed && <button className="primary" disabled={busy || !canFinish} onClick={() => act("finish")}>重试完成设置</button>} |
| 160 | <button disabled={busy || running} onClick={() => void check()}>重新检查状态</button> |
| 161 | </div> |
| 162 | {running && <button disabled={busy} onClick={() => act("stop")}>停止当前操作,保留进度</button>} |
| 163 | {state?.vm_running && <MacOSLogin initialSetup autoOpen={Boolean(permissions.managed_credential)} managedCredential={permissions.managed_credential} disabled={!canOperate} |
| 164 | label="打开客机画面" setupActions={controls} setupHint={`${selected.hint} 系统要求管理员时,用户名填 cagesetup;选中密码框后可点击「填写授权密码」。`} |
| 165 | setupStatus={failure || progress} setupError={Boolean(failure)} />} |
| 166 | </section> |
| 167 | {failure && <section className="initialization-notice" role="alert"><h2>这一步尚未完成</h2><p>{failure}</p><p>已有安装进度会保留。可以重新打开当前设置页,或重新检查状态后继续。</p></section>} |
| 168 | <details className="mac-setup-help"><summary>管理员密码与找不到设置页时的帮助</summary> |
| 169 | <p>系统要求管理员时,用户名填 <strong>cagesetup</strong>,{account.macos_password_pending ? "密码同步完成前可能仍需原客机密码。" : account.macos_credentials_ready ? "密码与 Cage 账户相同。" : "在客机画面中选中密码框,再点击「填写授权密码」。"}你确认授权后继续;此临时管理员在收尾时停用。</p> |
| 170 | <p>文件系统扩展的手动入口:客机「系统设置 → 通用 → 登录项与扩展 → 按类别 → 文件系统扩展」,同时打开 macFUSE 和 macFUSE (local)。</p> |
| 171 | <div className="initialization-recovery">{steps.map(({ id, label }) => <button key={id} disabled={!canOperate} onClick={() => act(id)}>重新打开{label}</button>)}</div> |
| 172 | </details> |
| 173 | <p className="mac-setup-retention">系统授权完成后,还会确认共享工作区和网络隔离。全部检查通过后即可进入工作台。</p> |
| 174 | <div className="initialization-support"><button className="text-button" onClick={() => setDetails(true)}>查看操作详情</button><button className="text-button" onClick={() => setDiagnostics(!diagnostics)}>日志与诊断</button></div> |
| 175 | {diagnostics && <DiagnosticSettings />} |
| 176 | {details && <Modal title="系统设置操作详情" onClose={() => setDetails(false)}><div className="modal-body"><p>{progress}</p>{failure && <p role="alert">{failure}</p>}<pre className="job-log">{state?.job?.log || "当前步骤没有额外操作日志。可通过「日志与诊断」导出完整记录。"}</pre></div></Modal>} |
| 177 | </section></main>; |
| 178 | } |