跳到主要内容

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

浏览文件

agent_parity_test.go

391 行 · 16.1 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "net/http"
9 "os"
10 "path/filepath"
11 "reflect"
12 "strings"
13 "testing"
14 "time"
15)
16
17func parityJSON(t *testing.T, value any) []byte {
18 t.Helper()
19 body, err := json.Marshal(value)
20 if err != nil {
21 t.Fatal(err)
22 }
23 return body
24}
25
26func parityUI(t *testing.T, s *Server, method, path string, value any, status int) []byte {
27 t.Helper()
28 body := ""
29 if value != nil {
30 body = string(parityJSON(t, value))
31 }
32 response := request(s, method, path, s.origin, body, true)
33 if response.Code != status {
34 t.Fatalf("UI %s %s: HTTP %d: %s", method, path, response.Code, response.Body.String())
35 }
36 return response.Body.Bytes()
37}
38
39func parityAgent(t *testing.T, s *Server, method, path string, value any, status int) []byte {
40 t.Helper()
41 var input io.Reader
42 if value != nil {
43 input = strings.NewReader(string(parityJSON(t, value)))
44 }
45 response, err := AgentRequest(context.Background(), s.configPath, AgentTarget{Scope: "local"}, method, path, input, "application/json", "")
46 if response.HTTPStatus != status {
47 t.Fatalf("Agent %s %s: HTTP %d, error %v", method, path, response.HTTPStatus, err)
48 }
49 if status == http.StatusOK && err != nil {
50 t.Fatalf("Agent %s %s: %v", method, path, err)
51 }
52 if status >= 400 && err == nil {
53 t.Fatalf("Agent reported success for HTTP %d", status)
54 }
55 return response.Data
56}
57
58func parityDecode[T any](t *testing.T, body []byte) T {
59 t.Helper()
60 var value T
61 if err := json.Unmarshal(body, &value); err != nil {
62 t.Fatalf("decode: %v: %s", err, body)
63 }
64 return value
65}
66
67func parityAccount(t *testing.T, s *Server) {
68 t.Helper()
69 s.account.lock()
70 a, err := loadLocalAccount(s.profile)
71 if err != nil {
72 t.Fatal(err)
73 }
74 if err := a.create("Parity account", "parity-old-password", ""); err != nil {
75 t.Fatal(err)
76 }
77 s.account = a
78 t.Cleanup(a.lock)
79}
80
81func TestAgentParityAccountProfilePasswordAndLock(t *testing.T) {
82 s := agentTestController(t)
83 parityAccount(t, s)
84 parityUI(t, s, "POST", "/api/account/profile", map[string]any{"username": "From UI", "avatar": ""}, 200)
85 view := parityDecode[accountView](t, parityAgent(t, s, "GET", "/api/account", nil, 200))
86 if view.Username != "From UI" {
87 t.Fatal("Agent did not read UI profile", view.Username)
88 }
89 data, err := AgentCall(context.Background(), s.configPath, "account.profile", parityJSON(t, map[string]any{"username": "From Agent", "avatar": ""}))
90 if err != nil {
91 t.Fatal(err)
92 }
93 if parityDecode[accountView](t, data).Username != "From Agent" {
94 t.Fatal("Agent profile not confirmed")
95 }
96 view = parityDecode[accountView](t, parityUI(t, s, "GET", "/api/account", nil, 200))
97 if view.Username != "From Agent" {
98 t.Fatal("UI did not read Agent profile")
99 }
100 stored, err := loadLocalAccount(s.profile)
101 if err != nil {
102 t.Fatal(err)
103 }
104 if stored.view().Username != "From Agent" {
105 t.Fatal("profile success preceded persistence")
106 }
107 before, err := os.ReadFile(s.account.path)
108 if err != nil {
109 t.Fatal(err)
110 }
111 wrong := map[string]any{"old_password": "wrong", "password": "parity-new-password", "confirm_password": "parity-new-password"}
112 parityAgent(t, s, "POST", "/api/account/password", wrong, 400)
113 s.account.mu.Lock()
114 s.account.nextAttempt = time.Time{}
115 s.account.mu.Unlock()
116 parityUI(t, s, "POST", "/api/account/password", wrong, 400)
117 s.account.mu.Lock()
118 s.account.nextAttempt = time.Time{}
119 s.account.mu.Unlock()
120 after, _ := os.ReadFile(s.account.path)
121 if string(before) != string(after) {
122 t.Fatal("rejected password change modified account")
123 }
124 parityAgent(t, s, "POST", "/api/account/password", map[string]any{"old_password": "parity-old-password", "password": "parity-new-password", "confirm_password": "parity-new-password"}, 200)
125 parityUI(t, s, "POST", "/api/account/lock", map[string]any{}, 200)
126 parityAgent(t, s, "GET", "/api/settings", nil, 423)
127 parityUI(t, s, "GET", "/api/settings", nil, 423)
128 parityUI(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-old-password"}, 400)
129 s.account.mu.Lock()
130 s.account.nextAttempt = time.Time{}
131 s.account.mu.Unlock()
132 parityAgent(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-new-password"}, 200)
133 parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200)
134 parityUI(t, s, "GET", "/api/settings", nil, 423)
135 parityUI(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-new-password"}, 200)
136 stored, err = loadLocalAccount(s.profile)
137 if err != nil {
138 t.Fatal(err)
139 }
140 defer stored.lock()
141 if err := stored.unlock("parity-new-password"); err != nil {
142 t.Fatal("password update did not survive reload", err)
143 }
144}
145
146func TestAgentParityAppearanceNestedValuesAndFavorites(t *testing.T) {
147 s := agentTestController(t)
148 appearance := defaultAppearance()
149 appearance.Mode = "dark"
150 appearance.UIFontSize = 18
151 appearance.Dark.Colors = map[string]string{"sidebar": "#123456", "focus": "#abcdef"}
152 appearance.Dark.Terminal = map[string]string{"background": "#101010", "brightRed": "#ee1111"}
153 appearance.CustomThemes = []SavedAppearanceTheme{{ID: "parity", Name: "Saved by UI", Light: appearance.Light, Dark: appearance.Dark}}
154 parityUI(t, s, "POST", "/api/appearance", appearance, 200)
155 read := parityDecode[Appearance](t, parityAgent(t, s, "GET", "/api/appearance", nil, 200))
156 if !reflect.DeepEqual(appearance, read) {
157 t.Fatalf("Agent lost nested appearance values: %+v", read)
158 }
159 read.CustomThemes[0].Name = "Renamed by Agent"
160 read.CodeFontSize = 17
161 read.Dark.Fonts.Code = "JetBrains Mono"
162 data, err := AgentCall(context.Background(), s.configPath, "appearance.set", parityJSON(t, read))
163 if err != nil {
164 t.Fatal(err)
165 }
166 if !reflect.DeepEqual(read, parityDecode[Appearance](t, data)) {
167 t.Fatal("Agent appearance confirmation differs")
168 }
169 if !reflect.DeepEqual(read, parityDecode[Appearance](t, parityUI(t, s, "GET", "/api/appearance", nil, 200))) {
170 t.Fatal("UI cannot see saved Agent appearance")
171 }
172 file, err := os.ReadFile(filepath.Join(s.profile, "appearance.json"))
173 if err != nil {
174 t.Fatal(err)
175 }
176 if !reflect.DeepEqual(read, parityDecode[Appearance](t, file)) {
177 t.Fatal("appearance not durable")
178 }
179 folders := parityDecode[Favorites](t, parityUI(t, s, "POST", "/api/favorites", map[string]any{"action": "save_folder", "title": "UI folder"}, 200))
180 if len(folders.Folders) != 1 {
181 t.Fatal("missing saved folder")
182 }
183 data, err = AgentCall(context.Background(), s.configPath, "favorites.change", parityJSON(t, map[string]any{"action": "save", "title": "Agent bookmark", "url": "https://example.test/path?q=one", "folder_id": folders.Folders[0].ID}))
184 if err != nil {
185 t.Fatal(err)
186 }
187 favorites := parityDecode[Favorites](t, data)
188 if len(favorites.Items) != 1 || favorites.Items[0].FolderID != folders.Folders[0].ID {
189 t.Fatal("Agent failed to use UI-created folder")
190 }
191 parityUI(t, s, "POST", "/api/favorites", map[string]any{"action": "save", "id": favorites.Items[0].ID, "title": "UI rename", "url": favorites.Items[0].URL, "folder_id": ""}, 200)
192 favorites = parityDecode[Favorites](t, parityAgent(t, s, "GET", "/api/favorites", nil, 200))
193 if favorites.Items[0].Title != "UI rename" || favorites.Items[0].FolderID != "" {
194 t.Fatal("Agent lost latest UI bookmark metadata")
195 }
196 file, err = os.ReadFile(filepath.Join(s.profile, "favorites.json"))
197 if err != nil {
198 t.Fatal(err)
199 }
200 if !reflect.DeepEqual(favorites, parityDecode[Favorites](t, file)) {
201 t.Fatal("favorites not durable")
202 }
203 parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200)
204 parityAgent(t, s, "POST", "/api/appearance", appearance, 423)
205 parityUI(t, s, "POST", "/api/appearance", appearance, 423)
206 parityAgent(t, s, "GET", "/api/favorites", nil, 423)
207 parityUI(t, s, "GET", "/api/favorites", nil, 423)
208}
209
210func TestAgentParityVaultMetadataAndReauthentication(t *testing.T) {
211 s := agentTestController(t)
212 parityAccount(t, s)
213 const secret = "parity-website-secret-should-not-be-redacted"
214 entry := map[string]any{"origin": "https://vault.example.test/login", "username": "[email protected]", "password": secret}
215 parityUI(t, s, "POST", "/api/vault", map[string]any{"action": "save", "entry": entry}, 200)
216 listBody := parityAgent(t, s, "GET", "/api/vault", nil, 200)
217 if strings.Contains(string(listBody), secret) {
218 t.Fatal("ordinary Agent list leaked password")
219 }
220 list := parityDecode[vaultData](t, listBody)
221 if len(list.Entries) != 1 || list.Entries[0].Origin != "https://vault.example.test" || list.Entries[0].Username != "[email protected]" {
222 t.Fatal("Agent cannot discover UI record", string(listBody))
223 }
224 id := list.Entries[0].ID
225 reveal := map[string]any{"action": "reveal", "id": id, "account_password": "parity-old-password"}
226 result, err := AgentCall(context.Background(), s.configPath, "vault.change", parityJSON(t, reveal))
227 if err != nil {
228 t.Fatal(err)
229 }
230 if parityDecode[struct {
231 Password string `json:"password"`
232 }](t, result).Password != secret {
233 t.Fatal("explicit authenticated reveal was redacted")
234 }
235 wrong := map[string]any{"action": "reveal", "id": id, "account_password": "wrong"}
236 parityAgent(t, s, "POST", "/api/vault", wrong, 400)
237 s.account.mu.Lock()
238 s.account.nextAttempt = time.Time{}
239 s.account.mu.Unlock()
240 parityUI(t, s, "POST", "/api/vault", wrong, 400)
241 s.account.mu.Lock()
242 s.account.nextAttempt = time.Time{}
243 s.account.mu.Unlock()
244 parityAgent(t, s, "POST", "/api/vault", map[string]any{"action": "save", "entry": map[string]any{"id": id, "origin": "https://vault.example.test", "username": "changed-by-agent", "password": ""}}, 200)
245 if parityDecode[struct {
246 Password string `json:"password"`
247 }](t, parityUI(t, s, "POST", "/api/vault", reveal, 200)).Password != secret {
248 t.Fatal("Agent metadata edit erased password")
249 }
250 list = parityDecode[vaultData](t, parityUI(t, s, "GET", "/api/vault", nil, 200))
251 if list.Entries[0].Username != "changed-by-agent" {
252 t.Fatal("UI missed Agent edit")
253 }
254 file, err := os.ReadFile(filepath.Join(s.profile, "password-vault.json"))
255 if err != nil {
256 t.Fatal(err)
257 }
258 if strings.Contains(string(file), secret) || strings.Contains(string(file), "changed-by-agent") {
259 t.Fatal("vault persisted plaintext")
260 }
261 parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200)
262 parityAgent(t, s, "POST", "/api/vault", reveal, 423)
263 parityUI(t, s, "POST", "/api/vault", reveal, 423)
264}
265
266func TestAgentParityBrowserHomeFailureAndLength(t *testing.T) {
267 s := agentTestController(t)
268 s.preferences.BrowserHomeURL = "https://old.example.test/"
269 s.preferences.ClaudeTerminalCommand = "claude --continue"
270 if err := writePrivate(filepath.Join(s.profile, "workbench.json"), s.preferences); err != nil {
271 t.Fatal(err)
272 }
273 before, err := os.ReadFile(filepath.Join(s.profile, "workbench.json"))
274 if err != nil {
275 t.Fatal(err)
276 }
277 s.ready = true
278 guestCalls := 0
279 s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) {
280 guestCalls++
281 if r.URL.Path != "/homepage" {
282 t.Fatal("unexpected guest lifecycle operation", r.URL.Path)
283 }
284 return nil, errors.New("simulated offline guest transport")
285 }))
286 const replacement = "https://new.example.test/"
287 parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": replacement}, 400)
288 _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": replacement}}))
289 if err == nil {
290 t.Fatal("Agent accepted homepage runtime failure")
291 }
292 if guestCalls != 2 {
293 t.Fatal("both entry points must reach the live browser", guestCalls)
294 }
295 after, _ := os.ReadFile(filepath.Join(s.profile, "workbench.json"))
296 if string(before) != string(after) || s.preferences.BrowserHomeURL != "https://old.example.test/" {
297 t.Fatal("failed update changed persisted or visible homepage")
298 }
299 tooLong := "https://example.test/" + strings.Repeat("a", 8192)
300 parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": tooLong}, 400)
301 parityAgent(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": tooLong}, 400)
302 _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": tooLong}}))
303 if err == nil {
304 t.Fatal("Agent patch bypassed homepage limit")
305 }
306 if guestCalls != 2 {
307 t.Fatal("invalid homepage reached guest")
308 }
309 s.ready = false
310 parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": replacement}, 200)
311 data, err := AgentCall(context.Background(), s.configPath, "browser.preferences.get", nil)
312 if err != nil {
313 t.Fatal(err)
314 }
315 if parityDecode[map[string]string](t, data)["browser_home_url"] != replacement {
316 t.Fatal("Agent cannot read UI homepage")
317 }
318 const final = "https://agent.example.test/"
319 _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": final}}))
320 if err != nil {
321 t.Fatal(err)
322 }
323 if parityDecode[map[string]string](t, parityUI(t, s, "GET", "/api/browser/preferences", nil, 200))["browser_home_url"] != final {
324 t.Fatal("UI missed Agent homepage")
325 }
326 var saved Preferences
327 body, _ := os.ReadFile(filepath.Join(s.profile, "workbench.json"))
328 _ = json.Unmarshal(body, &saved)
329 if saved.BrowserHomeURL != final || saved.ClaudeTerminalCommand != "claude --continue" {
330 t.Fatal("homepage success discarded unrelated preferences", saved)
331 }
332}
333
334func TestAgentParityClaudeSchedulingPointerValues(t *testing.T) {
335 s := agentTestController(t)
336 firstID, secondID := strings.Repeat("a", 24), strings.Repeat("b", 24)
337 list := claudeAccountList{Accounts: []claudeAccount{
338 {ID: firstID, Source: "default", Email: "[email protected]", Label: "First", Enabled: true, HandoffGroup: "shared"},
339 {ID: secondID, Source: "default", Email: "[email protected]", Label: "Second", Enabled: true, HandoffGroup: "shared"},
340 }, Scheduling: (claudeScheduling{}).defaults()}
341 if err := s.saveClaudeAccounts(list); err != nil {
342 t.Fatal(err)
343 }
344 // UI input explicitly sets a pointer bool false and clears a pointer string.
345 parityUI(t, s, "POST", "/api/claude-accounts", map[string]any{"action": "update", "id": firstID, "enabled": false, "handoff_group": ""}, 200)
346 data, err := AgentCall(context.Background(), s.configPath, "claude-accounts.get", nil)
347 if err != nil {
348 t.Fatal(err)
349 }
350 view := parityDecode[claudePanel](t, data)
351 if view.Accounts[0].Enabled || view.Accounts[0].HandoffGroup != "" {
352 t.Fatal("Agent lost explicit false/empty UI fields")
353 }
354 data, err = AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, map[string]any{"action": "update", "id": firstID, "enabled": true, "handoff_group": "from-agent"}))
355 if err != nil {
356 t.Fatal(err)
357 }
358 view = parityDecode[claudePanel](t, parityUI(t, s, "GET", "/api/claude-accounts", nil, 200))
359 if !view.Accounts[0].Enabled || view.Accounts[0].HandoffGroup != "from-agent" {
360 t.Fatal("UI missed Agent pointer-field update")
361 }
362 _, err = AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, map[string]any{"action": "scheduling", "scheduling": map[string]any{"mode": "sequential", "switch_policy": "wait"}, "order": []string{secondID, firstID}}))
363 if err != nil {
364 t.Fatal(err)
365 }
366 view = parityDecode[claudePanel](t, parityUI(t, s, "GET", "/api/claude-accounts", nil, 200))
367 if view.Scheduling.Mode != "sequential" || view.Scheduling.SwitchPolicy != "wait" || view.Accounts[0].ID != secondID {
368 t.Fatal("UI lost nested scheduling or order", view)
369 }
370 stored, err := s.loadClaudeAccounts()
371 if err != nil {
372 t.Fatal(err)
373 }
374 if stored.Scheduling != view.Scheduling || stored.Accounts[0].ID != secondID {
375 t.Fatal("scheduling/order success was not durable")
376 }
377 for _, input := range []map[string]any{
378 {"action": "update", "id": firstID, "enabled": "false"},
379 {"action": "scheduling", "scheduling": map[string]any{"mode": "sequential", "switch_policy": "wait", "unknown": true}},
380 } {
381 body, _ := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json"))
382 if _, err := AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, input)); err == nil {
383 t.Fatal("Agent accepted invalid nested/pointer value", input)
384 }
385 parityUI(t, s, "POST", "/api/claude-accounts", input, 400)
386 after, _ := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json"))
387 if string(body) != string(after) {
388 t.Fatal("invalid scheduling write changed saved registry")
389 }
390 }
391}