跳到主要内容

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

浏览文件

agent_test.go

262 行 · 9.1 KB历史下载
1package workbench
2
3import (
4 "archive/zip"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http/httptest"
10 "net/url"
11 "os"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "testing"
16 "time"
17
18 "github.com/sylvinus/agent-vm/internal/cage"
19 "github.com/sylvinus/agent-vm/internal/guestos"
20)
21
22func agentTestController(t *testing.T) *Server {
23 t.Helper()
24 s := testServer(t)
25 identity, err := currentController()
26 if err != nil {
27 t.Fatal(err)
28 }
29 s.identity = identity
30 server := httptest.NewServer(s.handler())
31 t.Cleanup(server.Close)
32 u, _ := url.Parse(server.URL)
33 port, _ := strconv.Atoi(u.Port())
34 s.origin = "http://localhost:" + u.Port()
35 lock, err := openControllerLock(s.profile, os.O_CREATE|os.O_RDWR)
36 if err != nil {
37 t.Fatal(err)
38 }
39 if err = lockController(lock); err != nil {
40 t.Fatal(err)
41 }
42 t.Cleanup(func() { unlockController(lock); lock.Close() })
43 if err := writePrivate(filepath.Join(s.profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: identity}); err != nil {
44 t.Fatal(err)
45 }
46 return s
47}
48
49func TestAgentAuthenticationAndLockedAccount(t *testing.T) {
50 s := agentTestController(t)
51 if _, err := AgentCall(context.Background(), s.configPath, "settings.get", nil); err != nil {
52 t.Fatal(err)
53 }
54 s.account.lock()
55 _, err := AgentCall(context.Background(), s.configPath, "settings.get", nil)
56 var ae *AgentError
57 if !errors.As(err, &ae) || ae.Code != "account_locked" {
58 t.Fatalf("locked: %v", err)
59 }
60 if _, err := AgentCall(context.Background(), s.configPath, "account.status", nil); err != nil {
61 t.Fatal(err)
62 }
63 if w := request(s, "POST", "/api/agent/settings", s.origin, `{"patch":{"keyboard":"native"}}`, false); w.Code != 401 {
64 t.Fatal("agent routes bypassed session", w.Code)
65 }
66}
67
68func TestAgentSettingsPatchPreservesOmittedFields(t *testing.T) {
69 s := agentTestController(t)
70 s.preferences.ClaudeTerminalCommand = "claude --verbose"
71 before, err := cage.Load(s.configPath)
72 if err != nil {
73 t.Fatal(err)
74 }
75 data, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"browser_home_url":"https://example.org/"},"dry_run":true}`))
76 if err != nil {
77 t.Fatal(err)
78 }
79 if !strings.Contains(string(data), "https://example.org/") || s.preferences.BrowserHomeURL != "" {
80 t.Fatalf("dry run: %s", data)
81 }
82 data, err = AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"browser_home_url":"https://example.org/"}}`))
83 if err != nil {
84 t.Fatal(err)
85 }
86 if !strings.Contains(string(data), "https://example.org/") {
87 t.Fatal("homepage was not confirmed", string(data))
88 }
89 if s.preferences.ClaudeTerminalCommand != "claude --verbose" || s.preferences.BrowserHomeURL != "https://example.org/" {
90 t.Fatalf("preferences lost: %+v", s.preferences)
91 }
92 after, _ := cage.Load(s.configPath)
93 if before != after {
94 t.Fatal("unrelated network config changed")
95 }
96 for _, input := range []string{`{"patch":{"proxy_url":"socks5://127.0.0.1:1"}}`, `{"patch":{"keyboard":null}}`, `{"patch":{"keyboard":"invalid"}}`, `{"patch":{}}`} {
97 if _, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(input)); err == nil {
98 t.Fatal("accepted invalid patch", input)
99 }
100 }
101}
102
103func TestAgentPartialExitPolicyPreservesAnchor(t *testing.T) {
104 s := agentTestController(t)
105 cfg, err := cage.Load(s.configPath)
106 if err != nil {
107 t.Fatal(err)
108 }
109 cfg.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "city", IP: "8.8.8.8", CountryCode: "US", Region: "California", City: "Los Angeles"}
110 if err := writePrivate(s.configPath, cfg); err != nil {
111 t.Fatal(err)
112 }
113 data, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"exit_policy":{"mode":"static"}},"dry_run":true}`))
114 if err != nil {
115 t.Fatal(err)
116 }
117 var view Settings
118 _ = json.Unmarshal(data, &view)
119 if view.ExitPolicy.Mode != "static" || view.ExitPolicy.Scope != "city" || view.ExitPolicy.IP != "8.8.8.8" || view.ExitPolicy.City != "Los Angeles" {
120 t.Fatalf("network anchor discarded: %+v", view.ExitPolicy)
121 }
122 _, err = AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"exit_policy":{"ip":null}},"dry_run":true}`))
123 if err == nil {
124 t.Fatal("null cleared network anchor")
125 }
126}
127
128func TestAgentJobIdentityAndCancellation(t *testing.T) {
129 s := agentTestController(t)
130 s.setJobForTest(Job{ID: "012345abcdef", Running: true})
131 if _, err := AgentJob(context.Background(), s.configPath, "012345abcdef"); err != nil {
132 t.Fatal(err)
133 }
134 s.setJobForTest(Job{ID: "abcdef012345"})
135 _, err := AgentJob(context.Background(), s.configPath, "012345abcdef")
136 var ae *AgentError
137 if !errors.As(err, &ae) || ae.Code != "job_not_found" {
138 t.Fatalf("wrong job accepted: %v", err)
139 }
140 var manager jobManager
141 manager.state = Job{ID: "012345abcdef", Running: true}
142 execution := &jobExecution{id: manager.state.ID, ctx: context.Background()}
143 manager.finishLocked(execution, context.Canceled)
144 if manager.state.Running || !manager.state.Canceled {
145 t.Fatalf("cancellation hidden: %+v", manager.state)
146 }
147}
148
149func TestAgentRedactionPreservesOperationalValues(t *testing.T) {
150 input := `{"id":"012345abcdef","clone_key":"` + strings.Repeat("a", 64) + `","workspace":"/Users/test/project","dns_url":"https://1.1.1.1/dns-query","error":"fetch https://secret.example/sub?token=very-secret failed","job":{"log":"password=hidden"}}`
151 output := agentRedact(input)
152 if !json.Valid([]byte(output)) || strings.Contains(output, "very-secret") || strings.Contains(output, "hidden") {
153 t.Fatal(output)
154 }
155 for _, value := range []string{"012345abcdef", strings.Repeat("a", 64), "/Users/test/project", "https://1.1.1.1/dns-query"} {
156 if !strings.Contains(output, value) {
157 t.Fatal("operational field redacted", output)
158 }
159 }
160}
161
162func TestAgentNoImplicitStartAndUnknownInput(t *testing.T) {
163 profile := t.TempDir()
164 path := filepath.Join(profile, "config.json")
165 for _, tc := range []struct{ op, input, code string }{{"does.not.exist", "{}", "unknown_operation"}, {"environment.stop", `{"surprise":true}`, "invalid_input"}, {"settings.get", "{}", "service_unavailable"}} {
166 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
167 _, err := AgentCall(ctx, path, tc.op, json.RawMessage(tc.input))
168 cancel()
169 var ae *AgentError
170 if !errors.As(err, &ae) || ae.Code != tc.code {
171 t.Fatalf("%s: %v", tc.op, err)
172 }
173 }
174 if _, err := os.Stat(path); !os.IsNotExist(err) {
175 t.Fatal("read created profile")
176 }
177 for _, path := range []string{"/api/agent/settings", "/api/agent/jobs/012345abcdef"} {
178 if !macOSWorkbenchRoute(path) || !windowsWorkbenchRoute(path) {
179 t.Fatal("missing native platform route", path)
180 }
181 }
182 if !macOSSetupRoute("/api/agent/jobs/012345abcdef") {
183 t.Fatal("cannot track first setup")
184 }
185}
186
187func TestAgentCannotFollowSelectedRemote(t *testing.T) {
188 s := agentTestController(t)
189 s.remote = newRemoteGateway(s.profile)
190 t.Cleanup(func() { s.remote.close() })
191 s.remote.setRemote(true)
192 _, err := AgentCall(context.Background(), s.configPath, "environment.stop", json.RawMessage(`{}`))
193 var ae *AgentError
194 if !errors.As(err, &ae) || ae.Code != "state_conflict" {
195 t.Fatalf("remote target accepted: %v", err)
196 }
197 if s.jobs.snapshot().ID != "" {
198 t.Fatal("remote rejection fell back to local mutation")
199 }
200}
201
202func TestAgentRejectsOtherConfigFileInSameProfile(t *testing.T) {
203 s := agentTestController(t)
204 _, err := AgentCall(context.Background(), filepath.Join(s.profile, "other.json"), "account.status", nil)
205 var ae *AgentError
206 if !errors.As(err, &ae) || ae.Code != "config_path_mismatch" {
207 t.Fatalf("wrong config accepted: %v", err)
208 }
209 s.clientOnly = true
210 _, err = AgentCall(context.Background(), s.configPath, "account.status", nil)
211 if !errors.As(err, &ae) || ae.Code != "controller_mismatch" {
212 t.Fatalf("remote-only client accepted: %v", err)
213 }
214}
215
216func TestAgentNativeDiagnosticExport(t *testing.T) {
217 for _, system := range []string{"linux", "macos", "windows"} {
218 t.Run(system, func(t *testing.T) {
219 s := agentTestController(t)
220 if system == "macos" {
221 s.macosGuest = &guestos.MacOSProfile{Instance: "test", User: "test"}
222 }
223 if system == "windows" {
224 s.windowsGuest = &guestos.WindowsProfile{}
225 }
226 s.account.lock()
227 path := filepath.Join(t.TempDir(), "diagnostics.zip")
228 if err := ExportAgentDiagnostics(s.configPath, path); err != nil {
229 t.Fatal(err)
230 }
231 before, err := os.ReadFile(path)
232 if err != nil || len(before) == 0 {
233 t.Fatal("missing bundle", err)
234 }
235 archive, err := zip.OpenReader(path)
236 if err != nil {
237 t.Fatal(err)
238 }
239 defer archive.Close()
240 for _, file := range archive.File {
241 if file.Name == "manifest.json" {
242 reader, err := file.Open()
243 if err != nil {
244 t.Fatal(err)
245 }
246 body, _ := io.ReadAll(reader)
247 reader.Close()
248 if !strings.Contains(string(body), `"guest_collection": "environment unavailable"`) {
249 t.Fatal("did not use authenticated native diagnostic endpoint", string(body))
250 }
251 }
252 }
253 if err := ExportAgentDiagnostics(s.configPath, path); err == nil {
254 t.Fatal("overwrote previous diagnostic")
255 }
256 after, _ := os.ReadFile(path)
257 if string(before) != string(after) {
258 t.Fatal("existing bundle changed")
259 }
260 })
261 }
262}