跳到主要内容

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

浏览文件

macos_resources_test.go

150 行 · 6.1 KB历史下载
1package workbench
2
3import (
4 "encoding/json"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10 "time"
11
12 "github.com/sylvinus/agent-vm/internal/cage"
13 "github.com/sylvinus/agent-vm/internal/guestos"
14 "github.com/sylvinus/agent-vm/internal/host"
15)
16
17func TestMacOSResourceSaveUsesGuestMinimumAndPreservesOtherData(t *testing.T) {
18 oldMemory, oldCPUs := host.MemGiB, host.CPUs
19 t.Cleanup(func() { host.MemGiB, host.CPUs = oldMemory, oldCPUs })
20 host.MemGiB = func() int { return 24 }
21 host.CPUs = func() int { return 10 }
22 t.Setenv("AGENT_VM_HOST_SHARE", "2")
23 s := testServer(t)
24 s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
25 if err := os.MkdirAll(s.instanceDir(), 0700); err != nil {
26 t.Fatal(err)
27 }
28 configuration := []byte("os: Darwin\nmemory: 4GiB\ncpus: 2\n")
29 if err := os.WriteFile(filepath.Join(s.instanceDir(), "lima.yaml"), configuration, 0600); err != nil {
30 t.Fatal(err)
31 }
32 network, _ := os.ReadFile(s.configPath)
33 for _, body := range []string{`{"allocation":{"memory_gib":2,"cpus":2}}`, `{"allocation":{"memory_gib":4,"cpus":1}}`, `{"allocation":{"memory_gib":13,"cpus":2}}`} {
34 response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/resources", []byte(body))
35 if response.Code == 200 {
36 t.Fatalf("accepted invalid macOS allocation %s", body)
37 }
38 }
39 response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/resources", []byte(`{"allocation":{"memory_gib":6,"cpus":3}}`))
40 if response.Code != 200 {
41 t.Fatalf("save failed %d %s", response.Code, response.Body.String())
42 }
43 allocation, err := cage.LoadResourceAllocation(s.configPath)
44 if err != nil || allocation.MemoryGiB != 6 || allocation.CPUs != 3 {
45 t.Fatalf("saved allocation %+v %v", allocation, err)
46 }
47 for filename, want := range map[string][]byte{s.configPath: network, filepath.Join(s.instanceDir(), "lima.yaml"): configuration} {
48 got, err := os.ReadFile(filename)
49 if err != nil || string(got) != string(want) {
50 t.Fatalf("save changed unrelated file %s", filename)
51 }
52 }
53 response = windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/resources", nil)
54 var status struct {
55 Runtime string
56 Policy string `json:"memory_policy"`
57 Minimum int `json:"min_memory_gib"`
58 Memory int `json:"memory_gib"`
59 Observation any
60 }
61 if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &status) != nil || status.Runtime != "vz-macos" || status.Policy != "fixed" || status.Minimum != 4 || status.Memory != 6 || status.Observation != nil {
62 t.Fatalf("status mismatch %s", response.Body.String())
63 }
64 s.op.Lock()
65 response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/resources", []byte(`{"allocation":{"automatic":true}}`))
66 s.op.Unlock()
67 if response.Code != 409 {
68 t.Fatal("resource save raced lifecycle operation")
69 }
70 if err = writePrivate(cage.ResourceAllocationPath(s.configPath), cage.ResourceAllocation{MemoryGiB: 2, CPUs: 1}); err != nil {
71 t.Fatal(err)
72 }
73 s.networkPaused = true
74 response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/resources", []byte(`{}`))
75 if response.Code != 200 {
76 t.Fatal(response.Code, response.Body.String())
77 }
78 job := awaitJobIdle(t, &s.jobs)
79 if !strings.Contains(job.Error, "至少需要") || !s.networkPaused {
80 t.Fatalf("invalid saved limit passed restart validation: %+v", job)
81 }
82}
83
84func TestMacOSResourceSamplesKeepUnknownCPUAndResetAcrossBoots(t *testing.T) {
85 sample := macOSResourceSample{Version: 1, Total: 4 << 30, Available: 2 << 30, Free: 1 << 30, Inactive: 1 << 30, CPUs: 2, CPUTicks: [4]uint32{10, 10, 80, 0}, Boot: 10}
86 data, _ := json.Marshal(sample)
87 if _, err := parseMacOSResourceSample(data, 4<<30, 2); err != nil {
88 t.Fatal(err)
89 }
90 observer := macOSResourceObserver{}
91 now := time.Now()
92 first := observer.observation(sample, now)
93 if first["cpu_percent"].(*float64) != nil {
94 t.Fatal("first CPU sample was fabricated")
95 }
96 if _, ok := first["pressure"]; ok {
97 t.Fatal("unavailable pressure was reported as observed")
98 }
99 sample.CPUTicks = [4]uint32{20, 20, 100, 0}
100 second := observer.observation(sample, now.Add(4*time.Second))
101 if value := second["cpu_percent"].(*float64); value == nil || *value != 50 {
102 t.Fatalf("CPU delta=%v", value)
103 }
104 sample.Boot++
105 if observer.observation(sample, now.Add(8*time.Second))["cpu_percent"].(*float64) != nil {
106 t.Fatal("CPU carried across guest restart")
107 }
108 sample.Boot--
109 if observer.observation(sample, now.Add(30*time.Second))["cpu_percent"].(*float64) != nil {
110 t.Fatal("CPU carried across stale observation")
111 }
112 for _, change := range []func(*macOSResourceSample){func(s *macOSResourceSample) { s.Total = 8 << 30 }, func(s *macOSResourceSample) { s.CPUs = 4 }, func(s *macOSResourceSample) { s.Available = 5 << 30 }, func(s *macOSResourceSample) { s.Inactive = 3 << 30 }, func(s *macOSResourceSample) { s.Boot = 0 }} {
113 invalid := sample
114 change(&invalid)
115 data, _ = json.Marshal(invalid)
116 if _, err := parseMacOSResourceSample(data, 4<<30, 2); err == nil {
117 t.Fatal("inconsistent guest metrics accepted")
118 }
119 }
120}
121
122func TestMacOSResourcesReadThroughBoundSSHAndDiscardFailures(t *testing.T) {
123 guest := newMacWorkspaceGuest(t)
124 s := guest.s
125 if err := os.WriteFile(filepath.Join(s.instanceDir(), "lima.yaml"), []byte("os: Darwin\nmemory: 4GiB\ncpus: 2\n"), 0600); err != nil {
126 t.Fatal(err)
127 }
128 read := func() map[string]any {
129 t.Helper()
130 response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/resources", nil)
131 var status map[string]any
132 if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &status) != nil {
133 t.Fatalf("resource HTTP response %d %s", response.Code, response.Body.String())
134 }
135 return status
136 }
137 first := read()
138 if first["observation"].(map[string]any)["cpu_percent"] != nil {
139 t.Fatal("first SSH sample fabricated CPU usage")
140 }
141 second := read()
142 if second["observation"].(map[string]any)["cpu_percent"] != float64(50) {
143 t.Fatal("bound SSH samples lost CPU delta")
144 }
145 guest.resourceFailure.Store(true)
146 failed := read()
147 if failed["observation"] != nil || failed["resource_error"] == "" {
148 t.Fatal("failed observation exposed stale metrics or hid the error")
149 }
150}