跳到主要内容

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

浏览文件

mobile_cli_http.go

466 行 · 14.4 KB历史下载
1package workbench
2
3import (
4 "errors"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10 "unicode/utf8"
11)
12
13func (s *Server) mobileCLIRoutes(mux routeRegistrar) {
14 // Desktop history follows the selected local or SSH host. Mobile routes
15 // remain pinned to the paired computer by the remote gateway.
16 mux.HandleFunc("GET /api/cli/sessions", s.mobileSessions)
17 mux.HandleFunc("GET /api/cli/sessions/{id}", s.mobileSessionView)
18 mux.HandleFunc("POST /api/cli/sessions/{id}/open", s.mobileOpenTerminal)
19 mux.HandleFunc("POST /api/cli/sessions/{id}/metadata", s.mobileSessionMetadata)
20 mux.HandleFunc("POST /api/cli/sessions/{id}/account", s.mobileSessionAccount)
21 mux.HandleFunc("POST /api/cli/sessions/{id}/archive", s.mobileArchiveSession)
22 mux.HandleFunc("POST /api/cli/sessions/{id}/restore", s.mobileRestoreSession)
23 mux.HandleFunc("POST /api/cli/sessions/{id}/purge", s.mobilePurgeSession)
24 mux.HandleFunc("GET /api/mobile/cli/projects", s.mobileProjects)
25 mux.HandleFunc("GET /api/mobile/cli/sessions", s.mobileSessions)
26 mux.HandleFunc("POST /api/mobile/cli/sessions", s.mobileNewSession)
27 mux.HandleFunc("GET /api/mobile/cli/sessions/{id}", s.mobileSessionView)
28 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/media", s.mobileSessionMedia)
29 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/messages", s.mobileMessage)
30 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/stop", s.mobileStop)
31 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/approval", s.mobileApprovalResponse)
32 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/open", s.mobileOpenTerminal)
33 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/metadata", s.mobileSessionMetadata)
34 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/account", s.mobileSessionAccount)
35 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/delete", s.mobileArchiveSession)
36 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/archive", s.mobileArchiveSession)
37 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/restore", s.mobileRestoreSession)
38 mux.HandleFunc("POST /api/mobile/cli/sessions/{id}/purge", s.mobilePurgeSession)
39}
40
41func (s *Server) mobileOpenTerminal(w http.ResponseWriter, r *http.Request) {
42 var input struct {
43 Automatic bool `json:"automatic"`
44 }
45 if !readJSON(w, r, &input) {
46 return
47 }
48 s.mobileConnectMu.Lock()
49 defer s.mobileConnectMu.Unlock()
50 view, ok := s.authorizedMobileSession(w, r)
51 if !ok {
52 return
53 }
54 if !s.isTerminalConversation(view.ID) {
55 if err := s.promoteMobileConversation(r.Context(), view.ID); err != nil {
56 http.Error(w, err.Error(), 409)
57 return
58 }
59 }
60 s.mobileCLI.mu.Lock()
61 record, err := s.mobileCLI.record(s.profile, view.ID)
62 s.mobileCLI.mu.Unlock()
63 if err != nil {
64 http.Error(w, "无法读取会话", 500)
65 return
66 }
67 existing := s.terminals.get(record.TerminalID)
68 needsTerminal := existing == nil || !existing.ownsConversation()
69 if needsTerminal {
70 s.mu.Lock()
71 launcher := claudeTerminalCommand(s.preferences)
72 s.mu.Unlock()
73 if !sharedCLILauncher(launcher) || record.Launcher != "" && launcher != record.Launcher {
74 http.Error(w, "主机启动命令与原会话不一致,请恢复原配置后重试", 422)
75 return
76 }
77 }
78 if (record.Resume || record.Connection != "") && needsTerminal {
79 var state struct {
80 Running bool `json:"running"`
81 ChannelReady bool `json:"channel_ready"`
82 Error string `json:"error"`
83 }
84 mode := "active"
85 if input.Automatic {
86 if err := s.terminals.canStart(); err != nil {
87 http.Error(w, err.Error(), 409)
88 return
89 }
90 mode = "handoff"
91 }
92 query := map[string]any{"cli_id": record.CLIID, "config": record.GuestConfig, "workspace": record.GuestWorkspace}
93 if err := s.windowsConversationInput(record, query); err != nil {
94 http.Error(w, err.Error(), http.StatusConflict)
95 return
96 }
97 if err := s.runCLIChannel(r.Context(), mode, query, &state); err != nil {
98 http.Error(w, err.Error(), 503)
99 return
100 }
101 if state.Error != "" {
102 http.Error(w, state.Error, 409)
103 return
104 }
105 if state.Running {
106 if input.Automatic {
107 if state.ChannelReady {
108 var result struct {
109 OK bool `json:"ok"`
110 }
111 resume := map[string]any{"cli_id": record.CLIID, "connection": record.Connection, "action": "resume"}
112 if err := s.windowsConversationInput(record, resume); err != nil {
113 http.Error(w, err.Error(), http.StatusConflict)
114 return
115 }
116 if err := s.runCLIChannel(r.Context(), "rpc", resume, &result); err != nil || !result.OK {
117 http.Error(w, "会话恢复暂未完成,请重试", 503)
118 return
119 }
120 }
121 view.ConnectionWaiting = true
122 jsonReply(w, view)
123 return
124 }
125 http.Error(w, "原会话仍在电脑终端运行,请先退出其中的 Claude Code,再接续同一段历史", 409)
126 return
127 }
128 }
129 terminal, err := s.createTerminal(terminalRequest{Workspace: view.Workspace, Kind: "claude", sharedID: view.ID, requestContext: r.Context()})
130 if err != nil {
131 http.Error(w, err.Error(), 409)
132 return
133 }
134 view.DesktopTerminalID = terminal.id
135 if input.Automatic {
136 view, err = s.terminalConversationView(r.Context(), view.ID)
137 if err != nil {
138 http.Error(w, err.Error(), 503)
139 return
140 }
141 }
142 jsonReply(w, view)
143}
144
145func (s *Server) mobileApprovalResponse(w http.ResponseWriter, r *http.Request) {
146 view, ok := s.authorizedMobileSession(w, r)
147 if !ok {
148 return
149 }
150 var input struct {
151 TurnID string `json:"request_id"`
152 ApprovalID string `json:"approval_id"`
153 Allow *bool `json:"allow"`
154 }
155 if !readJSON(w, r, &input) {
156 return
157 }
158 if !mobileID(input.TurnID) || !mobileID(input.ApprovalID) || input.Allow == nil {
159 http.Error(w, "需要本次操作的完整确认", 400)
160 return
161 }
162 if s.isTerminalConversation(view.ID) {
163 if len(view.Turns) == 0 || view.Turns[len(view.Turns)-1].ID != input.TurnID {
164 http.Error(w, "审批轮次已变化,请重新读取会话", 409)
165 return
166 }
167 result, err := s.terminalConversationAction(r.Context(), view.ID, map[string]any{"action": "approve", "approval_id": input.ApprovalID, "allow": *input.Allow})
168 if err != nil {
169 http.Error(w, err.Error(), 409)
170 return
171 }
172 jsonReply(w, result)
173 return
174 }
175 // Serialize the actual decision with explicit account locking. Do not
176 // retain either mutex while writing the HTTP response.
177 s.account.mu.Lock()
178 if !s.mobileAuthorized(r.Context()) {
179 s.account.mu.Unlock()
180 http.Error(w, "请先解锁 Cage", 423)
181 return
182 }
183 m := &s.mobileCLI
184 m.mu.Lock()
185 run := m.active[view.ID]
186 if run != nil && run.pending != nil && run.pending.ctx.Err() == nil {
187 turn := &run.record.Turns[len(run.record.Turns)-1]
188 if turn.ID == input.TurnID && turn.Status == "running" && turn.Approval != nil && turn.Approval.ID == input.ApprovalID {
189 run.pending.reply <- *input.Allow
190 run.pending = nil
191 turn.Approval = nil
192 run.record.changed()
193 view = run.record.snapshot()
194 m.mu.Unlock()
195 s.account.mu.Unlock()
196 jsonReply(w, view)
197 return
198 }
199 }
200 m.mu.Unlock()
201 s.account.mu.Unlock()
202 http.Error(w, "这项请求已结束或由其他设备处理,请重新读取会话", 409)
203}
204func (s *Server) mobileProjects(w http.ResponseWriter, r *http.Request) {
205 if s.windowsGuest != nil {
206 s.refreshWindowsComponents()
207 }
208 paths, err := s.projectPaths()
209 if err != nil {
210 http.Error(w, "无法读取已授权的项目", 500)
211 return
212 }
213 var projects = []map[string]string{}
214 for _, path := range paths {
215 projects = append(projects, map[string]string{"path": path, "name": filepath.Base(path)})
216 }
217 s.mu.Lock()
218 ready := s.ready && !s.closing
219 shared := sharedCLILauncher(claudeTerminalCommand(s.preferences))
220 if s.windowsGuest != nil {
221 available := s.windowsCapabilitiesLocked()["available"].(map[string]bool)
222 shared = shared && available["cli"] && available["terminal"] && available["projects"]
223 }
224 s.mu.Unlock()
225 name, _ := os.Hostname()
226 jsonReply(w, map[string]any{"projects": projects, "ready": ready, "host": name, "shared_sessions": shared})
227}
228func (s *Server) mobileSessions(w http.ResponseWriter, r *http.Request) {
229 paths, err := s.projectPaths()
230 if err != nil {
231 http.Error(w, "无法读取已授权的项目", 500)
232 return
233 }
234 granted := map[string]bool{}
235 for _, path := range paths {
236 granted[path] = true
237 }
238 archived := r.URL.Query().Get("archived") == "true"
239 sessions, err := s.mobileCLI.summaries(s.profile, granted, archived)
240 if err != nil {
241 http.Error(w, "无法读取主机上的 CLI 会话记录", 500)
242 return
243 }
244 var notice string
245 if err := s.discoverTerminalConversations(r.Context(), paths); err != nil {
246 notice = err.Error()
247 } else {
248 sessions, err = s.mobileCLI.summaries(s.profile, granted, archived)
249 if err != nil {
250 http.Error(w, "无法读取主机上的 CLI 会话记录", 500)
251 return
252 }
253 }
254 s.mu.Lock()
255 ready := s.ready && !s.closing
256 s.mu.Unlock()
257 if !ready || notice != "" {
258 for i := range sessions {
259 sessions[i].Active = false
260 }
261 }
262 jsonReply(w, map[string]any{"sessions": sessions, "notice": notice})
263}
264func (s *Server) mobileNewSession(w http.ResponseWriter, r *http.Request) {
265 var input struct {
266 ID string `json:"id"`
267 Workspace string `json:"workspace"`
268 Shared bool `json:"shared"` // Accepted for old clients; the host always creates a common session.
269 }
270 if !readJSON(w, r, &input) {
271 return
272 }
273 if !mobileID(input.ID) || input.Workspace == "" {
274 http.Error(w, "需要项目和有效的创建编号", 400)
275 return
276 }
277 workspace, err := s.projectWorkspace(input.Workspace)
278 if err != nil {
279 http.Error(w, "项目未授权或已不可用", 403)
280 return
281 }
282 s.mu.Lock()
283 shared := sharedCLILauncher(claudeTerminalCommand(s.preferences))
284 s.mu.Unlock()
285 if !shared {
286 http.Error(w, "当前启动命令无法连接手机,请在主机使用 claude 或 ccs 配置名", 409)
287 return
288 }
289 s.account.mu.Lock()
290 if !s.mobileAuthorized(r.Context()) {
291 s.account.mu.Unlock()
292 http.Error(w, errMobileLocked.Error(), 423)
293 return
294 }
295 view, err := s.mobileCLI.create(s.profile, workspace, input.ID)
296 s.account.mu.Unlock()
297 if err != nil {
298 http.Error(w, "无法创建会话,请检查编号、磁盘和目录权限", 409)
299 return
300 }
301 // Older phones do not send shared. The host chooses the common session
302 // implementation, so updating only the computer still fixes new sessions.
303 if len(view.Turns) == 0 {
304 if _, err := s.createTerminal(terminalRequest{Workspace: workspace, Kind: "claude", sharedID: view.ID, requestContext: r.Context()}); err != nil {
305 http.Error(w, err.Error(), 409)
306 return
307 }
308 s.mobileCLI.mu.Lock()
309 record, err := s.mobileCLI.record(s.profile, view.ID)
310 if err == nil {
311 view = record.snapshot()
312 }
313 s.mobileCLI.mu.Unlock()
314 }
315 jsonReply(w, view)
316}
317func (s *Server) authorizedMobileSession(w http.ResponseWriter, r *http.Request) (mobileSession, bool) {
318 view, terminal, ok := s.authorizedMobileSessionRecord(w, r)
319 if !ok {
320 return view, false
321 }
322 if view.Archived {
323 http.Error(w, "此会话已归档,请先在设置中的已归档会话撤销归档", http.StatusGone)
324 return view, false
325 }
326 if terminal {
327 var err error
328 view, err = s.terminalConversationView(r.Context(), view.ID)
329 if err != nil {
330 http.Error(w, err.Error(), 503)
331 return view, false
332 }
333 }
334 return view, true
335}
336
337// List operations need only the host record; an ended guest terminal need not
338// be reachable to rename, pin, or remove it.
339func (s *Server) authorizedMobileSessionRecord(w http.ResponseWriter, r *http.Request) (mobileSession, bool, bool) {
340 id := r.PathValue("id")
341 m := &s.mobileCLI
342 m.mu.Lock()
343 record, err := m.record(s.profile, id)
344 var view mobileSession
345 if err == nil {
346 if record.Deleted {
347 err = os.ErrNotExist
348 }
349 view = record.snapshot()
350 }
351 m.mu.Unlock()
352 if errors.Is(err, os.ErrNotExist) {
353 http.NotFound(w, r)
354 return view, false, false
355 }
356 if err != nil {
357 http.Error(w, "无法读取主机上的 CLI 会话记录", 500)
358 return view, false, false
359 }
360 if _, err := s.projectWorkspace(view.Workspace); err != nil {
361 http.Error(w, "项目未授权或已不可用", 403)
362 return view, false, false
363 }
364 return view, record.Terminal, true
365}
366func (s *Server) mobileSessionView(w http.ResponseWriter, r *http.Request) {
367 view, ok := s.authorizedMobileSession(w, r)
368 if !ok {
369 return
370 }
371 if value := r.URL.Query().Get("after"); value != "" {
372 revision, err := strconv.ParseUint(value, 10, 64)
373 if err != nil {
374 http.Error(w, "会话版本无效", 400)
375 return
376 }
377 epoch := r.URL.Query().Get("epoch")
378 if epoch != "" && !mobileID(epoch) {
379 http.Error(w, "服务标识无效", 400)
380 return
381 }
382 if revision == view.Revision && (epoch == "" || epoch == view.Generation) {
383 w.WriteHeader(http.StatusNoContent)
384 return
385 }
386 }
387 jsonReply(w, view)
388}
389func (s *Server) mobileMessage(w http.ResponseWriter, r *http.Request) {
390 view, ok := s.authorizedMobileSession(w, r)
391 if !ok {
392 return
393 }
394 var input struct {
395 ID string `json:"request_id"`
396 Text string `json:"text"`
397 }
398 if !readJSON(w, r, &input, 72<<10) {
399 return
400 }
401 if !mobileID(input.ID) || strings.TrimSpace(input.Text) == "" || len(input.Text) > mobilePromptLimit || !utf8.ValidString(input.Text) {
402 http.Error(w, "需要有效的发送编号和 32 KiB 以内的消息", 400)
403 return
404 }
405 if s.isTerminalConversation(view.ID) {
406 result, err := s.terminalConversationAction(r.Context(), view.ID, map[string]any{"action": "send", "request_id": input.ID, "text": input.Text})
407 if err != nil {
408 http.Error(w, err.Error(), 409)
409 return
410 }
411 jsonReply(w, result)
412 return
413 }
414 result, err := s.submitMobileTurn(r.Context(), view.ID, input.ID, input.Text)
415 if err != nil {
416 if errors.Is(err, errTerminalBusy) {
417 http.Error(w, "主机正在处理其他请求,请保留发送编号重试", http.StatusServiceUnavailable)
418 return
419 }
420 if errors.Is(err, errMobileLocked) {
421 http.Error(w, err.Error(), http.StatusLocked)
422 return
423 }
424 http.Error(w, err.Error(), 409)
425 return
426 }
427 jsonReply(w, result)
428}
429func (s *Server) mobileStop(w http.ResponseWriter, r *http.Request) {
430 view, ok := s.authorizedMobileSession(w, r)
431 if !ok {
432 return
433 }
434 var input struct {
435 ID string `json:"request_id"`
436 }
437 if !readJSON(w, r, &input) {
438 return
439 }
440 if !mobileID(input.ID) {
441 http.Error(w, "执行编号无效", 400)
442 return
443 }
444 if s.isTerminalConversation(view.ID) {
445 result, err := s.stopTerminalConversation(r.Context(), view, input.ID)
446 if err != nil {
447 http.Error(w, err.Error(), 409)
448 return
449 }
450 jsonReply(w, result)
451 return
452 }
453 s.account.mu.Lock()
454 if !s.mobileAuthorized(r.Context()) {
455 s.account.mu.Unlock()
456 http.Error(w, errMobileLocked.Error(), http.StatusLocked)
457 return
458 }
459 result, err := s.stopMobileTurn(view.ID, input.ID)
460 s.account.mu.Unlock()
461 if err != nil {
462 http.Error(w, "未找到这次执行", 404)
463 return
464 }
465 jsonReply(w, result)
466}