| 1 | import { isMac, terminalModifier } from "./platform.mjs"; |
| 2 | import React, { |
| 3 | useEffect, |
| 4 | useRef, |
| 5 | useState, |
| 6 | useImperativeHandle, |
| 7 | forwardRef, |
| 8 | } from "react"; |
| 9 | import { useAppearance } from "./appearance"; |
| 10 | import { terminalTheme, systemCodeFont } from "./appearance-state.mjs"; |
| 11 | import { Terminal } from "@xterm/xterm"; |
| 12 | import { WebLinksAddon } from "@xterm/addon-web-links"; |
| 13 | import { claudeLoginLink, isClaudeLoginLink } from "./terminal-login-link.mjs"; |
| 14 | import { FitAddon } from "@xterm/addon-fit"; |
| 15 | import RFB from "../.generated/novnc/core/rfb.js"; |
| 16 | import { api, writeClipboard, nativeAvailable } from "./api"; |
| 17 | import { runtimeSocketURL } from "./client-context.mjs"; |
| 18 | import { readClipboardContent, transferFiles, hasFiles, imagePayload, prepareClipboardPaste, sendImage } from "./image-transfer"; |
| 19 | import { terminalClipboardText } from "./terminal-clipboard.mjs"; |
| 20 | import { sendFiles, shellFilePaths } from "./file-transfer"; |
| 21 | import { installRemoteInput } from "./remote-input"; |
| 22 | import { useWindowVisibility } from "./window-visibility"; |
| 23 | import { displayGeometry, displaySizeSync, watchPixelRatio } from "./remote-display.mjs"; |
| 24 | import { installLocalCursorFallback } from "./remote-cursor.mjs"; |
| 25 | import { RefreshCw, Clipboard, ArrowUpRight } from "lucide-react"; |
| 26 | import { SessionAccount } from "./session-account"; |
| 27 | import "@xterm/xterm/css/xterm.css"; |
| 28 | |
| 29 | const terminalAccountRequest = (path, options) => api("/cli" + path, options.body); |
| 30 | |
| 31 | export const RemoteView = forwardRef(function RemoteView( |
| 32 | { visible, focused = true, keyboard, guestPlatform = "linux", systemClipboard = true, tabId, copyScope = tabId, onStatus, onFallback, desktop = false, zoom = 1 }, |
| 33 | ref, |
| 34 | ) { |
| 35 | const windowVisible = useWindowVisibility(); |
| 36 | const screenVisible = visible && windowVisible; |
| 37 | const box = useRef(), |
| 38 | rfb = useRef(), |
| 39 | input = useRef(), |
| 40 | current = useRef({ visible, keyboard, onStatus, onFallback }), |
| 41 | displayResize = useRef(); |
| 42 | current.current = { visible: screenVisible && focused, keyboard, guestPlatform, systemClipboard, tabId, onStatus, onFallback, zoom }; |
| 43 | const failures = useRef(0); |
| 44 | const [connection, setConnection] = useState("connecting"), |
| 45 | [attempt, setAttempt] = useState(0), |
| 46 | [sizeError, setSizeError] = useState(false); |
| 47 | useEffect(() => { displayResize.current?.update(); }, [zoom]); |
| 48 | useEffect(() => { input.current?.cancelCopy(); }, [copyScope]); |
| 49 | useImperativeHandle(ref, () => ({ |
| 50 | focus: () => rfb.current?.focus(), |
| 51 | edit: (action) => |
| 52 | input.current?.focused() |
| 53 | ? input.current?.edit(action) |
| 54 | : false, |
| 55 | copy: () => input.current?.copy(), |
| 56 | receiveCopy: (value) => input.current?.receiveCopy(value), |
| 57 | paste: () => input.current?.readAndPaste(), |
| 58 | pasteText: (text) => input.current?.paste(text), |
| 59 | transfer: () => |
| 60 | onFallback(input.current?.text() || "", "可在此使用本机复制、粘贴。"), |
| 61 | })); |
| 62 | useEffect(() => { |
| 63 | if (!screenVisible) return; |
| 64 | const container = box.current; |
| 65 | if (!container) return; |
| 66 | let disposed = false, |
| 67 | client, |
| 68 | resizeObserver, |
| 69 | unwatchDensity, |
| 70 | sizeSync, |
| 71 | reconnectTimer; |
| 72 | setConnection("connecting"); |
| 73 | setSizeError(false); |
| 74 | const retry = () => { |
| 75 | if (disposed) return; |
| 76 | setConnection("disconnected"); |
| 77 | clearTimeout(reconnectTimer); |
| 78 | reconnectTimer = setTimeout( |
| 79 | () => setAttempt((v) => v + 1), |
| 80 | Math.min(1000 * 2 ** failures.current++, 5000), |
| 81 | ); |
| 82 | }; |
| 83 | const desktopPrefix = desktop ? "/claude-desktop" : ""; |
| 84 | api(`${desktopPrefix}/vnc-credentials`) |
| 85 | .then(({ password, display_scale, dynamic_scale }) => { |
| 86 | if (disposed) return; |
| 87 | |
| 88 | let followScreen = dynamic_scale === true; |
| 89 | client = new RFB( |
| 90 | container, |
| 91 | runtimeSocketURL(`${desktopPrefix}/vnc`), |
| 92 | { credentials: { password }, cageBrowserDisplay: !desktop, cageCursorFallback: desktop && guestPlatform === "windows" }, |
| 93 | ); |
| 94 | rfb.current = client; |
| 95 | installLocalCursorFallback(client._cursor, |
| 96 | !desktop && ["darwin", "macos"].includes(guestPlatform)); |
| 97 | client.scaleViewport = true; |
| 98 | client.resizeSession = false; |
| 99 | client.background = "#ffffff"; |
| 100 | client.qualityLevel = 8; |
| 101 | client.compressionLevel = 2; |
| 102 | client.addEventListener("connect", () => { |
| 103 | if (disposed) return; |
| 104 | failures.current = 0; |
| 105 | setConnection("connected"); |
| 106 | sizeSync = displaySizeSync( |
| 107 | async (size) => { |
| 108 | const reply = await api(desktop ? "/claude-desktop/resize" : "/browser/resize", size); |
| 109 | |
| 110 | if (size.scale !== undefined && reply?.scale !== size.scale && followScreen) { |
| 111 | followScreen = false; |
| 112 | resize(); |
| 113 | } |
| 114 | }, |
| 115 | { onError: () => setSizeError(true), onSuccess: () => setSizeError(false) }, |
| 116 | ); |
| 117 | const resize = () => { |
| 118 | if (disposed) return; |
| 119 | sizeSync.update(displayGeometry(container.getBoundingClientRect(), { |
| 120 | desktop, zoom: current.current.zoom, density: display_scale, |
| 121 | pixelRatio: followScreen ? window.devicePixelRatio : undefined, |
| 122 | })); |
| 123 | }; |
| 124 | displayResize.current = { update: resize, retry: () => sizeSync.retry() }; |
| 125 | resizeObserver = new ResizeObserver(resize); |
| 126 | resizeObserver.observe(container); |
| 127 | unwatchDensity = watchPixelRatio(resize); |
| 128 | resize(); |
| 129 | const preparePaste = () => { |
| 130 | const id = current.current.tabId; |
| 131 | return prepareClipboardPaste(desktop ? "desktop" : "browser", id, { |
| 132 | valid: () => !disposed && current.current.visible && current.current.tabId === id, |
| 133 | }); |
| 134 | }; |
| 135 | input.current = installRemoteInput({ |
| 136 | events: client, |
| 137 | setKeyboardTarget: target => client.cageSetKeyboardTarget(target), |
| 138 | sendKey: (...key) => client.sendKey(...key), |
| 139 | focus: () => client.focus(), |
| 140 | pasteText: text => { |
| 141 | if (desktop || current.current.systemClipboard) return client.cagePasteText(text); |
| 142 | const prepared = preparePaste(); |
| 143 | return client.cageRunInput(() => prepared.send({ text })).finally(() => prepared.dispose()); |
| 144 | }, |
| 145 | runKeyAction: action => client.cageRunInput(action), |
| 146 | }, container, { |
| 147 | guestPlatform: () => current.current.guestPlatform, |
| 148 | systemClipboard: () => current.current.systemClipboard, |
| 149 | copyText: !desktop |
| 150 | ? (_sendCopy, valid, { id, context, key }) => { |
| 151 | if (current.current.systemClipboard !== false) return undefined; |
| 152 | if (!valid()) throw new Error("复制位置已切换,请重新复制"); |
| 153 | return api("/browser/" + (key === "x" ? "cut" : "copy"), { id, context }); |
| 154 | } |
| 155 | : undefined, |
| 156 | setCopyContext: desktop ? undefined : (context, valid) => client.cageRunInput(async () => { |
| 157 | if (!valid()) return; |
| 158 | try { await api("/browser/copy-context", { id: current.current.tabId, context }); } |
| 159 | catch { |
| 160 | if (valid()) { |
| 161 | input.current?.cancelCopy(); |
| 162 | current.current.onStatus("复制按钮同步暂未就绪,可使用复制快捷键或文本传递"); |
| 163 | } |
| 164 | |
| 165 | } |
| 166 | }), |
| 167 | preparePaste, |
| 168 | pasteContent: (content, prepared) => { |
| 169 | const id = current.current.tabId; |
| 170 | const valid = () => !disposed && current.current.visible && current.current.tabId === id; |
| 171 | return client.cagePasteContent(content, |
| 172 | (payload) => { |
| 173 | if (!valid()) throw new Error("输入目标已切换,请重新粘贴图片"); |
| 174 | return payload.files || payload.fileSelection |
| 175 | ? sendFiles(payload, desktop ? "desktop" : "browser", id, { valid }) |
| 176 | : sendImage(payload, desktop ? "desktop" : "browser", id, { prepared }); |
| 177 | }, valid, !desktop && !current.current.systemClipboard ? text => prepared.send({ text }) : undefined); |
| 178 | }, |
| 179 | insertText: (text) => { |
| 180 | if (desktop) { |
| 181 | if (!window.cageSharedClipboardActive) return client.cagePasteText(text); |
| 182 | return client.cageRunInput(async () => { |
| 183 | const valid = () => !disposed && current.current.visible; |
| 184 | const state = await api("/input", { target: "desktop", id: "desktop", mode: "status" }); |
| 185 | if (!state.available || !valid()) throw new Error("输入位置已失去焦点,请重新点击输入框"); |
| 186 | const session = crypto.randomUUID().replaceAll("-", ""); |
| 187 | const begun = await api("/input", { target: "desktop", id: "desktop", mode: "begin", context: state.context, session, sequence: 0 }); |
| 188 | if (!begun.available || !valid()) throw new Error("输入位置已失去焦点,请重新点击输入框"); |
| 189 | const result = await api("/input", { target: "desktop", id: "desktop", mode: "commit", session, sequence: 1, text }); |
| 190 | if (!result.available) throw new Error("文字输入未完成,请重新点击输入框"); |
| 191 | }); |
| 192 | } |
| 193 | const id = current.current.tabId; |
| 194 | return client.cageRunInput(() => { |
| 195 | if (disposed || !current.current.visible || current.current.tabId !== id) |
| 196 | throw new Error("输入位置已切换,请重新输入"); |
| 197 | return api("/browser/insert-text", { id, text }); |
| 198 | }); |
| 199 | }, |
| 200 | insertComposition: (id, value) => client.cageRunInput(async () => { |
| 201 | if (value.mode !== "cancel" && (disposed || !current.current.visible || |
| 202 | (desktop ? "desktop" : current.current.tabId) !== id)) |
| 203 | throw new Error("输入位置已切换,请重新输入"); |
| 204 | const result = await api("/input", { target: desktop ? "desktop" : "browser", id, ...value }); |
| 205 | if (value.mode !== "cancel" && !result.available) |
| 206 | throw new Error("输入位置已失去焦点,请重新输入"); |
| 207 | return result; |
| 208 | }), |
| 209 | tabId: () => desktop ? "desktop" : current.current.tabId, |
| 210 | caretRect: async (session) => { |
| 211 | const id = desktop ? "desktop" : current.current.tabId; |
| 212 | const value = await api("/input", { target: desktop ? "desktop" : "browser", id, mode: "status", session }); |
| 213 | return !disposed && current.current.visible && |
| 214 | (desktop ? "desktop" : current.current.tabId) === id ? value : null; |
| 215 | }, |
| 216 | mode: () => current.current.keyboard, |
| 217 | isActive: () => current.current.visible, |
| 218 | onStatus: (t) => current.current.onStatus(t), |
| 219 | onFallback: (...args) => current.current.onFallback(...args), |
| 220 | }); |
| 221 | if (current.current.visible && !document.activeElement?.closest(".chrome")) client.focus(); |
| 222 | }); |
| 223 | client.addEventListener("disconnect", () => { |
| 224 | if (disposed) return; |
| 225 | input.current?.dispose(); |
| 226 | input.current = null; |
| 227 | sizeSync?.dispose(); |
| 228 | resizeObserver?.disconnect(); |
| 229 | unwatchDensity?.(); |
| 230 | displayResize.current = null; |
| 231 | retry(); |
| 232 | }); |
| 233 | client.addEventListener("securityfailure", () => { |
| 234 | retry(); |
| 235 | }); |
| 236 | }) |
| 237 | .catch(() => { |
| 238 | retry(); |
| 239 | }); |
| 240 | return () => { |
| 241 | disposed = true; |
| 242 | sizeSync?.dispose(); |
| 243 | displayResize.current = null; |
| 244 | clearTimeout(reconnectTimer); |
| 245 | resizeObserver?.disconnect(); |
| 246 | unwatchDensity?.(); |
| 247 | input.current?.dispose(); |
| 248 | input.current = null; |
| 249 | client?.disconnect(); |
| 250 | rfb.current = null; |
| 251 | }; |
| 252 | }, [attempt, screenVisible, desktop]); |
| 253 | useEffect(() => { |
| 254 | if (focused && screenVisible && connection === "connected") { |
| 255 | const t = setTimeout(() => { if (!document.activeElement?.closest(".chrome")) rfb.current?.focus(); }, 80); |
| 256 | return () => clearTimeout(t); |
| 257 | } |
| 258 | }, [focused, screenVisible, connection]); |
| 259 | return ( |
| 260 | <div className={`remote-view ${visible ? "" : "concealed"}`}> |
| 261 | <div className="remote-canvas" ref={box} /> |
| 262 | {sizeError && connection === "connected" && ( |
| 263 | <div className="remote-size-warning connection-banner" role="alert"> |
| 264 | 画面尺寸未能同步,显示比例可能不准确。 |
| 265 | <button onClick={() => displayResize.current?.retry()}>重试调整</button> |
| 266 | </div> |
| 267 | )} |
| 268 | {connection !== "connected" && ( |
| 269 | <div className="view-overlay"> |
| 270 | <RefreshCw className={connection === "connecting" ? "spin" : ""} /> |
| 271 | <h3> |
| 272 | {connection === "connecting" ? "正在连接画面" : "画面连接已断开"} |
| 273 | </h3> |
| 274 | <p>后台任务不会因画面断开而自动结束。</p> |
| 275 | {connection === "disconnected" && ( |
| 276 | <button |
| 277 | className="primary" |
| 278 | onClick={() => setAttempt((v) => v + 1)} |
| 279 | > |
| 280 | 重新连接画面 |
| 281 | </button> |
| 282 | )} |
| 283 | </div> |
| 284 | )} |
| 285 | </div> |
| 286 | ); |
| 287 | }); |
| 288 | |
| 289 | export function TerminalView({ session, visible, focused = true, onStatus, onControls, onAccountChanged, onLoginTab }) { |
| 290 | const { appearance, theme, variant } = useAppearance(); |
| 291 | const box = useRef(), |
| 292 | instance = useRef(), |
| 293 | fit = useRef(), |
| 294 | socket = useRef(); |
| 295 | const [connected, setConnected] = useState(false), |
| 296 | [attempt, setAttempt] = useState(0), |
| 297 | [preparing, setPreparing] = useState(Boolean(session.cli_session_id && !session.closed)); |
| 298 | const revealStartup = useRef(); |
| 299 | const visibleRef = useRef(visible); |
| 300 | visibleRef.current = visible; |
| 301 | const focusedRef = useRef(focused); |
| 302 | focusedRef.current = focused; |
| 303 | useEffect(() => { |
| 304 | let disposed = false, emittingPaste = false, inputChain = Promise.resolve(); |
| 305 | const enqueue = (action) => { |
| 306 | const result = inputChain.then(action); |
| 307 | inputChain = result; |
| 308 | const reset = () => { if (inputChain === result) inputChain = Promise.resolve(); }; |
| 309 | result.then(reset, reset); |
| 310 | return result; |
| 311 | }; |
| 312 | const activateLogin = async (_event, uri) => { |
| 313 | if (disposed || !visibleRef.current || !focusedRef.current || !isClaudeLoginLink(uri)) return; |
| 314 | try { |
| 315 | const tab = await api(`/terminals/${session.id}/login-link`, { url: uri }); |
| 316 | if (!disposed && visibleRef.current && focusedRef.current) onLoginTab?.(tab); |
| 317 | } catch (error) { if (!disposed) onStatus(error.message); } |
| 318 | }; |
| 319 | const terminal = new Terminal({ |
| 320 | linkHandler: { activate(event, uri) { |
| 321 | if (isClaudeLoginLink(uri)) return void activateLogin(event, uri); |
| 322 | |
| 323 | if (window.confirm(`打开此终端链接?\n${uri}`)) window.open(uri, "_blank", "noopener,noreferrer"); |
| 324 | } }, |
| 325 | fontFamily: theme.fonts.code || systemCodeFont, |
| 326 | fontSize: appearance.codeFontSize, |
| 327 | lineHeight: 1.3, |
| 328 | cursorBlink: true, |
| 329 | macOptionClickForcesSelection: true, |
| 330 | minimumContrastRatio: 4.5, |
| 331 | scrollback: 6000, |
| 332 | theme: terminalTheme(theme, variant), |
| 333 | }); |
| 334 | const fitter = new FitAddon(); |
| 335 | terminal.loadAddon(fitter); |
| 336 | terminal.loadAddon(new WebLinksAddon(activateLogin, { urlRegex: claudeLoginLink })); |
| 337 | terminal.open(box.current); |
| 338 | instance.current = terminal; |
| 339 | fit.current = fitter; |
| 340 | const ws = new WebSocket( |
| 341 | runtimeSocketURL(`/terminals/${session.id}/stream`), |
| 342 | ); |
| 343 | ws.binaryType = "arraybuffer"; |
| 344 | socket.current = ws; |
| 345 | let startupPending = Boolean(session.cli_session_id && !session.closed); |
| 346 | let startupVisible = !startupPending; |
| 347 | setPreparing(startupPending); |
| 348 | const reveal = () => { |
| 349 | if (disposed || startupVisible) return; |
| 350 | startupVisible = true; |
| 351 | clearTimeout(startupTimer); |
| 352 | setPreparing(false); |
| 353 | if (visibleRef.current && focusedRef.current) terminal.focus(); |
| 354 | }; |
| 355 | revealStartup.current = reveal; |
| 356 | |
| 357 | |
| 358 | const startupTimer = startupPending ? setTimeout(reveal, 8000) : null; |
| 359 | const painted = () => { |
| 360 | if (disposed || startupPending || startupVisible) return; |
| 361 | const buffer = terminal.buffer.active; |
| 362 | const screen = Array.from({ length: terminal.rows }, (_, row) => |
| 363 | buffer.getLine(buffer.viewportY + row)?.translateToString(true) || "", |
| 364 | ).join("").replace(/\s/g, ""); |
| 365 | |
| 366 | |
| 367 | if (!screen.includes("WARNING:Loadingdevelopmentchannels")) reveal(); |
| 368 | }; |
| 369 | const startupRender = terminal.onRender(painted); |
| 370 | const resize = () => { |
| 371 | if (!visibleRef.current) return; |
| 372 | try { |
| 373 | fitter.fit(); |
| 374 | if (ws.readyState === WebSocket.OPEN) |
| 375 | ws.send( |
| 376 | JSON.stringify({ |
| 377 | type: "resize", |
| 378 | cols: terminal.cols, |
| 379 | rows: terminal.rows, |
| 380 | }), |
| 381 | ); |
| 382 | } catch {} |
| 383 | }; |
| 384 | ws.onopen = () => { |
| 385 | setConnected(true); |
| 386 | resize(); |
| 387 | if (startupVisible && visibleRef.current && focusedRef.current) terminal.focus(); |
| 388 | }; |
| 389 | let historyFrame = false, replayingHistory = false; |
| 390 | const clipboardHandler = terminal.parser.registerOscHandler(52, async (data) => { |
| 391 | if (disposed || replayingHistory || !visibleRef.current || !focusedRef.current || !box.current?.contains(document.activeElement)) return true; |
| 392 | const text = terminalClipboardText(data); |
| 393 | if (text === undefined) return true; |
| 394 | try { |
| 395 | await writeClipboard(text); |
| 396 | if (!disposed) onStatus("已复制终端选中文本"); |
| 397 | } catch { if (!disposed) onStatus("无法写入本机剪贴板"); } |
| 398 | return true; |
| 399 | }); |
| 400 | ws.onmessage = (event) => { |
| 401 | if (typeof event.data === "string") { |
| 402 | let state; |
| 403 | try { state = JSON.parse(event.data); } catch { return; } |
| 404 | if (state.type === "cli-startup") { |
| 405 | startupPending = state.pending; |
| 406 | terminal.refresh(0, terminal.rows - 1); |
| 407 | } |
| 408 | if (state.type === "history") historyFrame = true; |
| 409 | return; |
| 410 | } |
| 411 | if (historyFrame) { |
| 412 | historyFrame = false; |
| 413 | replayingHistory = true; |
| 414 | terminal.write(new Uint8Array(event.data), () => { replayingHistory = false; }); |
| 415 | } else terminal.write(new Uint8Array(event.data)); |
| 416 | }; |
| 417 | ws.onclose = () => { setConnected(false); reveal(); }; |
| 418 | const send = (data) => { |
| 419 | if (disposed || ws.readyState !== WebSocket.OPEN) throw new Error("终端已断开,请重新连接后重试"); |
| 420 | ws.send(JSON.stringify({ type: "input", data })); |
| 421 | }; |
| 422 | terminal.onData((data) => { |
| 423 | if (emittingPaste) send(data); |
| 424 | else void enqueue(() => send(data)).catch(() => {}); |
| 425 | }); |
| 426 | const receive = (content) => { |
| 427 | |
| 428 | const ready = Promise.resolve(content).then(value => ({ value }), error => ({ error })); |
| 429 | onStatus("正在传递剪贴板内容…"); |
| 430 | void enqueue(async () => { |
| 431 | const { value, error } = await ready; |
| 432 | if (error) throw error; |
| 433 | if (disposed || !visibleRef.current || !focusedRef.current || ws.readyState !== WebSocket.OPEN) throw new Error("终端已切换或断开,请重新粘贴"); |
| 434 | let text = value.text || ""; |
| 435 | if (value.files || value.fileSelection) { |
| 436 | const result = await sendFiles(value, "terminal", session.id, { valid: () => !disposed && visibleRef.current && focusedRef.current && ws.readyState === WebSocket.OPEN }); |
| 437 | text = shellFilePaths(result.paths); |
| 438 | } |
| 439 | if (value.png) { |
| 440 | const result = await sendImage(value, "terminal", session.id, { valid: () => !disposed && visibleRef.current && focusedRef.current && ws.readyState === WebSocket.OPEN }); |
| 441 | text = shellFilePaths([result.path]); |
| 442 | } |
| 443 | if (disposed || !visibleRef.current || !focusedRef.current) throw new Error("终端已切换,请回到原终端重新粘贴"); |
| 444 | |
| 445 | emittingPaste = true; |
| 446 | try { terminal.paste(text); } finally { emittingPaste = false; } |
| 447 | onStatus(value.png || value.files || value.fileSelection ? "附件已保存到 Cage,路径已插入终端" : "已粘贴"); |
| 448 | }).catch((error) => { if (!disposed) onStatus(error.message); }); |
| 449 | }; |
| 450 | const host = box.current; |
| 451 | const onPaste = (event) => { |
| 452 | if (!visibleRef.current || !focusedRef.current) return; |
| 453 | event.preventDefault(); event.stopImmediatePropagation(); |
| 454 | const files = transferFiles(event.clipboardData); |
| 455 | if (files.length === 1 && files[0].type.startsWith("image/")) receive(imagePayload(files[0])); |
| 456 | else if (files.length) receive({ files }); |
| 457 | else if (event.clipboardData?.types.includes("text/plain")) receive({ text: event.clipboardData.getData("text/plain") }); |
| 458 | }; |
| 459 | const onDragOver = (event) => { |
| 460 | if (!visibleRef.current || !hasFiles(event.dataTransfer)) return; |
| 461 | event.preventDefault(); event.dataTransfer.dropEffect = "copy"; |
| 462 | }; |
| 463 | const onDrop = (event) => { |
| 464 | if (!visibleRef.current || !hasFiles(event.dataTransfer)) return; |
| 465 | event.preventDefault(); event.stopPropagation(); |
| 466 | receive({ files: transferFiles(event.dataTransfer), kind: "drop" }); |
| 467 | terminal.focus(); |
| 468 | }; |
| 469 | host.addEventListener("paste", onPaste, true); |
| 470 | host.addEventListener("dragover", onDragOver); |
| 471 | host.addEventListener("drop", onDrop); |
| 472 | const copySelection = () => { |
| 473 | const text = terminal.getSelection(); |
| 474 | if (!text) { |
| 475 | |
| 476 | |
| 477 | if (terminal.modes.mouseTrackingMode !== "none") |
| 478 | void enqueue(() => send("\x1b[99;6u")).catch(() => {}); |
| 479 | onStatus(terminal.modes.mouseTrackingMode === "none" |
| 480 | ? "请先拖选要复制的终端文字" |
| 481 | : `当前程序接管了鼠标。请按住 ${isMac ? "Option" : "Shift"} 拖选文字,再复制。`); |
| 482 | return; |
| 483 | } |
| 484 | void writeClipboard(text) |
| 485 | .then(() => onStatus("已复制终端选中文本")) |
| 486 | .catch(() => onStatus("无法写入本机剪贴板")); |
| 487 | }; |
| 488 | const onCopy = (event) => { |
| 489 | if (!visibleRef.current || !focusedRef.current) return; |
| 490 | event.preventDefault(); event.stopImmediatePropagation(); |
| 491 | const text = terminal.getSelection(); |
| 492 | if (text) event.clipboardData?.setData("text/plain", text); |
| 493 | copySelection(); |
| 494 | }; |
| 495 | host.addEventListener("copy", onCopy, true); |
| 496 | onControls?.({ |
| 497 | edit(action) { |
| 498 | if (!box.current?.contains(document.activeElement)) return false; |
| 499 | if (action === "copy") { |
| 500 | copySelection(); |
| 501 | return true; |
| 502 | } |
| 503 | if (action === "paste") { |
| 504 | receive(readClipboardContent()); |
| 505 | return true; |
| 506 | } |
| 507 | if (action === "selectAll") { |
| 508 | terminal.selectAll(); |
| 509 | return true; |
| 510 | } |
| 511 | return false; |
| 512 | }, |
| 513 | }); |
| 514 | terminal.attachCustomKeyEventHandler((event) => { |
| 515 | if (event.key === "Enter" && event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey && |
| 516 | !event.isComposing && event.keyCode !== 229) { |
| 517 | event.preventDefault(); |
| 518 | if (event.type === "keydown") { |
| 519 | |
| 520 | |
| 521 | void enqueue(() => send(terminal.modes.bracketedPasteMode |
| 522 | ? "\x1b[200~\n\x1b[201~" : "\x1b[13;2u")).catch(() => {}); |
| 523 | } |
| 524 | return false; |
| 525 | } |
| 526 | if (event.type !== "keydown") return true; |
| 527 | const claudeImagePaste = ((session.terminalKind || session.kind) === "claude" || session.cli_session_id) && |
| 528 | event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "v"; |
| 529 | if (claudeImagePaste && nativeAvailable()) { |
| 530 | event.preventDefault(); |
| 531 | receive(readClipboardContent()); |
| 532 | return false; |
| 533 | } |
| 534 | if (!terminalModifier(event)) return true; |
| 535 | const key = event.key.toLowerCase(); |
| 536 | if (key === "c") { |
| 537 | event.preventDefault(); |
| 538 | copySelection(); |
| 539 | return false; |
| 540 | } |
| 541 | if (key === "v") { |
| 542 | if (!nativeAvailable()) return true; |
| 543 | event.preventDefault(); |
| 544 | receive(readClipboardContent()); |
| 545 | return false; |
| 546 | } |
| 547 | if (key === "a") { |
| 548 | event.preventDefault(); |
| 549 | terminal.selectAll(); |
| 550 | return false; |
| 551 | } |
| 552 | if (["+", "=", "-"].includes(key)) { |
| 553 | event.preventDefault(); |
| 554 | terminal.options.fontSize = Math.max( |
| 555 | 10, |
| 556 | Math.min(26, terminal.options.fontSize + (key === "-" ? -1 : 1)), |
| 557 | ); |
| 558 | resize(); |
| 559 | return false; |
| 560 | } |
| 561 | return !terminalModifier(event); |
| 562 | }); |
| 563 | const observer = new ResizeObserver(resize); |
| 564 | observer.observe(box.current); |
| 565 | resize(); |
| 566 | return () => { |
| 567 | disposed = true; |
| 568 | clearTimeout(startupTimer); |
| 569 | revealStartup.current = null; |
| 570 | startupRender.dispose(); |
| 571 | clipboardHandler.dispose(); |
| 572 | host.removeEventListener("paste", onPaste, true); |
| 573 | host.removeEventListener("copy", onCopy, true); |
| 574 | host.removeEventListener("dragover", onDragOver); |
| 575 | host.removeEventListener("drop", onDrop); |
| 576 | onControls?.(null); |
| 577 | observer.disconnect(); |
| 578 | ws.close(); |
| 579 | terminal.dispose(); |
| 580 | instance.current = null; |
| 581 | }; |
| 582 | }, [session.id, attempt]); |
| 583 | useEffect(() => { |
| 584 | if (visible) { |
| 585 | fit.current?.fit(); |
| 586 | if (focused && !preparing) instance.current?.focus(); |
| 587 | const ws = socket.current, |
| 588 | t = instance.current; |
| 589 | if (ws?.readyState === WebSocket.OPEN && t) |
| 590 | ws.send(JSON.stringify({ type: "resize", cols: t.cols, rows: t.rows })); |
| 591 | } |
| 592 | }, [visible, focused, preparing]); |
| 593 | useEffect(() => { |
| 594 | if (!instance.current) return; |
| 595 | instance.current.options.theme = terminalTheme(theme, variant); |
| 596 | instance.current.options.fontFamily = theme.fonts.code || systemCodeFont; |
| 597 | instance.current.options.fontSize = appearance.codeFontSize; |
| 598 | if (visibleRef.current) fit.current?.fit(); |
| 599 | }, [theme, variant, appearance.codeFontSize]); |
| 600 | return ( |
| 601 | <div className={`terminal-view ${visible ? "" : "concealed"}`}> |
| 602 | {session.workspace_notice && <p className="connection-banner" role="status">{session.workspace_notice}</p>} |
| 603 | {visible && session.cli_session_id && <SessionAccount id={session.cli_session_id} request={terminalAccountRequest} compact |
| 604 | onChanged={onAccountChanged} />} |
| 605 | <div className={`terminal-host ${preparing ? "terminal-preparing" : ""}`} ref={box} aria-hidden={preparing || undefined} /> |
| 606 | {preparing && ( |
| 607 | <div className="terminal-startup" role="status"> |
| 608 | <span>正在准备 Claude 会话…</span> |
| 609 | <button onClick={() => revealStartup.current?.()}>显示启动过程</button> |
| 610 | </div> |
| 611 | )} |
| 612 | {!connected && ( |
| 613 | <div className="terminal-note"> |
| 614 | {session.closed |
| 615 | ? "终端会话已结束。可点击项目右侧的终端图标新建终端。" |
| 616 | : "正在连接终端…"} |
| 617 | {!session.closed && ( |
| 618 | <button onClick={() => setAttempt((v) => v + 1)}> |
| 619 | <RefreshCw size={13} /> |
| 620 | 重新连接 |
| 621 | </button> |
| 622 | )} |
| 623 | </div> |
| 624 | )} |
| 625 | </div> |
| 626 | ); |
| 627 | } |
| 628 | |
| 629 | export { Modal } from "./modal"; |