| 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | import { Check, ChevronLeft, LoaderCircle, ShieldCheck } from "lucide-react"; |
| 3 | import { api, native, nativeAvailable } from "./api"; |
| 4 | import { isRemoteClient } from "./client-context.mjs"; |
| 5 | import { MacOSAccountGate, useAccount } from "./account"; |
| 6 | import { GuestSystemPicker, HostCloneSummary, validGuestChoice } from "./guest-system-picker"; |
| 7 | import { InitializationStorage } from "./initialization-storage"; |
| 8 | import { ProxySettings } from "./proxy-settings"; |
| 9 | import { SetupProgress } from "./setup-progress"; |
| 10 | import { DiagnosticSettings } from "./diagnostics.jsx"; |
| 11 | import { MacOSFirstSetup } from "./macos-first-setup"; |
| 12 | import { InitializationProjectApproval } from "./macos-project-approval"; |
| 13 | import { InitializationChecks, InitializationDetails } from "./initialization-checks"; |
| 14 | import { MacOSLogin } from "./macos-login"; |
| 15 | import { Modal } from "./modal"; |
| 16 | import { SafetyMessage } from "./safety-message"; |
| 17 | import { bindDetectedMacOSExit } from "./safety"; |
| 18 | import { needsProxySetup } from "./onboarding-state.mjs"; |
| 19 | import { networkState } from "./safety-state.mjs"; |
| 20 | import { useSSHNavigation } from "./remote-hosts"; |
| 21 | import logo from "./logo.png"; |
| 22 | import "./initialization.css"; |
| 23 | |
| 24 | const steps = [["system", "系统与存储"], ["proxy", "网络代理"], ["install", "安装与检查"]]; |
| 25 | |
| 26 | function InitializationFrame({ children }) { |
| 27 | return <main className="initialization"><header className="initialization-brand"><img src={logo} alt="" /><strong>Cage</strong><span>首次设置</span></header>{children}</main>; |
| 28 | } |
| 29 | |
| 30 | export function InitializationGate({ children }) { |
| 31 | const { account } = useAccount(); |
| 32 | const [state, setState] = useState(null); |
| 33 | const [error, setError] = useState(""); |
| 34 | const [attempt, retry] = useState(0); |
| 35 | const remote = isRemoteClient(); |
| 36 | useEffect(() => { |
| 37 | if (remote) return; |
| 38 | let live = true; |
| 39 | setError(""); |
| 40 | (async () => { |
| 41 | const next = await api("/environment/initialization"); |
| 42 | if (next.required && !next.tracked && !next.started && !account?.initial_mac_setup) await api("/environment/initialization", { action: "begin" }); |
| 43 | if (live) setState(next); |
| 44 | })().catch(error => { if (live) setError(error.message); }); |
| 45 | return () => { live = false; }; |
| 46 | }, [remote, attempt, account?.initial_mac_setup]); |
| 47 | if (remote) return children; |
| 48 | if (account?.initial_mac_setup) return <MacOSAccountGate><MacOSFirstSetup /></MacOSAccountGate>; |
| 49 | if (error) return <InitializationFrame><section className="initialization-content"><h1>继续准备 Cage</h1><p role="alert"><SafetyMessage message={error} /></p><button className="primary" onClick={() => retry(value => value + 1)}>重新连接</button><DiagnosticSettings /></section></InitializationFrame>; |
| 50 | if (!state) return <InitializationFrame><section className="initialization-content"><h1>正在读取环境状态</h1><p role="status"><LoaderCircle size={18} className="spin" />正在检查已有配置和安装进度…</p></section></InitializationFrame>; |
| 51 | return state.required ? <MacOSAccountGate><Initialization initial={state} onComplete={() => setState({ required: false })} /></MacOSAccountGate> : children; |
| 52 | } |
| 53 | |
| 54 | function Initialization({ initial, onComplete }) { |
| 55 | const { account, refresh } = useAccount(); |
| 56 | const navigation = useSSHNavigation(); |
| 57 | const [step, setStep] = useState(initial.started || account?.guest_system ? "install" : "system"); |
| 58 | const [status, setStatus] = useState(null); |
| 59 | const [proxy, setProxy] = useState(null); |
| 60 | const [choice, setChoice] = useState(undefined); |
| 61 | const [storage, setStorage] = useState(null); |
| 62 | const [pending, setPending] = useState(null); |
| 63 | const [submitting, setSubmitting] = useState(false); |
| 64 | const [error, setError] = useState(""); |
| 65 | const [connectionError, setConnectionError] = useState(""); |
| 66 | const [git, setGit] = useState(null); |
| 67 | const [details, setDetails] = useState(false); |
| 68 | const [help, setHelp] = useState(false); |
| 69 | const [dialog, setDialog] = useState(null); |
| 70 | const [approvalWorkspace, setApprovalWorkspace] = useState(""); |
| 71 | const [proxyDirty, setProxyDirty] = useState(false); |
| 72 | const alive = useRef(true); |
| 73 | const pollNow = useRef(null); |
| 74 | const activation = useRef(false); |
| 75 | const actionPending = useRef(false); |
| 76 | const restored = useRef(false); |
| 77 | const job = status?.job || {}; |
| 78 | const busy = submitting || Boolean(job.running); |
| 79 | const network = networkState(status); |
| 80 | const exitCandidate = status?.guest_system === "macos" && status.safety?.macos_exit_candidate?.ip; |
| 81 | const needsExitRestart = status?.guest_system === "macos" && status.safety?.error === "已保存固定出口。请重启 macOS 客机,登录后重新检测。"; |
| 82 | const ready = Boolean(status?.ready && status.vm_running && !busy && !job.error && !needsExitRestart && network.mode === "open"); |
| 83 | const confirm = options => new Promise(resolve => setDialog({ ...options, resolve })); |
| 84 | const settleDialog = value => { dialog?.resolve(value); setDialog(null); }; |
| 85 | |
| 86 | useEffect(() => { |
| 87 | alive.current = true; |
| 88 | let timer, polling = false; |
| 89 | async function poll() { |
| 90 | if (polling || !alive.current) return; |
| 91 | clearTimeout(timer); |
| 92 | polling = true; |
| 93 | try { |
| 94 | const next = await api("/status"); |
| 95 | if (!alive.current) return; |
| 96 | setStatus(next); |
| 97 | setConnectionError(""); |
| 98 | const results = await Promise.allSettled([ |
| 99 | api("/proxy"), |
| 100 | account?.guest_system ? Promise.resolve(null) : api("/environment/guest-systems"), |
| 101 | ]); |
| 102 | if (!alive.current) return; |
| 103 | if (results[0].status === "fulfilled") setProxy(results[0].value); |
| 104 | else setConnectionError(results[0].reason.message); |
| 105 | if (results[1].status === "fulfilled") { |
| 106 | const install = results[1].value; |
| 107 | setPending(install?.pending || null); |
| 108 | if (!restored.current) { |
| 109 | restored.current = true; |
| 110 | if (initial.started && !initial.prepared && !account?.guest_system && !install?.pending && !next.job?.running && !next.job?.setup_progress && !next.ready) setStep("system"); |
| 111 | } |
| 112 | if (install?.activate && !activation.current) { |
| 113 | activation.current = true; |
| 114 | setStep("install"); |
| 115 | try { |
| 116 | await api("/environment/guest-systems/activate", {}); |
| 117 | await native("reconnect"); |
| 118 | } catch (error) { |
| 119 | activation.current = false; |
| 120 | if (alive.current) setError(error.message); |
| 121 | } |
| 122 | } |
| 123 | } else setConnectionError(results[1].reason.message); |
| 124 | if (next.job?.running && ["start", "guest-install", "safety"].includes(next.job.kind)) setStep("install"); |
| 125 | } catch (error) { if (alive.current) setConnectionError(error.message); } |
| 126 | finally { |
| 127 | polling = false; |
| 128 | if (alive.current) timer = setTimeout(poll, 1200); |
| 129 | } |
| 130 | } |
| 131 | pollNow.current = poll; |
| 132 | poll(); |
| 133 | if (nativeAvailable()) native("workbenchReady").catch(() => {}); |
| 134 | window.cageWorkbenchAction = async action => { if (action === "quit") await native("quitNow"); }; |
| 135 | return () => { alive.current = false; clearTimeout(timer); pollNow.current = null; delete window.cageWorkbenchAction; }; |
| 136 | }, [account?.guest_system]); |
| 137 | |
| 138 | async function run(operation) { |
| 139 | if (actionPending.current) return; |
| 140 | actionPending.current = true; |
| 141 | setSubmitting(true); setError(""); |
| 142 | try { await operation(); } |
| 143 | catch (error) { if (alive.current) setError(error.message); } |
| 144 | finally { actionPending.current = false; if (alive.current) { setSubmitting(false); pollNow.current?.(); } } |
| 145 | } |
| 146 | function startOptions() { |
| 147 | if (account?.guest_system) return {}; |
| 148 | if (pending) return { guest_system: pending.system }; |
| 149 | if (!choice) return job.setup_progress?.system ? { guest_system: job.setup_progress.system } : {}; |
| 150 | return { guest_system: choice.guest_system, media: choice.media, sha256: choice.sha256, clone_key: choice.clone_key, editor_terms: choice.editor_terms }; |
| 151 | } |
| 152 | async function install() { |
| 153 | if (needsProxySetup(null, status, proxy)) { setError("请先选择并应用代理节点。"); setStep("proxy"); return; } |
| 154 | await run(async () => { |
| 155 | const check = await api("/host/git"); |
| 156 | if (!check.ready) { setGit(check); return; } |
| 157 | await api("/environment/initialization", { action: "install" }); |
| 158 | const accepted = await api("/start", startOptions()); |
| 159 | if (!alive.current) return; |
| 160 | setGit(null); setStep("install"); |
| 161 | setStatus(current => ({ ...current, job: { ...accepted, running: true, kind: accepted.kind || "start", message: accepted.message || "正在准备客机环境…" } })); |
| 162 | }); |
| 163 | } |
| 164 | async function enableGit() { |
| 165 | await run(async () => { const next = await api("/host/git", { confirm: true }); setGit(next.ready ? null : next); }); |
| 166 | } |
| 167 | async function stop() { |
| 168 | if (!await confirm({ title: "停止当前安装?", body: "安装进度、已下载文件和虚拟磁盘会保留。你可以在此界面继续安装。", confirm: "停止安装" })) return; |
| 169 | await run(async () => { const accepted = await api("/stop", {}); setStatus(current => ({ ...current, job: { ...accepted, running: true } })); }); |
| 170 | } |
| 171 | async function enter() { |
| 172 | await run(async () => { await api("/environment/initialization", { action: "complete" }); await refresh(); if (alive.current) onComplete(); }); |
| 173 | } |
| 174 | async function waitForJob(accepted, kind) { |
| 175 | if (!accepted.id) throw new Error("操作未返回任务编号,请核对状态后重试。"); |
| 176 | while (alive.current) { |
| 177 | const next = await api("/status"); |
| 178 | if (!alive.current) break; |
| 179 | setStatus(next); |
| 180 | const current = next.job; |
| 181 | if (current?.id !== accepted.id || current.kind !== kind) throw new Error("操作状态已变化,请核对状态后重试。"); |
| 182 | if (current.error || current.canceled) throw new Error(current.error || "操作已取消,请核对状态后重试。"); |
| 183 | if (!current.running) return next; |
| 184 | await new Promise(resolve => setTimeout(resolve, 300)); |
| 185 | } |
| 186 | throw new Error("初始化页面已关闭,操作未继续。"); |
| 187 | } |
| 188 | async function bindExit() { |
| 189 | await run(async () => { |
| 190 | const accepted = await bindDetectedMacOSExit(exitCandidate, confirm); |
| 191 | if (!accepted) return; |
| 192 | await waitForJob(accepted, "settings"); |
| 193 | }); |
| 194 | } |
| 195 | async function restart() { |
| 196 | await run(async () => { |
| 197 | const running = status.vm_running; |
| 198 | if (!await confirm({ title: running ? "重启虚拟 Mac 并检查?" : "启动客机并重新检测?", body: "请先保存文件。当前终端会话会结束,浏览器登录和项目文件会保留。重新检测通过前,外网保持关闭。", confirm: running ? "重启并检查" : "启动并检测" })) return; |
| 199 | const current = await api("/status"); |
| 200 | if (!alive.current) return; |
| 201 | if (current.job?.running) throw new Error("其他操作仍在进行,请等待完成后重试。"); |
| 202 | if (current.vm_running) { |
| 203 | const stopped = await waitForJob(await api("/stop", {}), "stop"); |
| 204 | if (stopped.vm_running) throw new Error("客机尚未停止,请核对状态后重试。"); |
| 205 | } |
| 206 | if (!alive.current) return; |
| 207 | const accepted = await api("/start", {}); |
| 208 | if (!accepted.id) throw new Error("启动请求未返回任务编号,请核对状态后重试。"); |
| 209 | setStatus(current => ({ ...current, job: { ...accepted, running: true, kind: "start", message: accepted.message || "正在启动并检查客机…" } })); |
| 210 | }); |
| 211 | } |
| 212 | async function checkNetwork() { |
| 213 | await run(async () => { |
| 214 | const accepted = await api("/safety/check", {}); |
| 215 | setStatus(current => ({ ...current, job: { ...accepted, running: true, kind: "safety", message: "正在检查代理出口和环境隔离…" } })); |
| 216 | }); |
| 217 | } |
| 218 | async function back() { |
| 219 | if (step === "proxy" && proxyDirty && !await confirm({ title: "放弃尚未应用的代理修改?", body: "已经保存并应用的代理会保留,当前未应用的表单修改会丢弃。", confirm: "放弃修改" })) return; |
| 220 | setProxyDirty(false); |
| 221 | setStep(step === "install" ? "proxy" : pending || account?.guest_system ? "install" : "system"); |
| 222 | } |
| 223 | async function nextFromSystem() { |
| 224 | await run(async () => { |
| 225 | const directory = storage.directory.trim(); |
| 226 | if (directory !== storage.location.directory) { |
| 227 | const accepted = await api("/environment/storage", { directory, previous: storage.location.directory, migrate: false }); |
| 228 | let job; |
| 229 | do { |
| 230 | await new Promise(resolve => setTimeout(resolve, 300)); |
| 231 | if (!alive.current) return; |
| 232 | const next = await api("/status"); |
| 233 | setStatus(next); job = next.job; |
| 234 | if (job.id !== accepted.id) throw new Error("存储操作状态已变化,请核对目录后重试。"); |
| 235 | } while (job.running); |
| 236 | if (job.error) throw new Error(job.error); |
| 237 | const location = await api("/environment/storage"); |
| 238 | if (location.directory !== directory) throw new Error("存储目录尚未保存,请重新选择后重试。"); |
| 239 | setStorage({ location, directory: location.directory }); |
| 240 | } |
| 241 | setStep("proxy"); |
| 242 | }); |
| 243 | } |
| 244 | const failed = Boolean(job.error || error); |
| 245 | const networkPending = Boolean(status?.ready && status.vm_running && network.mode !== "open"); |
| 246 | const progress = !status?.ready && job.setup_progress ? { ...job, setup_progress: job.setup_progress } : null; |
| 247 | const title = step === "system" ? "为 Cage 准备独立环境" : step === "proxy" ? "连接你的网络代理" : ready ? "Cage 已准备就绪" : !busy && networkPending ? "环境已启动,等待联网检查" : failed ? "继续完成环境安装" : busy ? "正在准备你的环境" : "安装并检查客机环境"; |
| 248 | const index = steps.findIndex(([key]) => key === step); |
| 249 | return <InitializationFrame> |
| 250 | <section className="initialization-content"> |
| 251 | <ol className="initialization-steps" aria-label="初始化步骤">{steps.map(([key, label], position) => <li key={key} aria-current={step === key ? "step" : undefined}><span>{position < index ? <Check size={14} /> : position + 1}</span>{label}</li>)}</ol> |
| 252 | <div className="initialization-title"><h1>{title}</h1><p>{step === "system" ? "选择客机系统和存储位置。初始化完成后,再进入工作台。" : step === "proxy" ? "这里的代理供客机内的进程和开发工具使用。系统镜像通过主机代理下载,遵循 Clash 等软件的系统代理或 TUN 设置。" : ready ? "系统、开发组件和网络检查均已完成,可以进入工作台开始使用。" : "下载、安装、必要授权和检查都在这里完成。中断后可以继续原任务。"}</p></div> |
| 253 | {connectionError && <div className="initialization-notice" role="alert"><SafetyMessage message={connectionError} /><button onClick={() => pollNow.current?.()}>重新连接</button></div>} |
| 254 | {!status ? <p role="status"><LoaderCircle size={18} className="spin" />正在读取安装状态…</p> : <> |
| 255 | <div className="initialization-stage" key={step}> |
| 256 | {step === "system" && <> |
| 257 | <GuestSystemPicker system={choice} onChange={setChoice} preserveOnUnmount deferMatch /> |
| 258 | <InitializationStorage value={storage} onChange={setStorage} disabled={busy} /> |
| 259 | </>} |
| 260 | {step === "proxy" && <><ProxySettings initializing status={status} onConfirm={confirm} onDirty={setProxyDirty} onApplied={async () => { setProxy(await api("/proxy")); pollNow.current?.(); }} />{choice?.clone && !needsProxySetup(null, status, proxy) && <HostCloneSummary pending={choice.pending} onChange={setChoice} />}</>} |
| 261 | {step === "install" && (ready ? <div className="initialization-ready"><ShieldCheck size={36} /><h2>环境已就绪</h2><p>独立客机已安装,工具、文件和登录状态会持续保存。以后打开 Cage 可直接进入工作台。</p></div> : <> |
| 262 | {exitCandidate && <section className="initialization-notice" aria-label="确认固定出口"><p>客机终端、浏览器和代理已测得一致出口。请确认是否将它绑定为固定出口。</p><button disabled={busy || Boolean(connectionError)} onClick={bindExit}>绑定检测到的固定出口 {exitCandidate}</button></section>} |
| 263 | {needsExitRestart && <section className="initialization-notice" aria-label="固定出口已保存"><p>固定出口已保存。重启客机并重新检测后才能进入工作台。</p><button className="primary" disabled={busy || Boolean(connectionError)} onClick={restart}>{status.vm_running ? "重启客机并重新检测" : "启动客机并重新检测"}</button></section>} |
| 264 | {progress ? <SetupProgress job={progress} onDetails={() => setDetails(true)} onStop={stop} onRetry={needsExitRestart ? restart : install} disconnected={Boolean(connectionError) || submitting} /> : (busy || status.guest_system !== "macos" || !networkPending) && <div className="initialization-operation" role="status">{busy && <LoaderCircle size={22} className="spin" />}<p>{job.message || (status.vm_running ? "请完成客机连接和网络检查。" : "准备继续原安装,已有文件和磁盘会保留。")}</p>{!busy && !job.error && !needsExitRestart && <button className="primary" disabled={Boolean(connectionError)} onClick={install}>{status.ready ? "重新启动并检查" : "继续安装"}</button>}{busy && <button onClick={stop} disabled={submitting}>停止安装</button>}</div>} |
| 265 | {job.error && !progress && !(status.guest_system === "macos" && networkPending) && <div className="initialization-notice" role="alert"><SafetyMessage message={job.error} />{!networkPending && !needsExitRestart && <button className="primary" disabled={busy || Boolean(connectionError)} onClick={install}>继续安装</button>}</div>} |
| 266 | {status.guest_system === "macos" && status.vm_running && !status.ready && !busy && <section className="initialization-notice"><h2>连接虚拟 Mac</h2><p>{status.environment_update_error || "客机已经启动,尚未建立工作台连接。请先检查客机是否停在登录画面。"}</p><MacOSLogin onSessionClosed={() => pollNow.current?.()} /><button disabled={Boolean(connectionError)} onClick={install}>重新连接并检查</button></section>} |
| 267 | {status.ready && network.mode !== "open" && !busy && !needsExitRestart && <> |
| 268 | {status.guest_system === "macos" && <InitializationChecks status={status} busy={Boolean(connectionError)} onWorkspace={setApprovalWorkspace} onCheck={checkNetwork} onStart={install} onRestart={restart} onUpdate={() => run(() => api("/environment/update", {}))} onDiagnostics={() => setHelp(true)} />} |
| 269 | <div className="initialization-network"><p>{status.safety?.error || job.error || status.network_error || "客机已经连接,请完成网络和隔离检查后进入工作台。"}</p><button disabled={Boolean(connectionError)} onClick={checkNetwork}>运行网络与隔离检查</button></div> |
| 270 | </>} |
| 271 | {(progress?.setup_progress.phase === "image" || (failed && !networkPending)) && <p>系统镜像和在主机上准备的 macOS 安装组件遵循主机代理设置。下载失败时,可在操作详情中查看当前文件和重试记录。客机内的联网请求使用 Cage 代理。</p>} |
| 272 | <div className="initialization-recovery"><button onClick={() => setStep("proxy")} disabled={busy}>检查 Cage 代理配置</button>{!progress && <button onClick={() => setDetails(true)}>查看操作详情</button>}</div> |
| 273 | </>)} |
| 274 | </div> |
| 275 | {git && <section className="initialization-notice" aria-label="Git 安全保护"><h2>安装前,保护本机 Git</h2><p>{git.message}</p>{git.can_enable && <><p>启用后,Git 会忽略未经你明确指定的裸仓库。该操作会修改当前用户的全局设置,影响本机其他 Git 工具,普通项目保持原有操作。</p><pre>git config --global safe.bareRepository explicit</pre><button className="primary" disabled={busy} onClick={enableGit}>启用 Git 保护</button></>}<button disabled={busy} onClick={install}>重新检查并安装</button></section>} |
| 276 | {error && <p className="initialization-notice" role="alert"><SafetyMessage message={error} /></p>} |
| 277 | <footer className="initialization-actions"> |
| 278 | {step === "system" ? <span /> : <button className="text-button" disabled={busy} onClick={back}><ChevronLeft size={16} />上一步</button>} |
| 279 | {step === "system" && <button className="primary" disabled={busy || !storage?.directory.trim() || choice === undefined || (!choice?.clone && !validGuestChoice(choice)) || choice?.clone && choice.guest_system === "windows-11" && !choice.editor_terms || Boolean(connectionError)} onClick={nextFromSystem}>{submitting && <LoaderCircle size={16} className="spin" />}下一步:配置代理</button>} |
| 280 | {step === "proxy" && <button className="primary" disabled={busy || proxyDirty || !account?.guest_system && !pending && !validGuestChoice(choice) || needsProxySetup(null, status, proxy) || Boolean(connectionError)} onClick={install}>{submitting ? <LoaderCircle size={16} className="spin" /> : null}开始安装</button>} |
| 281 | {step === "install" && ready && <button className="primary" disabled={submitting || Boolean(connectionError)} onClick={enter}>进入工作台</button>} |
| 282 | </footer> |
| 283 | </>} |
| 284 | <div className="initialization-support"><button className="text-button" aria-expanded={help} onClick={() => setHelp(!help)}>日志与诊断</button>{navigation && !busy && <button className="text-button" onClick={() => navigation.open()}>只连接 SSH 主机</button>}</div> |
| 285 | {help && <DiagnosticSettings />} |
| 286 | </section> |
| 287 | {approvalWorkspace && <InitializationProjectApproval workspace={approvalWorkspace} jobRunning={Boolean(job.running)} onClose={() => { setApprovalWorkspace(""); pollNow.current?.(); }} onApproved={() => { setApprovalWorkspace(""); void checkNetwork(); }} />} |
| 288 | {details && <Modal title="初始化操作详情" onClose={() => setDetails(false)}><InitializationDetails status={status} /></Modal>} |
| 289 | {dialog && <Modal title={dialog.title} onClose={() => settleDialog(false)} footer={<><button onClick={() => settleDialog(false)}>取消</button><button className="primary" onClick={() => settleDialog(true)}>{dialog.confirm}</button></>}><div className="modal-body"><p>{dialog.body}</p></div></Modal>} |
| 290 | </InitializationFrame>; |
| 291 | } |