跳到主要内容

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

浏览文件

claude_switch.go

471 行 · 15.5 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "net/http"
7 "strings"
8 "time"
9
10 "github.com/google/uuid"
11)
12
13type claudeSwitchInput struct {
14 Action string `json:"action"`
15 Policy string `json:"policy"`
16 Target string `json:"target"`
17 RequestID string `json:"request_id"`
18 SourceID string `json:"source_id"`
19 Confirm bool `json:"confirm"`
20 Continue bool `json:"continue"`
21}
22
23type claudeSwitchOption struct {
24 ID string `json:"id"`
25 Label string `json:"label"`
26}
27
28func validSwitchPolicy(policy string) bool {
29 return policy == "ask" || policy == "allow" || policy == "wait"
30}
31
32// Explicit groups prevent a work transcript from silently moving to a personal
33// identity. Empty groups never authorize a cross-account transfer.
34func switchCandidates(list claudeAccountList, record *mobileRecord) []claudeSwitchOption {
35 options := []claudeSwitchOption{}
36 source := list.find(record.Account.ID)
37 if source == nil || source.HandoffGroup == "" || source.guestID() != record.Account.GuestID || claudeIdentityHash(source.Email, source.Organization) != record.Account.Subject {
38 return options
39 }
40 for _, a := range list.Accounts {
41 _, available := a.headroom(time.Now())
42 if a.ID != source.ID && a.Enabled && a.Status == "ready" && a.HandoffGroup == source.HandoffGroup && available {
43 options = append(options, claudeSwitchOption{a.ID, a.Label})
44 }
45 }
46 return options
47}
48
49func (s *Server) mobileSessionAccount(w http.ResponseWriter, r *http.Request) {
50 view, terminal, ok := s.authorizedMobileSessionRecord(w, r)
51 if !ok {
52 return
53 }
54 var input claudeSwitchInput
55 if !readJSON(w, r, &input) {
56 return
57 }
58 if input.Action == "switch" {
59 if !input.Confirm || !mobileID(input.RequestID) || !validCLIUUID(input.SourceID) {
60 http.Error(w, "请确认本次账号接续并提供当前会话标识", 400)
61 return
62 }
63 if err := s.switchClaudeAccount(r.Context(), view.ID, input, false); err != nil {
64 http.Error(w, err.Error(), 409)
65 return
66 }
67 } else if input.Action == "cancel" {
68 if err := s.cancelClaudeSwitch(r.Context(), view.ID, input.RequestID); err != nil {
69 http.Error(w, err.Error(), 409)
70 return
71 }
72 } else if input.Action == "policy" {
73 if !validSwitchPolicy(input.Policy) {
74 http.Error(w, "切换授权无效", 400)
75 return
76 }
77 if !s.op.TryLock() {
78 http.Error(w, errTerminalBusy.Error(), 409)
79 return
80 }
81 defer s.op.Unlock()
82 s.account.mu.Lock()
83 if !s.mobileAuthorized(r.Context()) {
84 s.account.mu.Unlock()
85 http.Error(w, errMobileLocked.Error(), 423)
86 return
87 }
88 s.mobileCLI.mu.Lock()
89 record, err := s.mobileCLI.record(s.profile, view.ID)
90 if err == nil {
91 if record.Switch != nil && record.Switch.Phase != "completed" {
92 err = errors.New("账号交接中,请等待完成后修改授权")
93 } else {
94 record.SwitchPolicy = input.Policy
95 record.changed()
96 err = writePrivate(mobileRecordPath(s.profile, view.ID), record)
97 }
98 }
99 s.mobileCLI.mu.Unlock()
100 s.account.mu.Unlock()
101 if err != nil {
102 requestError(w, err)
103 return
104 }
105 } else if input.Action != "inspect" {
106 http.Error(w, "未知账号操作", 400)
107 return
108 }
109 if terminal {
110 if _, err := s.terminalConversationView(r.Context(), view.ID); err != nil && input.Action != "inspect" {
111 http.Error(w, err.Error(), 503)
112 return
113 }
114 }
115 s.claudeAccounts.mu.Lock()
116 list, err := s.loadClaudeAccounts()
117 s.claudeAccounts.mu.Unlock()
118 if err != nil {
119 requestError(w, err)
120 return
121 }
122 s.mobileCLI.mu.Lock()
123 record, err := s.mobileCLI.record(s.profile, view.ID)
124 if err != nil {
125 s.mobileCLI.mu.Unlock()
126 requestError(w, err)
127 return
128 }
129 if a := list.find(record.Account.ID); a != nil {
130 record.AccountLabel = a.Label
131 }
132 snapshot := record.snapshot()
133 policy := record.SwitchPolicy
134 if policy == "" {
135 policy = list.Scheduling.SwitchPolicy
136 }
137 sourceID := record.CLIID
138 options := switchCandidates(list, record)
139 supported := record.Terminal && record.Launcher == "claude" && record.Account.ID != ""
140 s.mobileCLI.mu.Unlock()
141 jsonReply(w, map[string]any{"session": snapshot, "source_id": sourceID, "switch_policy": policy, "candidates": options, "supported": supported})
142}
143
144func (s *Server) switchClaudeAccount(ctx context.Context, id string, input claudeSwitchInput, automatic bool) error {
145 if !s.op.TryLock() {
146 return errTerminalBusy
147 }
148 defer s.op.Unlock()
149 s.conversationMu.Lock()
150 defer s.conversationMu.Unlock()
151 s.account.mu.Lock()
152 allowed := s.mobileAuthorized(ctx)
153 s.account.mu.Unlock()
154 if !allowed {
155 return errMobileLocked
156 }
157 s.mu.Lock()
158 ready := s.ready && !s.closing && !s.guestUpdateRequired && claudeTerminalCommand(s.preferences) == "claude"
159 s.mu.Unlock()
160 if !ready {
161 return errTerminalNotReady
162 }
163 s.claudeAccounts.mu.Lock()
164 list, err := s.loadClaudeAccounts()
165 s.claudeAccounts.mu.Unlock()
166 if err != nil {
167 return err
168 }
169 m := &s.mobileCLI
170 m.mu.Lock()
171 record, err := m.record(s.profile, id)
172 m.mu.Unlock()
173 if err != nil {
174 return err
175 }
176 if record.Archived || record.Deleted || !record.Terminal || record.Launcher != "claude" {
177 return errors.New("此会话不能进行账号接续")
178 }
179 if sw := record.Switch; sw != nil && sw.ID == input.RequestID && sw.Phase == "completed" {
180 return nil
181 }
182 if record.Switch != nil && record.Switch.Phase != "completed" && record.Switch.ID != input.RequestID {
183 return errors.New("已有账号交接待恢复,请重试原操作")
184 }
185 if input.SourceID != record.CLIID && (record.Switch == nil || record.Switch.ID != input.RequestID || record.Switch.Source.CLIID != input.SourceID) {
186 return errors.New("会话账号已变化,请刷新后确认")
187 }
188 if record.Switch == nil || record.Switch.ID != input.RequestID {
189 if automatic {
190 policy := record.SwitchPolicy
191 if policy == "" {
192 policy = list.Scheduling.SwitchPolicy
193 }
194 a := list.find(record.Account.ID)
195 if policy != "allow" || record.AccountFailure != "rate_limit" || a == nil {
196 return errors.New("当前会话需要手动确认切换")
197 }
198 if _, available := a.headroom(time.Now()); available {
199 return errors.New("尚未确认订阅额度耗尽,保留原账号")
200 }
201 }
202 found := false
203 for _, option := range switchCandidates(list, record) {
204 if option.ID == input.Target {
205 found = true
206 }
207 }
208 if !found {
209 return errors.New("目标账号不可用,请将允许接续的账号设置为同一分组并检查额度")
210 }
211 a := list.find(input.Target)
212 selection := claudeSelection{ID: a.ID, GuestID: a.guestID(), Subject: claudeIdentityHash(a.Email, a.Organization)}
213 // Check the official CLI identity before stopping any existing work.
214 status, probeErr := s.probeClaude(ctx, selection.GuestID)
215 if probeErr != nil || status.subject() != selection.Subject {
216 return errors.New("无法确认目标账号登录,请先检查账号状态")
217 }
218 sourceStatus, sourceErr := s.probeClaude(ctx, record.Account.GuestID)
219 if sourceErr != nil || sourceStatus.subject() != record.Account.Subject {
220 return errors.New("原账号身份已改变,请先检查原会话登录")
221 }
222 record.Switch = &claudeAccountSwitch{ID: input.RequestID, Phase: "preparing", Source: claudeExecution{record.CLIID, record.Account, record.GuestConfig}, Target: selection, TargetLabel: a.Label, TargetID: uuid.NewString(), Connection: record.Connection, Continue: input.Continue}
223 if err := s.saveClaudeSwitch(record); err != nil {
224 return err
225 }
226 }
227 sw := record.Switch
228 fail := func(err error) error { sw.Error = err.Error(); _ = s.saveClaudeSwitch(record); return err }
229 if sw.Phase == "preparing" {
230 // Authorization can be revoked or the target identity can change while
231 // an interrupted preparation is waiting for a retry.
232 target := list.find(sw.Target.ID)
233 eligible := false
234 for _, option := range switchCandidates(list, record) {
235 eligible = eligible || option.ID == sw.Target.ID
236 }
237 if !eligible || target == nil || target.guestID() != sw.Target.GuestID || claudeIdentityHash(target.Email, target.Organization) != sw.Target.Subject {
238 return fail(errors.New("目标账号或接续分组已变化,请取消本次交接后重新选择"))
239 }
240 status, err := s.probeClaude(ctx, sw.Target.GuestID)
241 if err != nil || status.subject() != sw.Target.Subject {
242 return fail(errors.New("目标账号登录已变化,请取消交接后检查账号"))
243 }
244 var result struct {
245 Transcript string `json:"transcript"`
246 Error string `json:"error"`
247 }
248 if sw.Source.Config == "" || sw.Connection == "" {
249 return fail(errors.New("原会话连接尚未就绪,请先打开原会话"))
250 }
251 query := map[string]any{"cli_id": sw.Source.CLIID, "config": sw.Source.Config, "connection": sw.Connection, "workspace": record.GuestWorkspace, "target_cli_id": sw.TargetID, "switch_id": sw.ID}
252 if err := s.windowsConversationInput(record, query); err != nil {
253 return fail(err)
254 }
255 err = s.runCLIChannel(ctx, "account-switch", query, &result)
256 if err != nil {
257 return fail(err)
258 }
259 if result.Error != "" {
260 return fail(errors.New(result.Error))
261 }
262 if !strings.HasPrefix(result.Transcript, "/") && !(s.windowsGuest != nil && windowsCLIAbsolutePath(result.Transcript)) {
263 return fail(errors.New("原会话历史未确认,未启动目标账号"))
264 }
265 if old := s.terminals.get(record.TerminalID); old != nil {
266 s.terminals.remove(old.id)
267 }
268 record.Executions = append(record.Executions, sw.Source)
269 record.CLIID, record.Account, record.AccountLabel = sw.TargetID, sw.Target, sw.TargetLabel
270 record.GuestConfig, record.Connection, record.TerminalID = "", "", ""
271 record.Resume, record.TerminalRunning, record.Active = false, false, false
272 record.ResumeTranscript = result.Transcript
273 record.AccountFailure = ""
274 sw.Phase, sw.Error = "prepared", ""
275 if err := s.saveClaudeSwitch(record); err != nil {
276 return err
277 }
278 }
279 if sw.Phase == "prepared" {
280 // Treat a previous launch with unknown HTTP outcome as owned until its
281 // PTY or the guest registry proves otherwise. The connection UUID is
282 // deterministic for this switch, and guest launch also rejects duplicates.
283 var state struct {
284 Running bool `json:"running"`
285 }
286 query := map[string]any{"cli_id": record.CLIID, "config": record.GuestConfig, "account": record.Account.GuestID}
287 if err := s.windowsConversationInput(record, query); err != nil {
288 return fail(err)
289 }
290 if err := s.runCLIChannel(ctx, "active", query, &state); err != nil {
291 return fail(err)
292 }
293 if state.Running {
294 sw.Phase = "starting"
295 return s.saveClaudeSwitch(record)
296 }
297 status, err := s.probeClaude(ctx, record.Account.GuestID)
298 if err != nil || status.subject() != record.Account.Subject {
299 return fail(errors.New("目标账号身份无法确认,保留待恢复历史"))
300 }
301 _, err = s.createTerminalLocked(terminalRequest{Workspace: record.Workspace, Kind: "claude", sharedID: id, requestContext: ctx})
302 if err != nil {
303 return fail(err)
304 }
305 // A launched process may outlive the HTTP request. Never launch it again
306 // while its published PTY or guest registry can still own this execution.
307 m.mu.Lock()
308 latest, loadErr := m.record(s.profile, id)
309 m.mu.Unlock()
310 if loadErr != nil {
311 return loadErr
312 }
313 record = latest
314 record.Switch.Phase = "starting"
315 if err := s.saveClaudeSwitch(record); err != nil {
316 return err
317 }
318 }
319 return nil
320}
321
322func (s *Server) cancelClaudeSwitch(ctx context.Context, id, requestID string) error {
323 if !s.op.TryLock() {
324 return errTerminalBusy
325 }
326 defer s.op.Unlock()
327 s.conversationMu.Lock()
328 defer s.conversationMu.Unlock()
329 s.account.mu.Lock()
330 allowed := s.mobileAuthorized(ctx)
331 s.account.mu.Unlock()
332 if !allowed {
333 return errMobileLocked
334 }
335 s.mobileCLI.mu.Lock()
336 record, err := s.mobileCLI.record(s.profile, id)
337 s.mobileCLI.mu.Unlock()
338 if err != nil {
339 return err
340 }
341 if record.Switch == nil {
342 return nil
343 }
344 sw := record.Switch
345 if sw.ID != requestID || sw.Phase != "preparing" {
346 return errors.New("目标账号已接管历史,请在当前会话继续")
347 }
348 var response struct {
349 OK bool `json:"ok"`
350 Error string `json:"error"`
351 }
352 query := map[string]any{"cli_id": sw.Source.CLIID, "connection": sw.Connection, "switch_id": sw.ID}
353 if err := s.windowsConversationInput(record, query); err != nil {
354 return err
355 }
356 if err := s.runCLIChannel(ctx, "account-switch-cancel", query, &response); err != nil {
357 return err
358 }
359 if !response.OK {
360 return errors.New(response.Error)
361 }
362 record.Switch = nil
363 return s.saveClaudeSwitch(record)
364}
365
366// Preserve metadata written concurrently while committing execution ownership.
367func (s *Server) saveClaudeSwitch(record *mobileRecord) error {
368 m := &s.mobileCLI
369 m.mu.Lock()
370 defer m.mu.Unlock()
371 current, err := m.record(s.profile, record.ID)
372 if err != nil {
373 return err
374 }
375 record.CustomTitle, record.Pinned, record.Archived, record.Deleted = current.CustomTitle, current.Pinned, current.Archived, current.Deleted
376 record.SwitchPolicy = current.SwitchPolicy
377 record.Revision = current.Revision
378 record.changed()
379 return writePrivate(mobileRecordPath(s.profile, record.ID), record)
380}
381
382func (s *Server) monitorClaudeAccount(terminal *terminalSession, id string) {
383 ctx, cancel := context.WithCancel(s.lifetimeContext())
384 s.activities.Add(1)
385 go func() {
386 defer s.activities.Done()
387 defer cancel()
388 var lastUsageCheck time.Time
389 ticker := time.NewTicker(10 * time.Second)
390 defer ticker.Stop()
391 for {
392 select {
393 case <-ctx.Done():
394 return
395 case <-terminal.done:
396 return
397 case <-ticker.C:
398 }
399 epoch, ok := s.account.access()
400 if !ok {
401 continue
402 }
403 // Locking pauses observation; unlocking resumes it for the same
404 // terminal. Cancel an in-flight attempt if its access epoch ends.
405 attempt, finish := context.WithCancel(context.WithValue(ctx, mobileEpochKey{}, epoch))
406 stop := context.AfterFunc(epoch, finish)
407 s.maybeSwitchClaudeAccount(attempt, id, &lastUsageCheck)
408 stop()
409 finish()
410 }
411 }()
412}
413
414func (s *Server) maybeSwitchClaudeAccount(ctx context.Context, id string, lastUsageCheck *time.Time) {
415 view, err := s.terminalConversationView(ctx, id)
416 if err != nil || view.AccountFailure != "rate_limit" || view.SwitchPolicy != "allow" || view.AccountSwitch != nil && view.AccountSwitch.Phase != "completed" {
417 return
418 }
419 s.claudeAccounts.mu.Lock()
420 list, err := s.loadClaudeAccounts()
421 s.claudeAccounts.mu.Unlock()
422 if err != nil {
423 return
424 }
425 s.mobileCLI.mu.Lock()
426 record, err := s.mobileCLI.record(s.profile, id)
427 s.mobileCLI.mu.Unlock()
428 if err != nil {
429 return
430 }
431 options := switchCandidates(list, record)
432 if len(options) == 0 {
433 return
434 }
435 // One bounded quota refresh on the failure path. The CLI owns this
436 // query and its tokens; no model prompt is generated for probing.
437 if time.Since(*lastUsageCheck) >= claudeUsageInterval {
438 *lastUsageCheck = time.Now()
439 _ = s.refreshClaudeUsage(ctx, claudeAccountInput{Action: "refresh", ID: record.Account.ID})
440 }
441 // Apply the same scheduling mode to eligible handoff targets.
442 candidates := claudeAccountList{Scheduling: list.Scheduling}
443 for _, a := range list.Accounts {
444 for _, option := range options {
445 if option.ID == a.ID {
446 candidates.Accounts = append(candidates.Accounts, a)
447 }
448 }
449 }
450 active := s.mobileCLI.activeAccounts()
451 logins := make(map[string]bool)
452 for _, terminal := range s.terminals.snapshot() {
453 if terminal["closed"] == true {
454 continue
455 }
456 account, _ := terminal["claude_account_id"].(string)
457 if terminal["kind"] == "claude-login" {
458 logins[account] = true
459 } else {
460 active[account]++
461 }
462 }
463 s.claudeAccounts.mu.Lock()
464 last := s.claudeAccounts.lastPick
465 s.claudeAccounts.mu.Unlock()
466 target := pickClaudeAccount(candidates, active, logins, last, "", time.Now())
467 if target == "" {
468 return
469 }
470 _ = s.switchClaudeAccount(ctx, id, claudeSwitchInput{RequestID: uuid.NewString(), SourceID: record.CLIID, Target: target, Continue: true}, true)
471}