跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

claude-accounts.jsx

404 行 · 23.5 KB历史下载
1import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
2import { Check, Pencil, Plus, RefreshCw, TerminalSquare, Timer } from "lucide-react";
3import { api } from "./api";
4import { InlineSelect } from "./inline-select";
5import crabIcon from "./claude-account-crab.svg";
6import "./claude-accounts.css";
7
8// Ordinary reads never start an upstream usage query.
9export function useClaudeAccounts() {
10 const [registry, setRegistry] = useState(null);
11 const [error, setError] = useState("");
12 const generation = useRef(0);
13 const pendingMutation = useRef(0);
14 const polling = useRef(false);
15 const load = useCallback(async (change, visiblePanel = false) => {
16 if (!change && (pendingMutation.current || (visiblePanel && polling.current))) return;
17 const request = ++generation.current;
18 if (change) pendingMutation.current++;
19 else if (visiblePanel) polling.current = true;
20 try {
21 const value = await api(visiblePanel ? "/claude-accounts?panel=visible" : "/claude-accounts", change);
22 if (!Array.isArray(value?.accounts)) throw new Error("无法读取 Claude 账号列表");
23 if (generation.current === request) {
24 setRegistry(value);
25 setError("");
26 }
27 return value.accounts;
28 } catch (e) {
29 if (generation.current === request) setError(e.message);
30 if (change) throw e;
31 } finally {
32 if (change) pendingMutation.current--;
33 else if (visiblePanel) polling.current = false;
34 }
35 }, []);
36 useEffect(() => { load(); return () => { generation.current++; }; }, [load]);
37 return { accounts: registry?.accounts ?? null, detected: registry?.detected,
38 detectionStatus: registry?.detection_status, detectionError: registry?.detection_error,
39 usageRunning: registry?.usage_panel_running, usageUnavailable: registry?.usage_unavailable_reason,
40 scheduling: registry?.scheduling || {mode:"balanced",switch_policy:"ask"}, loginNotice: registry?.login_notice, error, load };
41}
42
43const statusLabels = {
44 pending: "等待登录", ready: "已登录", signed_out: "需要登录",
45 duplicate: "账号已在列表中", changed: "登录身份已改变",
46};
47const localTimestamp = new Intl.DateTimeFormat(undefined, {
48 month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit",
49});
50const timeLabel = (seconds) => localTimestamp.format(seconds * 1000);
51
52const usageUpdatedAt = (profile) => Math.max(profile.quota?.five_hour?.observed_at || 0,
53 profile.quota?.seven_day?.observed_at || 0) || profile.usage_checked_at || 0;
54const ageUnit = (elapsed) => elapsed < 3600 ? 60 : elapsed < 86400 ? 3600 : 86400;
55function relativeTimeLabel(seconds, now) {
56 const elapsed = Math.max(0, now - seconds);
57 if (elapsed < 60) return "刚刚";
58 if (elapsed < 3600) return `${Math.floor(elapsed / 60)}分钟前`;
59 if (elapsed < 86400) return `${Math.floor(elapsed / 3600)}小时前`;
60 return `${Math.floor(elapsed / 86400)}天前`;
61}
62
63const QuotaTime = createContext(0);
64
65// All rows share a clock. Only quota readings subscribe; a tick doesn't render
66// the account forms or fetch data. Sleep until the next visible unit changes.
67function QuotaClock({ accounts, children }) {
68 const [now, setNow] = useState(() => Math.floor(Date.now() / 1000));
69 useEffect(() => {
70 let timer;
71 const update = () => {
72 clearTimeout(timer);
73 if (document.hidden) return;
74 const millis = Date.now();
75 const seconds = Math.floor(millis / 1000);
76 setNow(seconds);
77 let delay = Infinity;
78 for (const account of accounts || []) {
79 const updated = usageUpdatedAt(account);
80 if (updated > 0) {
81 const elapsed = Math.max(0, seconds - updated);
82 const unit = ageUnit(elapsed);
83 delay = Math.min(delay, unit - elapsed % unit);
84 }
85 for (const window of [account.quota?.five_hour, account.quota?.seven_day]) {
86 const left = window?.resets_at - seconds;
87 if (left > 0) delay = Math.min(delay, left <= 60 ? 1 : (left - 1) % 60 + 1);
88 const seen = window?.observed_at;
89 if (window && seen && seen + 901 > seconds) delay = Math.min(delay, seen + 901 - seconds);
90 }
91 }
92 if (Number.isFinite(delay)) timer = setTimeout(update, delay * 1000 - millis % 1000);
93 };
94 update();
95 document.addEventListener("visibilitychange", update);
96 return () => { clearTimeout(timer); document.removeEventListener("visibilitychange", update); };
97 }, [accounts]);
98 return <QuotaTime.Provider value={now}>{children}</QuotaTime.Provider>;
99}
100
101function resetCountdown(seconds) {
102 if (seconds < 60) return `${seconds}秒后`;
103 const minutes = Math.ceil(seconds / 60);
104 if (minutes < 60) return `${minutes}分后`;
105 const hours = Math.floor(minutes / 60);
106 if (hours < 24) return `${hours}时 ${minutes % 60}分后`;
107 return `${Math.floor(hours / 24)}天 ${hours % 24}时后`;
108}
109
110const usageLabels = {
111 checking: "正在查询额度…", reported: "已获取额度", partial: "本次只返回了部分额度",
112 cached: "本次只有缓存读数", unavailable: "本次未返回额度", error: "额度查询失败",
113 not_applicable: "当前登录不提供订阅额度",
114 identity_changed: "登录身份已改变,本次读数已丢弃", offline: "环境离线,无法查询",
115 update_required: "需同步环境组件后才能查询", blocked: "暂时无法查询额度",
116 signed_out: "登录后可查询额度", local: "已有会话读数", unknown: "尚未查询额度",
117};
118
119function useUsageCheck(profile, environment, perform, change) {
120 const [manual, setManual] = useState(null);
121 const check = () => perform(async () => {
122 setManual({ state: "checking" });
123 try {
124 await change(profile.id ? { action: "refresh", id: profile.id } :
125 { action: "refresh_default", identity: profile.identity });
126 setManual(null);
127 } catch (e) {
128 setManual({ state: "error", previousCheck: profile.usage_checked_at, previousStatus: profile.usage_status });
129 await change(); // A failed identity check can still change which default account the panel should show.
130 throw e;
131 }
132 });
133 let state = profile.usage_status || (profile.quota ? "local" : "unknown");
134 if (profile.status === "changed" || profile.status === "duplicate") state = "identity_changed";
135 if (profile.status === "signed_out" || profile.status === "pending") state = "signed_out";
136 if (manual?.state === "error" && manual.previousCheck === profile.usage_checked_at && manual.previousStatus === profile.usage_status) state = "error";
137 if (profile.usage_checking || manual?.state === "checking") state = "checking";
138 if (environment) state = environment;
139 return { state, check };
140}
141
142function QuotaWindow({ label, snapshot, state }) {
143 const now = useContext(QuotaTime);
144 const reset = snapshot?.resets_at;
145 const remaining = reset ? reset - now : null;
146 const expired = remaining !== null && remaining <= 0;
147 const hasReading = Number.isFinite(snapshot?.used_percentage);
148 const known = !expired && hasReading;
149 const lastSeen = snapshot?.observed_at;
150 const stale = known && (!lastSeen || now - lastSeen > 15 * 60 ||
151 !["reported", "partial"].includes(state));
152 const countdown = expired ? "等待更新" : remaining !== null ? resetCountdown(remaining) :
153 known ? "重置时间未知" : state === "checking" ? "查询中" : "暂无读数";
154 return <div className="claude-quota-row" role="group" aria-label={label + " 额度"}>
155 <span className="claude-quota-period">{label}</span>
156 {known
157 ? <progress aria-label={label + " 已用额度"} value={snapshot.used_percentage} max={100} />
158 : <span className="claude-quota-unknown" aria-hidden="true" />}
159 <div className="claude-quota-reading">
160 {stale && <span className="claude-quota-stale" title={lastSeen ? `历史读数 · ${timeLabel(lastSeen)}` : "历史读数"}>历史读数</span>}
161 {known && <strong title={lastSeen ? `已用额度 · 读取于 ${timeLabel(lastSeen)}` : "已用额度"}>{snapshot.used_percentage}%</strong>}
162 <span className="claude-quota-reset" title={reset ? `${timeLabel(reset)} 重置` : "尚无重置时间"}>
163 {remaining > 0 && <Timer size={12} aria-hidden="true" />}{countdown}
164 </span>
165 </div>
166 {hasReading && (expired || stale || state === "partial") && <small className="claude-quota-history">
167 {expired && `上次 ${snapshot.used_percentage}% · `}
168 {lastSeen > 0 ? <>{!expired && "读取于 "}<time dateTime={new Date(lastSeen * 1000).toISOString()}>{timeLabel(lastSeen)}</time></> : "读数时间未知"}
169 </small>}
170 </div>;
171}
172
173function ProfileUsage({ quota, state }) {
174 return <div className="claude-quota-grid">
175 <QuotaWindow label="5h" snapshot={quota?.five_hour} state={state} />
176 <QuotaWindow label="7d" snapshot={quota?.seven_day} state={state} />
177 </div>;
178}
179
180function UsageNote({ profile, state }) {
181 const now = useContext(QuotaTime);
182 const updated = usageUpdatedAt(profile);
183 return <small className="claude-quota-age">
184 <span>{usageLabels[state] || "暂无额度信息"}</span>
185 {updated > 0 && <span>最近更新 <time dateTime={new Date(updated * 1000).toISOString()} title={timeLabel(updated)}>
186 {relativeTimeLabel(updated, now)}</time></span>}
187 </small>;
188}
189
190function DetectedProfile({ profile, usageEnvironment, busy, join, perform, change }) {
191 const usage = useUsageCheck(profile, usageEnvironment, perform, change);
192 return <article className="claude-profile claude-detected" aria-label={profile.email}>
193 <div className="claude-profile-heading">
194 <span className="claude-profile-avatar" aria-hidden="true"><img src={crabIcon} alt="" /></span>
195 <div className="claude-profile-identity">
196 <div className="claude-profile-name">
197 <h4 title={profile.email}>{profile.email}</h4>
198 {profile.plan && <span className="claude-profile-plan">{profile.plan}</span>}
199 </div>
200 <div className="claude-profile-meta">
201 <span className="claude-profile-status">普通终端 · 已发现,未加入</span>
202 {profile.organization && <span className="claude-profile-email" title={profile.organization}>{profile.organization}</span>}
203 </div>
204 </div>
205 </div>
206 <ProfileUsage quota={profile.quota} state={usage.state} />
207 <div className="claude-profile-actions">
208 <button className="quiet-button" disabled={busy} onClick={join}><Plus size={14} />加入调度</button>
209 <button className="quiet-button" disabled={busy || !!usageEnvironment || usage.state === "checking"} onClick={usage.check}>
210 <RefreshCw size={14} />检查状态</button>
211 <UsageNote profile={profile} state={usage.state} />
212 </div>
213 </article>;
214}
215
216function ProfileCard({ profile, environment, usageEnvironment, busy, active, defaultActive, perform, change, login, cancelDraft }) {
217 const [renaming, setRenaming] = useState(false);
218 const [label, setLabel] = useState("");
219 const [group, setGroup] = useState(profile.handoff_group || "");
220 const displayName = profile.label || profile.email;
221 const fromTerminal = profile.source === "default";
222 const savedLabel = label.trim() || profile.email;
223 const usage = useUsageCheck(profile, usageEnvironment, perform, change);
224 return <article className="claude-profile" aria-label={displayName} data-enabled={profile.enabled}>
225 <div className="claude-profile-heading">
226 <span className="claude-profile-avatar" aria-hidden="true"><img src={crabIcon} alt="" /></span>
227 <div className="claude-profile-identity">
228 {renaming ? <form className="claude-profile-rename" onSubmit={(e) => {
229 e.preventDefault();
230 perform(async () => { await change({ action: "update", id: profile.id, label: savedLabel }); setRenaming(false); });
231 }}>
232 <input autoFocus aria-label="账号备注" maxLength={64} placeholder={profile.email || "账号名称"} value={label} onChange={(e) => setLabel(e.target.value)} />
233 <button disabled={busy || !savedLabel} aria-label="保存备注"><Check size={15} /></button>
234 <button type="button" disabled={busy} onClick={() => setRenaming(false)}>取消</button>
235 </form> : <div className="claude-profile-name">
236 <h4 title={displayName}>{displayName}</h4>
237 {profile.plan && <span className="claude-profile-plan">{profile.plan}</span>}
238 <button type="button" className="icon-button" disabled={busy} aria-label={`修改 ${displayName} 的备注`}
239 onClick={() => { setLabel(profile.label === profile.email ? "" : profile.label || ""); setRenaming(true); }}><Pencil size={14} /></button>
240 </div>}
241 <div className="claude-profile-meta">
242 <span className="claude-profile-status" data-ready={profile.status === "ready"}>{statusLabels[profile.status] || "状态未知"}</span>
243 {profile.email && <span className="claude-profile-email" title={[profile.email, profile.organization].filter(Boolean).join(" · ")}>
244 {[profile.email !== displayName && profile.email, profile.organization].filter(Boolean).join(" · ")}
245 </span>}
246 </div>
247 </div>
248 <label className="check-line claude-participation">
249 <input type="checkbox" aria-label="参与自动分配" checked={profile.enabled} disabled={busy}
250 onChange={(e) => { const enabled = e.target.checked; perform(() => change({ action: "update", id: profile.id, enabled })); }} />
251 <span className="claude-switch-track" aria-hidden="true" />
252 <span>{profile.enabled ? "参与分配" : "已暂停"}</span>
253 </label>
254 </div>
255 <ProfileUsage quota={profile.quota} state={usage.state} />
256 <form className="claude-handoff-group" onSubmit={event => { event.preventDefault(); perform(() => change({action:"update",id:profile.id,handoff_group:group})); }}>
257 <label>接续分组<input aria-label={`${displayName} 的接续分组`} value={group} maxLength={32} placeholder="未分组,不跨账号接续" onChange={event => setGroup(event.target.value)} /></label>
258 <button disabled={busy || group === (profile.handoff_group || "")}>保存分组</button>
259 </form>
260 {active > 0 && <p className="claude-profile-note">{active} 个终端仍在运行{!fromTerminal && ",关闭后可重新登录"}</p>}
261 {!fromTerminal && defaultActive > 0 && <p className="field-help">
262 其中 {defaultActive} 个工作终端仍使用普通终端的登录。若普通终端已换号,请重新打开这些会话确认身份。
263 </p>}
264 {fromTerminal && ["changed", "signed_out"].includes(profile.status) && <p className="field-help">
265 {profile.status === "changed" ? "普通终端已换号,此账号暂不参与分配。新身份需单独加入。" : "普通终端已退出。要继续使用此账号,请先重新登录原身份。"}
266 {active > 0 && " 原工作终端仍保留首次分配的标签。请重新打开工作会话确认身份。"}
267 </p>}
268 {!fromTerminal && profile.status === "changed" && <p className="field-help">请用原账号重新登录。若要使用新的身份,请点击「登录新账号」。</p>}
269 {profile.status === "duplicate" && <p className="field-help">同一订阅只参与一次分配。请在此位置登录另一个账号。</p>}
270 <div className="claude-profile-actions">
271 {fromTerminal ? <span className="claude-profile-source">普通终端账号</span> :
272 <button className="quiet-button" disabled={busy || !!environment || active > 0} onClick={() => perform(() => login(profile.id))}>
273 <TerminalSquare size={14} />{profile.status === "ready" ? "重新登录" : "打开登录终端"}</button>}
274 <button className="quiet-button" disabled={busy || !!usageEnvironment || usage.state === "checking"} onClick={usage.check}>
275 <RefreshCw size={14} />检查状态</button>
276 {!fromTerminal && !profile.email && !active && ["pending", "signed_out", "duplicate"].includes(profile.status) &&
277 <button className="text-button" disabled={busy} onClick={() => perform(() => cancelDraft(profile))}>撤销添加</button>}
278 <UsageNote profile={profile} state={usage.state} />
279 </div>
280 </article>;
281}
282
283export function ClaudeAccountsPanel({ store, running, environmentBusy, tabs, login, onConfirm }) {
284 const { accounts, detected, detectionStatus, detectionError, loginNotice, usageRunning, usageUnavailable, load, error } = store;
285 const [busy, setBusy] = useState(false);
286 const [requestingUsage, setRequestingUsage] = useState(false);
287 const [actionError, setActionError] = useState("");
288 const visibleProfiles = useMemo(() => detected ? [detected, ...(accounts || [])] : accounts, [accounts, detected]);
289 const environment = !running || detectionStatus === "offline" ? "offline" :
290 detectionStatus === "update_required" ? "update_required" : "";
291 const usageEnvironment = environment || (usageUnavailable ? "blocked" : "");
292 const checking = !usageEnvironment && (usageRunning || visibleProfiles?.some((profile) => profile.usage_checking));
293 const activeCounts = useMemo(() => {
294 const counts = new Map();
295 for (const tab of tabs) {
296 if (!tab.claude_account_id || tab.closed) continue;
297 const count = counts.get(tab.claude_account_id) || { all: 0, fromDefault: 0 };
298 count.all++;
299 if (tab.claude_account_source === "default") count.fromDefault++;
300 counts.set(tab.claude_account_id, count);
301 }
302 return counts;
303 }, [tabs]);
304 useEffect(() => {
305 let requested = false, mounted = true;
306 const openPanel = () => {
307 if (requested || document.hidden) return;
308 requested = true;
309 setRequestingUsage(running);
310 if (running) {
311 load({ action: "usage_panel" })
312 .catch(() => {})
313 .finally(() => { if (mounted) setRequestingUsage(false); });
314 } else load();
315 };
316 openPanel();
317 document.addEventListener("visibilitychange", openPanel);
318 return () => { mounted = false; document.removeEventListener("visibilitychange", openPanel); };
319 }, [load, running]);
320 useEffect(() => {
321 const timer = setInterval(() => { if (!document.hidden) load(undefined, true); }, checking ? 2000 : 12000);
322 return () => clearInterval(timer);
323 }, [load, checking]);
324 const perform = async (operation) => {
325 if (busy) return;
326 setBusy(true);
327 setActionError("");
328 try { await operation(); }
329 catch (e) { setActionError(e.message); }
330 finally { setBusy(false); }
331 };
332 const cancelDraft = async (profile) => {
333 const last = accounts.length === 1;
334 if (await onConfirm({ title: `撤销添加「${profile.label}」?`,
335 body: last
336 ? "这是列表中的最后一个账号。撤销后,新建 Claude 终端会沿用环境原有的登录。虚拟机中的资料会保留。"
337 : "此账号会从列表中移除,虚拟机中的资料会保留。",
338 confirm: "撤销添加" })) {
339 await load({ action: "cancel", id: profile.id });
340 }
341 };
342 const joinDetected = async () => {
343 try { await load({ action: "join", identity: detected.identity }); }
344 catch (e) {
345 await load(); // The identity shown when the user clicked may no longer be signed in.
346 throw e;
347 }
348 };
349 return <section className="claude-profiles" aria-label="Claude 账号管理">
350 <div className="section-title">
351 <h3>Claude 账号</h3>
352 <p>将普通终端已登录的订阅加入调度,或单独登录一个新账号。新建 Claude 终端时自动分配。</p>
353 </div>
354 <details className="claude-scheduling">
355 <summary>调度设置 · {store.scheduling.mode === "sequential" ? "顺序优先" : "均衡分配"}</summary>
356 <label>新会话分配<InlineSelect aria-label="新会话分配" value={store.scheduling.mode} disabled={busy}
357 onValueChange={mode => perform(() => load({action:"scheduling",scheduling:{...store.scheduling,mode}}))}>
358 <option value="balanced">均衡分配</option><option value="sequential">按列表顺序优先</option>
359 </InlineSelect></label>
360 <label>新会话切换授权<InlineSelect aria-label="新会话切换授权" value={store.scheduling.switch_policy} disabled={busy}
361 onValueChange={switch_policy => perform(() => load({action:"scheduling",scheduling:{...store.scheduling,switch_policy}}))}>
362 <option value="ask">每次询问</option><option value="allow">额度耗尽后自动接续</option><option value="wait">始终等待原账号</option>
363 </InlineSelect></label>
364 <p className="field-help">已有会话保持原账号和授权。自动接续只在限额已确认、原任务可安全停止且目标账号属于同一接续分组时进行;跨账号可能重建缓存。</p>
365 {store.scheduling.mode === "sequential" && accounts?.length > 1 && <div className="claude-account-order" aria-label="账号优先顺序">
366 {accounts.map((profile,index) => <div key={profile.id}><span>{index+1}. {profile.label || profile.email}</span>
367 <button disabled={busy || index===0} aria-label={`提高 ${profile.label} 的优先级`} onClick={() => {
368 const order=accounts.map(a=>a.id); [order[index-1],order[index]]=[order[index],order[index-1]];
369 perform(() => load({action:"scheduling",scheduling:store.scheduling,order}));
370 }}>上移</button></div>)}
371 </div>}
372 </details>
373 <div className="claude-add-profile">
374 <button className="primary" disabled={busy || environmentBusy || !!environment}
375 onClick={() => perform(() => login())}><Plus size={16} />登录新账号</button>
376 </div>
377 {(actionError || error) && <p className="account-error" role="alert">{actionError || error}</p>}
378 {loginNotice && <p className="claude-profile-note" role="status">{loginNotice}</p>}
379 {detectionError && <p className="account-error" role="alert">{detectionError}</p>}
380 {usageUnavailable && !environment && <p className="claude-profile-note" role="status">{usageUnavailable}</p>}
381 {!running ? <p className="claude-profile-note">启动 Cage 环境后可检测普通终端的登录,也可登录新账号。</p> :
382 detectionStatus === "offline" ? <p className="claude-profile-note">工作环境就绪后可检测和登录账号。</p> :
383 detectionStatus === "signed_out" && <p className="claude-profile-note">普通终端尚未登录 Claude 订阅。可在其中运行 <code>claude auth login</code>,登录后会在这里出现。</p>}
384 <div className="claude-list-heading">
385 <h4>账号列表 <span>{visibleProfiles?.length ?? "—"}</span></h4>
386 {requestingUsage || checking ? <small role="status">{requestingUsage ? "正在请求账号用量…" : "正在查询账号用量…"}</small> :
387 accounts?.length > 0 && <small>{accounts.filter((a) => a.enabled).length} 个启用调度</small>}
388 </div>
389 <div className="claude-profile-list" role="region" aria-label="账号列表" tabIndex={0}>
390 {accounts === null && !error && <p role="status">正在读取账号…</p>}
391 {accounts?.length === 0 && !detected && <div className="claude-profile-empty">
392 <img src={crabIcon} alt="" /><p>尚无已加入调度的账号。</p><small>加入第一个账号前,新终端沿用环境原有的登录。</small>
393 </div>}
394 <QuotaClock accounts={visibleProfiles}>
395 {detected && <DetectedProfile key={detected.identity} profile={detected} usageEnvironment={usageEnvironment} busy={busy || environmentBusy || !!environment}
396 perform={perform} change={load}
397 join={() => perform(joinDetected)} />}
398 {accounts?.map((profile) => <ProfileCard key={profile.id} profile={profile} environment={environment} usageEnvironment={usageEnvironment}
399 busy={busy || environmentBusy} perform={perform} change={load} login={login} cancelDraft={cancelDraft}
400 active={activeCounts.get(profile.id)?.all || 0} defaultActive={activeCounts.get(profile.id)?.fromDefault || 0} />)}
401 </QuotaClock>
402 </div>
403 </section>;
404}