| 1 | import { shortcut, primaryModifier } from "./platform.mjs"; |
| 2 | import logo from "./logo.png"; |
| 3 | import React, { useEffect, useRef, useState } from "react"; |
| 4 | import { |
| 5 | Clock3, |
| 6 | FileCode2, |
| 7 | FolderOpen, |
| 8 | Globe2, |
| 9 | LoaderCircle, |
| 10 | MapPin, |
| 11 | MoreHorizontal, |
| 12 | Power, |
| 13 | RefreshCw, |
| 14 | Shield, |
| 15 | TerminalSquare, |
| 16 | X, |
| 17 | } from "lucide-react"; |
| 18 | import { api, normalizeURL, native, nativeAvailable } from "./api"; |
| 19 | import { clientKeyboard, clientStorageKey, getClientContext, isRemoteClient, runtimeURL, runtimeSocketURL } from "./client-context.mjs"; |
| 20 | import { shareClipboard } from "./shared-clipboard.mjs"; |
| 21 | import { RemoteView, TerminalView, Modal } from "./views"; |
| 22 | import { usePasswordVault } from "./password-vault"; |
| 23 | import { SettingsPanel } from "./settings"; |
| 24 | import { SetupProgress } from "./setup-progress"; |
| 25 | import { GuestSystemPicker, validGuestChoice } from "./guest-system-picker"; |
| 26 | import { AppearanceProvider } from "./appearance"; |
| 27 | import { EnvironmentShield } from "./environment-shield"; |
| 28 | import { TailscalePanel } from "./tailscale"; |
| 29 | import { WorkspaceSidebar } from "./workspace-sidebar"; |
| 30 | import { useCLISessions, sessionsChanged } from "./cli-sessions"; |
| 31 | import { TerminalMenu } from "./terminal-menu"; |
| 32 | import { InitializationGate } from "./initialization"; |
| 33 | import { MacOSLogin } from "./macos-login"; |
| 34 | import { MacOSClaudeWindow } from "./macos-claude-window"; |
| 35 | import { ProjectRecovery } from "./project-recovery"; |
| 36 | import { ClaudeDesktop } from "./claude-desktop"; |
| 37 | import { useClaudeAccounts } from "./claude-accounts"; |
| 38 | import { AccountProvider, AccountGate, useAccount } from "./account"; |
| 39 | import { BrowserHeader, BrowserTabRail, TerminalHeader, ExpandSidebar, ExpandPane } from "./pane-headers"; |
| 40 | import { BrowserDownloads, useDownloadNotifications, useDesktopFiles } from "./browser-downloads"; |
| 41 | import { BrowserUploads } from "./browser-uploads"; |
| 42 | import { BrowserSettingsPage } from "./browser-settings"; |
| 43 | import { AudioControls, useAudioOutput } from "./audio"; |
| 44 | import { ProjectDialog } from "./project-dialog"; |
| 45 | import { |
| 46 | readLocal, |
| 47 | orderedTabs, |
| 48 | focusTab, |
| 49 | splitTab, |
| 50 | projectName, |
| 51 | tabName, |
| 52 | } from "./workspace-state.mjs"; |
| 53 | import { SafetyPanel } from "./safety"; |
| 54 | import { SafetyChecklistContext, SafetyMessage } from "./safety-message"; |
| 55 | import { networkState, isGuestLocalURL } from "./safety-state.mjs"; |
| 56 | import { needsProxySetup } from "./onboarding-state.mjs"; |
| 57 | import { HostGitPreparation } from "./host-git"; |
| 58 | import { NetworkLatency } from "./network-latency"; |
| 59 | import { useWindowVisibility } from "./window-visibility"; |
| 60 | import { AppUpdateButton, useAppUpdates } from "./app-updates"; |
| 61 | import "./appearance.css"; |
| 62 | import { stopAndExit } from "./quit"; |
| 63 | |
| 64 | function App() { |
| 65 | const { account } = useAccount(); |
| 66 | const macGuest = account?.guest_system === "macos"; |
| 67 | const nativeGuestLabel = {macos: "macOS", "windows-11": "Windows"}[account?.guest_system]; |
| 68 | const [, refreshClientPreferences] = useState(0); |
| 69 | useEffect(() => { |
| 70 | const refresh = () => refreshClientPreferences((value) => value + 1); |
| 71 | window.addEventListener("cage-client-preferences", refresh); |
| 72 | return () => window.removeEventListener("cage-client-preferences", refresh); |
| 73 | }, []); |
| 74 | const claudeProfiles = useClaudeAccounts(); |
| 75 | const [tailscaleOpen, setTailscaleOpen] = useState(false); |
| 76 | const [desktopOpen, setDesktopOpen] = useState(false); |
| 77 | const [terminalChoice, setTerminalChoice] = useState(null); |
| 78 | const [openingSession, setOpeningSession] = useState(""); |
| 79 | const [sessionOpenError, setSessionOpenError] = useState(null); |
| 80 | const sessionOpenRequest = useRef(null); |
| 81 | useEffect(() => () => { |
| 82 | const request = sessionOpenRequest.current; |
| 83 | sessionOpenRequest.current = null; |
| 84 | request?.controller.abort(); |
| 85 | }, []); |
| 86 | const terminalTrigger = useRef(null); |
| 87 | const appUpdates = useAppUpdates(); |
| 88 | const [recoveringEditor, setRecoveringEditor] = useState(false); |
| 89 | const windowVisible = useWindowVisibility(); |
| 90 | const windowVisibleRef = useRef(windowVisible); |
| 91 | windowVisibleRef.current = windowVisible; |
| 92 | const [serverStatus, setStatus] = useState(null), |
| 93 | [settings, setSettings] = useState(null), |
| 94 | [proxy, setProxy] = useState(null), |
| 95 | [tabs, setTabs] = useState([]), |
| 96 | [layout, setLayout] = useState(() => ({ active: localStorage.getItem(clientStorageKey("cage-active")) || "" })), |
| 97 | [browser, setBrowser] = useState({ tabs: [] }), |
| 98 | [browserSettingsRevision, setBrowserSettingsRevision] = useState(0), |
| 99 | [settingsOpen, setSettingsOpen] = useState(false), |
| 100 | [startOptions, setStartOptions] = useState(null), |
| 101 | [guestSystem, setGuestSystem] = useState(undefined), |
| 102 | [startRequest, setStartRequest] = useState(null), |
| 103 | [settingsSection, setSettingsSection] = useState("keyboard"), |
| 104 | [home, setHome] = useState(true), |
| 105 | [sidebarCollapsed, setSidebarCollapsed] = useState( |
| 106 | readLocal(clientStorageKey("cage-sidebar-collapsed"), false), |
| 107 | ), |
| 108 | [browserTabLayout, setBrowserTabLayout] = useState( |
| 109 | readLocal(clientStorageKey("cage-browser-tab-layout"), "horizontal"), |
| 110 | ), |
| 111 | [selectedProject, setSelectedProject] = useState(""), |
| 112 | [savedTabs, setSavedTabs] = useState(readLocal(clientStorageKey("cage-tab-layout"), {})), |
| 113 | [privateTabMetadata, setPrivateTabMetadata] = useState({}), |
| 114 | [projectDialog, setProjectDialog] = useState(null), |
| 115 | [rename, setRename] = useState(null), |
| 116 | [toast, setToast] = useState(""), |
| 117 | [fatal, setFatal] = useState(""), |
| 118 | [connectionError, setConnectionError] = useState(""), |
| 119 | [browserError, setBrowserError] = useState(""), |
| 120 | [dialog, setDialog] = useState(null), |
| 121 | [transfer, setTransfer] = useState(null), |
| 122 | [details, setDetails] = useState(false), |
| 123 | [safetyOpen, setSafetyOpen] = useState(false), |
| 124 | [quitting, setQuitting] = useState(null); |
| 125 | |
| 126 | const clientStatus = serverStatus && { ...serverStatus, keyboard: clientKeyboard(serverStatus.keyboard) }; |
| 127 | const hostGitOpen = startOptions !== null; |
| 128 | const status = clientStatus && (hostGitOpen || startRequest) |
| 129 | ? { ...clientStatus, job: { running: true, kind: "start", message: hostGitOpen |
| 130 | ? isRemoteClient() ? "正在检查云端主机 Git 安全保护…" : "正在检查本机 Git 安全保护…" : "正在启动 Cage 环境…" } } |
| 131 | : clientStatus; |
| 132 | const { active } = layout; |
| 133 | const setActive = id => setLayout(previous => focusTab(previous, id)); |
| 134 | const workspaceBox = useRef(null); |
| 135 | const [dropSide, setDropSide] = useState(null); |
| 136 | const terminalControls = useRef(new Map()); |
| 137 | const remote = useRef(), |
| 138 | activeRef = useRef(active), |
| 139 | lastBrowserTab = useRef(""), |
| 140 | readyRef = useRef(false), |
| 141 | browserIds = useRef(new Set()), |
| 142 | initialized = useRef(false), |
| 143 | browserStreamReady = useRef(false), |
| 144 | browserSnapshot = useRef({ tabs: [] }), |
| 145 | refreshStatus = useRef(null), |
| 146 | launchAcknowledged = useRef(false), |
| 147 | lastJob = useRef(""), |
| 148 | quitAfterStop = useRef(null); |
| 149 | activeRef.current = active; |
| 150 | readyRef.current = Boolean(status?.ready); |
| 151 | const storageRecovery = status?.storage_recovery?.required; |
| 152 | const current = tabs.find((t) => t.id === active), |
| 153 | terminal = !desktopOpen && current?.kind === "terminal", |
| 154 | busy = Boolean(status?.job?.running), |
| 155 | showHome = storageRecovery || !desktopOpen && (home || !status?.vm_running || !current); |
| 156 | const setupProgress = status?.job?.setup_progress && (busy || status.job.error); |
| 157 | const cliSessions = useCLISessions(Boolean(status && !busy && !storageRecovery), windowVisible); |
| 158 | useEffect(() => { |
| 159 | if (storageRecovery) { |
| 160 | setDesktopOpen(false); |
| 161 | setHome(true); |
| 162 | setStartOptions(null); |
| 163 | setStartRequest(null); |
| 164 | } |
| 165 | }, [storageRecovery]); |
| 166 | const other = tabs.find(tab => tab.id === layout.other); |
| 167 | const split = Boolean(other && current && !showHome && !desktopOpen); |
| 168 | const panes = !split ? [current].filter(Boolean) |
| 169 | : layout.side === "left" ? [current, other] : [other, current]; |
| 170 | const webPanes = panes.filter(tab => tab.kind !== "terminal"); |
| 171 | const passwordVault = usePasswordVault(Boolean(status?.ready), browser.active); |
| 172 | const dualBrowser = split && webPanes.length === 2; |
| 173 | const leftId = dualBrowser ? panes[0].id : ""; |
| 174 | const rightId = dualBrowser ? panes[1].id : ""; |
| 175 | const nativeSplit = browser.split; |
| 176 | const splitReady = dualBrowser |
| 177 | ? nativeSplit?.left === leftId && nativeSplit?.right === rightId |
| 178 | : !nativeSplit; |
| 179 | const liveBrowser = webPanes.find(tab => tab.id === browser.active) || webPanes[0]; |
| 180 | const liveBrowserVisible = !desktopOpen && !showHome && status?.ready && |
| 181 | liveBrowser && splitReady && (!split || browser.active === liveBrowser.id); |
| 182 | const viewBeforeBrowser = useRef(null); |
| 183 | const browserDismissed = useRef(false); |
| 184 | const browserVisible = !desktopOpen && !showHome && webPanes.length > 0; |
| 185 | const browserWasVisible = useRef(false); |
| 186 | useEffect(() => { |
| 187 | |
| 188 | |
| 189 | if (browserWasVisible.current && !tabs.some(tab => tab.kind !== "terminal")) closeBrowser(); |
| 190 | else if (!browserVisible) viewBeforeBrowser.current = { |
| 191 | layout, home: showHome, desktopOpen, selectedProject, |
| 192 | }; |
| 193 | browserWasVisible.current = browserVisible; |
| 194 | }, [browserVisible, layout, showHome, desktopOpen, selectedProject, tabs]); |
| 195 | const closeBrowser = () => { |
| 196 | const previous = viewBeforeBrowser.current; |
| 197 | browserDismissed.current = true; |
| 198 | const available = id => tabs.some(tab => tab.id === id); |
| 199 | const restored = previous?.layout; |
| 200 | const id = [restored?.active, restored?.other].find(available); |
| 201 | setLayout(id ? { ...restored, active: id, |
| 202 | other: restored.other !== id && available(restored.other) ? restored.other : undefined, |
| 203 | } : { active }); |
| 204 | setHome(Boolean(previous?.home || !previous?.desktopOpen && !id)); |
| 205 | setDesktopOpen(Boolean(previous?.desktopOpen)); |
| 206 | if (previous?.selectedProject) setSelectedProject(previous.selectedProject); |
| 207 | }; |
| 208 | const splitQueue = useRef(Promise.resolve()); |
| 209 | const requestedSplit = useRef(false); |
| 210 | const nativeSplitRef = useRef(null); |
| 211 | nativeSplitRef.current = nativeSplit; |
| 212 | useEffect(() => { |
| 213 | if (!status?.ready) { requestedSplit.current = false; return; } |
| 214 | if (!leftId && !requestedSplit.current && !nativeSplitRef.current) return; |
| 215 | requestedSplit.current = Boolean(leftId); |
| 216 | let cancelled = false; |
| 217 | const apply = async () => { |
| 218 | if (cancelled) return; |
| 219 | const id = activeRef.current; |
| 220 | try { |
| 221 | const result = await api("/browser/split", { left: leftId, right: rightId, |
| 222 | id: leftId ? (id === rightId ? rightId : leftId) : id }); |
| 223 | if (!cancelled) setBrowser(previous => ({ ...previous, split: result.split })); |
| 224 | } catch { |
| 225 | if (!cancelled) { |
| 226 | setToast(tabs.some(tab => [leftId, rightId].includes(tab.id) && tab.incognito) |
| 227 | ? "无痕标签可与终端分屏;两个网页分屏目前仅支持普通标签。" |
| 228 | : "无法调整浏览器分屏。请确认环境组件已更新,两个网页属于同一浏览器配置,且客机 Chromium 为 155 或更高版本。"); |
| 229 | setLayout(previous => ({ active: previous.active })); |
| 230 | } |
| 231 | } |
| 232 | }; |
| 233 | splitQueue.current = splitQueue.current.then(apply); |
| 234 | return () => { cancelled = true; }; |
| 235 | }, [leftId, rightId, status?.ready, Boolean(!leftId && nativeSplit)]); |
| 236 | const layoutRef = useRef(layout); |
| 237 | layoutRef.current = layout; |
| 238 | useEffect(() => { |
| 239 | if (!layout.other) return; |
| 240 | if (!status?.vm_running || !other || !current) { |
| 241 | const survivor = current || other; |
| 242 | setLayout({ active: survivor?.id || "" }); |
| 243 | if (!current && survivor && survivor.kind !== "terminal" && status?.ready) { |
| 244 | api("/browser/activate", { id: survivor.id }).catch(error => setToast(error.message)); |
| 245 | } |
| 246 | } |
| 247 | }, [layout, other, current, status?.vm_running, status?.ready]); |
| 248 | const paneSide = id => !split ? "" : id === active ? layout.side : |
| 249 | layout.side === "left" ? "right" : "left"; |
| 250 | const running = Boolean(status?.vm_running); |
| 251 | const mixedBrowserId = split && !dualBrowser ? webPanes[0]?.id : null; |
| 252 | useEffect(() => { |
| 253 | if (status?.ready && mixedBrowserId && mixedBrowserId !== browser.active) |
| 254 | api("/browser/activate", { id: mixedBrowserId }).catch(error => setToast(error.message)); |
| 255 | }, [mixedBrowserId, status?.ready, browser.active]); |
| 256 | const finishedLogins = tabs.filter((tab) => tab.terminalKind === "claude-login" && tab.closed).map((tab) => tab.id).sort().join(","); |
| 257 | useEffect(() => { |
| 258 | if (finishedLogins) claudeProfiles.load(); |
| 259 | }, [finishedLogins, claudeProfiles.load]); |
| 260 | const audio = useAudioOutput(running && !storageRecovery && !status?.environment_update_required && !connectionError); |
| 261 | useEffect(() => { |
| 262 | if (audio.error) setToast(audio.error); |
| 263 | }, [audio.error]); |
| 264 | const projects = status?.projects || []; |
| 265 | const workspace = selectedProject || status?.workspace; |
| 266 | const contentWorkspace = |
| 267 | terminal && !showHome ? current.workspace : workspace; |
| 268 | const setupProxy = !nativeGuestLabel && needsProxySetup(settings, status, proxy); |
| 269 | const network = connectionError |
| 270 | ? { mode: "unknown", label: "外网状态待确认" } |
| 271 | : networkState(status); |
| 272 | const runtimeLabel = connectionError |
| 273 | ? "连接中断" |
| 274 | : busy |
| 275 | ? network.mode === "checking" || status?.job?.kind === "safety" |
| 276 | ? "检查中" |
| 277 | : status?.job?.kind === "stop" |
| 278 | ? "停止中" |
| 279 | : running |
| 280 | ? "应用中" |
| 281 | : "启动中" |
| 282 | : status?.ready |
| 283 | ? network.mode === "open" |
| 284 | ? "运行中" |
| 285 | : "离线可用" |
| 286 | : running |
| 287 | ? status?.environment_update_required ? "环境待更新" : "浏览器待恢复" |
| 288 | : "已停止"; |
| 289 | const notify = (text) => setToast(text); |
| 290 | const clipboardConnection = getClientContext().connection_id; |
| 291 | useEffect(() => { |
| 292 | if (!status?.ready || !nativeAvailable()) return; |
| 293 | const clipboard = shareClipboard({ |
| 294 | connect: () => new WebSocket(runtimeSocketURL("/clipboard")), native, |
| 295 | onStatus: setToast, |
| 296 | setActive: active => { window.cageSharedClipboardActive = active; }, |
| 297 | }); |
| 298 | window.cageSyncClipboard = () => clipboard.sync(); |
| 299 | return () => { clipboard.dispose(); delete window.cageSyncClipboard; }; |
| 300 | }, [status?.ready, clipboardConnection]); |
| 301 | const desktopFiles = useDesktopFiles(Boolean(status?.ready), notify); |
| 302 | const downloads = [...(browser.downloads || []), ...desktopFiles.downloads]; |
| 303 | useDownloadNotifications(downloads, notify, Boolean(browser.uploads?.length || desktopFiles.uploads.length)); |
| 304 | const refreshSettings = async () => { |
| 305 | const results = await Promise.allSettled([api("/settings"), api("/proxy")]); |
| 306 | if (results[0].status === "fulfilled") setSettings(results[0].value); |
| 307 | else notify(results[0].reason.message); |
| 308 | if (results[1].status === "fulfilled") setProxy(results[1].value); |
| 309 | else setProxy(null); |
| 310 | }; |
| 311 | const confirm = (options) => |
| 312 | new Promise((resolve) => setDialog({ ...options, resolve })); |
| 313 | const openSettings = (section = "keyboard") => { |
| 314 | setSafetyOpen(false); |
| 315 | setSettingsSection(section); |
| 316 | setSettingsOpen(true); |
| 317 | }; |
| 318 | const select = async (id, focusContent = true) => { |
| 319 | const tab = tabs.find((t) => t.id === id); |
| 320 | if (tab && tab.kind !== "terminal") browserDismissed.current = false; |
| 321 | setDesktopOpen(false); |
| 322 | setHome(false); |
| 323 | if (tab?.kind === "browser-settings") setLayout({ active: id }); |
| 324 | else setActive(id); |
| 325 | if (!tab?.incognito) localStorage.setItem(clientStorageKey("cage-active"), id); |
| 326 | if (tab?.kind === "terminal") setSelectedProject(tab.workspace); |
| 327 | if (tab && tab.kind !== "terminal") { |
| 328 | try { |
| 329 | await api("/browser/activate", { id }); |
| 330 | if (activeRef.current === id) { |
| 331 | setBrowser(previous => ({ ...previous, active: id })); |
| 332 | if (focusContent) remote.current?.focus(); |
| 333 | } |
| 334 | } catch (e) { |
| 335 | notify(e.message); |
| 336 | } |
| 337 | } |
| 338 | }; |
| 339 | const destination = (id, x, y) => { |
| 340 | const box = workspaceBox.current?.getBoundingClientRect(); |
| 341 | if (!box || busy || !running || desktopOpen || tabs.length < 2 || |
| 342 | document.elementFromPoint(x, y)?.closest(".chrome") || |
| 343 | !tabs.some(tab => tab.id === id) || tabs.find(tab => tab.id === id)?.kind === "browser-settings" || |
| 344 | current?.kind === "browser-settings" || x < box.left || x > box.right || |
| 345 | y < box.top || y > box.bottom) return null; |
| 346 | return x < box.left + box.width * (dualBrowser && nativeSplit?.fraction || 0.5) ? "left" : "right"; |
| 347 | }; |
| 348 | const splitDrag = { |
| 349 | clear: () => setDropSide(null), |
| 350 | hover(id, x, y) { |
| 351 | const side = destination(id, x, y); |
| 352 | setDropSide(side); |
| 353 | return side; |
| 354 | }, |
| 355 | drop(id, x, y) { |
| 356 | const side = destination(id, x, y); |
| 357 | if (!side) return false; |
| 358 | setLayout(previous => splitTab(previous, tabs, id, side)); |
| 359 | void select(id); |
| 360 | return true; |
| 361 | }, |
| 362 | }; |
| 363 | const action = async (path, body = {}) => { |
| 364 | try { |
| 365 | return await api(path, body); |
| 366 | } catch (e) { |
| 367 | notify(e.message); |
| 368 | return null; |
| 369 | } |
| 370 | }; |
| 371 | const openBrowserPage = async ( |
| 372 | url = settings?.browser_home_url || "https://www.bing.com/", |
| 373 | incognito = Boolean(current?.incognito), |
| 374 | ) => { |
| 375 | browserDismissed.current = false; |
| 376 | const result = await action("/browser/new", { url, incognito }); |
| 377 | if (result) { |
| 378 | setDesktopOpen(false); |
| 379 | setHome(false); |
| 380 | setTabs((list) => |
| 381 | list.some((t) => t.id === result.id) |
| 382 | ? list |
| 383 | : [ |
| 384 | ...list, |
| 385 | { |
| 386 | id: result.id, |
| 387 | incognito, |
| 388 | kind: "web", |
| 389 | url, |
| 390 | title: "新标签页", |
| 391 | }, |
| 392 | ], |
| 393 | ); |
| 394 | setActive(result.id); |
| 395 | } |
| 396 | return result; |
| 397 | }; |
| 398 | const newPage = () => openBrowserPage(); |
| 399 | const showBrowserResult = result => { |
| 400 | if (!result?.id) return; |
| 401 | browserDismissed.current = false; |
| 402 | setDesktopOpen(false); setHome(false); |
| 403 | setTabs(previous => previous.some(tab => tab.id === result.id) |
| 404 | ? previous.map(tab => tab.id === result.id ? { ...tab, ...result } : tab) |
| 405 | : [...previous, result]); |
| 406 | setLayout({ active: result.id }); |
| 407 | }; |
| 408 | const openBrowserSettings = async (section = "general") => { |
| 409 | const result = await action("/browser/settings", { mode: section }); |
| 410 | if (result) showBrowserResult(result); |
| 411 | }; |
| 412 | const openInternalPage = async (mode, id) => { |
| 413 | const result = await action("/browser/internal-page", { mode, id }); |
| 414 | if (result) showBrowserResult(result); |
| 415 | }; |
| 416 | const openSettingsPageResult = result => result.id ? showBrowserResult(result) : openBrowserPage(result.url, false); |
| 417 | const openBrowser = () => { |
| 418 | const tab = |
| 419 | tabs.find( |
| 420 | (t) => t.id === lastBrowserTab.current && t.kind !== "terminal", |
| 421 | ) || |
| 422 | tabs.find((t) => t.id === browser.active && t.kind !== "terminal") || |
| 423 | tabs.find((t) => t.kind !== "terminal"); |
| 424 | return tab ? select(tab.id) : newPage(); |
| 425 | }; |
| 426 | const newTerminal = (path = workspace, anchor = terminalTrigger.current) => |
| 427 | setTerminalChoice((previous) => |
| 428 | previous?.anchor === anchor ? null : { path, anchor }, |
| 429 | ); |
| 430 | const createTerminal = async (path, kind, loginAccountId) => { |
| 431 | setTerminalChoice(null); |
| 432 | const result = await api("/terminals", { |
| 433 | workspace: path, kind, |
| 434 | ...(loginAccountId && { claude_account_id: loginAccountId }), |
| 435 | }); |
| 436 | showTerminal(result); |
| 437 | sessionsChanged(); |
| 438 | if (kind === "claude" && result.claude_account_id && |
| 439 | !claudeProfiles.accounts?.some((profile) => profile.id === result.claude_account_id)) { |
| 440 | claudeProfiles.load(); |
| 441 | } |
| 442 | }; |
| 443 | const showTerminal = result => { |
| 444 | const tab = { |
| 445 | ...result, id: "terminal:" + result.id, sessionId: result.id, |
| 446 | terminalKind: result.kind, kind: "terminal", |
| 447 | }; |
| 448 | setTabs((list) => [...list.filter((t) => t.id !== tab.id && (!tab.cli_session_id || t.cli_session_id !== tab.cli_session_id)), tab]); |
| 449 | setSelectedProject(result.workspace); |
| 450 | setDesktopOpen(false); |
| 451 | setHome(false); |
| 452 | setActive(tab.id); |
| 453 | }; |
| 454 | const openSessionTerminal = async session => { |
| 455 | if (session.running) return; |
| 456 | if (sessionOpenRequest.current?.id === session.id) return; |
| 457 | sessionOpenRequest.current?.controller.abort(); |
| 458 | const controller = new AbortController(); |
| 459 | const request = { id: session.id, controller }; |
| 460 | sessionOpenRequest.current = request; |
| 461 | setOpeningSession(session.id); |
| 462 | setSessionOpenError(null); |
| 463 | const timer = setTimeout(() => controller.abort(new Error("打开会话超时,历史已保留。请重新打开;若仍失败,请在设置中导出诊断包。")), 60000); |
| 464 | try { |
| 465 | const view = await api("/cli/sessions/" + session.id + "/open", {}, undefined, {}, { signal: controller.signal }); |
| 466 | const terminals = await api("/terminals", undefined, undefined, {}, { signal: controller.signal }); |
| 467 | if (sessionOpenRequest.current !== request) return; |
| 468 | const terminal = terminals.find(item => item.id === view.desktop_terminal_id && item.cli_session_id === session.id); |
| 469 | if (!terminal) throw new Error("终端状态已变化,请重新打开会话"); |
| 470 | showTerminal(terminal); |
| 471 | sessionsChanged(); |
| 472 | } catch (error) { |
| 473 | if (sessionOpenRequest.current === request && error.code !== "connection_changed") { |
| 474 | const message = (controller.signal.aborted ? controller.signal.reason : error).message; |
| 475 | setSessionOpenError({ id: session.id, message }); |
| 476 | } |
| 477 | } finally { |
| 478 | clearTimeout(timer); |
| 479 | if (sessionOpenRequest.current === request) { |
| 480 | sessionOpenRequest.current = null; |
| 481 | setOpeningSession(""); |
| 482 | } |
| 483 | } |
| 484 | }; |
| 485 | const archiveSession = async (session, anchor) => { |
| 486 | await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", pendingLabel:"正在归档…", anchor, |
| 487 | submit: async () => { |
| 488 | await api("/cli/sessions/" + session.id + "/archive", {}); |
| 489 | setTabs(list => list.filter(tab => tab.cli_session_id !== session.id)); |
| 490 | sessionsChanged(); |
| 491 | refreshStatus.current?.(); |
| 492 | }, |
| 493 | }); |
| 494 | }; |
| 495 | const pinSession = async session => { |
| 496 | try { |
| 497 | await api("/cli/sessions/" + session.id + "/metadata", {pinned:!session.pinned}); |
| 498 | sessionsChanged(); |
| 499 | } catch (error) { notify(error.message); } |
| 500 | }; |
| 501 | const newTerminalHere = (event) => |
| 502 | newTerminal(contentWorkspace, event?.currentTarget?.tagName === "BUTTON" |
| 503 | ? event.currentTarget : terminalTrigger.current); |
| 504 | const terminalMenuAt = (location) => terminalChoice?.anchor?.dataset.terminalLocation === location && ( |
| 505 | <TerminalMenu choice={terminalChoice} busy={busy} |
| 506 | onClose={() => setTerminalChoice(null)} |
| 507 | onSelect={(kind) => createTerminal(terminalChoice.path, kind).catch((e) => notify(e.message))} /> |
| 508 | ); |
| 509 | const openEditor = async (path = workspace) => { |
| 510 | browserDismissed.current = false; |
| 511 | const result = await action("/browser/editor", { workspace: path }); |
| 512 | if (result) { |
| 513 | setDesktopOpen(false); |
| 514 | setHome(false); |
| 515 | setTabs((list) => |
| 516 | list.some((t) => t.id === result.id) |
| 517 | ? list |
| 518 | : [ |
| 519 | ...list, |
| 520 | { |
| 521 | id: result.id, |
| 522 | kind: "editor", |
| 523 | workspace: path, |
| 524 | url: `http://127.0.0.1:18080/?folder=${encodeURIComponent(path)}`, |
| 525 | title: "文件编辑器", |
| 526 | }, |
| 527 | ], |
| 528 | ); |
| 529 | setActive(result.id); |
| 530 | } |
| 531 | }; |
| 532 | const closeTab = async (tab, anchor) => { |
| 533 | if (tab.cli_session_id) return archiveSession({id:tab.cli_session_id, title:tab.title}, anchor); |
| 534 | if (tab.kind === "terminal") { |
| 535 | if ( |
| 536 | !tab.closed && |
| 537 | !(await confirm({ |
| 538 | title: "关闭这个终端会话?", |
| 539 | body: "该终端中的交互命令可能被中断。网页和其他终端不受影响。", |
| 540 | confirm: "关闭终端", |
| 541 | })) |
| 542 | ) |
| 543 | return; |
| 544 | try { |
| 545 | await api("/terminals/" + tab.sessionId, undefined, "DELETE"); |
| 546 | } catch (e) { |
| 547 | notify(e.message); |
| 548 | return; |
| 549 | } |
| 550 | } else { |
| 551 | if ( |
| 552 | tab.kind === "editor" && |
| 553 | !(await confirm({ |
| 554 | title: "关闭文件编辑器?", |
| 555 | body: "请先保存未完成的修改。文件仍保留在共享项目中。", |
| 556 | confirm: "关闭编辑器", |
| 557 | })) |
| 558 | ) |
| 559 | return; |
| 560 | if (!(await action("/browser/close", { id: tab.id }))) return; |
| 561 | } |
| 562 | setTabs((list) => list.filter((t) => t.id !== tab.id)); |
| 563 | if (tab.incognito) setPrivateTabMetadata(previous => Object.fromEntries(Object.entries(previous).map(([key, value]) => [key, |
| 564 | Object.fromEntries(Object.entries(value).filter(([id]) => id !== tab.id).map(([id, item]) => |
| 565 | [id, id === "order" ? item.filter(id => id !== tab.id) : item])), |
| 566 | ]))); |
| 567 | |
| 568 | |
| 569 | if (tab.kind !== "terminal" && !tabs.some(item => item.id !== tab.id && item.kind !== "terminal")) return; |
| 570 | if (split && (tab.id === active || tab.id === other.id)) { |
| 571 | const remaining = tab.id === active ? other.id : active; |
| 572 | setLayout({ active: remaining }); |
| 573 | await select(remaining); |
| 574 | } else if (active === tab.id) { |
| 575 | const group = displayTabs.filter((item) => |
| 576 | tab.kind === "terminal" |
| 577 | ? item.kind === "terminal" && item.workspace === tab.workspace |
| 578 | : item.kind !== "terminal", |
| 579 | ); |
| 580 | const at = group.findIndex((item) => item.id === tab.id); |
| 581 | const next = group[at + 1] || group[at - 1]; |
| 582 | if (next) await select(next.id); |
| 583 | else setActive(""); |
| 584 | } |
| 585 | }; |
| 586 | const navigate = async (id, address) => { |
| 587 | try { |
| 588 | const internal = /^cage:\/\/settings(?:#(general|appearance|privacy|extensions|about))?\/?$/.exec(address.trim()); |
| 589 | if (internal) { await openBrowserSettings(internal[1] || "general"); return; } |
| 590 | const url = normalizeURL(address); |
| 591 | if (network.mode !== "open" && !isGuestLocalURL(url)) { |
| 592 | setSafetyOpen(true); |
| 593 | notify("请先完成关键检查,再访问外部网站。"); |
| 594 | return; |
| 595 | } |
| 596 | await action("/browser/navigate", { id, url }); |
| 597 | remote.current?.focus(); |
| 598 | } catch (error) { |
| 599 | notify(error.message); |
| 600 | } |
| 601 | }; |
| 602 | const stop = async () => { |
| 603 | if ( |
| 604 | await confirm({ |
| 605 | title: setupProgress ? "停止安装环境?" : "停止当前环境?", |
| 606 | body: setupProgress ? "当前安装任务会停止。下次启动环境时可以继续安装。" : "请先保存文件。当前终端会话会结束,浏览器登录和项目文件会保留。", |
| 607 | confirm: setupProgress ? "停止安装" : "停止环境", |
| 608 | }) |
| 609 | ) |
| 610 | await action("/stop"); |
| 611 | }; |
| 612 | const cancelAutomaticExit = () => { |
| 613 | quitAfterStop.current = null; |
| 614 | setQuitting(null); |
| 615 | }; |
| 616 | const stopAndQuit = async () => { |
| 617 | const request = { id: null }; |
| 618 | quitAfterStop.current = request; |
| 619 | setQuitting({ error: "" }); |
| 620 | try { |
| 621 | await stopAndExit({ |
| 622 | stop: () => api("/stop", {}), |
| 623 | readStatus: () => api("/status"), |
| 624 | exit: () => native("quitNow"), |
| 625 | isCancelled: () => quitAfterStop.current !== request, |
| 626 | onStatus: setStatus, |
| 627 | }); |
| 628 | } catch (error) { |
| 629 | if (quitAfterStop.current === request) { |
| 630 | quitAfterStop.current = null; |
| 631 | setQuitting({ error: error.message }); |
| 632 | } |
| 633 | } |
| 634 | }; |
| 635 | useEffect(() => { |
| 636 | let live = true, |
| 637 | timer, |
| 638 | polling = false; |
| 639 | const poll = async () => { |
| 640 | if (!live || polling) return; |
| 641 | clearTimeout(timer); |
| 642 | polling = true; |
| 643 | let jobRunning = false; |
| 644 | try { |
| 645 | const next = await api("/status"); |
| 646 | if (!live) return; |
| 647 | jobRunning = next.job.running; |
| 648 | setStatus(next); |
| 649 | setStartRequest(pending => pending?.id && pending.id === next.job.id ? null : pending); |
| 650 | setConnectionError(""); |
| 651 | if ( |
| 652 | !next.job.running && |
| 653 | next.job.id && |
| 654 | lastJob.current !== next.job.id |
| 655 | ) { |
| 656 | lastJob.current = next.job.id; |
| 657 | await refreshSettings(); |
| 658 | if (next.job.kind === "guest-install" && !next.job.error) { |
| 659 | const install = await api("/environment/guest-systems"); |
| 660 | if (live && install.activate) setGuestSystem(previous => ({ ...previous, activate:true })); |
| 661 | } |
| 662 | if (next.job.error) notify(next.job.error); |
| 663 | } |
| 664 | if (next.ready) { |
| 665 | const fetchBrowser = !browserStreamReady.current || !initialized.current; |
| 666 | const [browserResult, t] = await Promise.all([ |
| 667 | fetchBrowser ? api("/browser/tabs").then(result => { |
| 668 | if (live) setBrowserError(""); |
| 669 | return result; |
| 670 | }).catch(error => { |
| 671 | if (live) setBrowserError(error.message); |
| 672 | return null; |
| 673 | }) : null, |
| 674 | api("/terminals"), |
| 675 | ]); |
| 676 | if (!live) return; |
| 677 | const b = browserResult || browserSnapshot.current; |
| 678 | const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_identity_directory || next.environment_directory || next.workspace] || {}; |
| 679 | for (const item of t) { |
| 680 | const saved = legacyMetadata["terminal:" + item.id]; |
| 681 | if (!item.cli_session_id || item.metadata_set || !saved || (!saved.title && !saved.pinned)) continue; |
| 682 | try { |
| 683 | const updated = await api("/terminals/" + item.id + "/metadata", { |
| 684 | ...(saved.title ? {title:saved.title} : {}), pinned:Boolean(saved.pinned), |
| 685 | }); |
| 686 | Object.assign(item, {title:updated.title, custom_title:updated.custom_title, pinned:updated.pinned, metadata_set:true}); |
| 687 | } catch { } |
| 688 | } |
| 689 | if (!live) return; |
| 690 | browserSnapshot.current = b; |
| 691 | setBrowser(b); |
| 692 | const all = [ |
| 693 | ...b.tabs, |
| 694 | ...t.map((item) => ({ |
| 695 | ...item, |
| 696 | id: "terminal:" + item.id, |
| 697 | sessionId: item.id, |
| 698 | terminalKind: item.kind, |
| 699 | kind: "terminal", |
| 700 | })), |
| 701 | ]; |
| 702 | setTabs((previous) => { |
| 703 | const map = new Map(all.map((item) => [item.id, item])); |
| 704 | return [ |
| 705 | ...previous |
| 706 | .filter((item) => map.has(item.id)) |
| 707 | .map((item) => map.get(item.id)), |
| 708 | ...all.filter((item) => !previous.some((p) => p.id === item.id)), |
| 709 | ]; |
| 710 | }); |
| 711 | if (!browserDismissed.current && initialized.current && b.active && b.active !== activeRef.current && !browserIds.current.has(b.active)) { |
| 712 | setDesktopOpen(false); |
| 713 | setHome(false); |
| 714 | } |
| 715 | if ( |
| 716 | !activeRef.current || |
| 717 | !all.some((item) => item.id === activeRef.current) || |
| 718 | (!browserDismissed.current && initialized.current && |
| 719 | b.active && |
| 720 | !browserIds.current.has(b.active)) |
| 721 | ) { |
| 722 | if (browserDismissed.current && !all.some(item => item.id === activeRef.current)) setHome(true); |
| 723 | |
| 724 | if (!layoutRef.current.other || all.some(item => item.id === activeRef.current)) |
| 725 | setActive(b.active || all[0]?.id || ""); |
| 726 | } |
| 727 | browserIds.current = new Set(b.tabs.map((item) => item.id)); |
| 728 | initialized.current = true; |
| 729 | } |
| 730 | } catch (e) { |
| 731 | if (live) setConnectionError(e.message); |
| 732 | } finally { |
| 733 | polling = false; |
| 734 | if (live) |
| 735 | timer = setTimeout( |
| 736 | poll, |
| 737 | jobRunning ? 1200 : windowVisibleRef.current ? 3000 : 15000, |
| 738 | ); |
| 739 | } |
| 740 | }; |
| 741 | (async () => { |
| 742 | try { |
| 743 | const token = location.hash.slice(1); |
| 744 | if (token) { |
| 745 | await api("/session", { token }); |
| 746 | history.replaceState(null, "", location.pathname); |
| 747 | } |
| 748 | const config = await api("/settings"); |
| 749 | window.dispatchEvent(new Event("cage-session-ready")); |
| 750 | if (!live) return; |
| 751 | setSettings(config); |
| 752 | try { |
| 753 | const proxyState = await api("/proxy"); |
| 754 | if (!live) return; |
| 755 | setProxy(proxyState); |
| 756 | } catch { |
| 757 | |
| 758 | } |
| 759 | refreshStatus.current = poll; |
| 760 | await poll(); |
| 761 | } catch (e) { |
| 762 | if (live) setFatal(e.message); |
| 763 | } |
| 764 | })(); |
| 765 | return () => { |
| 766 | live = false; |
| 767 | refreshStatus.current = null; |
| 768 | clearTimeout(timer); |
| 769 | }; |
| 770 | }, []); |
| 771 | useEffect(() => { |
| 772 | if (windowVisible) refreshStatus.current?.(); |
| 773 | }, [windowVisible]); |
| 774 | useEffect(() => { |
| 775 | if (!settings || !status || fatal || connectionError || launchAcknowledged.current || !nativeAvailable()) return; |
| 776 | |
| 777 | |
| 778 | let live = true; |
| 779 | native("workbenchReady").then((accepted) => { |
| 780 | if (live && accepted === true) launchAcknowledged.current = true; |
| 781 | }).catch(() => {}); |
| 782 | return () => { live = false; }; |
| 783 | }, [settings, status, fatal, connectionError]); |
| 784 | useEffect(() => { |
| 785 | if (!status?.ready) return; |
| 786 | const stream = new EventSource(runtimeURL("/browser/events")); |
| 787 | stream.addEventListener("clipboard", (event) => { |
| 788 | remote.current?.receiveCopy(JSON.parse(event.data)); |
| 789 | }); |
| 790 | stream.onopen = () => { browserStreamReady.current = true; }; |
| 791 | stream.onerror = () => { browserStreamReady.current = false; }; |
| 792 | stream.onmessage = (event) => { |
| 793 | const b = JSON.parse(event.data); |
| 794 | setBrowserError(""); |
| 795 | if (b.desktopFocus === true) { |
| 796 | setDesktopOpen(true); |
| 797 | setHome(false); |
| 798 | setSettingsOpen(false); |
| 799 | } |
| 800 | const previousPair = browserSnapshot.current.split; |
| 801 | const local = layoutRef.current; |
| 802 | if (previousPair && !b.split && [local.active, local.other].includes(previousPair.left) && |
| 803 | [local.active, local.other].includes(previousPair.right)) { |
| 804 | const survivor = b.tabs.some(tab => tab.id === local.active) ? local.active : local.other; |
| 805 | setLayout({ active: survivor }); |
| 806 | } |
| 807 | browserSnapshot.current = b; |
| 808 | setBrowser((previous) => ({ ...previous, ...b })); |
| 809 | setTabs((previous) => { |
| 810 | const map = new Map(b.tabs.map((t) => [t.id, t])); |
| 811 | return [ |
| 812 | ...previous |
| 813 | .filter((t) => t.kind === "terminal" || map.has(t.id)) |
| 814 | .map((t) => map.get(t.id) || t), |
| 815 | ...b.tabs.filter((t) => !previous.some((p) => p.id === t.id)), |
| 816 | ]; |
| 817 | }); |
| 818 | if (!browserDismissed.current && b.active && b.focus) { |
| 819 | setDesktopOpen(false); |
| 820 | setHome(false); |
| 821 | } |
| 822 | if ( |
| 823 | b.active && |
| 824 | ((!browserDismissed.current && b.focus) || |
| 825 | !activeRef.current || |
| 826 | (!layoutRef.current.other && !activeRef.current.startsWith("terminal:"))) |
| 827 | ) |
| 828 | setActive(b.active); |
| 829 | browserIds.current = new Set(b.tabs.map((t) => t.id)); |
| 830 | }; |
| 831 | return () => { |
| 832 | browserStreamReady.current = false; |
| 833 | stream.close(); |
| 834 | }; |
| 835 | }, [status?.ready]); |
| 836 | useEffect(() => { |
| 837 | if (current && current.kind !== "terminal") |
| 838 | lastBrowserTab.current = current.id; |
| 839 | document.title = |
| 840 | (current?.title && current.title !== "新标签页" |
| 841 | ? current.title + " · " |
| 842 | : "") + "Cage"; |
| 843 | if (active && !current?.incognito) localStorage.setItem(clientStorageKey("cage-active"), active); |
| 844 | }, [current?.url, current?.title, current?.incognito, active]); |
| 845 | useEffect(() => { |
| 846 | if (!toast) return; |
| 847 | const timer = setTimeout(() => setToast(""), 4500); |
| 848 | return () => clearTimeout(timer); |
| 849 | }, [toast]); |
| 850 | useEffect(() => { |
| 851 | const key = (event) => { |
| 852 | if (document.querySelector("[data-environment-dialog]") || !primaryModifier(event)) return; |
| 853 | const k = event.key.toLowerCase(); |
| 854 | if (document.querySelector("[data-browser-dialog], .mac-login-fullscreen")) { |
| 855 | if (k === "w") { |
| 856 | event.preventDefault(); |
| 857 | event.stopImmediatePropagation(); |
| 858 | document.dispatchEvent(new Event("cage-close-modal")); |
| 859 | } |
| 860 | return; |
| 861 | } |
| 862 | if (dialog) { |
| 863 | if (k === "w") { |
| 864 | event.preventDefault(); |
| 865 | event.stopImmediatePropagation(); |
| 866 | void finishDialog(false); |
| 867 | } |
| 868 | return; |
| 869 | } |
| 870 | if (k === "," && !projectDialog && !rename && !hostGitOpen) { |
| 871 | event.preventDefault(); |
| 872 | event.stopImmediatePropagation(); |
| 873 | openSettings(); |
| 874 | return; |
| 875 | } |
| 876 | if ( |
| 877 | settingsOpen || |
| 878 | hostGitOpen || |
| 879 | transfer || |
| 880 | details || |
| 881 | safetyOpen || |
| 882 | projectDialog || |
| 883 | terminalChoice || |
| 884 | rename |
| 885 | ) { |
| 886 | if (k === "w") { |
| 887 | event.preventDefault(); |
| 888 | event.stopImmediatePropagation(); |
| 889 | document.dispatchEvent(new Event("cage-close-modal")); |
| 890 | } |
| 891 | return; |
| 892 | } |
| 893 | let handle; |
| 894 | if (k === "o") { |
| 895 | event.preventDefault(); |
| 896 | event.stopImmediatePropagation(); |
| 897 | if (event.shiftKey) { |
| 898 | document.dispatchEvent(new Event("cage-show-favorites")); |
| 899 | return; |
| 900 | } |
| 901 | if (!busy && running) setProjectDialog({ path: "" }); |
| 902 | return; |
| 903 | } |
| 904 | if (k === "t" && !event.shiftKey) handle = newPage; |
| 905 | if (k === "n" && event.shiftKey) handle = () => openBrowserPage(undefined, true); |
| 906 | if (k === "d") handle = () => document.dispatchEvent(new Event("cage-add-favorite")); |
| 907 | if (k === "enter" && event.shiftKey) handle = newTerminalHere; |
| 908 | if (k === "l") |
| 909 | handle = () => { |
| 910 | const input = [...document.querySelectorAll("[data-browser-tab]")].find(node => node.dataset.browserTab === active)?.querySelector(".address-bar input"); |
| 911 | input?.focus(); |
| 912 | input?.select(); |
| 913 | }; |
| 914 | if (k === "w" && current && !desktopOpen) handle = () => closeTab(current); |
| 915 | if (/^[1-9]$/.test(k)) { |
| 916 | const tab = k === "9" ? switchTabs.at(-1) : switchTabs[Number(k) - 1]; |
| 917 | if (tab) handle = () => select(tab.id); |
| 918 | } |
| 919 | if (event.shiftKey && ["[", "]", "{", "}"].includes(k)) { |
| 920 | const direction = ["[", "{"].includes(k) ? -1 : 1, |
| 921 | at = switchTabs.findIndex((t) => t.id === active), |
| 922 | tab = |
| 923 | switchTabs[ |
| 924 | (at + direction + switchTabs.length) % switchTabs.length |
| 925 | ]; |
| 926 | if (tab) handle = () => select(tab.id); |
| 927 | } |
| 928 | if (handle) { |
| 929 | event.preventDefault(); |
| 930 | event.stopImmediatePropagation(); |
| 931 | if ( |
| 932 | !busy && |
| 933 | (status?.ready || |
| 934 | (running && k === "enter") || |
| 935 | (k === "w" && terminal)) |
| 936 | ) |
| 937 | void handle(); |
| 938 | } |
| 939 | }; |
| 940 | window.addEventListener("keydown", key, true); |
| 941 | window.cageEditAction = (command) => { |
| 942 | if (document.querySelector(".mac-login-fullscreen")) return false; |
| 943 | if ( |
| 944 | settingsOpen || |
| 945 | transfer || |
| 946 | dialog || |
| 947 | details || |
| 948 | safetyOpen || |
| 949 | projectDialog || |
| 950 | terminalChoice || |
| 951 | rename || |
| 952 | showHome |
| 953 | ) |
| 954 | return false; |
| 955 | if (terminal) |
| 956 | return terminalControls.current.get(current.id)?.edit(command) || false; |
| 957 | return remote.current?.edit(command) || false; |
| 958 | }; |
| 959 | window.cageWorkbenchAction = async (command) => { |
| 960 | if (document.querySelector(".mac-login-fullscreen")) { |
| 961 | if (command === "closeTab" || command === "quit") document.dispatchEvent(new Event("cage-close-modal")); |
| 962 | if (command !== "quit") return; |
| 963 | } |
| 964 | if (document.querySelector("[data-environment-dialog]")) { |
| 965 | if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal")); |
| 966 | return; |
| 967 | } |
| 968 | if (hostGitOpen && command !== "quit") { |
| 969 | if (command === "closeTab") |
| 970 | document.dispatchEvent(new Event("cage-close-modal")); |
| 971 | return; |
| 972 | } |
| 973 | if (command === "settings") { |
| 974 | if (!projectDialog && !rename && !dialog) openSettings(); |
| 975 | return; |
| 976 | } |
| 977 | if (storageRecovery && ["openProject", "newTab", "newTerminal"].includes(command)) { |
| 978 | openSettings("project"); |
| 979 | return; |
| 980 | } |
| 981 | if (command === "openProject") { |
| 982 | if ( |
| 983 | !busy && |
| 984 | running && |
| 985 | !settingsOpen && |
| 986 | !dialog && |
| 987 | !projectDialog && |
| 988 | !rename |
| 989 | ) |
| 990 | setProjectDialog({ path: "" }); |
| 991 | return; |
| 992 | } |
| 993 | if ( |
| 994 | (settingsOpen || dialog || projectDialog || terminalChoice || rename) && |
| 995 | ["newTab", "newTerminal"].includes(command) |
| 996 | ) |
| 997 | return; |
| 998 | if (command === "newTab" && status?.ready) await newPage(); |
| 999 | if (command === "newTerminal" && status?.vm_running) |
| 1000 | await newTerminalHere(); |
| 1001 | if (command === "closeTab") { |
| 1002 | if (document.querySelector("[data-browser-dialog], .mac-login-fullscreen")) { |
| 1003 | document.dispatchEvent(new Event("cage-close-modal")); |
| 1004 | return; |
| 1005 | } |
| 1006 | if (dialog) { |
| 1007 | void finishDialog(false); |
| 1008 | } else if ( |
| 1009 | settingsOpen || |
| 1010 | transfer || |
| 1011 | details || |
| 1012 | safetyOpen || |
| 1013 | projectDialog || |
| 1014 | terminalChoice || |
| 1015 | rename |
| 1016 | ) |
| 1017 | document.dispatchEvent(new Event("cage-close-modal")); |
| 1018 | else if (desktopOpen) setDesktopOpen(false); |
| 1019 | else if (current) await closeTab(current); |
| 1020 | } |
| 1021 | if (command === "quit") { |
| 1022 | if (quitAfterStop.current) return; |
| 1023 | if (isRemoteClient()) { |
| 1024 | await native("quitNow"); |
| 1025 | return; |
| 1026 | } |
| 1027 | if (status && !connectionError && !status.vm_running && !busy) { |
| 1028 | await native("quitNow"); |
| 1029 | return; |
| 1030 | } |
| 1031 | if (connectionError || fatal) { |
| 1032 | setDialog({ |
| 1033 | title: "退出 Cage", |
| 1034 | body: "工作台连接已中断,暂时无法确认环境状态。仍在运行的后台任务会继续。", |
| 1035 | confirm: "仅退出桌面应用", |
| 1036 | resolve: (confirmed) => confirmed && native("quitNow"), |
| 1037 | }); |
| 1038 | return; |
| 1039 | } |
| 1040 | setDialog({ |
| 1041 | title: "退出 Cage", |
| 1042 | body: "退出前请保存文件和设置。可以保留环境,让后台任务继续运行;下次打开会重新连接。", |
| 1043 | confirm: "停止环境并退出", |
| 1044 | secondary: "保留运行并退出", |
| 1045 | resolve: async (result) => { |
| 1046 | if (result === "secondary") { |
| 1047 | await native("quitNow"); |
| 1048 | } else if (result) { |
| 1049 | await stopAndQuit(); |
| 1050 | } |
| 1051 | }, |
| 1052 | }); |
| 1053 | } |
| 1054 | }; |
| 1055 | return () => { |
| 1056 | window.removeEventListener("keydown", key, true); |
| 1057 | delete window.cageWorkbenchAction; |
| 1058 | delete window.cageEditAction; |
| 1059 | }; |
| 1060 | }, [ |
| 1061 | status, |
| 1062 | settingsOpen, |
| 1063 | hostGitOpen, |
| 1064 | safetyOpen, |
| 1065 | details, |
| 1066 | transfer, |
| 1067 | dialog, |
| 1068 | current, |
| 1069 | tabs, |
| 1070 | busy, |
| 1071 | active, |
| 1072 | connectionError, |
| 1073 | fatal, |
| 1074 | projectDialog, |
| 1075 | rename, |
| 1076 | showHome, |
| 1077 | savedTabs, |
| 1078 | selectedProject, |
| 1079 | desktopOpen, |
| 1080 | terminalChoice, |
| 1081 | ]); |
| 1082 | const project = projectName(contentWorkspace, status?.environment_directory); |
| 1083 | const tabLayoutKey = status?.environment_identity_directory || status?.environment_directory || status?.workspace; |
| 1084 | const metadata = { ...(savedTabs[tabLayoutKey] || {}), ...(privateTabMetadata[tabLayoutKey] || {}) }; |
| 1085 | for (const tab of tabs) { |
| 1086 | if (tab.cli_session_id && tab.metadata_set) metadata[tab.id] = { |
| 1087 | ...metadata[tab.id], title:tab.custom_title || tab.title, pinned:Boolean(tab.pinned), |
| 1088 | }; |
| 1089 | } |
| 1090 | const claudeLabels = new Map(claudeProfiles.accounts?.map((account) => [account.id, account.label || account.email])); |
| 1091 | const claudeNumbers = new Map(claudeProfiles.accounts?.map((account, index) => [account.id, index + 1])); |
| 1092 | const terminalAccountName = (tab) => claudeLabels.get(tab.claude_account_id) || |
| 1093 | (tab.terminalKind === "claude-login" ? "新账号登录" : tab.claude_account_id ? "Claude 账号" : ""); |
| 1094 | const displayTabs = orderedTabs(tabs, metadata).map((tab) => |
| 1095 | tab.claude_account_id || tab.terminalKind === "claude-login" ? { ...tab, |
| 1096 | claudeLabel: terminalAccountName(tab), claudeAccountNumber: claudeNumbers.get(tab.claude_account_id) } : tab); |
| 1097 | const browserTabs = displayTabs.filter((tab) => tab.kind !== "terminal"); |
| 1098 | const switchTabs = |
| 1099 | terminal && !showHome |
| 1100 | ? displayTabs.filter( |
| 1101 | (tab) => |
| 1102 | tab.kind === "terminal" && tab.workspace === current.workspace, |
| 1103 | ) |
| 1104 | : dualBrowser ? browserTabs.filter(tab => current.id === rightId ? tab.id === rightId : tab.id !== rightId) : browserTabs; |
| 1105 | const renameTab = (tab) => |
| 1106 | setRename({ id: tab.id, title: tabName({ ...tab, incognito: false }, metadata, project) }); |
| 1107 | const updateSharedMetadata = async (tab, changes) => { |
| 1108 | const updated = await api("/terminals/" + tab.sessionId + "/metadata", changes); |
| 1109 | setTabs(list => list.map(item => item.id === tab.id ? { |
| 1110 | ...item, title:updated.title, custom_title:updated.custom_title, pinned:updated.pinned, metadata_set:true, |
| 1111 | } : item)); |
| 1112 | }; |
| 1113 | const pinTab = (id) => { |
| 1114 | const tab = tabs.find(tab => tab.id === id); |
| 1115 | if (tab?.cli_session_id) { |
| 1116 | void updateSharedMetadata(tab, {pinned:!metadata[id]?.pinned}).catch(error => notify(error.message)); |
| 1117 | return; |
| 1118 | } |
| 1119 | changeTabMetadata({ |
| 1120 | ...metadata, |
| 1121 | [id]: { ...metadata[id], pinned: !metadata[id]?.pinned }, |
| 1122 | }); |
| 1123 | }; |
| 1124 | const persist = (key, value, setter) => { |
| 1125 | try { |
| 1126 | localStorage.setItem(clientStorageKey(key), JSON.stringify(value)); |
| 1127 | setter(value); |
| 1128 | } catch { |
| 1129 | notify("未能保存界面偏好,请检查本地存储空间。"); |
| 1130 | } |
| 1131 | }; |
| 1132 | const changeTabMetadata = (next) => { |
| 1133 | const currentPrivateIDs = new Set(tabs.filter(tab => tab.incognito).map(tab => tab.id)); |
| 1134 | const privateIDs = new Set([...currentPrivateIDs, ...Object.keys(privateTabMetadata[tabLayoutKey] || {}).filter(id => id !== "order" && id !== "sessionOrder")]); |
| 1135 | const persistent = Object.fromEntries(Object.entries(next).filter(([id]) => !privateIDs.has(id))); |
| 1136 | if (next.order) persistent.order = next.order.filter(id => !privateIDs.has(id) && tabs.some(tab => tab.id === id)); |
| 1137 | setPrivateTabMetadata(previous => ({ ...previous, [tabLayoutKey]: { |
| 1138 | ...Object.fromEntries(Object.entries(next).filter(([id]) => currentPrivateIDs.has(id))), |
| 1139 | ...(next.order ? { order: next.order } : {}), |
| 1140 | } })); |
| 1141 | persist( |
| 1142 | "cage-tab-layout", |
| 1143 | { ...savedTabs, [tabLayoutKey]: persistent }, |
| 1144 | setSavedTabs, |
| 1145 | ); |
| 1146 | }; |
| 1147 | const reorder = (from, to, scopeOrder) => { |
| 1148 | if (scopeOrder) { |
| 1149 | const ids = new Set(scopeOrder); |
| 1150 | let index = 0; |
| 1151 | const order = displayTabs.map((tab) => ids.has(tab.id) ? scopeOrder[index++] : tab.id); |
| 1152 | changeTabMetadata({ ...metadata, order }); |
| 1153 | return; |
| 1154 | } |
| 1155 | if (from === to) return; |
| 1156 | const order = displayTabs.map((tab) => tab.id).filter((id) => id !== from); |
| 1157 | order.splice(order.indexOf(to), 0, from); |
| 1158 | changeTabMetadata({ ...metadata, order }); |
| 1159 | }; |
| 1160 | const openedProject = async (path) => { |
| 1161 | await refreshSettings(); |
| 1162 | await refreshStatus.current?.(); |
| 1163 | setSelectedProject(path); |
| 1164 | setProjectDialog(null); |
| 1165 | setHome(true); |
| 1166 | }; |
| 1167 | useEffect(() => { |
| 1168 | if (status?.workspace) setSelectedProject(status.workspace); |
| 1169 | }, [status?.workspace]); |
| 1170 | const finishDialog = async (value) => { |
| 1171 | if (!dialog || dialog.pending) return; |
| 1172 | if (value === true && dialog.submit) { |
| 1173 | setDialog({ ...dialog, pending: true, error: "" }); |
| 1174 | try { await dialog.submit(); } |
| 1175 | catch (error) { |
| 1176 | setDialog({ ...dialog, pending: false, error: error.message }); |
| 1177 | return; |
| 1178 | } |
| 1179 | } |
| 1180 | const resolve = dialog.resolve; |
| 1181 | setDialog(null); |
| 1182 | resolve(value); |
| 1183 | }; |
| 1184 | const sidebarButton = side => sidebarCollapsed && side !== "right" && |
| 1185 | <ExpandSidebar onClick={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />; |
| 1186 | const expandButton = tab => split && tab && <ExpandPane onClick={() => { |
| 1187 | setLayout({ active: tab.id }); |
| 1188 | void select(tab.id); |
| 1189 | }} />; |
| 1190 | const focusHeader = tab => { |
| 1191 | if (tab && tab.id !== activeRef.current) void select(tab.id, false); |
| 1192 | }; |
| 1193 | const terminalHeader = tab => { |
| 1194 | const path = tab?.workspace || workspace; |
| 1195 | const account = tab?.claude_account_id && terminalAccountName(tab); |
| 1196 | const detail = tab?.terminalKind === "claude-login" ? `登录 · ${account || "新账号"}` |
| 1197 | : account ? `Claude · ${account}${tab.claude_account_source === "default" ? "(启动时账号)" : ""}` : ""; |
| 1198 | const location = split && tab ? `heading-${tab.id}` : "heading"; |
| 1199 | return <TerminalHeader tab={tab} project={projectName(path, status?.environment_directory)} metadata={metadata} |
| 1200 | contentWorkspace={path} terminalDetail={detail} terminalDetailHint={tab?.claude_account_source === "default" |
| 1201 | ? "此终端按启动时的普通终端登录标记。若普通终端已换号,请重新打开工作会话确认身份。" : detail} |
| 1202 | busy={busy} onHome={() => setHome(true)} |
| 1203 | sidebarButton={sidebarButton(paneSide(tab?.id))} exitButton={expandButton(tab)} |
| 1204 | location={location} triggerRef={!tab || tab.id === active ? terminalTrigger : undefined} |
| 1205 | menu={terminalMenuAt(location)} onClose={() => closeTab(tab)} />; |
| 1206 | }; |
| 1207 | const recoverEditor = async tab => { |
| 1208 | if (!(await confirm({ title: "重启编辑器?", body: "请先保存文件。浏览器、终端和环境会继续运行。", confirm: "重启编辑器" }))) return; |
| 1209 | setRecoveringEditor(true); |
| 1210 | try { await api("/browser/editor-restart", { workspace: tab.workspace || workspace }); notify("编辑器已恢复"); } |
| 1211 | catch (error) { notify(error.message); } |
| 1212 | finally { setRecoveringEditor(false); } |
| 1213 | }; |
| 1214 | const paneTabs = tab => !dualBrowser ? browserTabs : browserTabs.filter(item => |
| 1215 | item.id === tab.id || (tab.id === leftId && item.id !== rightId)); |
| 1216 | const browserHeader = tab => <BrowserHeader vault={passwordVault} onManageVault={() => openSettings("vault")} tab={tab} tabs={paneTabs(tab)} metadata={metadata} |
| 1217 | vertical={browserTabLayout === "vertical"} |
| 1218 | ready={status.ready} busy={busy} focused={active === tab.id} compact={split} splitDrag={splitDrag} |
| 1219 | sidebarButton={sidebarButton(paneSide(tab.id))} exitButton={expandButton(tab)} |
| 1220 | triggerRef={tab.id === active ? terminalTrigger : undefined} |
| 1221 | location={split ? `heading-${tab.id}` : "heading"} menu={terminalMenuAt(split ? `heading-${tab.id}` : "heading")} |
| 1222 | back={tab.kind !== "browser-settings" && (browser.split?.history?.[tab.id]?.back ?? (tab.id === browser.active && browser.back))} |
| 1223 | forward={tab.kind !== "browser-settings" && (browser.split?.history?.[tab.id]?.forward ?? (tab.id === browser.active && browser.forward))} |
| 1224 | action={action} onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder} |
| 1225 | onNew={newPage} onNavigate={address => navigate(tab.id, address)} onOpen={openBrowserPage} |
| 1226 | onNewPrivate={() => openBrowserPage(undefined, true)} onNewRegular={() => openBrowserPage(undefined, false)} |
| 1227 | onSettings={openBrowserSettings} |
| 1228 | onReload={() => tab.kind === "browser-settings" ? setBrowserSettingsRevision(value => value + 1) : action("/browser/reload", { id: tab.id })} |
| 1229 | onCloseBrowser={!dualBrowser || tab.id === rightId ? closeBrowser : undefined} |
| 1230 | downloads={downloads} onStatus={notify} |
| 1231 | onEditor={() => openEditor(tab.workspace || workspace)} recoveringEditor={recoveringEditor} |
| 1232 | onRecover={() => recoverEditor(tab)} />; |
| 1233 | const dialogs = ( |
| 1234 | <> |
| 1235 | {hostGitOpen && ( |
| 1236 | <HostGitPreparation |
| 1237 | onClose={() => setStartOptions(null)} |
| 1238 | onReady={async () => { |
| 1239 | setStartRequest({ id: null }); |
| 1240 | setStartOptions(null); |
| 1241 | const result = await action("/start", startOptions); |
| 1242 | setStartRequest(result ? { id: result.id } : null); |
| 1243 | if (result) refreshStatus.current?.(); |
| 1244 | }} |
| 1245 | /> |
| 1246 | )} |
| 1247 | {dialog && ( |
| 1248 | <Modal |
| 1249 | title={dialog.title} |
| 1250 | anchor={dialog.anchor} |
| 1251 | onClose={dialog.pending ? undefined : () => finishDialog(false)} |
| 1252 | footer={ |
| 1253 | <> |
| 1254 | <button disabled={dialog.pending} onClick={() => finishDialog(false)}>取消</button> |
| 1255 | {dialog.secondary && ( |
| 1256 | <button disabled={dialog.pending} onClick={() => finishDialog("secondary")}> |
| 1257 | {dialog.secondary} |
| 1258 | </button> |
| 1259 | )} |
| 1260 | <button className="primary" disabled={dialog.pending} onClick={() => finishDialog(true)}> |
| 1261 | {dialog.pending ? dialog.pendingLabel : dialog.confirm} |
| 1262 | </button> |
| 1263 | </> |
| 1264 | } |
| 1265 | > |
| 1266 | <div className="modal-body"> |
| 1267 | <p>{dialog.body}</p> |
| 1268 | {dialog.error && <div className="error-message" role="alert">{dialog.error}</div>} |
| 1269 | </div> |
| 1270 | </Modal> |
| 1271 | )} |
| 1272 | {quitting && ( |
| 1273 | <Modal |
| 1274 | title={quitting.error ? "未能完成退出" : "正在停止环境"} |
| 1275 | onClose={cancelAutomaticExit} |
| 1276 | footer={ |
| 1277 | <> |
| 1278 | <button onClick={cancelAutomaticExit}> |
| 1279 | {quitting.error ? "留在 Cage" : "取消自动退出"} |
| 1280 | </button> |
| 1281 | {quitting.error && ( |
| 1282 | <button className="primary" onClick={stopAndQuit}> |
| 1283 | 重试停止并退出 |
| 1284 | </button> |
| 1285 | )} |
| 1286 | </> |
| 1287 | } |
| 1288 | > |
| 1289 | <div |
| 1290 | className="modal-body" |
| 1291 | role={quitting.error ? "alert" : "status"} |
| 1292 | > |
| 1293 | <p> |
| 1294 | {quitting.error || |
| 1295 | (connectionError |
| 1296 | ? "正在恢复工作台连接,恢复后会继续确认停止结果。" |
| 1297 | : "停止完成后 Cage 会自动退出。取消自动退出只保留窗口,环境仍会停止。")} |
| 1298 | </p> |
| 1299 | {!quitting.error && ( |
| 1300 | <p> |
| 1301 | <LoaderCircle size={16} className="spin" />{" "} |
| 1302 | {status?.job?.running |
| 1303 | ? status.job.message |
| 1304 | : "正在确认环境已停止…"} |
| 1305 | </p> |
| 1306 | )} |
| 1307 | </div> |
| 1308 | </Modal> |
| 1309 | )} |
| 1310 | </> |
| 1311 | ); |
| 1312 | if (fatal) |
| 1313 | return ( |
| 1314 | <> |
| 1315 | <div className="boot-screen"> |
| 1316 | <Shield size={36} /> |
| 1317 | <h1>连接 Cage 工作台</h1> |
| 1318 | <p>{fatal}</p> |
| 1319 | <p className="muted"> |
| 1320 | 请从 Cage 应用打开,或在终端运行 <code>cage desktop</code>。 |
| 1321 | </p> |
| 1322 | <button |
| 1323 | className="primary" |
| 1324 | onClick={() => |
| 1325 | nativeAvailable() ? native("reconnect") : location.reload() |
| 1326 | } |
| 1327 | > |
| 1328 | 重新连接 |
| 1329 | </button> |
| 1330 | </div> |
| 1331 | {dialogs} |
| 1332 | </> |
| 1333 | ); |
| 1334 | if (!status || !settings) |
| 1335 | return ( |
| 1336 | <> |
| 1337 | <div className="boot-screen"> |
| 1338 | <div className="brand-mark">C</div> |
| 1339 | <h1>Cage</h1> |
| 1340 | <p> |
| 1341 | <LoaderCircle size={16} className="spin" /> |
| 1342 | 正在连接工作区… |
| 1343 | </p> |
| 1344 | </div> |
| 1345 | {dialogs} |
| 1346 | </> |
| 1347 | ); |
| 1348 | return ( |
| 1349 | <SafetyChecklistContext.Provider value={() => setSafetyOpen(true)}> |
| 1350 | <div className={`app ${sidebarCollapsed ? "sidebar-collapsed" : ""}`}> |
| 1351 | <div |
| 1352 | className="workbench-shell" |
| 1353 | inert={settingsOpen || hostGitOpen || undefined} |
| 1354 | > |
| 1355 | {!sidebarCollapsed && ( |
| 1356 | <WorkspaceSidebar |
| 1357 | downloadAction={<BrowserDownloads sidebar downloads={downloads} ready={status.ready && !busy} onStatus={notify} />} |
| 1358 | updateAction={<AppUpdateButton updates={appUpdates} />} |
| 1359 | workspace={selectedProject || status.workspace} |
| 1360 | guestSystem={account?.guest_system || status.guest_system || guestSystem?.guest_system || "debian-13"} |
| 1361 | defaultWorkspace={status.environment_directory} |
| 1362 | projects={projects} |
| 1363 | tabs={displayTabs} |
| 1364 | sessions={cliSessions.sessions.map(session => ({ ...session, |
| 1365 | claudeAccountNumber: claudeNumbers.get(session.account_id) }))} |
| 1366 | sessionError={cliSessions.error} |
| 1367 | sessionRefreshing={cliSessions.loading} |
| 1368 | onSessionRefresh={cliSessions.refresh} |
| 1369 | onSessionOpen={openSessionTerminal} |
| 1370 | openingSession={openingSession} |
| 1371 | sessionOpenError={sessionOpenError} |
| 1372 | onSessionArchive={archiveSession} |
| 1373 | onSessionPin={pinSession} |
| 1374 | onSessionRename={session => setRename({id:session.id, title:session.title, session:true})} |
| 1375 | saved={metadata} |
| 1376 | active={active} |
| 1377 | home={showHome} |
| 1378 | busy={busy || storageRecovery} |
| 1379 | ready={status.ready} |
| 1380 | running={running} |
| 1381 | runtimeLabel={runtimeLabel} |
| 1382 | network={network} |
| 1383 | onHome={() => { setDesktopOpen(false); setHome(true); }} |
| 1384 | onOpenProject={(path = "") => setProjectDialog({ path })} |
| 1385 | onSelect={select} |
| 1386 | onClose={closeTab} |
| 1387 | onRename={renameTab} |
| 1388 | onPin={pinTab} |
| 1389 | splitDrag={splitDrag} |
| 1390 | onReorder={reorder} |
| 1391 | onSessionReorder={(path, order) => changeTabMetadata({ ...metadata, |
| 1392 | sessionOrder: { ...metadata.sessionOrder, [path]: order } })} |
| 1393 | onProjectSelect={setSelectedProject} |
| 1394 | onNewTerminal={newTerminal} |
| 1395 | terminalMenuAt={terminalMenuAt} |
| 1396 | onBrowser={openBrowser} |
| 1397 | onTailscale={() => setTailscaleOpen(true)} |
| 1398 | desktopOpen={desktopOpen} |
| 1399 | onClaudeWeb={() => openBrowserPage("https://claude.ai/")} |
| 1400 | onClaudeDesktop={() => { setHome(false); setDesktopOpen(true); }} |
| 1401 | onEditor={openEditor} |
| 1402 | onSettings={openSettings} |
| 1403 | onAccountConfirm={confirm} |
| 1404 | onAccountStatus={notify} |
| 1405 | onSafety={() => setSafetyOpen(true)} |
| 1406 | onCollapse={() => |
| 1407 | persist("cage-sidebar-collapsed", true, setSidebarCollapsed) |
| 1408 | } |
| 1409 | /> |
| 1410 | )} |
| 1411 | <div className="workbench-main"> |
| 1412 | {showHome && terminalHeader(null)} |
| 1413 | {browserError && running && !connectionError && <div className="connection-banner" role="status"> |
| 1414 | <span>客机浏览器暂时无法连接。{browserError}</span> |
| 1415 | <button onClick={() => refreshStatus.current?.()}>重试</button> |
| 1416 | </div>} |
| 1417 | {connectionError && ( |
| 1418 | <div className="connection-banner" role="alert"> |
| 1419 | 工作台连接中断,后台状态暂时未知。 |
| 1420 | <button |
| 1421 | onClick={() => |
| 1422 | nativeAvailable() ? native("reconnect") : location.reload() |
| 1423 | } |
| 1424 | > |
| 1425 | 重新连接工作台 |
| 1426 | </button> |
| 1427 | </div> |
| 1428 | )} |
| 1429 | <main className={`workspace ${split ? "workspace-split" : ""}`} ref={workspaceBox} |
| 1430 | style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}> |
| 1431 | {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>} |
| 1432 | {!storageRecovery && desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote} |
| 1433 | onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} visible={!settingsOpen} onConfirm={confirm} |
| 1434 | sidebarCollapsed={sidebarCollapsed} onExpand={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />} |
| 1435 | {!storageRecovery && desktopOpen && !macGuest && <ClaudeDesktop |
| 1436 | uploads={desktopFiles.uploads} |
| 1437 | onProjectOpened={() => refreshStatus.current?.()} |
| 1438 | status={status} visible={!settingsOpen} remoteRef={remote} |
| 1439 | onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} |
| 1440 | onConfirm={confirm} onDetails={() => setDetails(true)} |
| 1441 | sidebarCollapsed={sidebarCollapsed} |
| 1442 | onExpand={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} |
| 1443 | />} |
| 1444 | {status.environment_update_required && !busy && ( |
| 1445 | <div className="environment-update-banner" role="status"> |
| 1446 | <span>{status.environment_update_error || "环境组件需要更新。请先保存编辑器中的文件。"}</span> |
| 1447 | <button onClick={() => openSettings("project")}>查看并更新</button> |
| 1448 | </div> |
| 1449 | )} |
| 1450 | {!storageRecovery && (status.vm_running || terminal) && ( |
| 1451 | <> |
| 1452 | {!desktopOpen && !showHome && webPanes.length > 0 && ( |
| 1453 | <section className={`pane-lane browser-lane ${browserTabLayout === "vertical" ? "vertical-browser" : ""} ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}> |
| 1454 | {browserTabLayout === "vertical" && <BrowserTabRail tabs={browserTabs} metadata={metadata} |
| 1455 | active={liveBrowser?.id} ready={status.ready} busy={busy} splitDrag={splitDrag} |
| 1456 | sidebarButton={sidebarButton(paneSide(webPanes[0].id))} |
| 1457 | onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder} |
| 1458 | onNew={newPage} />} |
| 1459 | <div className="browser-headers">{webPanes.map(tab => |
| 1460 | <div key={paneSide(tab.id) || "single"} className="browser-header-cell" data-focused={active === tab.id} |
| 1461 | onPointerDownCapture={() => focusHeader(tab)} onFocusCapture={() => focusHeader(tab)}> |
| 1462 | {browserHeader(tab)} |
| 1463 | </div>)}</div> |
| 1464 | <div className="pane-body" onPointerDownCapture={() => { |
| 1465 | if (!dualBrowser && liveBrowser?.id !== active) focusHeader(liveBrowser); |
| 1466 | }}> |
| 1467 | {status.ready && liveBrowser?.kind === "browser-settings" && <BrowserSettingsPage |
| 1468 | key={`${liveBrowser.id}:${browserSettingsRevision}`} tab={liveBrowser} tabs={tabs} |
| 1469 | currentHome={settings.browser_home_url} layout={browserTabLayout} |
| 1470 | onLayoutChange={value => persist("cage-browser-tab-layout", value, setBrowserTabLayout)} |
| 1471 | onSectionChange={openBrowserSettings} |
| 1472 | onSaved={next => setSettings(previous => ({ ...previous, ...next }))} |
| 1473 | onInternal={openInternalPage} onOpenPage={openSettingsPageResult} onConfirm={confirm} />} |
| 1474 | {status.ready && <RemoteView ref={remote} visible={Boolean(liveBrowserVisible && !settingsOpen && liveBrowser?.kind !== "browser-settings")} |
| 1475 | copyScope={webPanes.map(tab => `${tab.id}:${tab.document || ""}`).join("|")} |
| 1476 | focused={dualBrowser || liveBrowser?.id === active} keyboard={status.keyboard} |
| 1477 | guestPlatform={status.guest_system} systemClipboard={browser.capabilities?.systemClipboard !== false} |
| 1478 | tabId={liveBrowser?.id} onStatus={notify} |
| 1479 | onFallback={(text, message) => setTransfer({ text, message })} />} |
| 1480 | {!status.ready && <div className="view-overlay"> |
| 1481 | <RefreshCw /><h3>浏览器连接暂时不可用</h3> |
| 1482 | <p>环境和终端仍可运行;恢复浏览器不会停止现有终端。</p> |
| 1483 | <button className="primary" disabled={busy} onClick={() => setStartOptions({})}>恢复浏览器</button> |
| 1484 | </div>} |
| 1485 | {status.ready && !splitReady && <div className="view-overlay">正在调整浏览器布局…</div>} |
| 1486 | </div> |
| 1487 | </section> |
| 1488 | )} |
| 1489 | {tabs.filter(t => t.kind === "terminal").map(tab => { |
| 1490 | const visible = !desktopOpen && !showHome && panes.some(pane => pane.id === tab.id); |
| 1491 | return <section key={tab.id} className={`pane-lane terminal-lane split-${paneSide(tab.id)}`} |
| 1492 | data-focused={active === tab.id} hidden={!visible} |
| 1493 | onPointerDownCapture={() => focusHeader(tab)} onFocusCapture={() => focusHeader(tab)}> |
| 1494 | {visible && terminalHeader(tab)} |
| 1495 | <div className="pane-body"> |
| 1496 | <TerminalView |
| 1497 | session={{ ...tab, id: tab.sessionId }} |
| 1498 | onLoginTab={({ id }) => showBrowserResult({ id, kind: "web", login: true, incognito: true, title: "账号授权" })} |
| 1499 | onControls={(control) => |
| 1500 | control |
| 1501 | ? terminalControls.current.set(tab.id, control) |
| 1502 | : terminalControls.current.delete(tab.id) |
| 1503 | } |
| 1504 | visible={visible && !settingsOpen} |
| 1505 | focused={active === tab.id} |
| 1506 | onStatus={notify} |
| 1507 | onAccountChanged={view => { if (view?.desktop_terminal_id && view.desktop_terminal_id !== tab.sessionId) void openSessionTerminal({id:tab.cli_session_id}); }} |
| 1508 | /> |
| 1509 | </div> |
| 1510 | </section>; |
| 1511 | })} |
| 1512 | </> |
| 1513 | )} |
| 1514 | {showHome && ( |
| 1515 | <div className="welcome"> |
| 1516 | <div className="welcome-content"> |
| 1517 | <img className="welcome-logo" src={logo} alt="Cage" /> |
| 1518 | {storageRecovery ? <> |
| 1519 | <h1>环境存储需要恢复</h1> |
| 1520 | <p className="welcome-subtitle"><SafetyMessage message={status.storage_recovery.error} /></p> |
| 1521 | <p className="field-help">在设置中恢复环境存储后,再启动浏览器和终端。诊断包可以从同一页面导出。</p> |
| 1522 | <button className="primary" onClick={() => openSettings("project")}>恢复环境存储</button> |
| 1523 | </> : setupProgress ? <> |
| 1524 | <h1>{status.job.error ? "环境安装未完成" : "正在安装 Cage 环境"}</h1> |
| 1525 | <SetupProgress job={status.job} onDetails={() => setDetails(true)} |
| 1526 | onStop={stop} onRetry={() => setStartOptions(status.job.kind === "guest-install" ? { guest_system: status.job.setup_progress.system } : {})} disconnected={Boolean(connectionError)} /> |
| 1527 | </> : <> |
| 1528 | <h1> |
| 1529 | {busy |
| 1530 | ? status.job.kind === "stop" |
| 1531 | ? "正在停止 Cage 环境" |
| 1532 | : status.job.kind === "storage" |
| 1533 | ? "正在调整环境存储" |
| 1534 | : status.job.kind === "project" |
| 1535 | ? "正在打开项目" |
| 1536 | : "正在准备 Cage 环境" |
| 1537 | : running |
| 1538 | ? !status.ready |
| 1539 | ? "Cage 环境正在连接" |
| 1540 | : "Cage 环境已就绪" |
| 1541 | : setupProxy |
| 1542 | ? "为 Claude 准备独立工作区" |
| 1543 | : "先启动 Cage 环境"} |
| 1544 | </h1> |
| 1545 | <p className="welcome-subtitle"> |
| 1546 | <SafetyMessage message={busy |
| 1547 | ? status.job.message |
| 1548 | : running |
| 1549 | ? !status.ready |
| 1550 | ? status.environment_update_error || "浏览器连接尚未就绪,可以恢复连接或继续使用终端。" |
| 1551 | : network.mode === "open" |
| 1552 | ? "环境已连接,网络检查通过。可以浏览网页或打开本地项目。" |
| 1553 | : `${network.label}。终端与本地文件仍可使用。` |
| 1554 | : setupProxy |
| 1555 | ? "先连接你的代理,再启动浏览器、终端和编辑器。无需安装额外的代理软件。" |
| 1556 | : "准备独立的浏览器和终端,完成网络检查后开始工作。"} /> |
| 1557 | </p> |
| 1558 | {!running && !nativeGuestLabel && ( |
| 1559 | <ol className="onboarding-steps" aria-label="开始使用 Cage"> |
| 1560 | {["配置代理", "启动环境", "开始工作"].map( |
| 1561 | (label, index) => ( |
| 1562 | <li |
| 1563 | key={label} |
| 1564 | aria-current={ |
| 1565 | index === (setupProxy ? 0 : 1) |
| 1566 | ? "step" |
| 1567 | : undefined |
| 1568 | } |
| 1569 | > |
| 1570 | <span>{index + 1}</span> |
| 1571 | {label} |
| 1572 | </li> |
| 1573 | ), |
| 1574 | )} |
| 1575 | </ol> |
| 1576 | )} |
| 1577 | <div className="start-project-box"> |
| 1578 | <div className="environment-summary"> |
| 1579 | <EnvironmentShield |
| 1580 | healthy={status.ready && network.mode === "open"} |
| 1581 | size={24} |
| 1582 | /> |
| 1583 | <span> |
| 1584 | <strong>Cage 隔离环境</strong> |
| 1585 | <small> |
| 1586 | {running |
| 1587 | ? runtimeLabel |
| 1588 | : setupProxy |
| 1589 | ? "自备代理订阅、YAML 配置或节点" |
| 1590 | : nativeGuestLabel ? `${nativeGuestLabel} 客机已安装` : "代理已配置,首次启动会下载开发环境"} |
| 1591 | </small> |
| 1592 | </span> |
| 1593 | </div> |
| 1594 | {!busy && !running && !account?.guest_system && status.local_vm_storage && !isRemoteClient() && <GuestSystemPicker system={guestSystem} onChange={setGuestSystem} />} |
| 1595 | {!running && !nativeGuestLabel && status.local_vm_storage && !isRemoteClient() && <button className="storage-entry text-button" disabled={busy} onClick={() => openSettings("project")}>选择环境存储位置</button>} |
| 1596 | <div className="start-project-footer"> |
| 1597 | <span> |
| 1598 | <i className={`status-dot ${network.mode}`} /> |
| 1599 | {busy |
| 1600 | ? runtimeLabel |
| 1601 | : running |
| 1602 | ? network.label |
| 1603 | : setupProxy |
| 1604 | ? "等待配置代理" |
| 1605 | : "环境已停止"} |
| 1606 | </span> |
| 1607 | <button |
| 1608 | className="primary" |
| 1609 | data-terminal-location="start" |
| 1610 | disabled={busy || Boolean(connectionError) || (!running && !setupProxy && |
| 1611 | ((!account?.guest_system && status.local_vm_storage && !isRemoteClient() && guestSystem === undefined) || !validGuestChoice(guestSystem)))} |
| 1612 | onClick={(event) => { |
| 1613 | if (!running && guestSystem?.activate) { |
| 1614 | api("/environment/guest-systems/activate", {}).then(() => native("reconnect")).catch((e) => setToast(e.message)); |
| 1615 | } else if (!running && setupProxy) openSettings("network"); |
| 1616 | else if (!running || !status.ready) |
| 1617 | setStartOptions(!running && guestSystem?.guest_system === "debian-13" && !guestSystem.clone ? { guest_system: "debian-13" } : !running && guestSystem ? { |
| 1618 | guest_system: guestSystem.guest_system, media: guestSystem.media, sha256: guestSystem.sha256, |
| 1619 | clone_key: guestSystem.clone_key, |
| 1620 | editor_terms: guestSystem.editor_terms, |
| 1621 | } : {}); |
| 1622 | else if (status.environment_workspace) |
| 1623 | setProjectDialog({ path: "" }); |
| 1624 | else newTerminal(workspace, event.currentTarget); |
| 1625 | }} |
| 1626 | > |
| 1627 | {busy ? ( |
| 1628 | <LoaderCircle size={16} className="spin" /> |
| 1629 | ) : !running && setupProxy ? ( |
| 1630 | <Globe2 size={16} /> |
| 1631 | ) : !running ? ( |
| 1632 | <Power size={16} /> |
| 1633 | ) : !status.ready ? ( |
| 1634 | <RefreshCw size={16} /> |
| 1635 | ) : status.environment_workspace ? ( |
| 1636 | <FolderOpen size={16} /> |
| 1637 | ) : ( |
| 1638 | <TerminalSquare size={16} /> |
| 1639 | )} |
| 1640 | {busy |
| 1641 | ? "正在处理…" |
| 1642 | : !running |
| 1643 | ? setupProxy |
| 1644 | ? "配置网络与代理" |
| 1645 | : guestSystem?.activate ? "打开工作台" : guestSystem?.pending ? "继续安装" : |
| 1646 | guestSystem && guestSystem.guest_system !== "debian-13" ? "安装客户机" : "启动 Cage 环境" |
| 1647 | : !status.ready |
| 1648 | ? "恢复浏览器" |
| 1649 | : status.environment_workspace |
| 1650 | ? "打开项目" |
| 1651 | : "新建终端"} |
| 1652 | </button> |
| 1653 | </div> |
| 1654 | {terminalMenuAt("start")} |
| 1655 | </div> |
| 1656 | {running && ( |
| 1657 | <div className="welcome-shortcuts"> |
| 1658 | {macGuest && <MacOSLogin disabled={!status.ready || busy} />} |
| 1659 | <button onClick={newTerminalHere} data-terminal-location="shortcuts" aria-haspopup="menu" disabled={busy}> |
| 1660 | <TerminalSquare size={16} /> |
| 1661 | 新建终端 |
| 1662 | </button> |
| 1663 | <button |
| 1664 | onClick={() => openEditor(contentWorkspace)} |
| 1665 | disabled={!status.ready || busy} |
| 1666 | > |
| 1667 | <FileCode2 size={16} /> |
| 1668 | 浏览文件 |
| 1669 | </button> |
| 1670 | </div> |
| 1671 | )} |
| 1672 | {terminalMenuAt("shortcuts")} |
| 1673 | {!running && !nativeGuestLabel && ( |
| 1674 | <p className="welcome-hint"> |
| 1675 | {setupProxy |
| 1676 | ? "Cage 不提供代理或 Claude 账户。连接后,在 Cage 内完成 Claude 登录。" |
| 1677 | : "首次安装时可在操作详情中查看下载和配置进度;中断后可以继续安装。"} |
| 1678 | </p> |
| 1679 | )} |
| 1680 | {running && status.ready && ( |
| 1681 | <p className="welcome-hint"> |
| 1682 | 打开项目后,在终端输入 <code>claude</code> |
| 1683 | ,按提示登录你的账户。 |
| 1684 | <br /> |
| 1685 | {isRemoteClient() ? "默认工作区和打开的项目位于云端,编辑和删除会直接影响云端文件。" : "默认工作区和打开的项目与本机共享,编辑和删除文件会同步。"} |
| 1686 | </p> |
| 1687 | )} |
| 1688 | </>} |
| 1689 | {status.project_error && ( |
| 1690 | <div className="start-error" role="alert"> |
| 1691 | <strong>部分项目文件夹尚未连接</strong> |
| 1692 | <p>环境和浏览器可继续使用。</p> |
| 1693 | {status.project_errors?.length ? ( |
| 1694 | <ul className="project-connection-errors"> |
| 1695 | {status.project_errors.map(({ path, message, recovery }) => ( |
| 1696 | <li key={path}> |
| 1697 | <strong>{projectName(path, status.environment_directory)}</strong> |
| 1698 | <span className="project-error-path">{path}</span> |
| 1699 | <p>{message}</p> |
| 1700 | <ProjectRecovery recovery={recovery} disabled={!status.ready || busy} |
| 1701 | onRetry={() => setProjectDialog({ path })} onSettings={() => openSettings("project")} /> |
| 1702 | </li> |
| 1703 | ))} |
| 1704 | </ul> |
| 1705 | ) : <p>{status.project_error}</p>} |
| 1706 | </div> |
| 1707 | )} |
| 1708 | {!storageRecovery && !setupProgress && status.job?.error && ( |
| 1709 | <div className="start-error" role="alert"> |
| 1710 | <strong>{status.job.message || "本次操作未完成"}</strong> |
| 1711 | <p><SafetyMessage message={status.job.error} /></p> |
| 1712 | {status.can_restore && ( |
| 1713 | <button |
| 1714 | className="text-button" |
| 1715 | onClick={() => openSettings("project")} |
| 1716 | > |
| 1717 | 查看恢复选项 |
| 1718 | </button> |
| 1719 | )} |
| 1720 | </div> |
| 1721 | )} |
| 1722 | {!setupProgress && status.job?.log && ( |
| 1723 | <button |
| 1724 | className="text-button details-link" |
| 1725 | onClick={() => setDetails(true)} |
| 1726 | > |
| 1727 | 查看操作详情 |
| 1728 | </button> |
| 1729 | )} |
| 1730 | </div> |
| 1731 | </div> |
| 1732 | )} |
| 1733 | </main> |
| 1734 | <footer className="status-bar"> |
| 1735 | {sidebarCollapsed && <AppUpdateButton updates={appUpdates} />} |
| 1736 | <button onClick={() => setSafetyOpen(true)} title="网络与隔离检查"> |
| 1737 | <EnvironmentShield |
| 1738 | size={14} |
| 1739 | healthy={status.ready && network.mode === "open"} |
| 1740 | /> |
| 1741 | <span>{running ? network.label : "网络检查"}</span> |
| 1742 | </button> |
| 1743 | <span className="status-divider" /> |
| 1744 | <button onClick={() => openSettings("network")}> |
| 1745 | <MapPin size={12} /> |
| 1746 | <span> |
| 1747 | {status.network_error |
| 1748 | ? "出口待确认" |
| 1749 | : status.location || status.safety?.exit_ip |
| 1750 | ? [ |
| 1751 | status.safety?.exit_ip || status.location?.ip, |
| 1752 | status.location?.country, |
| 1753 | status.location?.city, |
| 1754 | ].filter(Boolean).join(" · ") |
| 1755 | : "指定代理出口"} |
| 1756 | </span> |
| 1757 | </button> |
| 1758 | <span className="status-divider" /> |
| 1759 | <button onClick={() => openSettings("region")}> |
| 1760 | <Clock3 size={12} /> |
| 1761 | {settings.timezone} |
| 1762 | {settings.auto_timezone ? " · 自动" : ""} |
| 1763 | </button> |
| 1764 | <span className="status-divider" /> |
| 1765 | <NetworkLatency |
| 1766 | key={`${proxy?.selected}:${proxy?.revision}:${running}:${busy}:${Boolean(connectionError)}`} |
| 1767 | enabled={running && !busy && !connectionError} |
| 1768 | revision={proxy?.revision} |
| 1769 | selected={proxy?.selected} |
| 1770 | /> |
| 1771 | <span className="status-spacer" /> |
| 1772 | <AudioControls audio={audio} /> |
| 1773 | <span className="status-feedback" role="status"> |
| 1774 | <SafetyMessage message={toast || |
| 1775 | (busy |
| 1776 | ? status.job.message |
| 1777 | : running |
| 1778 | ? status.ready |
| 1779 | ? isRemoteClient() ? "文件保存在云端" : "文件与本机同步" |
| 1780 | : "环境运行中 · 浏览器待恢复" |
| 1781 | : "")} /> |
| 1782 | </span> |
| 1783 | {status.job?.log && ( |
| 1784 | <button title="操作详情" onClick={() => setDetails(true)}> |
| 1785 | <MoreHorizontal size={15} /> |
| 1786 | </button> |
| 1787 | )} |
| 1788 | <button |
| 1789 | onClick={stop} |
| 1790 | disabled={ |
| 1791 | Boolean(startRequest) || (!running && !busy) || (status?.job?.kind === "stop" && busy) |
| 1792 | } |
| 1793 | title="停止当前环境" |
| 1794 | > |
| 1795 | <Power size={12} /> |
| 1796 | <span>停止环境</span> |
| 1797 | </button> |
| 1798 | </footer> |
| 1799 | </div> |
| 1800 | </div> |
| 1801 | <BrowserUploads requests={status.ready ? browser.uploads : []} onStatus={notify} /> |
| 1802 | {settingsOpen && ( |
| 1803 | <SettingsPanel |
| 1804 | current={settings} |
| 1805 | status={status} |
| 1806 | initialSection={settingsSection} |
| 1807 | claudeProfiles={claudeProfiles} |
| 1808 | terminalTabs={tabs} |
| 1809 | onClaudeLogin={(id) => createTerminal(workspace, "claude-login", id)} |
| 1810 | onClose={() => setSettingsOpen(false)} |
| 1811 | onSaved={refreshSettings} |
| 1812 | onConfirm={confirm} |
| 1813 | /> |
| 1814 | )} |
| 1815 | {tailscaleOpen && <TailscalePanel status={status} onClose={() => setTailscaleOpen(false)} |
| 1816 | onConfirm={confirm} onInstall={async () => { |
| 1817 | const nativeGuest = ["macos", "windows-11"].includes(status.guest_system); |
| 1818 | if (nativeGuest && !await confirm({ title: "更新环境组件?", body: "更新会重新连接浏览器和显示组件,请先保存工作。设备身份、公钥和个人数据保留。", confirm: "更新组件" })) return; |
| 1819 | await action(nativeGuest ? "/environment/update" : "/tailscale/install", {}); |
| 1820 | }} |
| 1821 | onOpenBrowser={async url => { const result = await openBrowserPage(url, false); if (result) setTailscaleOpen(false); return Boolean(result); }} />} |
| 1822 | {projectDialog && ( |
| 1823 | <ProjectDialog |
| 1824 | current={settings} |
| 1825 | status={status} |
| 1826 | initialPath={projectDialog.path} |
| 1827 | onClose={() => setProjectDialog(null)} |
| 1828 | onSettings={() => { setProjectDialog(null); openSettings("project"); }} |
| 1829 | onOpened={openedProject} |
| 1830 | onRemoved={async (removed, workspace) => { |
| 1831 | await refreshSettings(); |
| 1832 | await refreshStatus.current?.(); |
| 1833 | if (selectedProject === removed) setSelectedProject(workspace); |
| 1834 | }} |
| 1835 | /> |
| 1836 | )} |
| 1837 | {rename && ( |
| 1838 | <Modal |
| 1839 | title="重命名标签" |
| 1840 | onClose={() => setRename(null)} |
| 1841 | footer={ |
| 1842 | <> |
| 1843 | <span className="save-note">仅修改工作台中显示的名称</span> |
| 1844 | <button onClick={() => setRename(null)}>取消</button> |
| 1845 | <button |
| 1846 | className="primary" |
| 1847 | form="rename-tab" |
| 1848 | type="submit" |
| 1849 | disabled={!rename.title.trim()} |
| 1850 | > |
| 1851 | 保存名称 |
| 1852 | </button> |
| 1853 | </> |
| 1854 | } |
| 1855 | > |
| 1856 | <form |
| 1857 | className="modal-body project-form" |
| 1858 | id="rename-tab" |
| 1859 | onSubmit={async (event) => { |
| 1860 | event.preventDefault(); |
| 1861 | if (!rename.title.trim()) return; |
| 1862 | if (rename.session) { |
| 1863 | try { |
| 1864 | await api("/cli/sessions/" + rename.id + "/metadata", {title:rename.title.trim()}); |
| 1865 | sessionsChanged(); setRename(null); |
| 1866 | } catch (error) { notify(error.message); } |
| 1867 | return; |
| 1868 | } |
| 1869 | const tab = tabs.find(tab => tab.id === rename.id); |
| 1870 | if (tab?.cli_session_id) { |
| 1871 | try { |
| 1872 | await updateSharedMetadata(tab, {title:rename.title.trim()}); |
| 1873 | setRename(null); |
| 1874 | } catch (error) { notify(error.message); } |
| 1875 | return; |
| 1876 | } |
| 1877 | changeTabMetadata({ |
| 1878 | ...metadata, |
| 1879 | [rename.id]: { |
| 1880 | ...metadata[rename.id], |
| 1881 | title: rename.title.trim(), |
| 1882 | }, |
| 1883 | }); |
| 1884 | setRename(null); |
| 1885 | }} |
| 1886 | > |
| 1887 | <label htmlFor="tab-title">标签名称</label> |
| 1888 | <input |
| 1889 | id="tab-title" |
| 1890 | autoFocus |
| 1891 | maxLength={100} |
| 1892 | value={rename.title} |
| 1893 | onChange={(event) => |
| 1894 | setRename({ ...rename, title: event.target.value }) |
| 1895 | } |
| 1896 | /> |
| 1897 | </form> |
| 1898 | </Modal> |
| 1899 | )} |
| 1900 | {transfer && ( |
| 1901 | <Modal |
| 1902 | title="文本传递" |
| 1903 | onClose={() => setTransfer(null)} |
| 1904 | footer={ |
| 1905 | <> |
| 1906 | <span className="save-note">仅在你的操作下传递文本</span> |
| 1907 | <button onClick={() => setTransfer(null)}>关闭</button> |
| 1908 | <button |
| 1909 | className="primary" |
| 1910 | onClick={() => { |
| 1911 | remote.current?.pasteText(transfer.text); |
| 1912 | setTransfer(null); |
| 1913 | }} |
| 1914 | > |
| 1915 | 粘贴到 Cage |
| 1916 | </button> |
| 1917 | </> |
| 1918 | } |
| 1919 | > |
| 1920 | <div className="modal-body"> |
| 1921 | <p>{transfer.message}</p> |
| 1922 | <textarea |
| 1923 | aria-label="待传递文本" |
| 1924 | className="transfer-text" |
| 1925 | value={transfer.text} |
| 1926 | onChange={(e) => |
| 1927 | setTransfer({ ...transfer, text: e.target.value }) |
| 1928 | } |
| 1929 | /> |
| 1930 | </div> |
| 1931 | </Modal> |
| 1932 | )} |
| 1933 | {details && ( |
| 1934 | <Modal title="操作详情" wide onClose={() => setDetails(false)}> |
| 1935 | <div className="modal-body"> |
| 1936 | <p><SafetyMessage message={status.job.message} /></p> |
| 1937 | {status.job.error && ( |
| 1938 | <div className="error-message"><SafetyMessage message={status.job.error} /></div> |
| 1939 | )} |
| 1940 | <pre className="job-log">{status.job.log || "暂无日志"}</pre> |
| 1941 | </div> |
| 1942 | </Modal> |
| 1943 | )} |
| 1944 | {safetyOpen && ( |
| 1945 | <SafetyPanel |
| 1946 | status={ |
| 1947 | connectionError |
| 1948 | ? { |
| 1949 | ...status, |
| 1950 | safety: { |
| 1951 | ...status.safety, |
| 1952 | gate: null, |
| 1953 | error: "控制服务连接中断,无法确认当前外网状态", |
| 1954 | }, |
| 1955 | } |
| 1956 | : status |
| 1957 | } |
| 1958 | onClose={() => setSafetyOpen(false)} |
| 1959 | onSettings={openSettings} |
| 1960 | onOpenPage={openBrowserPage} |
| 1961 | onConfirm={confirm} |
| 1962 | /> |
| 1963 | )} |
| 1964 | {dialogs} |
| 1965 | </div> |
| 1966 | </SafetyChecklistContext.Provider> |
| 1967 | ); |
| 1968 | } |
| 1969 | export default function Workbench() { |
| 1970 | return <AccountProvider><AppearanceProvider><AccountGate><InitializationGate><App /></InitializationGate></AccountGate></AppearanceProvider></AccountProvider>; |
| 1971 | } |