| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os/exec" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | "al.essio.dev/pkg/shellescape" |
| 14 | ) |
| 15 | |
| 16 | var ( |
| 17 | errTerminalsClosed = errors.New("后台正在退出,请重新打开 Cage。") |
| 18 | errTerminalBusy = errors.New("环境正在执行其他操作") |
| 19 | errTerminalNotReady = errors.New("环境尚未就绪或正在重启") |
| 20 | errTerminalLimit = errors.New("最多保留 12 个终端,请先关闭不用的会话") |
| 21 | errTerminalStart = errors.New("无法创建终端连接") |
| 22 | ) |
| 23 | |
| 24 | type terminalRequest struct { |
| 25 | Workspace string `json:"workspace"` |
| 26 | Kind string `json:"kind"` |
| 27 | ClaudeAccountID string `json:"claude_account_id"` |
| 28 | sharedID string |
| 29 | requestContext context.Context |
| 30 | } |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | type terminalManager struct { |
| 36 | mu sync.Mutex |
| 37 | sessions map[string]*terminalSession |
| 38 | sequence int |
| 39 | closed bool |
| 40 | workers sync.WaitGroup |
| 41 | } |
| 42 | |
| 43 | func (m *terminalManager) startSession(cmd *exec.Cmd, workspace, kind string, selection claudeSelection, finished func()) (*terminalSession, error) { |
| 44 | return m.startSessionWithPTY(cmd, workspace, kind, selection, finished, func() (terminalPTY, error) { return startTerminal(cmd, 100, 30) }) |
| 45 | } |
| 46 | |
| 47 | func (m *terminalManager) startSessionWithPTY(cmd *exec.Cmd, workspace, kind string, selection claudeSelection, finished func(), start func() (terminalPTY, error)) (*terminalSession, error) { |
| 48 | m.mu.Lock() |
| 49 | defer m.mu.Unlock() |
| 50 | if err := m.admissionErrorLocked(); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | file, err := start() |
| 54 | if err != nil { |
| 55 | return nil, errTerminalStart |
| 56 | } |
| 57 | m.sequence++ |
| 58 | title := fmt.Sprintf("终端 %d", m.sequence) |
| 59 | if kind == "claude" { |
| 60 | title = fmt.Sprintf("Claude %d", m.sequence) |
| 61 | } else if kind == "claude-login" { |
| 62 | title = "Claude 账号登录" |
| 63 | } |
| 64 | session := newTerminalSession(file) |
| 65 | session.id, session.title, session.workspace, session.cmd = randomToken()[:16], title, workspace, cmd |
| 66 | session.kind, session.claudeAccountID = kind, selection.ID |
| 67 | if kind == "claude-login" { |
| 68 | session.loginGuestID = selection.GuestID |
| 69 | } |
| 70 | if selection.GuestID == "default" { |
| 71 | session.claudeAccountSource = "default" |
| 72 | } else if selection.ID != "" { |
| 73 | session.claudeAccountSource = "managed" |
| 74 | } |
| 75 | if m.sessions == nil { |
| 76 | m.sessions = make(map[string]*terminalSession) |
| 77 | } |
| 78 | m.sessions[session.id] = session |
| 79 | m.workers.Add(1) |
| 80 | go func() { |
| 81 | defer m.workers.Done() |
| 82 | session.run() |
| 83 | if finished != nil { |
| 84 | finished() |
| 85 | } |
| 86 | }() |
| 87 | return session, nil |
| 88 | } |
| 89 | |
| 90 | func (m *terminalManager) admissionErrorLocked() error { |
| 91 | if m.closed { |
| 92 | return errTerminalsClosed |
| 93 | } |
| 94 | if len(m.sessions) >= 12 { |
| 95 | return errTerminalLimit |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | func (m *terminalManager) canStart() error { |
| 101 | m.mu.Lock() |
| 102 | defer m.mu.Unlock() |
| 103 | return m.admissionErrorLocked() |
| 104 | } |
| 105 | |
| 106 | func (m *terminalManager) snapshot() []map[string]any { |
| 107 | m.mu.Lock() |
| 108 | defer m.mu.Unlock() |
| 109 | out := make([]map[string]any, 0, len(m.sessions)) |
| 110 | for _, session := range m.sessions { |
| 111 | out = append(out, session.summary()) |
| 112 | } |
| 113 | return out |
| 114 | } |
| 115 | |
| 116 | func (m *terminalManager) hasLive() bool { |
| 117 | m.mu.Lock() |
| 118 | defer m.mu.Unlock() |
| 119 | for _, session := range m.sessions { |
| 120 | session.mu.Lock() |
| 121 | closed := session.closed |
| 122 | session.mu.Unlock() |
| 123 | if !closed { |
| 124 | return true |
| 125 | } |
| 126 | if session.done != nil { |
| 127 | select { |
| 128 | case <-session.done: |
| 129 | default: |
| 130 | return true |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | return false |
| 135 | } |
| 136 | |
| 137 | func (m *terminalManager) get(id string) *terminalSession { |
| 138 | m.mu.Lock() |
| 139 | defer m.mu.Unlock() |
| 140 | return m.sessions[id] |
| 141 | } |
| 142 | |
| 143 | func (m *terminalManager) forConversation(connection string) *terminalSession { |
| 144 | m.mu.Lock() |
| 145 | defer m.mu.Unlock() |
| 146 | for _, session := range m.sessions { |
| 147 | session.mu.Lock() |
| 148 | matches := session.connectionID == connection && !session.closed |
| 149 | session.mu.Unlock() |
| 150 | if matches { |
| 151 | return session |
| 152 | } |
| 153 | } |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | |
| 158 | |
| 159 | func (m *terminalManager) existingClaudeLogin(id string, login bool) (*terminalSession, error) { |
| 160 | m.mu.Lock() |
| 161 | defer m.mu.Unlock() |
| 162 | for _, session := range m.sessions { |
| 163 | if session.claudeAccountID != id { |
| 164 | continue |
| 165 | } |
| 166 | select { |
| 167 | case <-session.done: |
| 168 | continue |
| 169 | default: |
| 170 | } |
| 171 | if session.kind == "claude-login" && login { |
| 172 | return session, nil |
| 173 | } |
| 174 | if login || session.kind == "claude-login" { |
| 175 | return nil, errors.New("请先结束此账号的登录或运行中的终端,再更改登录身份") |
| 176 | } |
| 177 | } |
| 178 | return nil, nil |
| 179 | } |
| 180 | |
| 181 | func (m *terminalManager) remove(id string) { |
| 182 | m.mu.Lock() |
| 183 | session := m.sessions[id] |
| 184 | m.mu.Unlock() |
| 185 | if session != nil { |
| 186 | |
| 187 | session.close() |
| 188 | m.mu.Lock() |
| 189 | delete(m.sessions, id) |
| 190 | m.mu.Unlock() |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | func (m *terminalManager) closeAll() { |
| 198 | m.mu.Lock() |
| 199 | sessions := make([]*terminalSession, 0, len(m.sessions)) |
| 200 | for _, session := range m.sessions { |
| 201 | sessions = append(sessions, session) |
| 202 | } |
| 203 | m.mu.Unlock() |
| 204 | for _, session := range sessions { |
| 205 | session.close() |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func (m *terminalManager) close() { |
| 210 | m.mu.Lock() |
| 211 | m.closed = true |
| 212 | m.mu.Unlock() |
| 213 | m.closeAll() |
| 214 | |
| 215 | m.workers.Wait() |
| 216 | } |
| 217 | |
| 218 | func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) { |
| 219 | if !s.op.TryLock() { |
| 220 | return nil, errTerminalBusy |
| 221 | } |
| 222 | defer s.op.Unlock() |
| 223 | return s.createTerminalLocked(input) |
| 224 | } |
| 225 | |
| 226 | |
| 227 | func (s *Server) createTerminalLocked(input terminalRequest) (*terminalSession, error) { |
| 228 | if s.windowsGuest != nil { |
| 229 | return s.createWindowsTerminal(input) |
| 230 | } |
| 231 | var sharedRecord *mobileRecord |
| 232 | if input.sharedID != "" { |
| 233 | s.mobileCLI.mu.Lock() |
| 234 | record, err := s.mobileCLI.record(s.profile, input.sharedID) |
| 235 | s.mobileCLI.mu.Unlock() |
| 236 | if err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | sharedRecord = record |
| 240 | if record.Switch != nil && record.Switch.Phase == "preparing" { |
| 241 | return nil, errors.New("账号交接尚未完成,请先重试或取消交接") |
| 242 | } |
| 243 | if record.Archived || record.Deleted { |
| 244 | return nil, errors.New("此会话已归档或删除,请先从已归档会话恢复") |
| 245 | } |
| 246 | |
| 247 | |
| 248 | if existing := s.terminals.get(record.TerminalID); existing != nil && existing.ownsConversation() { |
| 249 | return existing, nil |
| 250 | } |
| 251 | if existing := s.terminals.get(record.TerminalID); existing != nil && existing.summary()["closed"] == true { |
| 252 | s.terminals.remove(record.TerminalID) |
| 253 | } |
| 254 | } |
| 255 | s.mu.Lock() |
| 256 | closing := s.closing |
| 257 | componentUpdate := s.guestUpdateRequired |
| 258 | command := claudeTerminalCommand(s.preferences) |
| 259 | s.mu.Unlock() |
| 260 | if closing { |
| 261 | return nil, errTerminalsClosed |
| 262 | } |
| 263 | if sharedRecord != nil && (!sharedCLILauncher(command) || sharedRecord.Launcher != "" && sharedRecord.Launcher != command) { |
| 264 | return nil, errors.New("主机启动命令与原会话不一致,请恢复原配置后重试") |
| 265 | } |
| 266 | if s.macosGuest != nil { |
| 267 | if input.Kind == "claude" && !sharedCLILauncher(command) { |
| 268 | return nil, errors.New("macOS 客机支持 claude 或 ccs 配置名启动命令") |
| 269 | } |
| 270 | s.mu.Lock() |
| 271 | ready := s.ready |
| 272 | s.mu.Unlock() |
| 273 | if !ready { |
| 274 | return nil, errTerminalNotReady |
| 275 | } |
| 276 | } |
| 277 | if !s.vmRunning() || s.busy() { |
| 278 | return nil, errTerminalNotReady |
| 279 | } |
| 280 | |
| 281 | |
| 282 | if input.Kind != "claude-login" { |
| 283 | if err := s.terminals.canStart(); err != nil { |
| 284 | return nil, err |
| 285 | } |
| 286 | } |
| 287 | if input.Kind != "" && input.Kind != "shell" && input.Kind != "claude" && input.Kind != "claude-login" { |
| 288 | return nil, errors.New("终端类型无效") |
| 289 | } |
| 290 | managed := input.Kind == "claude" || input.Kind == "claude-login" |
| 291 | if !managed && input.ClaudeAccountID != "" { |
| 292 | return nil, errors.New("普通终端不能指定 Claude 账号") |
| 293 | } |
| 294 | |
| 295 | |
| 296 | workspace := s.workspace() |
| 297 | var err error |
| 298 | if input.Kind != "claude-login" { |
| 299 | if s.macOSLegacyWorkspace(sharedRecord) != "" { |
| 300 | workspace, err = s.projectWorkspace(sharedRecord.Workspace) |
| 301 | } else { |
| 302 | workspace, err = s.connectProject(input.Workspace, false) |
| 303 | } |
| 304 | if err != nil { |
| 305 | return nil, err |
| 306 | } |
| 307 | } |
| 308 | script := terminalScript(s.cliWorkspace(workspace), input.Kind, command) |
| 309 | if s.macosGuest != nil { |
| 310 | script = `cd -- "$HOME" && exec env TERM=xterm-256color COLORTERM=truecolor /bin/zsh -l` |
| 311 | if input.Kind != "claude-login" { |
| 312 | script = "exec /usr/local/libexec/cage-macos-terminal " + shellescape.Quote(macOSProjectPath(s.macosGuest.User, workspace)) |
| 313 | } |
| 314 | } |
| 315 | var selection claudeSelection |
| 316 | var finished func() |
| 317 | if managed { |
| 318 | login := input.Kind == "claude-login" |
| 319 | if sharedRecord != nil && sharedRecord.Terminal { |
| 320 | selection = sharedRecord.Account |
| 321 | } else { |
| 322 | selection, err = s.selectTerminalClaudeAccount(command, input.ClaudeAccountID, login, workspace) |
| 323 | } |
| 324 | if err != nil { |
| 325 | return nil, err |
| 326 | } |
| 327 | if selection.ID != "" { |
| 328 | if componentUpdate { |
| 329 | return nil, errGuestUpdateRequired |
| 330 | } |
| 331 | if !validClaudeID(selection.ID) || !validClaudeGuestID(selection.GuestID) || (login && selection.GuestID == "default") { |
| 332 | return nil, errors.New("Claude 账号 ID 无效") |
| 333 | } |
| 334 | if login && s.mobileCLI.activeAccounts()[selection.ID] > 0 { |
| 335 | return nil, errors.New("请先结束该账号正在执行的移动 CLI 轮次,再重新登录") |
| 336 | } |
| 337 | if existing, conflict := s.terminals.existingClaudeLogin(selection.ID, login); existing != nil || conflict != nil { |
| 338 | return existing, conflict |
| 339 | } |
| 340 | if !login && selection.Subject == "" { |
| 341 | return nil, errors.New("Claude 账号状态已变化,请重试") |
| 342 | } |
| 343 | script = managedClaudeTerminalScript(s.cliWorkspace(workspace), command, selection.GuestID, selection.Subject, login) |
| 344 | if login { |
| 345 | if s.macosGuest != nil { |
| 346 | ctx, cancel := context.WithTimeout(s.lifetimeContext(), 20*time.Second) |
| 347 | _, browserErr := s.guestAPI(ctx, "", "GET", "/health", nil) |
| 348 | cancel() |
| 349 | if browserErr != nil { |
| 350 | return nil, errors.New("客机登录浏览器尚未就绪,请恢复浏览器连接后重试") |
| 351 | } |
| 352 | } |
| 353 | finished = func() { |
| 354 | ctx, cancel := context.WithTimeout(s.lifetimeContext(), 12*time.Second) |
| 355 | defer cancel() |
| 356 | _ = s.confirmClaudeLogin(ctx, selection.ID) |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | var conversation *mobileRecord |
| 362 | if input.Kind == "claude" && sharedCLILauncher(command) { |
| 363 | script, conversation, err = s.prepareTerminalConversation(workspace, selection, input.sharedID) |
| 364 | if err != nil { |
| 365 | return nil, err |
| 366 | } |
| 367 | } |
| 368 | cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", script) |
| 369 | if input.requestContext != nil { |
| 370 | s.account.mu.Lock() |
| 371 | if !s.mobileAuthorized(input.requestContext) { |
| 372 | s.account.mu.Unlock() |
| 373 | return nil, errMobileLocked |
| 374 | } |
| 375 | } |
| 376 | session, err := s.terminals.startSession(cmd, workspace, input.Kind, selection, finished) |
| 377 | if input.requestContext != nil { |
| 378 | s.account.mu.Unlock() |
| 379 | } |
| 380 | if err == nil && conversation != nil { |
| 381 | session.mu.Lock() |
| 382 | session.sharedID = conversation.ID |
| 383 | session.connectionID = conversation.Connection |
| 384 | session.mu.Unlock() |
| 385 | s.mobileCLI.mu.Lock() |
| 386 | conversation.TerminalID = session.id |
| 387 | if saveErr := writePrivate(mobileRecordPath(s.profile, conversation.ID), conversation); saveErr != nil { |
| 388 | err = saveErr |
| 389 | } |
| 390 | s.mobileCLI.mu.Unlock() |
| 391 | if err != nil { |
| 392 | s.terminals.remove(session.id) |
| 393 | return nil, err |
| 394 | } |
| 395 | s.prepareCLIConnection(session, conversation.ID) |
| 396 | s.monitorClaudeAccount(session, conversation.ID) |
| 397 | } |
| 398 | if err == nil && input.Kind == "claude" && selection.ID != "" { |
| 399 | s.noteClaudeSelection(selection.ID, workspace) |
| 400 | } |
| 401 | return session, err |
| 402 | } |
| 403 | |
| 404 | func validClaudeGuestID(id string) bool { return id == "default" || validClaudeID(id) } |
| 405 | |
| 406 | func (s *Server) selectTerminalClaudeAccount(command, requested string, login bool, workspace string) (claudeSelection, error) { |
| 407 | parts, valid := mobileLaunchArgs(command, claudeSelection{}) |
| 408 | if !login && valid == nil && len(parts) == 2 && parts[0] == "ccs" { |
| 409 | if requested != "" && requested != "auto" { |
| 410 | return claudeSelection{}, errors.New("CCS 使用自己的配置,不能指定 Cage 账号") |
| 411 | } |
| 412 | return claudeSelection{}, nil |
| 413 | } |
| 414 | return s.selectClaudeAccount(requested, login, workspace) |
| 415 | } |
| 416 | |
| 417 | func (s *Server) readClaudeGuestSnapshot(ctx context.Context, id string) (claudeGuestSnapshot, error) { |
| 418 | if s.windowsGuest != nil { |
| 419 | return s.readWindowsClaudeAccount(ctx, "snapshot", id, "") |
| 420 | } |
| 421 | return s.readClaudeGuestReport(ctx, id, claudeSnapshotCommand(id)) |
| 422 | } |
| 423 | |
| 424 | func (s *Server) readClaudeGuestUsage(ctx context.Context, id, subject string) (claudeGuestSnapshot, error) { |
| 425 | if _, err := hex.DecodeString(subject); err != nil || len(subject) != 64 { |
| 426 | return claudeGuestSnapshot{}, errors.New("Claude 账号身份无效") |
| 427 | } |
| 428 | if s.windowsGuest != nil { |
| 429 | return s.readWindowsClaudeAccount(ctx, "usage", id, subject) |
| 430 | } |
| 431 | return s.readClaudeGuestReport(ctx, id, claudeGuestReportCommand(id, subject)) |
| 432 | } |
| 433 | |
| 434 | func (s *Server) readClaudeGuestReport(ctx context.Context, id, command string) (claudeGuestSnapshot, error) { |
| 435 | var snapshot claudeGuestSnapshot |
| 436 | if !validClaudeGuestID(id) { |
| 437 | return snapshot, errors.New("Claude 账号 ID 无效") |
| 438 | } |
| 439 | data, err := s.guest(ctx, command) |
| 440 | if err != nil || json.Unmarshal(data, &snapshot) != nil { |
| 441 | return snapshot, errors.New("无法读取账号状态,请确认环境已启动并同步环境组件") |
| 442 | } |
| 443 | return snapshot, nil |
| 444 | } |
| 445 | |
| 446 | func claudeSnapshotCommand(id string) string { |
| 447 | return claudeGuestReportCommand(id, "") |
| 448 | } |
| 449 | |
| 450 | func claudeGuestReportCommand(id, subject string) string { |
| 451 | command := "exec /usr/local/bin/cage-claude-account snapshot " + id |
| 452 | if subject != "" { |
| 453 | command = "exec /usr/local/bin/cage-claude-account usage " + id + " " + shellescape.Quote(subject) |
| 454 | } |
| 455 | if id == "default" { |
| 456 | |
| 457 | |
| 458 | |
| 459 | command = `set -o pipefail; cd "$HOME" && env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 /bin/bash -lic ` + |
| 460 | shellescape.Quote(`printf '\nCAGE_CLAUDE_SNAPSHOT '; `+command) + |
| 461 | ` | sed -n 's/^CAGE_CLAUDE_SNAPSHOT //p'` |
| 462 | } |
| 463 | return command |
| 464 | } |
| 465 | |
| 466 | func managedClaudeTerminalScript(workspace, command, accountID, subject string, login bool) string { |
| 467 | if login { |
| 468 | return "cd \"$HOME\" && exec /usr/local/bin/cage-claude-account login " + shellescape.Quote(accountID) |
| 469 | } |
| 470 | |
| 471 | |
| 472 | |
| 473 | env := `export CAGE_CLAUDE_ACCOUNT_ID=` + shellescape.Quote(accountID) + |
| 474 | ` CAGE_CLAUDE_SUBJECT=` + shellescape.Quote(subject) + "; " |
| 475 | if accountID != "default" { |
| 476 | env += `export CLAUDE_CONFIG_DIR="$HOME/.local/share/cage/claude-accounts/$CAGE_CLAUDE_ACCOUNT_ID/config"; ` |
| 477 | } |
| 478 | env += `export PATH="/usr/local/lib/cage-claude-bin:$PATH"; ` |
| 479 | body := env + `eval "$CAGE_TERMINAL_COMMAND"; unset CAGE_TERMINAL_COMMAND; exec bash -i` |
| 480 | return "cd " + shellescape.Quote(workspace) + |
| 481 | " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 CAGE_TERMINAL_COMMAND=" + |
| 482 | shellescape.Quote(command) + " bash -lic " + shellescape.Quote(body) |
| 483 | } |
| 484 | |
| 485 | |
| 486 | |
| 487 | func terminalScript(workspace, kind, command string) string { |
| 488 | prefix := "cd " + shellescape.Quote(workspace) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 " |
| 489 | if kind != "claude" { |
| 490 | return prefix + "bash -l" |
| 491 | } |
| 492 | return prefix + "CAGE_TERMINAL_COMMAND=" + shellescape.Quote(command) + " bash -lic " + shellescape.Quote("eval \"$CAGE_TERMINAL_COMMAND\"; unset CAGE_TERMINAL_COMMAND; exec bash -il") |
| 493 | } |