| 1 | import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; |
| 2 | import { createRoot } from "react-dom/client"; |
| 3 | import { Archive, ArrowLeft, ArrowUp, LoaderCircle, Monitor, RefreshCw, Settings, Square, Terminal } from "lucide-react"; |
| 4 | import { RemoteDisplay } from "./remote-browser"; |
| 5 | import { CodeNavigation, ProjectTree, WorkspaceDrawer, workspaceTools } from "./workspace-drawer"; |
| 6 | import { deviceCommand } from "./device-navigation.mjs"; |
| 7 | import cageLogo from "../logo.png"; |
| 8 | import { accessDenied, request, sessionPath } from "./transport.mjs"; |
| 9 | import { recoverPendingMessage, retryableSessionError, sessionFailureMessage, sessionRetryDelay, sessionRetryLimit } from "./session-recovery.mjs"; |
| 10 | import { SessionActionDialog, sortSessions } from "./session-row"; |
| 11 | import { ArchivedSessions } from "../cli-sessions"; |
| 12 | import { SessionAccount } from "../session-account"; |
| 13 | import "./mobile.css"; |
| 14 | import { MessageBody, ToolActivity, TranscriptContext } from "./transcript"; |
| 15 | |
| 16 | const labels = { |
| 17 | queued: "消息已送达", |
| 18 | running: "正在运行", stopping: "正在停止", completed: "已完成", |
| 19 | failed: "运行失败", stopped: "已停止", interrupted: "运行中断", |
| 20 | }; |
| 21 | const active = (status) => status === "running" || status === "stopping" || status === "queued"; |
| 22 | const nativePhone = navigator.userAgent.includes("CageMobile/1"); |
| 23 | const phoneWorkspace = nativePhone || location.pathname === "/"; |
| 24 | const dateFormat = new Intl.DateTimeFormat("zh-CN", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" }); |
| 25 | function displayTime(value) { |
| 26 | if (!value) return ""; |
| 27 | const date = new Date(value); |
| 28 | return Number.isNaN(date.valueOf()) ? "" : dateFormat.format(date); |
| 29 | } |
| 30 | function route() { |
| 31 | const value = history.state?.cageCLI || (new URLSearchParams(location.search).get("page") === "archived" ? {tool:"archived"} : null); |
| 32 | const id = value?.displayID || value?.browser; |
| 33 | const displayID = typeof id === "string" && /^[a-f0-9-]{36}$/.test(id) ? id : ""; |
| 34 | const tool = ["settings", "archived"].includes(value?.tool) ? value.tool : displayID && ["browser", "claude", "desktop"].includes(value.tool) ? value.tool : displayID ? "browser" : "code"; |
| 35 | return {tool, displayID, project: typeof value?.project === "string" ? value.project : "", session: typeof value?.session === "string" ? value.session : ""}; |
| 36 | } |
| 37 | function saveRoute(next, push) { |
| 38 | history[push ? "pushState" : "replaceState"]({ ...history.state, cageCLI: next }, ""); |
| 39 | } |
| 40 | |
| 41 | function Status({ value, awaitingApproval }) { |
| 42 | const tone = active(value) ? "live" : value === "failed" || value === "interrupted" ? "bad" : ""; |
| 43 | return <span className={"status-label " + tone} role="status"><i className="status-dot" />{awaitingApproval ? "等待审批" : labels[value] || "就绪"}</span>; |
| 44 | } |
| 45 | function Notice({ children, onRetry, label = "重新读取" }) { |
| 46 | return <div className="notice" role="alert">{children} |
| 47 | {onRetry && <button type="button" className="action secondary" onClick={onRetry}><RefreshCw size={15} />{label}</button>} |
| 48 | </div>; |
| 49 | } |
| 50 | function Empty({ icon: Icon, title, children }) { |
| 51 | return <div className="center-message"><Icon size={25} strokeWidth={1.6} /><strong>{title}</strong>{children && <p className="note">{children}</p>}</div>; |
| 52 | } |
| 53 | |
| 54 | function App() { |
| 55 | const [current, setCurrent] = useState(route); |
| 56 | const [addressSlot, setAddressSlot] = useState(null); |
| 57 | const [drawer, setDrawer] = useState(() => phoneWorkspace && !history.state?.cageCLI && route().tool === "code"); |
| 58 | const drafts = useRef(new Map()); |
| 59 | const [expanded, setExpanded] = useState(() => new Map()); |
| 60 | const [catalog, setCatalog] = useState(null); |
| 61 | const [error, setError] = useState(""); |
| 62 | const [gate, setGate] = useState(""); |
| 63 | const [refresh, setRefresh] = useState(0); |
| 64 | const [visible, setVisible] = useState(!document.hidden); |
| 65 | const [creating, setCreating] = useState(false); |
| 66 | const [sessionAction, setSessionAction] = useState(null); |
| 67 | const [actionBusy, setActionBusy] = useState(false); |
| 68 | const [sessionActionError, setSessionActionError] = useState(""); |
| 69 | const mutationBusy = useRef(false); |
| 70 | const catalogGeneration = useRef(0); |
| 71 | const archivedSessions = useRef(new Set()); |
| 72 | const [devices, setDevices] = useState(() => window.__cageDevices || { current: "", devices: [] }); |
| 73 | const createRequest = useRef(null); |
| 74 | const openBrowserRequest = useRef(null); |
| 75 | const browserControls = useRef(null); |
| 76 | const createBusy = useRef(false); |
| 77 | const pageGeneration = useRef(0); |
| 78 | const accessGeneration = useRef(0); |
| 79 | const refreshAll = useCallback(() => setRefresh((n) => n + 1), []); |
| 80 | useEffect(() => { |
| 81 | const update = event => setDevices(event.detail); |
| 82 | window.addEventListener("cage-devices", update); |
| 83 | |
| 84 | if (window.__cageDevices) setDevices(window.__cageDevices); |
| 85 | return () => window.removeEventListener("cage-devices", update); |
| 86 | }, []); |
| 87 | useEffect(() => { |
| 88 | if (catalog?.host && devices.current) deviceCommand("name", { id: devices.current, name: catalog.host }); |
| 89 | }, [catalog?.host, devices.current]); |
| 90 | const restricted = useCallback((error) => { |
| 91 | pageGeneration.current++; |
| 92 | accessGeneration.current++; |
| 93 | drafts.current.clear(); |
| 94 | setSessionAction(null); |
| 95 | if (route().displayID) { |
| 96 | const next = {...route(), tool: "code", displayID: ""}; |
| 97 | saveRoute(next, false); |
| 98 | setCurrent(next); |
| 99 | } |
| 100 | setGate(error.message); setCatalog(null); setError(""); |
| 101 | }, []); |
| 102 | useEffect(() => { |
| 103 | const goBack = () => { openBrowserRequest.current = null; pageGeneration.current++; setCurrent(route()); setDrawer(phoneWorkspace && !history.state?.cageCLI); setError(""); }; |
| 104 | const visibility = () => setVisible(!document.hidden); |
| 105 | const viewport = window.visualViewport; |
| 106 | const resize = () => { |
| 107 | if (viewport?.scale === 1) document.documentElement.style.setProperty("--mobile-height", viewport.height + "px"); |
| 108 | }; |
| 109 | resize(); |
| 110 | window.addEventListener("popstate", goBack); |
| 111 | window.addEventListener("online", refreshAll); |
| 112 | document.addEventListener("visibilitychange", visibility); |
| 113 | viewport?.addEventListener("resize", resize); |
| 114 | return () => { |
| 115 | window.removeEventListener("popstate", goBack); |
| 116 | window.removeEventListener("online", refreshAll); |
| 117 | document.removeEventListener("visibilitychange", visibility); |
| 118 | viewport?.removeEventListener("resize", resize); |
| 119 | }; |
| 120 | }, [refreshAll]); |
| 121 | useEffect(() => { |
| 122 | if (!visible) return; |
| 123 | const controller = new AbortController(); |
| 124 | const options = { signal: controller.signal }; |
| 125 | const expectedAccess = accessGeneration.current; |
| 126 | let timer; |
| 127 | const load = async () => { |
| 128 | const expectedCatalog = catalogGeneration.current; |
| 129 | try { |
| 130 | const [info, list] = await Promise.all([request("/projects", options), request("/sessions", options)]); |
| 131 | if (controller.signal.aborted || expectedAccess !== accessGeneration.current || expectedCatalog !== catalogGeneration.current) return; |
| 132 | for (const session of list.sessions || []) archivedSessions.current.delete(session.id); |
| 133 | setCatalog({ ...info, sessions: (list.sessions || []).map(session => list.notice ? {...session, active:false} : session) }); setGate(""); setError(list.notice || ""); |
| 134 | } catch (error) { |
| 135 | if (controller.signal.aborted) return; |
| 136 | if (accessDenied(error)) { restricted(error); return; } |
| 137 | setError(error.message); |
| 138 | setCatalog(previous => previous && ({...previous, sessions:previous.sessions.map(session => ({...session, active:false}))})); |
| 139 | } |
| 140 | if (!controller.signal.aborted && (drawer || current.tool !== "code" || !current.session)) timer = setTimeout(load, 5000); |
| 141 | }; |
| 142 | void load(); |
| 143 | return () => { clearTimeout(timer); controller.abort(); }; |
| 144 | }, [refresh, visible, restricted, current.session, current.tool, drawer]); |
| 145 | const open = (project, session = "", push = false) => { |
| 146 | const next = {tool: "code", displayID: "", project, session}; |
| 147 | pageGeneration.current++; |
| 148 | saveRoute(next, push); setCurrent(next); setError(""); |
| 149 | }; |
| 150 | const updateSession = useCallback((snapshot) => { |
| 151 | setCatalog((old) => { |
| 152 | if (!old) return old; |
| 153 | const { id, workspace, title, revision, updated_at, generation, pinned, custom_title, metadata_set, active } = snapshot; |
| 154 | if (archivedSessions.current.has(id)) return old; |
| 155 | const previous = old.sessions.find((s) => s.id === id); |
| 156 | if (previous && previous.generation === generation && previous.revision >= revision) return old; |
| 157 | return { ...old, sessions: [{ id, workspace, title, revision, updated_at, generation, pinned, custom_title, metadata_set, active }, ...old.sessions.filter((s) => s.id !== id)] }; |
| 158 | }); |
| 159 | }, []); |
| 160 | const projects = catalog?.projects || []; |
| 161 | const project = projects.find((p) => p.path === current.project) || projects[0]; |
| 162 | const sessions = catalog?.sessions.filter((s) => s.workspace === project?.path) |
| 163 | .sort(sortSessions) || []; |
| 164 | const missingSession = useCallback(() => { |
| 165 | const selected = route(); |
| 166 | drafts.current.delete(selected.session); |
| 167 | const next = {...selected, session:""}; |
| 168 | saveRoute(next, false); setCurrent(next); setDrawer(phoneWorkspace); refreshAll(); |
| 169 | }, [refreshAll]); |
| 170 | const mutateSession = async (kind, target, body) => { |
| 171 | if (mutationBusy.current) return; |
| 172 | mutationBusy.current = true; setActionBusy(true); setSessionActionError(""); |
| 173 | catalogGeneration.current++; |
| 174 | try { |
| 175 | const result = await request(sessionPath(target.id) + (kind === "archive" ? "/archive" : "/metadata"), {body}); |
| 176 | if (kind === "archive") { |
| 177 | archivedSessions.current.add(target.id); |
| 178 | drafts.current.delete(target.id); |
| 179 | setCatalog(old => old && ({...old, sessions:old.sessions.filter(s => s.id !== target.id)})); |
| 180 | if (route().session === target.id) missingSession(); |
| 181 | } else updateSession(result); |
| 182 | setSessionAction(null); |
| 183 | } catch (error) { |
| 184 | if (accessDenied(error)) restricted(error); |
| 185 | else if (kind === "pin") setError(error.message); |
| 186 | else setSessionActionError(error.message); |
| 187 | } finally { |
| 188 | catalogGeneration.current++; |
| 189 | mutationBusy.current = false; setActionBusy(false); refreshAll(); |
| 190 | } |
| 191 | }; |
| 192 | const chooseSessionAction = (kind, target) => { |
| 193 | if (mutationBusy.current) return; |
| 194 | if (kind === "pin") void mutateSession(kind, target, {pinned:!target.pinned}); |
| 195 | else { setSessionActionError(""); setSessionAction({kind, session:target}); } |
| 196 | }; |
| 197 | const start = async target => { |
| 198 | if (!target || createBusy.current || !catalog.ready) return; |
| 199 | createBusy.current = true; setCreating(true); setError(""); |
| 200 | const generation = pageGeneration.current; |
| 201 | try { |
| 202 | if (createRequest.current?.workspace !== target.path) createRequest.current = { |
| 203 | id: crypto.randomUUID(), workspace: target.path, ...(catalog.shared_sessions ? {shared:true} : {}), |
| 204 | }; |
| 205 | const session = await request("/sessions", { body: createRequest.current }); |
| 206 | createRequest.current = null; |
| 207 | if (generation !== pageGeneration.current) return; |
| 208 | updateSession(session); |
| 209 | setExpanded(previous => new Map(previous).set(target.path, true)); |
| 210 | open(target.path, session.id, true); setDrawer(false); |
| 211 | } catch (error) { |
| 212 | if (generation !== pageGeneration.current) return; |
| 213 | if (error.status && error.status < 500) createRequest.current = null; |
| 214 | if (accessDenied(error)) restricted(error); else setError(error.message); |
| 215 | } finally { createBusy.current = false; setCreating(false); } |
| 216 | }; |
| 217 | const session = current.session; |
| 218 | const selectTool = (tool, push = true, url = "") => { |
| 219 | if (tool !== current.tool || !push) { |
| 220 | const id = crypto.randomUUID(); |
| 221 | openBrowserRequest.current = {id, url}; |
| 222 | const next = {...current, tool, displayID:id}; |
| 223 | pageGeneration.current++; |
| 224 | saveRoute(next, push); setCurrent(next); |
| 225 | } |
| 226 | setDrawer(false); |
| 227 | }; |
| 228 | const leaveDisplay = () => { |
| 229 | browserControls.current?.close(); |
| 230 | open(current.project, session); |
| 231 | setDrawer(!openBrowserRequest.current?.url); |
| 232 | }; |
| 233 | const exitWorkspace = () => { |
| 234 | if (current.displayID) leaveDisplay(); |
| 235 | return deviceCommand("home"); |
| 236 | }; |
| 237 | const codeNavigation = <CodeNavigation catalog={catalog} project={project} sessions={sessions} current={session} |
| 238 | creating={creating || actionBusy} onAction={chooseSessionAction} onProject={path => open(path)} onNew={() => start(project)} formatTime={displayTime} |
| 239 | onSession={id => {open(project.path, id, true); setDrawer(false);}} />; |
| 240 | const activeTool = workspaceTools.find(entry => entry.id === current.tool); |
| 241 | const ActiveToolIcon = ["settings", "archived"].includes(current.tool) ? Settings : activeTool?.icon || Terminal; |
| 242 | const settingsPage = tool => { |
| 243 | browserControls.current?.close(); |
| 244 | const next = {tool, displayID:"", project:current.project, session:""}; |
| 245 | pageGeneration.current++; |
| 246 | saveRoute(next, true); setCurrent(next); setDrawer(false); |
| 247 | }; |
| 248 | const leaveSettings = () => { |
| 249 | if (current.tool === "archived") settingsPage("settings"); |
| 250 | else { open(current.project); setDrawer(true); } |
| 251 | }; |
| 252 | useEffect(() => { |
| 253 | const openArchives = () => settingsPage("archived"); |
| 254 | window.addEventListener("cage-open-archives", openArchives); |
| 255 | return () => window.removeEventListener("cage-open-archives", openArchives); |
| 256 | }, [current.project]); |
| 257 | return <main className={["mobile-app", phoneWorkspace && "phone-workspace", nativePhone && "native-phone"].filter(Boolean).join(" ")}> |
| 258 | <header className="topbar workspace-topbar"> |
| 259 | {phoneWorkspace |
| 260 | ? <button type="button" className="icon-button" aria-haspopup="dialog" aria-expanded={drawer} aria-label="展开侧栏" |
| 261 | onClick={() => setDrawer(true)}><img className="brand-mark" src={cageLogo} alt="Cage" /></button> |
| 262 | : <a className="icon-button" href="/" aria-label="返回工作台"><img className="brand-mark" src={cageLogo} alt="Cage" /></a>} |
| 263 | {phoneWorkspace && (current.tool === "browser" || current.tool === "claude") && <div className="workspace-address-slot" ref={setAddressSlot} />} |
| 264 | <div className="top-actions">{phoneWorkspace |
| 265 | ? <span className="workspace-tool-icon" role="img" aria-label={activeTool?.name || "Claude Code"}><ActiveToolIcon size={19} aria-hidden="true" /></span> |
| 266 | : <div className="connection-host"><Monitor size={16} /><span>{catalog?.host || "连接电脑"}</span></div>}</div> |
| 267 | </header> |
| 268 | {gate ? <Notice onRetry={refreshAll}>{gate}</Notice> : !catalog |
| 269 | ? <section className="page-scroll">{error ? <Notice onRetry={refreshAll}>{error}</Notice> : <Empty icon={LoaderCircle} title="正在读取项目…" />}</section> |
| 270 | : current.tool === "settings" || current.tool === "archived" |
| 271 | ? <section className="page-scroll mobile-session-settings" aria-label="会话设置"> |
| 272 | <button className="action" onClick={leaveSettings}><ArrowLeft size={17} />{current.tool === "archived" ? "返回设置" : "返回会话"}</button> |
| 273 | {current.tool === "archived" ? <ArchivedSessions request={request} ready={catalog.ready} |
| 274 | onRestored={id => {archivedSessions.current.delete(id); refreshAll();}} /> |
| 275 | : <><h1>设置</h1><button className="action secondary" onClick={() => settingsPage("archived")}><Archive size={18} />已归档会话</button></>} |
| 276 | </section> |
| 277 | : current.displayID |
| 278 | ? <RemoteDisplay controls={browserControls} key={current.displayID} id={current.displayID} tool={current.tool} addressSlot={addressSlot} |
| 279 | start={openBrowserRequest.current?.id === current.displayID} initialURL={openBrowserRequest.current?.url || ""} visible={visible} |
| 280 | onBack={leaveDisplay} onReopen={() => selectTool(current.tool, false, openBrowserRequest.current?.url)} /> |
| 281 | : session |
| 282 | ? <Chat key={session} id={session} drafts={drafts.current} ready={catalog.ready} visible={visible} refresh={refresh} |
| 283 | onOpenWeb={url => selectTool("browser", true, url)} onDenied={restricted} onMissing={missingSession} onSnapshot={updateSession} onBack={phoneWorkspace ? undefined : () => open(current.project)} /> |
| 284 | : phoneWorkspace |
| 285 | ? <div className="workspace-placeholder"><Terminal size={28} /><p>{project ? "在侧栏选择或新建会话" : "请选择远程工具"}</p></div> |
| 286 | : <section className="page-scroll">{error && <Notice onRetry={refreshAll}>{error}</Notice>}{codeNavigation}</section>} |
| 287 | {phoneWorkspace && <WorkspaceDrawer open={drawer} active={current.tool} name={catalog?.host || devices.devices.find(d => d.id === devices.current)?.name} |
| 288 | onClose={() => setDrawer(false)} onTool={selectTool} onSettings={() => settingsPage("settings")} nativePhone={nativePhone} onExit={exitWorkspace}> |
| 289 | {error && <Notice onRetry={refreshAll}>{error}</Notice>} |
| 290 | {gate ? <Notice onRetry={refreshAll}>{gate}</Notice> : <ProjectTree catalog={catalog} projectPath={current.project} |
| 291 | sessionID={current.tool === "code" ? session : ""} creating={creating || actionBusy} onNew={start} onAction={chooseSessionAction} |
| 292 | onSession={(path,id) => {open(path,id,true); setDrawer(false);}} expanded={expanded} |
| 293 | toggle={(path,next) => setExpanded(previous => new Map(previous).set(path,next))} />} |
| 294 | </WorkspaceDrawer>} |
| 295 | {sessionAction && <SessionActionDialog key={sessionAction.kind + sessionAction.session.id} action={sessionAction} busy={actionBusy} |
| 296 | error={sessionActionError} onCancel={() => setSessionAction(null)} onSubmit={body => mutateSession(sessionAction.kind, sessionAction.session, body)}/>} |
| 297 | </main>; |
| 298 | } |
| 299 | |
| 300 | function Chat({ id, drafts, ready, visible, refresh, onOpenWeb, onDenied, onMissing, onSnapshot, onBack }) { |
| 301 | const [session, setSession] = useState(null); |
| 302 | const [readError, setReadError] = useState(""); |
| 303 | const [connectionError, setConnectionError] = useState(""); |
| 304 | const [actionError, setActionError] = useState(""); |
| 305 | const [readProgress, setReadProgress] = useState(""); |
| 306 | const [connectionProgress, setConnectionProgress] = useState(""); |
| 307 | const [sendProgress, setSendProgress] = useState(""); |
| 308 | const [confirming, setConfirming] = useState(false); |
| 309 | const [draft, setDraft] = useState(() => drafts.get(id)?.text || ""); |
| 310 | const [busy, setBusy] = useState(false); |
| 311 | const [uncertain, setUncertain] = useState(() => !!drafts.get(id)?.pending); |
| 312 | const [reload, setReload] = useState(0); |
| 313 | const [approvalFeedback, setApprovalFeedback] = useState(null); |
| 314 | const checkApproval = useRef(null); |
| 315 | const readFailures = useRef(0); |
| 316 | const live = useRef(true); |
| 317 | const latest = useRef(null); |
| 318 | const submission = useRef(drafts.get(id)?.pending || null); |
| 319 | const actionBusy = useRef(false); |
| 320 | const transcript = useRef(null); |
| 321 | const transcriptContext = useMemo(() => ({sessionID:id, openWeb:onOpenWeb}), [id, onOpenWeb]); |
| 322 | const composerInput = useRef(null); |
| 323 | const follow = useRef(true); |
| 324 | const last = session?.turns?.at(-1); |
| 325 | const running = active(last?.status); |
| 326 | useEffect(() => { |
| 327 | live.current = true; |
| 328 | return () => { live.current = false; }; |
| 329 | }, []); |
| 330 | const accept = useCallback((snapshot, expectedGeneration) => { |
| 331 | if (!live.current || snapshot?.id !== id) return; |
| 332 | const current = latest.current; |
| 333 | if (current && snapshot.generation !== current.generation && expectedGeneration !== current.generation) return; |
| 334 | if (submission.current && (snapshot.acknowledged_request_id === submission.current.request_id || snapshot.turns?.some((turn) => turn.id === submission.current.request_id))) { |
| 335 | drafts.delete(id); submission.current = null; setUncertain(false); setDraft(""); setActionError(""); setSendProgress(""); |
| 336 | } |
| 337 | if (current && snapshot.generation === current.generation && snapshot.revision < current.revision) return; |
| 338 | latest.current = snapshot; setSession(snapshot); onSnapshot(snapshot); |
| 339 | const pending = snapshot.turns?.at(-1)?.approval?.id; |
| 340 | if (checkApproval.current && pending !== checkApproval.current.id) checkApproval.current = null; |
| 341 | setApprovalFeedback((old) => old?.id === pending ? old : null); |
| 342 | }, [id, drafts, onSnapshot]); |
| 343 | const fetchSession = useCallback(async (signal, incremental) => { |
| 344 | const checking = checkApproval.current; |
| 345 | const generation = latest.current?.generation; |
| 346 | const after = incremental && !checking && latest.current ? "?after=" + encodeURIComponent(latest.current.revision) |
| 347 | + (generation ? "&epoch=" + encodeURIComponent(generation) : "") : ""; |
| 348 | try { |
| 349 | const snapshot = await request(sessionPath(id) + after, { signal }); |
| 350 | if (signal.aborted || !live.current) return; |
| 351 | if (snapshot) accept(snapshot, generation); |
| 352 | if (snapshot && checking && checkApproval.current === checking && latest.current?.turns?.at(-1)?.approval?.id === checking.id) { |
| 353 | checkApproval.current = null; |
| 354 | setApprovalFeedback({ id: checking.id, message: "主机仍在等待这次审批。请核对参数后再次选择。" }); |
| 355 | } |
| 356 | setReadError(""); |
| 357 | readFailures.current = 0; setReadProgress(""); |
| 358 | return active(latest.current?.turns?.at(-1)?.status) ? 1000 : 4000; |
| 359 | } catch (error) { |
| 360 | if (signal.aborted || !live.current) return; |
| 361 | if (accessDenied(error)) onDenied(error); else if (error.status === 404 || error.status === 410) onMissing(); |
| 362 | else if (retryableSessionError(error) && ++readFailures.current <= sessionRetryLimit) { |
| 363 | setReadError(""); setReadProgress(`${sessionFailureMessage(error)} 正在自动重连(${readFailures.current}/${sessionRetryLimit})…`); |
| 364 | return sessionRetryDelay(readFailures.current); |
| 365 | } else { |
| 366 | setReadProgress(""); |
| 367 | setReadError(sessionFailureMessage(error) + (retryableSessionError(error) ? " 已自动重连5次,仍未恢复。可以稍后再次连接。" : "")); |
| 368 | } |
| 369 | return null; |
| 370 | } |
| 371 | }, [id, accept, onDenied, onMissing]); |
| 372 | useEffect(() => { |
| 373 | if (!visible || uncertain) return; |
| 374 | const controller = new AbortController(); |
| 375 | let timer, incremental = false; |
| 376 | const poll = async () => { |
| 377 | const delay = await fetchSession(controller.signal, incremental); |
| 378 | incremental = true; |
| 379 | if (!controller.signal.aborted && delay != null) timer = setTimeout(poll, delay); |
| 380 | }; |
| 381 | void poll(); |
| 382 | return () => { clearTimeout(timer); controller.abort(); }; |
| 383 | }, [fetchSession, visible, refresh, reload, uncertain]); |
| 384 | useEffect(() => { |
| 385 | if (!uncertain || !visible || !ready) return; |
| 386 | const controller = new AbortController(); |
| 387 | setConfirming(true); setActionError(""); setReadError(""); setReadProgress(""); |
| 388 | const recovering = recoverPendingMessage({ |
| 389 | signal:controller.signal, pending:() => submission.current, |
| 390 | progress:attempt => setSendProgress(`正在重连并确认消息是否送达(${attempt}/${sessionRetryLimit})…`), |
| 391 | read:async () => { |
| 392 | const generation = latest.current?.generation; |
| 393 | const snapshot = await request(sessionPath(id), {signal:controller.signal}); |
| 394 | if (!controller.signal.aborted) { accept(snapshot, generation); setReadError(""); setReadProgress(""); readFailures.current = 0; } |
| 395 | return latest.current; |
| 396 | }, |
| 397 | send:async message => { |
| 398 | const generation = latest.current?.generation; |
| 399 | const snapshot = await request(sessionPath(id) + "/messages", {body:message, signal:controller.signal}); |
| 400 | if (!controller.signal.aborted) accept(snapshot, generation); |
| 401 | }, |
| 402 | }); |
| 403 | void recovering.then(confirmed => { |
| 404 | if (!controller.signal.aborted && !confirmed) setActionError("消息是否送达仍未确认。已自动重连5次,原消息已保留。再次连接后会继续确认,避免重复执行。"); |
| 405 | }).catch(error => { |
| 406 | if (controller.signal.aborted) return; |
| 407 | if (accessDenied(error)) onDenied(error); else if ([404,410].includes(error.status)) onMissing(); else setActionError(sessionFailureMessage(error)); |
| 408 | }).finally(() => { if (!controller.signal.aborted) { setConfirming(false); setSendProgress(""); } }); |
| 409 | return () => { controller.abort(); setConfirming(false); setSendProgress(""); }; |
| 410 | }, [id, uncertain, visible, ready, accept, onDenied, onMissing, reload]); |
| 411 | const needsConnection = ready && visible && session?.terminal_available && session.can_send === false; |
| 412 | useEffect(() => { |
| 413 | if (!needsConnection) { setConnectionError(""); setConnectionProgress(""); return; } |
| 414 | setConnectionError(""); |
| 415 | const controller = new AbortController(); |
| 416 | let timer; |
| 417 | let started = Date.now(); |
| 418 | let failures = 0; |
| 419 | const connect = async () => { |
| 420 | let delay = 1000; |
| 421 | try { |
| 422 | const generation = latest.current?.generation; |
| 423 | const snapshot = await request(sessionPath(id) + "/open", { body: {automatic:true}, signal:controller.signal }); |
| 424 | if (controller.signal.aborted) return; |
| 425 | if (snapshot) accept(snapshot, generation); |
| 426 | failures = 0; setConnectionProgress(""); |
| 427 | if (snapshot?.can_send) return; |
| 428 | if (snapshot?.connection_waiting) started = Date.now(); |
| 429 | if (!snapshot?.connection_waiting && Date.now() - started > 60000) { |
| 430 | setConnectionError("会话连接暂未就绪,请重试。"); |
| 431 | return; |
| 432 | } |
| 433 | } catch (error) { |
| 434 | if (controller.signal.aborted) return; |
| 435 | if (accessDenied(error)) { onDenied(error); return; } |
| 436 | if (retryableSessionError(error) && ++failures <= sessionRetryLimit) { |
| 437 | setConnectionProgress(`正在恢复会话连接(${failures}/${sessionRetryLimit})…`); |
| 438 | delay = sessionRetryDelay(failures); |
| 439 | } else if (error.status !== 409 || Date.now() - started > 60000) { |
| 440 | setConnectionProgress(""); |
| 441 | setConnectionError(sessionFailureMessage(error) + (retryableSessionError(error) ? " 已自动重连5次,可以稍后再次连接。" : "")); return; |
| 442 | } |
| 443 | } |
| 444 | timer = setTimeout(connect, delay); |
| 445 | }; |
| 446 | void connect(); |
| 447 | return () => { controller.abort(); clearTimeout(timer); }; |
| 448 | }, [id, needsConnection, accept, onDenied, reload]); |
| 449 | useEffect(() => { |
| 450 | if (follow.current && transcript.current) transcript.current.scrollTop = transcript.current.scrollHeight; |
| 451 | }, [session?.revision]); |
| 452 | useEffect(() => { |
| 453 | const input = composerInput.current; |
| 454 | if (!input) return; |
| 455 | input.style.height = "24px"; |
| 456 | input.style.height = Math.min(input.scrollHeight, 144) + "px"; |
| 457 | }, [draft]); |
| 458 | const send = async (event) => { |
| 459 | event?.preventDefault(); |
| 460 | if (actionBusy.current || confirming || readProgress || readError || running || !ready || !session || session.single_turn || session.can_send === false || !draft.trim()) return; |
| 461 | actionBusy.current = true; setBusy(true); setActionError(""); |
| 462 | setSendProgress("正在发送消息…"); |
| 463 | try { |
| 464 | follow.current = true; |
| 465 | const generation = latest.current?.generation; |
| 466 | submission.current ||= { request_id: crypto.randomUUID(), text: draft.trim() }; |
| 467 | drafts.set(id, {text:draft, pending:submission.current}); |
| 468 | const snapshot = await request(sessionPath(id) + "/messages", { body: submission.current }); |
| 469 | if (live.current) { accept(snapshot, generation); setReload(n => n + 1); } |
| 470 | } catch (error) { |
| 471 | if (!live.current) return; |
| 472 | if (accessDenied(error)) onDenied(error); |
| 473 | else if (submission.current) { |
| 474 | const unknown = !error.status || error.status >= 500; |
| 475 | if (!unknown) {submission.current = null; drafts.set(id, {text:draft});} |
| 476 | setUncertain(unknown); setActionError(unknown ? "" : error.message); |
| 477 | if (!unknown) setSendProgress(""); |
| 478 | if (unknown) setReload((n) => n + 1); |
| 479 | } |
| 480 | } finally { actionBusy.current = false; if (live.current) setBusy(false); } |
| 481 | }; |
| 482 | const stop = async () => { |
| 483 | if (actionBusy.current || last?.status !== "running") return; |
| 484 | actionBusy.current = true; setBusy(true); setActionError(""); |
| 485 | const generation = latest.current?.generation; |
| 486 | try { accept(await request(sessionPath(id) + "/stop", { body: { request_id: last.id } }), generation); } |
| 487 | catch (error) { |
| 488 | if (!live.current) return; |
| 489 | if (accessDenied(error)) onDenied(error); |
| 490 | else { setActionError(error.message); setReload((n) => n + 1); } |
| 491 | } finally { actionBusy.current = false; if (live.current) setBusy(false); } |
| 492 | }; |
| 493 | const retry = () => { readFailures.current = 0; setReadError(""); setConnectionError(""); setReload((n) => n + 1); }; |
| 494 | const decide = async (turnId, approvalId, allow) => { |
| 495 | const turn = latest.current?.turns?.at(-1); |
| 496 | if (actionBusy.current || checkApproval.current?.id === approvalId || turn?.id !== turnId || turn?.status !== "running" || turn.approval?.id !== approvalId) return; |
| 497 | actionBusy.current = true; setBusy(true); setApprovalFeedback(null); |
| 498 | try { |
| 499 | const generation = latest.current?.generation; |
| 500 | accept(await request(sessionPath(id) + "/approval", { body: { request_id: turnId, approval_id: approvalId, allow } }), generation); |
| 501 | } catch (error) { |
| 502 | if (!live.current) return; |
| 503 | if (accessDenied(error)) onDenied(error); |
| 504 | else if (latest.current?.turns?.at(-1)?.approval?.id === approvalId) { |
| 505 | const checking = { id: approvalId, checking: true, message: error.status === 409 ? "这次请求的状态已变化,正在重新读取。" : "审批结果尚未确认,正在重新读取主机状态。" }; |
| 506 | checkApproval.current = checking; setApprovalFeedback(checking); retry(); |
| 507 | } |
| 508 | } finally { actionBusy.current = false; if (live.current) setBusy(false); } |
| 509 | }; |
| 510 | return <> |
| 511 | <section className="chat-header"> |
| 512 | <div className="title-line">{onBack && <button type="button" className="icon-button" aria-label="返回会话列表" onClick={onBack}><ArrowLeft size={18} /></button>}<h1>{session?.title || "Claude Code 会话"}</h1>{session && <Status value={last?.status} awaitingApproval={last?.status === "running" && last.approval} />}</div> |
| 513 | {session && <p className="note">{session.workspace}</p>} |
| 514 | </section> |
| 515 | {!uncertain && (readError || connectionError) && <Notice onRetry={retry} label="再次连接">{readError || connectionError}</Notice>} |
| 516 | {session && <SessionAccount id={id} request={request} onChanged={()=>setReload(n=>n+1)} compact />} |
| 517 | {(sendProgress || connectionProgress || readProgress) && <p className="note" role="status">{sendProgress || connectionProgress || readProgress}</p>} |
| 518 | {session?.connection_notice && <Notice>{session.connection_notice}</Notice>} |
| 519 | {session?.history_truncated && <p className="note">手机显示的历史已截断,完整内容保存在电脑 Claude Code 中。</p>} |
| 520 | <section className="transcript" ref={transcript} aria-label="会话消息" onScroll={(e) => { |
| 521 | const box = e.currentTarget; follow.current = box.scrollHeight - box.scrollTop - box.clientHeight < 64; |
| 522 | }}> |
| 523 | {!session && !readError && <Empty icon={LoaderCircle} title="正在读取会话…" />} |
| 524 | {session && !session.turns?.length && <Empty icon={Terminal} title="发送第一条消息">Claude Code 会在所选项目中处理你的请求。</Empty>} |
| 525 | <TranscriptContext.Provider value={transcriptContext}>{session?.turns?.map((turn) => <React.Fragment key={turn.id}> |
| 526 | <article className="message user" aria-label="你的消息"><MessageBody text={turn.prompt} /></article> |
| 527 | <article className="message" aria-label="回复"> |
| 528 | <ToolActivity tools={turn.tools} /> |
| 529 | {turn.text && <MessageBody text={turn.text} />} |
| 530 | {turn.truncated && <p className="note">本轮输出超过记录上限,仅显示已保存的部分。</p>} |
| 531 | {!turn.text && !turn.approval && active(turn.status) && <p className="note">等待输出…</p>} |
| 532 | {turn.id === last.id && turn.status === "running" && turn.approval?.id && <Approval |
| 533 | key={turn.approval.id} approval={turn.approval} busy={busy} feedback={approvalFeedback?.id === turn.approval.id ? approvalFeedback : null} |
| 534 | onDecide={(allow) => decide(turn.id, turn.approval.id, allow)} />} |
| 535 | {turn.error && <div className="turn-error">{turn.error}</div>} |
| 536 | {turn.denied_tools?.length > 0 && <div className="turn-tools">以下工具需要授权,本次调用已拒绝。<span>{turn.denied_tools.join("、")}</span></div>} |
| 537 | {["failed", "interrupted", "stopped"].includes(turn.status) && <p className="note">{labels[turn.status]}</p>} |
| 538 | </article> |
| 539 | </React.Fragment>)}</TranscriptContext.Provider> |
| 540 | </section> |
| 541 | <form className="compose" onSubmit={send}> |
| 542 | {actionError && <Notice onRetry={uncertain ? retry : undefined} label="再次连接">{actionError}</Notice>} |
| 543 | {session?.single_turn && <p className="note">当前凭据或路由只能验证本轮。请返回会话列表,新建会话后继续。</p>} |
| 544 | {!ready && <p className="note">请在电脑上启动 Cage 环境。</p>} |
| 545 | <div className="composer-field"> |
| 546 | <textarea ref={composerInput} aria-label="消息" rows="1" placeholder="给 Claude Code 发消息" value={draft} disabled={!session || session.single_turn || !ready || uncertain || busy} |
| 547 | onChange={(e) => { |
| 548 | const value = e.target.value; |
| 549 | if (value) drafts.set(id, {text:value}); else drafts.delete(id); |
| 550 | setDraft(value); |
| 551 | }} onKeyDown={(e) => { |
| 552 | if (e.key === "Enter" && !e.nativeEvent.isComposing && (e.ctrlKey || e.metaKey)) { e.preventDefault(); void send(); } |
| 553 | }} /> |
| 554 | {running ? <button type="button" className="composer-action" aria-label={last.status === "stopping" ? "正在停止" : "停止运行"} title={last.status === "stopping" ? "正在停止" : "停止运行"} disabled={busy || last.status !== "running"} onClick={stop}><Square size={17} /></button> |
| 555 | : <button type="submit" className="composer-action" aria-label={uncertain ? "再次尝试发送" : "发送"} title={uncertain ? "再次尝试发送" : "发送"} disabled={busy || confirming || !!readProgress || !!readError || !ready || !session || session.single_turn || session.can_send === false || !draft.trim()}><ArrowUp size={21} /></button>} |
| 556 | </div> |
| 557 | </form> |
| 558 | </>; |
| 559 | } |
| 560 | |
| 561 | function Approval({ approval, busy, feedback, onDecide }) { |
| 562 | let input = null; |
| 563 | if (approval.input && typeof approval.input === "object" && !Array.isArray(approval.input)) { |
| 564 | try { |
| 565 | |
| 566 | input = JSON.stringify(approval.input, null, 2).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, c => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")); |
| 567 | } catch { } |
| 568 | } |
| 569 | return <section className="approval" aria-label="工具审批"> |
| 570 | <h2>允许使用 {approval.tool}?</h2> |
| 571 | {input === null ? <p className="note">无法显示完整参数,请拒绝或重新读取。</p> |
| 572 | : <pre tabIndex={0} aria-label={approval.preview ? "工具参数预览" : "完整工具参数"}>{input}</pre>} |
| 573 | {approval.preview && <p className="note">参数预览由 Claude Code 提供。若显示省略内容,请在电脑查看完整参数后处理。</p>} |
| 574 | {feedback && <p className="note" role="status">{feedback.message}</p>} |
| 575 | <div className="approval-actions"> |
| 576 | <button type="button" className="action secondary" disabled={busy || feedback?.checking} onClick={() => onDecide(false)}>拒绝</button> |
| 577 | <button type="button" className="action primary" disabled={busy || feedback?.checking || input === null} onClick={() => onDecide(true)}>允许一次</button> |
| 578 | </div> |
| 579 | </section>; |
| 580 | } |
| 581 | |
| 582 | createRoot(document.getElementById("root")).render(<App />); |