跳到主要内容

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

浏览文件

claude_handoff_cli_test.go

134 行 · 5.9 KB历史下载
1//go:build !windows
2
3package workbench
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "sync/atomic"
17 "testing"
18 "time"
19
20 "github.com/google/uuid"
21)
22
23// Exercise the published CLI with two synthetic subscription identities. The
24// sandbox denies personal credentials and Internet access. This proves local
25// resume/tool semantics, not acceptance by Anthropic of real account switching.
26func TestClaudeCrossAccountTranscriptResume(t *testing.T) {
27 binary := os.Getenv("CAGE_TEST_CLAUDE_CLI")
28 if !filepath.IsAbs(binary) || runtime.GOOS != "darwin" {
29 t.Skip("requires an absolute CAGE_TEST_CLAUDE_CLI and macOS sandbox-exec")
30 }
31 binary, err := filepath.EvalSymlinks(binary)
32 if err != nil {
33 t.Fatal(err)
34 }
35 home, project := t.TempDir(), t.TempDir()
36 realHome, _ := os.UserHomeDir()
37 quote := func(s string) string { b, _ := json.Marshal(s); return string(b) }
38 policy := "(version 1)(allow default)(deny mach-lookup)(deny file-read* (subpath " + quote(realHome) + ") (subpath \"/Library/Keychains\"))(allow file-read* (literal " + quote(binary) + "))(deny network-outbound)(allow network-outbound (remote ip \"localhost:*\"))"
39 var resumed atomic.Bool
40 model := mobileTestModel(t, &resumed)
41 defer model.Close()
42 var aRequests, bRequests atomic.Int32
43 var target atomic.Int32
44 fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
45 if r.URL.Path == "/v1/messages" {
46 if target.Load() == 0 {
47 aRequests.Add(1)
48 } else {
49 bRequests.Add(1)
50 }
51 }
52 recorder := httptest.NewRecorder()
53 model.Config.Handler.ServeHTTP(recorder, r)
54 for k, values := range recorder.Header() {
55 w.Header()[k] = values
56 }
57 w.WriteHeader(recorder.Code)
58 body := strings.ReplaceAll(recorder.Body.String(), `printf approved \u003e mobile-approved.txt`, `printf performed \u003e\u003e handoff-tool-count.txt`)
59 _, _ = w.Write([]byte(body))
60 }))
61 defer fixture.Close()
62 proxy, ca := mobileOfficialTestProxy(t, fixture)
63 configs := []string{filepath.Join(home, "account-a"), filepath.Join(home, "account-b")}
64 save := func(path string, value any) {
65 t.Helper()
66 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
67 t.Fatal(err)
68 }
69 b, _ := json.Marshal(value)
70 if err := os.WriteFile(path, b, 0600); err != nil {
71 t.Fatal(err)
72 }
73 }
74 for i, config := range configs {
75 save(filepath.Join(config, ".claude.json"), map[string]any{"hasCompletedOnboarding": true, "oauthAccount": map[string]string{"accountUuid": uuid.NewString(), "emailAddress": fmt.Sprintf("account-%[email protected]", i), "organizationUuid": uuid.NewString()}})
76 save(filepath.Join(config, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{"accessToken": fmt.Sprintf("sk-ant-oat01-synthetic-%d", i), "refreshToken": "synthetic", "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "scopes": []string{"user:inference", "user:profile"}, "subscriptionType": "pro"}})
77 }
78 ctx, cancel := context.WithTimeout(context.Background(), 65*time.Second)
79 defer cancel()
80 run := func(account int, args ...string) []byte {
81 t.Helper()
82 cmd := exec.CommandContext(ctx, "/usr/bin/sandbox-exec", append([]string{"-p", policy, binary}, args...)...)
83 cmd.Dir = project
84 cmd.Env = []string{"HOME=" + home, "PATH=/usr/bin:/bin", "CLAUDE_CONFIG_DIR=" + configs[account], "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", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1"}
85 out, err := cmd.CombinedOutput()
86 if err != nil {
87 t.Fatalf("isolated account %d: %v\n%s", account, err, out)
88 }
89 return out
90 }
91 for i := range configs {
92 out := run(i, "auth", "status")
93 if !strings.Contains(string(out), fmt.Sprintf("account-%[email protected]", i)) || !strings.Contains(string(out), "claude.ai") {
94 t.Fatal("synthetic subscription identity was not selected", string(out))
95 }
96 }
97 flags := []string{"--model", "sonnet", "-p", "--output-format", "stream-json", "--verbose", "--setting-sources", "", "--strict-mcp-config", "--mcp-config", `{"mcpServers":{}}`, "--dangerously-skip-permissions", "--max-turns", "4"}
98 sourceID, targetID := uuid.NewString(), uuid.NewString()
99 firstOutput := run(0, append(append([]string{}, flags...), "--session-id", sourceID, "initial mobile prompt")...)
100 marker := filepath.Join(project, "handoff-tool-count.txt")
101 before, err := os.ReadFile(marker)
102 if err != nil || len(before) == 0 {
103 t.Fatalf("the real CLI did not execute the tool: %v\n%s", err, firstOutput)
104 }
105 paths, _ := filepath.Glob(filepath.Join(configs[0], "projects", "*", sourceID+".jsonl"))
106 if len(paths) != 1 {
107 t.Fatal("source transcript missing", paths)
108 }
109 sourceBefore, _ := os.ReadFile(paths[0])
110 if !strings.Contains(string(sourceBefore), "tool_result") {
111 t.Fatal("completed tool result absent")
112 }
113 target.Store(1)
114 out := run(1, append(append([]string{}, flags...), "--resume", paths[0], "--fork-session", "--session-id", targetID, "follow-up")...)
115 after, _ := os.ReadFile(marker)
116 sourceAfter, _ := os.ReadFile(paths[0])
117 if string(before) != string(after) {
118 t.Fatal("completed tool ran again")
119 }
120 if string(sourceBefore) != string(sourceAfter) {
121 t.Fatal("source account history changed")
122 }
123 if !resumed.Load() || aRequests.Load() < 2 || bRequests.Load() != 1 {
124 t.Fatalf("history was not reused: resumed=%t requests=%d/%d", resumed.Load(), aRequests.Load(), bRequests.Load())
125 }
126 if !strings.Contains(string(out), targetID) {
127 t.Fatal("target CLI session identity missing")
128 }
129 paths, _ = filepath.Glob(filepath.Join(configs[1], "projects", "*", targetID+".jsonl"))
130 if len(paths) != 1 {
131 t.Fatal("resumed history not persisted in target account")
132 }
133 t.Logf("official CLI: two isolated subscription identities; source requests=%d target requests=%d; completed tool count unchanged; source transcript unchanged; target history persisted", aRequests.Load(), bRequests.Load())
134}