跳到主要内容

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

浏览文件

cli_channel_test.go

980 行 · 36.7 KB历史下载
1//go:build !windows
2
3package workbench
4
5import (
6 "context"
7 "crypto/sha256"
8 "encoding/json"
9 "fmt"
10 "net/http"
11 "net/http/httptest"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "runtime"
17 "strconv"
18 "strings"
19 "sync/atomic"
20 "testing"
21 "time"
22 "unicode/utf16"
23
24 "al.essio.dev/pkg/shellescape"
25 "github.com/google/uuid"
26 "github.com/sylvinus/agent-vm/internal/mobilelink"
27 "github.com/sylvinus/agent-vm/internal/relay"
28 "github.com/sylvinus/agent-vm/internal/remotelink"
29)
30
31func TestCLIChannelProtocol(t *testing.T) {
32 python, err := exec.LookPath("python3")
33 if err != nil {
34 t.Skip("python3 unavailable")
35 }
36 cmd := exec.Command(python, "-I", "cli_channel_test.py")
37 if output, err := cmd.CombinedOutput(); err != nil {
38 t.Fatalf("channel protocol: %v\n%s", err, output)
39 }
40}
41
42func TestCLIChannelCommandFitsWindows(t *testing.T) {
43 // Leave room in CreateProcessW's 32767 UTF-16 limit for SSH paths and the
44 // login-shell quoting around this command.
45 command := cliChannelCommand("launch", `{"id":"`+uuid.NewString()+`","prefix":["claude"]}`)
46 t.Logf("embedded command: %d UTF-16 units", len(utf16.Encode([]rune(command))))
47 if size := len(utf16.Encode([]rune(command))); size > 16000 {
48 t.Fatalf("channel command uses %d UTF-16 units", size)
49 }
50}
51
52func TestSharedSendReceiptSurvivesReadFailure(t *testing.T) {
53 s, id, project := metadataFixture(t)
54 home := t.TempDir()
55 mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin"})
56 record, err := s.mobileCLI.record(s.profile, id)
57 if err != nil {
58 t.Fatal(err)
59 }
60 record.Terminal = true
61 record.Connection = uuid.NewString()
62 record.GuestWorkspace = guestPath(project)
63 if err = writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
64 t.Fatal(err)
65 }
66 // Keep the real host SSH/bootstrap/RPC path; replace only the guest
67 // operation boundary to lose the read immediately after an admitted send.
68 helper := filepath.Join(home, ".local/share/cage/cli-channel-code", fmt.Sprintf("%x.py", sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt))))
69 if err = os.MkdirAll(filepath.Dir(helper), 0700); err != nil {
70 t.Fatal(err)
71 }
72 code := "import json,sys\nrequest=json.load(sys.stdin)\nif sys.argv[1]=='rpc': print(json.dumps({'ok':True}))\nelse: sys.exit(3)\n"
73 if err = os.WriteFile(helper, []byte(code), 0600); err != nil {
74 t.Fatal(err)
75 }
76 epoch, ok := s.account.access()
77 if !ok {
78 t.Fatal("missing unlock epoch")
79 }
80 ctx := context.WithValue(context.Background(), mobileEpochKey{}, epoch)
81 requestID := uuid.NewString()
82 view, err := s.terminalConversationAction(ctx, id, map[string]any{"action": "send", "request_id": requestID, "text": "accepted message"})
83 if err != nil || view.AcknowledgedRequestID != requestID {
84 t.Fatalf("admitted send lost its receipt: %#v %v", view, err)
85 }
86 if len(view.Turns) != len(record.Turns)+1 || view.Turns[len(view.Turns)-1].Text != "" || view.Turns[len(view.Turns)-1].Status != "queued" {
87 t.Fatal("receipt did not preserve the accepted message without inventing a reply")
88 }
89}
90
91func TestSessionCatalogActivity(t *testing.T) {
92 s, id, project := metadataFixture(t)
93 record, err := s.mobileCLI.record(s.profile, id)
94 if err != nil {
95 t.Fatal(err)
96 }
97 record.Terminal = true
98 record.Active = true
99 if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
100 t.Fatal(err)
101 }
102 s.mobileCLI.catalog = nil
103 list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
104 if err != nil || len(list) != 1 || !list[0].Active {
105 t.Fatal("catalog lost task activity", list, err)
106 }
107 record.Terminal = false
108 record.Active = false
109 record.Turns = []mobileTurn{{Status: "running"}}
110 s.mobileCLI.active = map[string]*mobileRun{id: {record: record}}
111 list, err = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
112 if err != nil || !list[0].Active {
113 t.Fatal("mobile turn activity missing", list, err)
114 }
115 record.Turns[0].Status = "completed"
116 list, err = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
117 if err != nil || list[0].Active {
118 t.Fatal("completed turn stayed active", list, err)
119 }
120}
121
122func TestImportedCLIUUIDIsIndependentOfPublicSessionID(t *testing.T) {
123 profile, id := t.TempDir(), uuid.NewString()
124 record := &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: id, Workspace: "/project"}, Turns: []mobileTurn{}}, CLIID: "c4cbf880-92e8-11f1-8596-0242ac120002", Terminal: true}
125 if err := writePrivate(mobileRecordPath(profile, id), record); err != nil {
126 t.Fatal(err)
127 }
128 var store mobileCLIStore
129 if _, err := store.record(profile, id); err != nil {
130 t.Fatal(err)
131 }
132 if mobileID(record.CLIID) {
133 t.Fatal("CLI identity widened the client creation contract")
134 }
135}
136
137func TestArchivedCLIHistoryIsNotRediscovered(t *testing.T) {
138 s, id, project := metadataFixture(t)
139 home, _ := filepath.EvalSymlinks(t.TempDir())
140 bin := filepath.Join(home, "bin")
141 if err := os.MkdirAll(bin, 0700); err != nil {
142 t.Fatal(err)
143 }
144 // This archived history has no live CLI process. Keep the real discovery
145 // helper and SSH path independent of a developer's installed Claude CLI.
146 cli := "#!/bin/sh\n[ \"$#\" -eq 2 ] && [ \"$1\" = agents ] && [ \"$2\" = --json ] || exit 64\nprintf '[]\\n'\n"
147 if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(cli), 0700); err != nil {
148 t.Fatal(err)
149 }
150 if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte("export PATH="+shellescape.Quote(bin)+":/usr/bin:/bin\n"), 0600); err != nil {
151 t.Fatal(err)
152 }
153 mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=" + bin + ":/usr/bin:/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude")})
154 record, err := s.mobileCLI.record(s.profile, id)
155 if err != nil {
156 t.Fatal(err)
157 }
158 history := filepath.Join(home, ".claude", "projects", "fixture", record.CLIID+".jsonl")
159 if err := os.MkdirAll(filepath.Dir(history), 0700); err != nil {
160 t.Fatal(err)
161 }
162 row, _ := json.Marshal(map[string]any{"cwd": guestPath(project), "type": "user", "uuid": uuid.NewString(), "message": map[string]string{"content": "guest title"}})
163 if err := os.WriteFile(history, append(row, '\n'), 0600); err != nil {
164 t.Fatal(err)
165 }
166 if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
167 t.Fatal(err)
168 }
169 s.ready = true
170 if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
171 t.Fatal(err)
172 }
173 if w := request(s, "POST", "/api/mobile/cli/sessions/"+id+"/metadata", s.origin, `{"title":"保留用户命名","pinned":true}`, true); w.Code != 200 {
174 t.Fatal(w.Code, w.Body.String())
175 }
176 if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
177 t.Fatal(err)
178 }
179 list, _ := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
180 if len(list) != 1 || list[0].Title != "保留用户命名" || !list[0].Pinned {
181 t.Fatal("discovery overwrote metadata", list)
182 }
183 if err := s.setSessionArchived(id, true, nil); err != nil {
184 t.Fatal(err)
185 }
186 s.mobileCLI = mobileCLIStore{}
187 if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
188 t.Fatal(err)
189 }
190 if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
191 t.Fatal(err)
192 }
193 list, _ = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
194 if len(list) != 0 {
195 t.Fatal("guest history resurrected deleted entry", list)
196 }
197 if _, err := os.Stat(history); err != nil {
198 t.Fatal("CLI history was removed", err)
199 }
200}
201
202func TestDiscoveryRunningStateUpdatesCatalogAndClearsMissingHistory(t *testing.T) {
203 s, id, project := metadataFixture(t)
204 home, _ := filepath.EvalSymlinks(t.TempDir())
205 mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin"})
206 record, err := s.mobileCLI.record(s.profile, id)
207 if err != nil {
208 t.Fatal(err)
209 }
210 if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
211 t.Fatal(err)
212 }
213 // Keep the host bootstrap and SSH path; substitute the guest's observation.
214 observation := filepath.Join(home, "observation.json")
215 helper := filepath.Join(home, ".local/share/cage/cli-channel-code", fmt.Sprintf("%x.py", sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt))))
216 if err := os.MkdirAll(filepath.Dir(helper), 0700); err != nil {
217 t.Fatal(err)
218 }
219 code := fmt.Sprintf("import json,sys\njson.load(sys.stdin)\nprint(open(%q).read())\n", observation)
220 if err := os.WriteFile(helper, []byte(code), 0600); err != nil {
221 t.Fatal(err)
222 }
223 s.ready = true
224 for _, phase := range []struct{ present, running bool }{{true, true}, {true, false}, {true, true}, {false, false}} {
225 found := []terminalConversation{}
226 if phase.present {
227 found = append(found, terminalConversation{CLIID: record.CLIID, Workspace: guestPath(project), Config: filepath.Join(home, ".claude"), Running: phase.running})
228 }
229 if err := writePrivate(observation, found); err != nil {
230 t.Fatal(err)
231 }
232 if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
233 t.Fatal(err)
234 }
235 list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
236 if err != nil || len(list) != 1 || list[0].Running != phase.running {
237 t.Fatalf("phase %+v: summaries = %+v, error = %v", phase, list, err)
238 }
239 }
240}
241
242func sharedCLIWorkbench(t *testing.T) (*Server, string, *atomic.Bool) {
243 t.Helper()
244 binary, flags := os.Getenv("CAGE_TEST_CLAUDE_CLI"), os.Getenv("CAGE_TEST_CHANNEL_FEATURES")
245 if runtime.GOOS != "darwin" || !filepath.IsAbs(binary) || !filepath.IsAbs(flags) {
246 t.Skip("set CAGE_TEST_CLAUDE_CLI and CAGE_TEST_CHANNEL_FEATURES on macOS for the isolated interactive CLI test")
247 }
248 features, err := os.ReadFile(flags)
249 if err != nil {
250 t.Fatal(err)
251 }
252 var booleans map[string]bool
253 if err := json.Unmarshal(features, &booleans); err != nil {
254 t.Fatal(err)
255 }
256 s := testServer(t)
257 home, _ := filepath.EvalSymlinks(t.TempDir())
258 project, _ := filepath.EvalSymlinks(t.TempDir())
259 s.ready = true
260 s.preferences.Workspace = project
261 if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": project}); err != nil {
262 t.Fatal(err)
263 }
264 bin := filepath.Join(home, "bin")
265 if err := os.Mkdir(bin, 0700); err != nil {
266 t.Fatal(err)
267 }
268 actual, _ := filepath.EvalSymlinks(binary)
269 personal, _ := os.UserHomeDir()
270 quote := func(value string) string { b, _ := json.Marshal(value); return string(b) }
271 policy := "(version 1)(allow default)(deny mach-lookup)(deny file-read-data (subpath " + quote(personal) + ") (subpath \"/Library/Keychains\"))(allow file-read* (literal " + quote(actual) + "))(deny network-outbound)(allow network-outbound (remote ip \"localhost:*\"))"
272 debug := filepath.Join(home, "cli-debug.log")
273 t.Cleanup(func() {
274 if t.Failed() {
275 if data, err := os.ReadFile(debug); err == nil {
276 if len(data) > 16000 {
277 data = data[len(data)-16000:]
278 }
279 t.Log(string(data))
280 }
281 }
282 })
283 shim := "#!/bin/sh\nexec /usr/bin/sandbox-exec -p " + shellescape.Quote(policy) + " " + shellescape.Quote(actual) + " --debug-file " + shellescape.Quote(debug) + " --model sonnet --permission-mode manual \"$@\"\n"
284 if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(shim), 0700); err != nil {
285 t.Fatal(err)
286 }
287 if strings.Contains(t.Name(), "CCS") {
288 // Exercise the profile dispatch boundary with a deterministic dispatcher;
289 // the interactive process and Channels remain the genuine CLI.
290 if err := os.WriteFile(filepath.Join(bin, "ccs"), []byte("#!/bin/sh\n[ \"$1\" = cage-fixture ] || exit 1\nshift\nexec claude \"$@\"\n"), 0700); err != nil {
291 t.Fatal(err)
292 }
293 s.preferences.ClaudeTerminalCommand = "ccs cage-fixture"
294 }
295 if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte("export PATH="+shellescape.Quote(bin)+":/usr/bin:/bin\n"), 0600); err != nil {
296 t.Fatal(err)
297 }
298 key := "sk-ant-local-channel-test"
299 config := map[string]any{"hasCompletedOnboarding": true, "theme": "dark", "cachedGrowthBookFeatures": booleans,
300 "cachedGrowthBookFeaturesAt": time.Now().UnixMilli(), "customApiKeyResponses": map[string]any{"approved": []string{key[len(key)-20:]}, "rejected": []string{}},
301 "projects": map[string]any{project: map[string]bool{"hasTrustDialogAccepted": true}}}
302 if t.Name() == "TestSharedTerminalUntrustedProject" {
303 delete(config, "projects")
304 }
305 for _, path := range []string{filepath.Join(home, ".claude.json"), filepath.Join(home, ".claude", ".claude.json")} {
306 if err := writePrivate(path, config); err != nil {
307 t.Fatal(err)
308 }
309 }
310 var resumed atomic.Bool
311 model := mobileTestModel(t, &resumed)
312 t.Cleanup(model.Close)
313 mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=" + bin + ":/usr/bin:/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude"),
314 "ANTHROPIC_API_KEY=" + key, "ANTHROPIC_BASE_URL=" + model.URL, "DISABLE_AUTOUPDATER=1", "TERM=xterm-256color",
315 "HTTPS_PROXY=http://127.0.0.1:1", "HTTP_PROXY=http://127.0.0.1:1", "NO_PROXY=127.0.0.1,localhost"})
316 // The local SSH stand-in must reap its CLI and hook children before the
317 // isolated home is removed. Closing the host PTY only waits for local SSH.
318 t.Cleanup(func() {
319 deadline := time.Now().Add(3 * time.Second)
320 for time.Now().Before(deadline) {
321 output, _ := exec.Command("pgrep", "-f", regexp.QuoteMeta(home)).Output()
322 if len(strings.TrimSpace(string(output))) == 0 {
323 return
324 }
325 for _, value := range strings.Fields(string(output)) {
326 pid, err := strconv.Atoi(value)
327 if err == nil && pid > 0 {
328 child, _ := os.FindProcess(pid)
329 _ = child.Kill()
330 _ = child.Release()
331 }
332 }
333 time.Sleep(30 * time.Millisecond)
334 }
335 t.Error("isolated CLI children did not exit")
336 })
337 t.Cleanup(s.terminals.closeAll)
338 return s, project, &resumed
339}
340
341func TestSharedTerminalConversation(t *testing.T) {
342 testSharedTerminalConversation(t)
343}
344
345func TestSharedCCSTerminalConversation(t *testing.T) {
346 testSharedTerminalConversation(t)
347}
348
349func testSharedTerminalConversation(t *testing.T) {
350 s, project, resumed := sharedCLIWorkbench(t)
351 originalLauncher := claudeTerminalCommand(s.preferences)
352 if os.Getenv("CAGE_TEST_CHANNEL_BROWSER") != "" {
353 runSharedConversationBrowser(t, s, project)
354 return
355 }
356 api := func(method, path string, body any) mobileSession {
357 t.Helper()
358 data, _ := json.Marshal(body)
359 if body == nil {
360 data = nil
361 }
362 response := request(s, method, "/api/mobile/cli/"+path, s.origin, string(data), true)
363 if response.Code != http.StatusOK {
364 t.Fatalf("%s %s: %d %s", method, path, response.Code, response.Body.String())
365 }
366 var result mobileSession
367 if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
368 t.Fatal(err)
369 }
370 return result
371 }
372 id := uuid.NewString()
373 // A phone built before shared-session negotiation omits the flag.
374 api("POST", "sessions", map[string]any{"id": id, "workspace": project})
375 // A view polled before the guest starts can mark the cached running flag
376 // false. The already published host PTY must remain its sole owner.
377 s.mobileCLI.mu.Lock()
378 starting, err := s.mobileCLI.record(s.profile, id)
379 if err == nil {
380 starting.TerminalRunning = false
381 err = writePrivate(mobileRecordPath(s.profile, id), starting)
382 }
383 s.mobileCLI.mu.Unlock()
384 if err != nil {
385 t.Fatal(err)
386 }
387 if view := api("POST", "sessions", map[string]any{"id": id, "workspace": project, "shared": false}); !view.TerminalAvailable {
388 t.Fatal("a client flag created a phone-only session")
389 }
390 terminals := s.terminals.snapshot()
391 if len(terminals) != 1 || terminals[0]["cli_session_id"] != id {
392 t.Fatalf("mobile creation did not expose its desktop terminal: %#v", terminals)
393 }
394 terminal := s.terminals.get(terminals[0]["id"].(string))
395 deadline := time.Now().Add(30 * time.Second)
396 var current mobileSession
397 wait := func(predicate func(mobileSession) bool) {
398 t.Helper()
399 for time.Now().Before(deadline) {
400 current = api("GET", "sessions/"+id, nil)
401 if predicate(current) {
402 return
403 }
404 time.Sleep(100 * time.Millisecond)
405 }
406 terminal.mu.Lock()
407 defer terminal.mu.Unlock()
408 t.Fatalf("shared conversation did not reach state: %#v\n%s", current, terminal.history)
409 }
410 wait(func(view mobileSession) bool { return view.CanSend != nil && *view.CanSend })
411 turn := uuid.NewString()
412 message := map[string]any{"request_id": turn, "text": "initial mobile prompt"}
413 api("POST", "sessions/"+id+"/messages", message)
414 api("POST", "sessions/"+id+"/messages", message)
415 wait(func(view mobileSession) bool { return len(view.Turns) == 1 && view.Turns[0].Approval != nil })
416 if _, err := os.Stat(filepath.Join(project, "mobile-approved.txt")); !os.IsNotExist(err) {
417 t.Fatal("tool ran before permission")
418 }
419 approval := map[string]any{"request_id": turn, "approval_id": current.Turns[0].Approval.ID, "allow": true}
420 api("POST", "sessions/"+id+"/approval", approval)
421 wait(func(view mobileSession) bool {
422 return len(view.Turns) == 1 && view.Turns[0].Text == "isolated tool completed" && view.Turns[0].Status == "completed"
423 })
424 if err := terminal.enqueueInput(context.Background(), "follow-up\r"); err != nil {
425 t.Fatal(err)
426 }
427 wait(func(view mobileSession) bool {
428 return len(view.Turns) == 2 && view.Turns[1].Prompt == "follow-up" && view.Turns[1].Text == "isolated continuation"
429 })
430 if !resumed.Load() || current.Turns[0].ID != turn {
431 t.Fatal("desktop and mobile diverged or duplicated a request")
432 }
433 listing := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
434 var catalog struct {
435 Sessions []mobileSummary `json:"sessions"`
436 }
437 if err := json.Unmarshal(listing.Body.Bytes(), &catalog); err != nil || len(catalog.Sessions) != 1 || catalog.Sessions[0].ID != id {
438 t.Fatalf("catalog duplicated the terminal: %s", listing.Body.String())
439 }
440 mutate := func(path string, body string) {
441 t.Helper()
442 response := request(s, "POST", path, s.origin, body, true)
443 if response.Code != 200 {
444 t.Fatalf("%s: %d %s", path, response.Code, response.Body.String())
445 }
446 }
447 s.mobileCLI.mu.Lock()
448 record, err := s.mobileCLI.record(s.profile, id)
449 s.mobileCLI.mu.Unlock()
450 if err != nil {
451 t.Fatal(err)
452 }
453 cliID, config := record.CLIID, record.GuestConfig
454 mutate("/api/cli/sessions/"+id+"/archive", `{}`)
455 if len(s.terminals.snapshot()) != 0 {
456 t.Fatal("archive kept its terminal open")
457 }
458 mutate("/api/mobile/cli/sessions/"+id+"/restore", `{}`)
459 s.mu.Lock()
460 s.preferences.ClaudeTerminalCommand = "ccs changed"
461 s.mu.Unlock()
462 if response := request(s, "POST", "/api/mobile/cli/sessions/"+id+"/open", s.origin, `{"automatic":true}`, true); response.Code != 422 || len(s.terminals.snapshot()) != 0 {
463 t.Fatal("changed launcher created a terminal during automatic resume", response.Code)
464 }
465 s.mu.Lock()
466 s.preferences.ClaudeTerminalCommand = originalLauncher
467 s.mu.Unlock()
468 mutate("/api/cli/sessions/"+id+"/open", `{}`)
469 terminals = s.terminals.snapshot()
470 if len(terminals) != 1 {
471 t.Fatal("restore did not open a single terminal")
472 }
473 terminal = s.terminals.get(terminals[0]["id"].(string))
474 deadline = time.Now().Add(30 * time.Second)
475 wait(func(view mobileSession) bool { return view.CanSend != nil && *view.CanSend && len(view.Turns) == 2 })
476 // An acknowledgement lost before archival must not replay a turn after
477 // the same CLI history resumes through its new channel connection.
478 api("POST", "sessions/"+id+"/messages", message)
479 if current = api("GET", "sessions/"+id, nil); len(current.Turns) != 2 {
480 t.Fatal("resume lost message idempotency")
481 }
482 mutate("/api/mobile/cli/sessions/"+id+"/archive", `{}`)
483 purged := false
484 for attempt := 0; attempt < 20; attempt++ {
485 response := request(s, "POST", "/api/cli/sessions/"+id+"/purge", s.origin, `{"confirm":true}`, true)
486 if response.Code == 200 {
487 purged = true
488 break
489 }
490 if attempt == 19 {
491 t.Fatal(response.Code, response.Body.String())
492 }
493 time.Sleep(100 * time.Millisecond)
494 }
495 if !purged {
496 t.Fatal("purge did not complete")
497 }
498 mutate("/api/cli/sessions/"+id+"/purge", `{"confirm":true}`)
499 var removed terminalConversation
500 if err := s.runCLIChannel(context.Background(), "view", map[string]string{"cli_id": cliID, "config": config}, &removed); err != nil || removed.HasHistory || len(removed.Turns) != 0 {
501 t.Fatal("purge retained the CLI transcript", err)
502 }
503 probe := s.sshCommand(context.Background(), "-T", s.sshTarget(), "--", "claude --resume "+cliID+" --print")
504 output, err := probe.CombinedOutput()
505 if err == nil || !strings.Contains(strings.ToLower(string(output)), "no conversation found") {
506 t.Fatalf("Claude still resumed the deleted transcript: %v %s", err, output)
507 }
508 if response := request(s, "POST", "/api/cli/sessions/"+id+"/restore", s.origin, `{}`, true); response.Code != 404 {
509 t.Fatal("purged history was restored", response.Code)
510 }
511 s.account.lock()
512 if response := request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true); response.Code != 423 {
513 t.Fatal("lock did not revoke mobile access", response.Code)
514 }
515}
516
517func TestLegacyMobileSessionOpensOnDesktop(t *testing.T) {
518 s, project, _ := sharedCLIWorkbench(t)
519 id, requestID := uuid.NewString(), uuid.NewString()
520 if _, err := s.mobileCLI.create(s.profile, project, id); err != nil {
521 t.Fatal(err)
522 }
523 path := "/api/mobile/cli/sessions/" + id
524 body, _ := json.Marshal(map[string]string{"request_id": requestID, "text": "follow-up"})
525 if w := request(s, "POST", path+"/messages", s.origin, string(body), true); w.Code != 200 {
526 t.Fatal(w.Code, w.Body.String())
527 }
528 deadline := time.Now().Add(30 * time.Second)
529 read := func() mobileSession {
530 t.Helper()
531 w := request(s, "GET", path, s.origin, "", true)
532 if w.Code != 200 {
533 t.Fatal(w.Code, w.Body.String())
534 }
535 var view mobileSession
536 if err := json.Unmarshal(w.Body.Bytes(), &view); err != nil {
537 t.Fatal(err)
538 }
539 return view
540 }
541 for {
542 view := read()
543 if len(view.Turns) == 1 && view.Turns[0].Status == "completed" {
544 break
545 }
546 if time.Now().After(deadline) {
547 t.Fatalf("legacy turn did not finish: %#v", view)
548 }
549 time.Sleep(100 * time.Millisecond)
550 }
551 w := request(s, "POST", "/api/cli/sessions/"+id+"/open", s.origin, "{}", true)
552 if w.Code != 200 {
553 t.Fatal("desktop open", w.Code, w.Body.String())
554 }
555 var opened mobileSession
556 if err := json.Unmarshal(w.Body.Bytes(), &opened); err != nil {
557 t.Fatal(err)
558 }
559 terminal := s.terminals.get(opened.DesktopTerminalID)
560 if terminal == nil || terminal.sharedID != id {
561 t.Fatal("desktop did not attach the original session")
562 }
563 for {
564 view := read()
565 if view.CanSend != nil && *view.CanSend {
566 if len(view.Turns) != 1 || view.Turns[0].ID != requestID {
567 t.Fatalf("history changed: %#v", view)
568 }
569 break
570 }
571 if time.Now().After(deadline) {
572 t.Fatalf("adopted terminal not ready: %#v", view)
573 }
574 time.Sleep(100 * time.Millisecond)
575 }
576 // Retrying a pre-upgrade request acknowledges it without sending it again.
577 if w := request(s, "POST", path+"/messages", s.origin, string(body), true); w.Code != 200 || !strings.Contains(w.Body.String(), requestID) {
578 t.Fatal(w.Code, w.Body.String())
579 }
580 if view := read(); len(view.Turns) != 1 {
581 t.Fatal("old request was replayed", view)
582 }
583 newBody, _ := json.Marshal(map[string]string{"request_id": uuid.NewString(), "text": "follow-up"})
584 if w := request(s, "POST", path+"/messages", s.origin, string(newBody), true); w.Code != 200 {
585 t.Fatal(w.Code, w.Body.String())
586 }
587 for {
588 view := read()
589 if len(view.Turns) == 2 && view.Turns[1].Status == "completed" {
590 break
591 }
592 if time.Now().After(deadline) {
593 t.Fatalf("shared continuation failed: %#v", view)
594 }
595 time.Sleep(100 * time.Millisecond)
596 }
597}
598
599func TestFailedLegacyMobileSessionOpensOnDesktop(t *testing.T) {
600 s, project, _ := sharedCLIWorkbench(t)
601 id := uuid.NewString()
602 if _, err := s.mobileCLI.create(s.profile, project, id); err != nil {
603 t.Fatal(err)
604 }
605 record, err := s.mobileCLI.record(s.profile, id)
606 if err != nil {
607 t.Fatal(err)
608 }
609 record.Launcher = "claude"
610 record.Turns = []mobileTurn{{ID: uuid.NewString(), Prompt: "original failed message", Status: "failed", Error: "preflight failed"}}
611 if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
612 t.Fatal(err)
613 }
614 w := request(s, "POST", "/api/cli/sessions/"+id+"/open", s.origin, "{}", true)
615 if w.Code != 200 {
616 t.Fatal(w.Code, w.Body.String())
617 }
618 deadline := time.Now().Add(25 * time.Second)
619 for {
620 w = request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true)
621 if w.Code != 200 {
622 t.Fatal(w.Code, w.Body.String())
623 }
624 var view mobileSession
625 if err := json.Unmarshal(w.Body.Bytes(), &view); err != nil {
626 t.Fatal(err)
627 }
628 if view.CanSend != nil && *view.CanSend {
629 if len(view.Turns) != 1 || view.Turns[0].Error != "preflight failed" {
630 t.Fatalf("cached failure lost: %#v", view)
631 }
632 return
633 }
634 if time.Now().After(deadline) {
635 t.Fatalf("failed legacy session never became usable: %#v", view)
636 }
637 time.Sleep(100 * time.Millisecond)
638 }
639}
640
641func TestImportAndResumeDesktopConversation(t *testing.T) {
642 s, project, resumed := sharedCLIWorkbench(t)
643 cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", terminalScript(guestPath(project), "claude", "claude"))
644 original, err := s.terminals.startSession(cmd, project, "claude", claudeSelection{}, nil)
645 if err != nil {
646 t.Fatal(err)
647 }
648 deadline := time.Now().Add(60 * time.Second)
649 strip := regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]|\s+`)
650 waitScreen := func(terminal *terminalSession, phrase string) {
651 t.Helper()
652 var text string
653 for time.Now().Before(deadline) {
654 terminal.mu.Lock()
655 text = strip.ReplaceAllString(string(terminal.history), "")
656 terminal.mu.Unlock()
657 if strings.Contains(text, phrase) {
658 return
659 }
660 time.Sleep(50 * time.Millisecond)
661 }
662 if len(text) > 6000 {
663 text = text[len(text)-6000:]
664 }
665 t.Fatalf("terminal did not show %q: %s", phrase, text)
666 }
667 waitScreen(original, "manualmodeon")
668 _ = original.enqueueInput(context.Background(), "initial mobile prompt\r")
669 waitScreen(original, "Doyouwanttoproceed?")
670 waitScreen(original, "Tabtoamend")
671 // The interactive permission dialog ignores keys during its opening guard.
672 time.Sleep(700 * time.Millisecond)
673 _ = original.enqueueInput(context.Background(), "1\r")
674 waitScreen(original, "isolatedtoolcompleted")
675 var catalog struct {
676 Sessions []mobileSummary `json:"sessions"`
677 }
678 for time.Now().Before(deadline) {
679 response := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
680 if response.Code != 200 {
681 t.Fatal(response.Code, response.Body.String())
682 }
683 if err := json.Unmarshal(response.Body.Bytes(), &catalog); err != nil {
684 t.Fatal(err)
685 }
686 if len(catalog.Sessions) == 1 {
687 break
688 }
689 time.Sleep(100 * time.Millisecond)
690 }
691 if len(catalog.Sessions) != 1 {
692 t.Fatal("desktop history was not discovered")
693 }
694 id := catalog.Sessions[0].ID
695 path := "/api/mobile/cli/sessions/" + id
696 before := request(s, "GET", path, s.origin, "", true)
697 var view mobileSession
698 if before.Code != 200 || json.Unmarshal(before.Body.Bytes(), &view) != nil || len(view.Turns) != 1 || view.CanSend == nil || *view.CanSend {
699 t.Fatalf("unexpected imported history: %s", before.Body.String())
700 }
701 if response := request(s, "POST", path+"/open", s.origin, "{}", true); response.Code != 409 {
702 t.Fatal("opened a second live process for the same CLI history", response.Code)
703 }
704 var opened bool
705 for time.Now().Before(deadline) {
706 response := request(s, "POST", path+"/open", s.origin, `{"automatic":true}`, true)
707 if response.Code == 200 {
708 opened = true
709 break
710 }
711 if response.Code != 409 {
712 t.Fatal(response.Code, response.Body.String())
713 }
714 time.Sleep(100 * time.Millisecond)
715 }
716 if !opened {
717 original.mu.Lock()
718 output := strip.ReplaceAllString(string(original.history), "")
719 original.mu.Unlock()
720 t.Fatalf("original CLI did not exit: %s", output)
721 }
722 s.mobileCLI.mu.Lock()
723 record, err := s.mobileCLI.record(s.profile, id)
724 s.mobileCLI.mu.Unlock()
725 if err != nil {
726 t.Fatal(err)
727 }
728 terminal := s.terminals.get(record.TerminalID)
729 if terminal == nil || terminal == original {
730 t.Fatal("history did not open in a shared terminal")
731 }
732 for time.Now().Before(deadline) {
733 response := request(s, "GET", path, s.origin, "", true)
734 if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && view.CanSend != nil && *view.CanSend {
735 break
736 }
737 time.Sleep(100 * time.Millisecond)
738 }
739 message, _ := json.Marshal(map[string]string{"request_id": uuid.NewString(), "text": "follow-up"})
740 if response := request(s, "POST", path+"/messages", s.origin, string(message), true); response.Code != 200 {
741 t.Fatal(response.Code, response.Body.String())
742 }
743 for time.Now().Before(deadline) {
744 response := request(s, "GET", path, s.origin, "", true)
745 if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 2 && view.Turns[1].Text == "isolated continuation" {
746 if !resumed.Load() {
747 t.Fatal("resumed CLI lost the desktop context")
748 }
749 return
750 }
751 time.Sleep(100 * time.Millisecond)
752 }
753 t.Fatalf("resumed history did not finish: %#v", view)
754}
755
756func TestSharedTerminalUntrustedProject(t *testing.T) {
757 s, project, _ := sharedCLIWorkbench(t)
758 // Start without a CLI trust entry; Cage's project grant is sufficient for
759 // its own startup, without granting any tools or external MCP servers.
760 id := uuid.NewString()
761 body, _ := json.Marshal(map[string]any{"id": id, "workspace": project, "shared": true})
762 response := request(s, "POST", "/api/mobile/cli/sessions", s.origin, string(body), true)
763 if response.Code != 200 {
764 t.Fatal(response.Code, response.Body.String())
765 }
766 deadline := time.Now().Add(35 * time.Second)
767 for time.Now().Before(deadline) {
768 response = request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true)
769 var view mobileSession
770 if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && view.CanSend != nil && *view.CanSend {
771 return
772 }
773 time.Sleep(100 * time.Millisecond)
774 }
775 for _, summary := range s.terminals.snapshot() {
776 terminal := s.terminals.get(summary["id"].(string))
777 terminal.mu.Lock()
778 t.Log(cliStartupText(terminal.history))
779 terminal.mu.Unlock()
780 }
781 t.Fatal("untrusted project startup required desktop input")
782}
783
784func TestSharedTerminalStartupBrowser(t *testing.T) {
785 if os.Getenv("CAGE_TEST_CHANNEL_BROWSER") == "" {
786 t.Skip("set browser and isolated CLI fixture inputs")
787 }
788 s, project, _ := sharedCLIWorkbench(t)
789 server := httptest.NewServer(s.handler())
790 defer server.Close()
791 s.origin = server.URL
792 ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
793 defer cancel()
794 input, _ := json.Marshal(map[string]string{"origin": s.origin, "cookie": s.cookieName(), "session": s.session, "project": project})
795 driver := exec.CommandContext(ctx, "node", "../../ui/scripts/terminal-startup-live-smoke.mjs")
796 driver.Stdin = strings.NewReader(string(input))
797 if output, err := driver.CombinedOutput(); err != nil {
798 t.Fatalf("startup browser: %v\n%s", err, output)
799 } else {
800 t.Log(string(output))
801 }
802}
803
804func TestWaitingDesktopApprovalMovesToPhone(t *testing.T) {
805 s, project, _ := sharedCLIWorkbench(t)
806 cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", terminalScript(guestPath(project), "claude", "claude"))
807 original, err := s.terminals.startSession(cmd, project, "claude", claudeSelection{}, nil)
808 if err != nil {
809 t.Fatal(err)
810 }
811 deadline := time.Now().Add(45 * time.Second)
812 waitScreen := func(phrase string) {
813 t.Helper()
814 for time.Now().Before(deadline) {
815 original.mu.Lock()
816 text := cliStartupText(original.history)
817 original.mu.Unlock()
818 if strings.Contains(text, phrase) {
819 return
820 }
821 time.Sleep(50 * time.Millisecond)
822 }
823 t.Fatal("legacy CLI did not show ", phrase)
824 }
825 waitScreen("manualmodeon")
826 if err := original.enqueueInput(context.Background(), "initial mobile prompt\r"); err != nil {
827 t.Fatal(err)
828 }
829 waitScreen("Tabtoamend")
830 // Give the CLI's supported agent registry time to publish the dialog state.
831 for time.Now().Before(deadline) {
832 probe := s.sshCommand(context.Background(), "-T", s.sshTarget(), "--", "claude agents --json")
833 data, err := probe.Output()
834 if err != nil {
835 t.Fatal(err)
836 }
837 var rows []struct {
838 Status string `json:"status"`
839 }
840 if json.Unmarshal(data, &rows) == nil && len(rows) == 1 && rows[0].Status == "waiting" {
841 break
842 }
843 time.Sleep(100 * time.Millisecond)
844 }
845 listing := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
846 var catalog struct {
847 Sessions []mobileSummary `json:"sessions"`
848 }
849 if listing.Code != 200 || json.Unmarshal(listing.Body.Bytes(), &catalog) != nil || len(catalog.Sessions) != 1 {
850 t.Fatal("missing legacy history", listing.Body.String())
851 }
852 path := "/api/mobile/cli/sessions/" + catalog.Sessions[0].ID
853 opened := request(s, "POST", path+"/open", s.origin, `{"automatic":true}`, true)
854 if opened.Code != 200 {
855 t.Fatal(opened.Code, opened.Body.String())
856 }
857 var view mobileSession
858 for time.Now().Before(deadline) {
859 response := request(s, "GET", path, s.origin, "", true)
860 if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 1 && view.Turns[0].Approval != nil {
861 break
862 }
863 time.Sleep(100 * time.Millisecond)
864 }
865 if len(view.Turns) != 1 || view.Turns[0].Approval == nil {
866 t.Fatalf("phone did not receive fresh approval: %#v", view)
867 }
868 if view.Turns[0].Prompt != "initial mobile prompt" {
869 t.Fatal("internal reconnect notice leaked into the conversation")
870 }
871 if strings.Contains(view.Turns[0].Text, "No response requested.") {
872 t.Fatal("synthetic restart message leaked into the conversation")
873 }
874 if _, err := os.Stat(filepath.Join(project, "mobile-approved.txt")); !os.IsNotExist(err) {
875 t.Fatal("handoff approved the tool")
876 }
877 body, _ := json.Marshal(map[string]any{"request_id": view.Turns[0].ID, "approval_id": view.Turns[0].Approval.ID, "allow": true})
878 response := request(s, "POST", path+"/approval", s.origin, string(body), true)
879 if response.Code != 200 {
880 t.Fatal(response.Code, response.Body.String())
881 }
882 for time.Now().Before(deadline) {
883 response = request(s, "GET", path, s.origin, "", true)
884 if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 1 && view.Turns[0].Status == "completed" {
885 if data, err := os.ReadFile(filepath.Join(project, "mobile-approved.txt")); err != nil || string(data) != "approved" {
886 t.Fatal("approved task did not complete", err)
887 }
888 return
889 }
890 time.Sleep(100 * time.Millisecond)
891 }
892 t.Fatal("resumed task did not complete")
893}
894
895func runSharedConversationBrowser(t *testing.T, s *Server, project string) {
896 t.Helper()
897 ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
898 defer cancel()
899 server := httptest.NewServer(s.handler())
900 defer server.Close()
901 s.origin = server.URL
902 workbench, err := mobilelink.OpenWorkbench(ctx, s.origin, s.issueTicket())
903 if err != nil {
904 t.Fatal(err)
905 }
906 defer workbench.Close()
907 admin := strings.Repeat("c", 48)
908 service, err := relay.New(relay.Config{AdminToken: admin})
909 if err != nil {
910 t.Fatal(err)
911 }
912 defer service.Close()
913 relayServer := httptest.NewServer(service)
914 defer relayServer.Close()
915 hostIdentity, _ := remotelink.NewIdentity()
916 phoneIdentity, _ := remotelink.NewIdentity()
917 room, err := mobilelink.CreateRoom(ctx, relayServer.URL, admin)
918 if err != nil {
919 t.Fatal(err)
920 }
921 go func() {
922 _ = mobilelink.ServeHost(ctx, relayServer.URL, room.ID, room.HostToken, hostIdentity, phoneIdentity.Pin, workbench)
923 }()
924 client, err := mobilelink.ConnectClient(ctx, relayServer.URL, room.ID, room.ClientToken, phoneIdentity, hostIdentity.Pin)
925 if err != nil {
926 t.Fatal(err)
927 }
928 defer client.Close()
929 web := httptest.NewUnstartedServer(nil)
930 assets, _ := filepath.Abs("web")
931 handler, entry, err := mobilelink.NewBrowser("http://"+web.Listener.Addr().String(), assets, client)
932 if err != nil {
933 t.Fatal(err)
934 }
935 defer handler.Close()
936 web.Config.Handler = handler
937 web.Start()
938 defer web.Close()
939 // The browser must complete startup itself. This goroutine only verifies
940 // that a later desktop keyboard message still reaches the phone.
941 desktopCtx, stopDesktop := context.WithCancel(ctx)
942 done := make(chan struct{})
943 go func() {
944 defer close(done)
945 replied := false
946 strip := regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]|\s+`)
947 ticker := time.NewTicker(100 * time.Millisecond)
948 defer ticker.Stop()
949 for {
950 select {
951 case <-desktopCtx.Done():
952 return
953 case <-ticker.C:
954 for _, row := range s.terminals.snapshot() {
955 terminal := s.terminals.get(row["id"].(string))
956 terminal.mu.Lock()
957 output := strip.ReplaceAllString(string(terminal.history), "")
958 terminal.mu.Unlock()
959 if !replied && strings.Contains(output, "isolatedtoolcompleted") {
960 _ = terminal.enqueueInput(desktopCtx, "follow-up\r")
961 replied = true
962 }
963 }
964 }
965 }
966 }()
967 defer func() { stopDesktop(); <-done }()
968 driver := exec.CommandContext(ctx, "node", "../../ui/scripts/shared-cli-live-smoke.mjs")
969 driver.Stdin = strings.NewReader(entry)
970 driver.Env = append(os.Environ(), "CAGE_TEST_MOBILE_MARKER="+filepath.Join(project, "mobile-approved.txt"))
971 if output, err := driver.CombinedOutput(); err != nil {
972 for _, row := range s.terminals.snapshot() {
973 terminal := s.terminals.get(row["id"].(string))
974 terminal.mu.Lock()
975 t.Log(cliStartupText(terminal.history))
976 terminal.mu.Unlock()
977 }
978 t.Fatalf("shared browser: %v\n%s", err, output)
979 }
980}