| 1 | |
| 2 | |
| 3 | package workbench |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "io" |
| 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 | |
| 23 | "al.essio.dev/pkg/shellescape" |
| 24 | "github.com/google/uuid" |
| 25 | ) |
| 26 | |
| 27 | func TestClaudeAccountSwitchThroughSharedSession(t *testing.T) { |
| 28 | for _, automatic := range []bool{false, true} { |
| 29 | name := "manual" |
| 30 | if automatic { |
| 31 | name = "automatic" |
| 32 | } |
| 33 | t.Run(name, func(t *testing.T) { testClaudeAccountSwitchThroughSharedSession(t, automatic) }) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func testClaudeAccountSwitchThroughSharedSession(t *testing.T, automatic bool) { |
| 38 | binary := os.Getenv("CAGE_TEST_CLAUDE_CLI") |
| 39 | if runtime.GOOS != "darwin" || !filepath.IsAbs(binary) { |
| 40 | t.Skip("requires official CLI and macOS sandbox") |
| 41 | } |
| 42 | binary, _ = filepath.EvalSymlinks(binary) |
| 43 | s := testServer(t) |
| 44 | home, _ := filepath.EvalSymlinks(t.TempDir()) |
| 45 | project, _ := filepath.EvalSymlinks(t.TempDir()) |
| 46 | s.ready = true |
| 47 | s.preferences.Workspace = project |
| 48 | if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": project}); err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | personal, _ := os.UserHomeDir() |
| 52 | quote := func(value string) string { b, _ := json.Marshal(value); return string(b) } |
| 53 | policy := "(version 1)(allow default)(deny mach-lookup)(deny file-read-data (subpath " + quote(personal) + ") (subpath \"/Library/Keychains\"))(allow file-read* (literal " + quote(binary) + "))(deny network-outbound)(allow network-outbound (remote ip \"localhost:*\"))" |
| 54 | bin := filepath.Join(home, "bin") |
| 55 | _ = os.Mkdir(bin, 0700) |
| 56 | shim := "#!/bin/sh\nexec /usr/bin/sandbox-exec -p " + shellescape.Quote(policy) + " " + shellescape.Quote(binary) + " --model sonnet --permission-mode manual \"$@\"\n" |
| 57 | if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(shim), 0700); err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | _ = os.WriteFile(filepath.Join(home, ".bash_profile"), []byte("export PATH="+shellescape.Quote(bin)+":/usr/bin:/bin\n"), 0600) |
| 61 | helper := filepath.Join(bin, "cage-claude-account") |
| 62 | original, _ := os.ReadFile("../cage/claude-account.py") |
| 63 | if err := os.WriteFile(helper, original, 0700); err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | var resumed atomic.Bool |
| 67 | model := mobileTestModel(t, &resumed) |
| 68 | t.Cleanup(model.Close) |
| 69 | var sharedContext atomic.Bool |
| 70 | observed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 71 | if r.URL.Path == "/v1/messages" { |
| 72 | body, _ := io.ReadAll(r.Body) |
| 73 | r.Body = io.NopCloser(bytes.NewReader(body)) |
| 74 | if strings.Contains(string(body), "follow-up") { |
| 75 | sharedContext.Store(strings.Contains(string(body), "GLOBAL_SHARED_INSTRUCTION") && strings.Contains(string(body), "PROJECT_SHARED_INSTRUCTION") && strings.Contains(string(body), "shared-cage-test-skill") && strings.Contains(string(body), "PROJECT_SHARED_MEMORY")) |
| 76 | } |
| 77 | } |
| 78 | model.Config.Handler.ServeHTTP(w, r) |
| 79 | })) |
| 80 | t.Cleanup(observed.Close) |
| 81 | proxy, ca := mobileOfficialTestProxy(t, observed) |
| 82 | if err := os.MkdirAll(filepath.Join(home, ".claude/skills/shared-cage-test-skill"), 0700); err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | _ = os.WriteFile(filepath.Join(home, ".claude/skills/shared-cage-test-skill/SKILL.md"), []byte("---\nname: shared-cage-test-skill\ndescription: Fixture shared skill\n---\nUse for the fixture.\n"), 0600) |
| 86 | _ = os.WriteFile(filepath.Join(home, ".claude/CLAUDE.md"), []byte("GLOBAL_SHARED_INSTRUCTION"), 0600) |
| 87 | _ = os.WriteFile(filepath.Join(project, "CLAUDE.md"), []byte("PROJECT_SHARED_INSTRUCTION"), 0600) |
| 88 | memory := filepath.Join(home, ".claude/projects", regexp.MustCompile(`[^a-zA-Z0-9]`).ReplaceAllString(project, "-"), "memory") |
| 89 | _ = os.MkdirAll(memory, 0700) |
| 90 | _ = os.WriteFile(filepath.Join(memory, "MEMORY.md"), []byte("PROJECT_SHARED_MEMORY"), 0600) |
| 91 | list := claudeAccountList{Scheduling: claudeScheduling{Mode: "sequential", SwitchPolicy: "ask"}} |
| 92 | features := map[string]bool{} |
| 93 | if data, err := os.ReadFile(os.Getenv("CAGE_TEST_CHANNEL_FEATURES")); err == nil { |
| 94 | _ = json.Unmarshal(data, &features) |
| 95 | } |
| 96 | if err := writePrivate(filepath.Join(home, ".claude.json"), map[string]any{"hasCompletedOnboarding": true, "cachedGrowthBookFeatures": features, "cachedGrowthBookFeaturesAt": time.Now().UnixMilli()}); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | for _, id := range []string{strings.Repeat("a", 24), strings.Repeat("b", 24)} { |
| 100 | email := id[:1] + "@example.invalid" |
| 101 | list.Accounts = append(list.Accounts, claudeAccount{ID: id, Label: id[:1], Email: email, Enabled: true, Status: "ready", HandoffGroup: "test"}) |
| 102 | config := filepath.Join(home, ".local/share/cage/claude-accounts", id, "config") |
| 103 | if err := writePrivate(filepath.Join(config, ".claude.json"), map[string]any{"hasCompletedOnboarding": true, "cachedGrowthBookFeatures": features, "cachedGrowthBookFeaturesAt": time.Now().UnixMilli(), "oauthAccount": map[string]string{"accountUuid": uuid.NewString(), "emailAddress": email}, "projects": map[string]any{project: map[string]bool{"hasTrustDialogAccepted": true}}}); err != nil { |
| 104 | t.Fatal(err) |
| 105 | } |
| 106 | if err := writePrivate(filepath.Join(config, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-synthetic-" + id[:1], "refreshToken": "synthetic", "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "scopes": []string{"user:inference", "user:profile"}, "subscriptionType": "pro"}}); err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | if err := writePrivate(filepath.Join(config, "settings.json"), map[string]any{"skipDangerousModePermissionPrompt": true, "statusLine": map[string]string{"type": "command", "command": "printf test"}}); err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | } |
| 113 | if err := s.saveClaudeAccounts(list); err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | env := []string{"HOME=" + home, "PATH=" + bin + ":/usr/bin:/bin", "HTTP_PROXY=" + proxy, "HTTPS_PROXY=" + proxy, "NO_PROXY=localhost,127.0.0.1", "NODE_EXTRA_CA_CERTS=" + ca, "SSL_CERT_FILE=" + ca, "DISABLE_AUTOUPDATER=1", "TERM=xterm-256color"} |
| 117 | mobileTestSSHRewrite(t, s, home, env, func(command string) string { |
| 118 | return strings.ReplaceAll(command, "/usr/local/bin/cage-claude-account", helper) |
| 119 | }) |
| 120 | |
| 121 | s.claudeAccounts.probe = func(ctx context.Context, id string) (claudeGuestSnapshot, error) { |
| 122 | return claudeGuestSnapshot{LoggedIn: true, Email: id[:1] + "@example.invalid"}, nil |
| 123 | } |
| 124 | t.Cleanup(func() { |
| 125 | if t.Failed() { |
| 126 | states, _ := filepath.Glob(filepath.Join(home, ".local/share/cage/cli-channels/*/state.json")) |
| 127 | for _, path := range states { |
| 128 | b, _ := os.ReadFile(path) |
| 129 | t.Log(string(b)) |
| 130 | } |
| 131 | } |
| 132 | output, _ := exec.Command("pgrep", "-f", regexp.QuoteMeta(home)).Output() |
| 133 | for _, value := range strings.Fields(string(output)) { |
| 134 | pid, err := strconv.Atoi(value) |
| 135 | if err == nil && pid > 0 { |
| 136 | if t.Failed() { |
| 137 | out, _ := exec.Command("ps", "-o", "pid,ppid,stat,comm", "-p", value).Output() |
| 138 | t.Log(string(out)) |
| 139 | } |
| 140 | p, _ := os.FindProcess(pid) |
| 141 | _ = p.Kill() |
| 142 | _ = p.Release() |
| 143 | } |
| 144 | } |
| 145 | }) |
| 146 | t.Cleanup(s.terminals.closeAll) |
| 147 | id := uuid.NewString() |
| 148 | call := func(method, path string, body any) mobileSession { |
| 149 | t.Helper() |
| 150 | raw, _ := json.Marshal(body) |
| 151 | if body == nil { |
| 152 | raw = nil |
| 153 | } |
| 154 | response := request(s, method, "/api/mobile/cli/sessions/"+id+path, s.origin, string(raw), true) |
| 155 | if response.Code != 200 { |
| 156 | t.Fatalf("%s %s: %d %s", method, path, response.Code, response.Body.String()) |
| 157 | } |
| 158 | var view mobileSession |
| 159 | if err := json.Unmarshal(response.Body.Bytes(), &view); err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | return view |
| 163 | } |
| 164 | response := request(s, "POST", "/api/mobile/cli/sessions", s.origin, `{"id":"`+id+`","workspace":"`+project+`"}`, true) |
| 165 | if response.Code != 200 { |
| 166 | t.Fatal(response.Code, response.Body.String()) |
| 167 | } |
| 168 | wait := func(predicate func(mobileSession) bool) mobileSession { |
| 169 | t.Helper() |
| 170 | deadline := time.Now().Add(35 * time.Second) |
| 171 | var view mobileSession |
| 172 | for time.Now().Before(deadline) { |
| 173 | view = call("GET", "", nil) |
| 174 | if predicate(view) { |
| 175 | return view |
| 176 | } |
| 177 | time.Sleep(100 * time.Millisecond) |
| 178 | } |
| 179 | for _, terminal := range s.terminals.sessions { |
| 180 | terminal.mu.Lock() |
| 181 | t.Log(string(terminal.history)) |
| 182 | terminal.mu.Unlock() |
| 183 | } |
| 184 | t.Fatalf("session did not reach expected state: %#v", view) |
| 185 | return view |
| 186 | } |
| 187 | view := wait(func(v mobileSession) bool { return v.CanSend != nil && *v.CanSend }) |
| 188 | if view.AccountID != list.Accounts[0].ID { |
| 189 | t.Fatal("source account was not selected", view.AccountID) |
| 190 | } |
| 191 | messageID := uuid.NewString() |
| 192 | call("POST", "/messages", map[string]string{"request_id": messageID, "text": "initial mobile prompt"}) |
| 193 | view = wait(func(v mobileSession) bool { return len(v.Turns) > 0 && v.Turns[0].Approval != nil }) |
| 194 | call("POST", "/approval", map[string]any{"request_id": messageID, "approval_id": view.Turns[0].Approval.ID, "allow": true}) |
| 195 | view = wait(func(v mobileSession) bool { |
| 196 | return len(v.Turns) > 0 && v.Turns[0].Text == "isolated tool completed" && v.Turns[0].Status == "completed" |
| 197 | }) |
| 198 | before, err := os.ReadFile(filepath.Join(project, "mobile-approved.txt")) |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | m := &s.mobileCLI |
| 203 | m.mu.Lock() |
| 204 | record, _ := m.record(s.profile, id) |
| 205 | sourceID := record.CLIID |
| 206 | m.mu.Unlock() |
| 207 | switchID := uuid.NewString() |
| 208 | input := claudeSwitchInput{Action: "switch", RequestID: switchID, SourceID: sourceID, Target: list.Accounts[1].ID, Confirm: true} |
| 209 | raw, _ := json.Marshal(input) |
| 210 | if automatic { |
| 211 | |
| 212 | |
| 213 | record.SwitchPolicy = "allow" |
| 214 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | statePath := filepath.Join(home, ".local/share/cage/cli-channels", record.Connection, "state.json") |
| 218 | data, err := os.ReadFile(statePath) |
| 219 | if err != nil { |
| 220 | t.Fatal(err) |
| 221 | } |
| 222 | var state map[string]any |
| 223 | if err := json.Unmarshal(data, &state); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | state["account_failure"] = "rate_limit" |
| 227 | if err := writePrivate(statePath, state); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | list.Accounts[0].Quota = &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: time.Now().Add(time.Hour).Unix(), ObservedAt: time.Now().Unix()}} |
| 231 | if err := s.saveClaudeAccounts(list); err != nil { |
| 232 | t.Fatal(err) |
| 233 | } |
| 234 | epoch, _ := s.account.access() |
| 235 | ctx := context.WithValue(context.Background(), mobileEpochKey{}, epoch) |
| 236 | lastUsage := time.Now() |
| 237 | s.maybeSwitchClaudeAccount(ctx, id, &lastUsage) |
| 238 | m.mu.Lock() |
| 239 | latest, err := m.record(s.profile, id) |
| 240 | m.mu.Unlock() |
| 241 | if err != nil || latest.Switch == nil { |
| 242 | t.Fatalf("automatic handoff did not start: %v", err) |
| 243 | } |
| 244 | input.RequestID = latest.Switch.ID |
| 245 | raw, _ = json.Marshal(input) |
| 246 | } |
| 247 | response = request(s, "POST", "/api/cli/sessions/"+id+"/account", s.origin, string(raw), true) |
| 248 | if response.Code == 409 && strings.Contains(response.Body.String(), "原进程尚未退出") { |
| 249 | |
| 250 | |
| 251 | response = request(s, "POST", "/api/cli/sessions/"+id+"/account", s.origin, string(raw), true) |
| 252 | } |
| 253 | if response.Code != 200 { |
| 254 | t.Fatal(response.Code, response.Body.String()) |
| 255 | } |
| 256 | view = wait(func(v mobileSession) bool { |
| 257 | return v.CanSend != nil && *v.CanSend && v.AccountSwitch != nil && v.AccountSwitch.Phase == "completed" |
| 258 | }) |
| 259 | if len(view.Turns) != 1 || view.AccountID != list.Accounts[1].ID { |
| 260 | t.Fatalf("history or binding changed incorrectly: %#v", view) |
| 261 | } |
| 262 | |
| 263 | call("POST", "/messages", map[string]string{"request_id": messageID, "text": "initial mobile prompt"}) |
| 264 | call("POST", "/messages", map[string]string{"request_id": uuid.NewString(), "text": "follow-up"}) |
| 265 | view = wait(func(v mobileSession) bool { return len(v.Turns) == 2 && v.Turns[1].Text == "isolated continuation" }) |
| 266 | after, _ := os.ReadFile(filepath.Join(project, "mobile-approved.txt")) |
| 267 | if string(before) != string(after) || !resumed.Load() || !sharedContext.Load() { |
| 268 | t.Fatal("completed work lost or history not resumed") |
| 269 | } |
| 270 | response = request(s, "POST", "/api/cli/sessions/"+id+"/account", s.origin, string(raw), true) |
| 271 | if response.Code != 200 || len(s.terminals.snapshot()) != 1 { |
| 272 | t.Fatal("replayed switch created another execution", response.Code) |
| 273 | } |
| 274 | t.Log("shared session switched A to B through authenticated desktop/mobile routes, retained tool history, and deduplicated original message and switch") |
| 275 | } |